@ferronhooi/aihub 0.0.1 → 0.1.0-next.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.
package/dist/cli.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
- // Entry point. Commands are added per workflow in src/commands/.
3
- const [, , ...args] = process.argv;
4
- if (args[0] === "--version") {
5
- console.log("0.0.0");
6
- }
7
- else {
8
- console.log("aihub: under construction. Commands: pr, comments, cherry-pick, branch, story, pipeline, batch, work, init, skills, doctor.");
9
- }
10
- export {};
2
+ // Entry point. Commands are registered in src/router.ts.
3
+ import { main } from "./router.js";
4
+ const code = await main(process.argv.slice(2), {
5
+ cwd: process.cwd(),
6
+ env: process.env,
7
+ fetch,
8
+ out: (l) => process.stdout.write(l + "\n"),
9
+ err: (l) => process.stderr.write(l + "\n"),
10
+ });
11
+ process.exitCode = code;
@@ -0,0 +1,32 @@
1
+ import { parseArgs } from "node:util";
2
+ import { commentsGet, commentsReply } from "../lib/comments.js";
3
+ import { AihubError } from "../lib/errors.js";
4
+ export async function run(argv, ctx) {
5
+ const [sub, ...rest] = argv;
6
+ let v;
7
+ try {
8
+ v = parseArgs({
9
+ args: rest,
10
+ options: {
11
+ pr: { type: "string" },
12
+ "include-resolved": { type: "boolean" },
13
+ "replies-file": { type: "string" },
14
+ json: { type: "boolean" },
15
+ },
16
+ }).values;
17
+ }
18
+ catch (e) {
19
+ throw new AihubError(e.message);
20
+ }
21
+ if (sub === "get") {
22
+ ctx.out(await commentsGet(ctx, { pr: v.pr, includeResolved: !!v["include-resolved"], json: !!v.json }));
23
+ return;
24
+ }
25
+ if (sub === "reply") {
26
+ if (!v["replies-file"])
27
+ throw new AihubError("aihub comments reply needs --replies-file <file.yaml>");
28
+ ctx.out(await commentsReply(ctx, { pr: v.pr, repliesFile: v["replies-file"], json: !!v.json }));
29
+ return;
30
+ }
31
+ throw new AihubError("usage: aihub comments get|reply [flags]");
32
+ }
@@ -0,0 +1,75 @@
1
+ import { parseArgs } from "node:util";
2
+ import { AihubError } from "../lib/errors.js";
3
+ import { createPr, updatePr } from "../lib/pr.js";
4
+ function parse(argv, options) {
5
+ try {
6
+ return parseArgs({ args: argv, options, allowPositionals: true }).values;
7
+ }
8
+ catch (e) {
9
+ throw new AihubError(`${e.message}`);
10
+ }
11
+ }
12
+ function num(v, flag) {
13
+ if (v === undefined)
14
+ return undefined;
15
+ const n = Number(String(v).replace(/^AB#/i, ""));
16
+ if (!Number.isInteger(n) || n <= 0)
17
+ throw new AihubError(`${flag} must be a number`);
18
+ return n;
19
+ }
20
+ export async function run(argv, ctx) {
21
+ const [sub, ...rest] = argv;
22
+ if (sub === "create") {
23
+ const v = parse(rest, {
24
+ title: { type: "string" },
25
+ "body-file": { type: "string" },
26
+ target: { type: "string" },
27
+ draft: { type: "boolean" },
28
+ "work-item": { type: "string" },
29
+ "dry-run": { type: "boolean" },
30
+ json: { type: "boolean" },
31
+ });
32
+ ctx.out(await createPr(ctx, {
33
+ title: v.title,
34
+ bodyFile: v["body-file"],
35
+ target: v.target,
36
+ draft: v.draft,
37
+ workItem: num(v["work-item"], "--work-item"),
38
+ dryRun: v["dry-run"],
39
+ json: v.json,
40
+ }));
41
+ return;
42
+ }
43
+ if (sub === "update") {
44
+ const v = parse(rest, {
45
+ pr: { type: "string" },
46
+ "body-file": { type: "string" },
47
+ section: { type: "string" },
48
+ "append-file": { type: "string" },
49
+ "replace-file": { type: "string" },
50
+ title: { type: "string" },
51
+ draft: { type: "string" },
52
+ target: { type: "string" },
53
+ json: { type: "boolean" },
54
+ });
55
+ let draft;
56
+ if (v.draft !== undefined) {
57
+ if (v.draft !== "true" && v.draft !== "false")
58
+ throw new AihubError("--draft must be true or false");
59
+ draft = v.draft === "true";
60
+ }
61
+ ctx.out(await updatePr(ctx, {
62
+ pr: v.pr,
63
+ bodyFile: v["body-file"],
64
+ section: v.section,
65
+ appendFile: v["append-file"],
66
+ replaceFile: v["replace-file"],
67
+ title: v.title,
68
+ draft,
69
+ target: v.target,
70
+ json: v.json,
71
+ }));
72
+ return;
73
+ }
74
+ throw new AihubError("usage: aihub pr create|update [flags] (see README)");
75
+ }
@@ -0,0 +1,158 @@
1
+ import { AihubError } from "./errors.js";
2
+ export function parseRemote(url) {
3
+ const u = url.trim();
4
+ const dec = (s) => decodeURIComponent(s);
5
+ const make = (org, project, repo) => ({
6
+ org: dec(org),
7
+ project: dec(project),
8
+ repo: dec(repo),
9
+ orgUrl: `https://dev.azure.com/${encodeURIComponent(dec(org))}`,
10
+ });
11
+ let m;
12
+ // SSH: git@ssh.dev.azure.com:v3/org/project/repo | org@vs-ssh.visualstudio.com:v3/org/project/repo
13
+ if ((m = /^(?:ssh:\/\/)?[^@\s]+@(?:ssh\.dev\.azure\.com|vs-ssh\.visualstudio\.com)[:/](?:v3\/)?([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/.exec(u))) {
14
+ return make(m[1], m[2], m[3]);
15
+ }
16
+ // HTTPS dev.azure.com/org/project/_git/repo (optional user@)
17
+ if ((m = /^https?:\/\/(?:[^@/]+@)?dev\.azure\.com\/([^/]+)\/([^/]+)\/_git\/([^/?#]+?)(?:\.git)?\/?(?:[?#].*)?$/.exec(u))) {
18
+ return make(m[1], m[2], m[3]);
19
+ }
20
+ // HTTPS org.visualstudio.com/[DefaultCollection/]project/_git/repo
21
+ if ((m = /^https?:\/\/(?:[^@/]+@)?([^./]+)\.visualstudio\.com\/(?:DefaultCollection\/)?([^/]+)\/_git\/([^/?#]+?)(?:\.git)?\/?(?:[?#].*)?$/.exec(u))) {
22
+ return make(m[1], m[2], m[3]);
23
+ }
24
+ throw new AihubError(`remote '${u}' is not an Azure DevOps remote (dev.azure.com or visualstudio.com)`);
25
+ }
26
+ export const API_VERSION = "7.1";
27
+ export class AdoClient {
28
+ remote;
29
+ auth;
30
+ fetchFn;
31
+ constructor(remote, auth, fetchFn = fetch) {
32
+ this.remote = remote;
33
+ this.auth = auth;
34
+ this.fetchFn = fetchFn;
35
+ }
36
+ repoPath() {
37
+ return `git/repositories/${encodeURIComponent(this.remote.repo)}`;
38
+ }
39
+ prUrl(id) {
40
+ const r = this.remote;
41
+ return `${r.orgUrl}/${encodeURIComponent(r.project)}/_git/${encodeURIComponent(r.repo)}/pullrequest/${id}`;
42
+ }
43
+ url(path, query = {}) {
44
+ const q = new URLSearchParams();
45
+ for (const [k, v] of Object.entries(query))
46
+ if (v !== undefined)
47
+ q.set(k, String(v));
48
+ q.set("api-version", API_VERSION);
49
+ return `${this.remote.orgUrl}/${encodeURIComponent(this.remote.project)}/_apis/${path}?${q.toString()}`;
50
+ }
51
+ async request(method, path, opts = {}) {
52
+ const res = await this.fetchFn(this.url(path, opts.query), {
53
+ method,
54
+ headers: {
55
+ Authorization: await this.auth(),
56
+ Accept: opts.raw ? "text/plain" : "application/json",
57
+ ...(opts.body !== undefined ? { "Content-Type": "application/json; charset=utf-8" } : {}),
58
+ },
59
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
60
+ });
61
+ const text = await res.text();
62
+ const ctype = res.headers.get("content-type") ?? "";
63
+ // Azure DevOps answers a bad/missing credential with 203 + an HTML sign-in page.
64
+ if (res.status === 401 || res.status === 203 || (res.ok && !opts.raw && ctype.includes("text/html"))) {
65
+ throw new AihubError("not signed in to Azure DevOps: run 'az login' or set AIHUB_ADO_PAT");
66
+ }
67
+ if (!res.ok)
68
+ throw new AihubError(httpMessage(res.status, text, method, path));
69
+ if (opts.raw)
70
+ return { data: text, headers: res.headers };
71
+ return { data: (text ? JSON.parse(text) : {}), headers: res.headers };
72
+ }
73
+ get(path, query) {
74
+ return this.request("GET", path, { query }).then((r) => r.data);
75
+ }
76
+ /** GET a collection, following x-ms-continuationtoken. Returns all `value` items. */
77
+ async list(path, query = {}) {
78
+ const out = [];
79
+ let token = null;
80
+ for (let i = 0; i < 100; i++) {
81
+ const r = await this.request("GET", path, {
82
+ query: { ...query, ...(token ? { continuationToken: token } : {}) },
83
+ });
84
+ out.push(...(r.data.value ?? []));
85
+ token = r.headers.get("x-ms-continuationtoken");
86
+ if (!token)
87
+ break;
88
+ }
89
+ return out;
90
+ }
91
+ post(path, body, query) {
92
+ return this.request("POST", path, { body, query }).then((r) => r.data);
93
+ }
94
+ patch(path, body, query) {
95
+ return this.request("PATCH", path, { body, query }).then((r) => r.data);
96
+ }
97
+ getText(path, query) {
98
+ return this.request("GET", path, { query, raw: true }).then((r) => r.data);
99
+ }
100
+ }
101
+ function httpMessage(status, body, method, path) {
102
+ let detail = "";
103
+ try {
104
+ detail = JSON.parse(body).message ?? "";
105
+ }
106
+ catch {
107
+ detail = body.slice(0, 200);
108
+ }
109
+ detail = detail.replace(/\s+/g, " ").trim();
110
+ const p = path.split("?")[0];
111
+ if (status === 403)
112
+ return `Azure DevOps denied access (403): your account needs access to this repository${detail ? ` (${detail})` : ""}`;
113
+ if (status === 404)
114
+ return `Azure DevOps: not found (404) for ${method} ${p}${detail ? `: ${detail}` : ""}`;
115
+ return `Azure DevOps ${method} ${p} failed (${status})${detail ? `: ${detail}` : ""}`;
116
+ }
117
+ export const branchRef = (b) => (b.startsWith("refs/") ? b : `refs/heads/${b}`);
118
+ export const shortBranch = (r) => r.replace(/^refs\/heads\//, "");
119
+ export async function findActivePr(c, source, target) {
120
+ const prs = await c.list(`${c.repoPath()}/pullrequests`, {
121
+ "searchCriteria.sourceRefName": branchRef(source),
122
+ "searchCriteria.status": "active",
123
+ ...(target ? { "searchCriteria.targetRefName": branchRef(target) } : {}),
124
+ });
125
+ return prs[0];
126
+ }
127
+ export const getPr = (c, id) => c.get(`${c.repoPath()}/pullrequests/${id}`);
128
+ export async function repoDefaultBranch(c) {
129
+ const r = await c.get(c.repoPath());
130
+ return r.defaultBranch ? shortBranch(r.defaultBranch) : undefined;
131
+ }
132
+ export async function getWorkItemTitle(c, id) {
133
+ try {
134
+ const r = await c.get(`wit/workitems/${id}`, { fields: "System.Title" });
135
+ return r.fields?.["System.Title"];
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ }
141
+ /** PR ids linked to a work item through artifact links (vstfs:///Git/PullRequestId/<project>%2F<repo>%2F<id>). */
142
+ export async function getWorkItemPrIds(c, id) {
143
+ try {
144
+ const r = await c.get(`wit/workitems/${id}`, { $expand: "relations" });
145
+ const ids = [];
146
+ for (const rel of r.relations ?? []) {
147
+ if (rel.rel !== "ArtifactLink")
148
+ continue;
149
+ const m = /PullRequestId\/.*?(\d+)$/i.exec(decodeURIComponent(rel.url));
150
+ if (m)
151
+ ids.push(Number(m[1]));
152
+ }
153
+ return ids;
154
+ }
155
+ catch {
156
+ return [];
157
+ }
158
+ }
@@ -0,0 +1,68 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { AihubError } from "./errors.js";
6
+ export const ADO_RESOURCE = "499b84ac-1321-427f-aa17-267ca6975798";
7
+ export const defaultExec = (cmd, args, input) => {
8
+ const r = spawnSync(cmd, args, {
9
+ encoding: "utf8",
10
+ input,
11
+ shell: process.platform === "win32" && cmd === "az",
12
+ timeout: 30000,
13
+ });
14
+ if (r.error || r.status !== 0)
15
+ throw new Error(r.error?.message ?? (r.stderr || "").trim());
16
+ return r.stdout;
17
+ };
18
+ const basic = (pat) => `Basic ${Buffer.from(`:${pat}`).toString("base64")}`;
19
+ /** Order: PAT env -> az token (cached until expiry) -> git credential fill. */
20
+ export function makeAuth(deps = {}) {
21
+ const env = deps.env ?? process.env;
22
+ const exec = deps.exec ?? defaultExec;
23
+ const now = deps.now ?? Date.now;
24
+ const cacheFile = deps.cacheFile ?? join(tmpdir(), "aihub-az-token.json");
25
+ let cached;
26
+ return async () => {
27
+ if (cached)
28
+ return cached;
29
+ const pat = env.AIHUB_ADO_PAT || env.AZURE_DEVOPS_EXT_PAT;
30
+ if (pat)
31
+ return (cached = basic(pat));
32
+ try {
33
+ if (existsSync(cacheFile)) {
34
+ const c = JSON.parse(readFileSync(cacheFile, "utf8"));
35
+ if (c.token && c.expiresAt - 120_000 > now())
36
+ return (cached = `Bearer ${c.token}`);
37
+ }
38
+ }
39
+ catch {
40
+ /* ignore a broken cache */
41
+ }
42
+ try {
43
+ const out = exec("az", ["account", "get-access-token", "--resource", ADO_RESOURCE, "--output", "json"]);
44
+ const j = JSON.parse(out);
45
+ const expiresAt = j.expires_on ? Number(j.expires_on) * 1000 : Date.parse(j.expiresOn ?? "") || now() + 30 * 60_000;
46
+ try {
47
+ writeFileSync(cacheFile, JSON.stringify({ token: j.accessToken, expiresAt }), { mode: 0o600 });
48
+ }
49
+ catch {
50
+ /* cache is optional */
51
+ }
52
+ return (cached = `Bearer ${j.accessToken}`);
53
+ }
54
+ catch {
55
+ /* fall through to git credential */
56
+ }
57
+ try {
58
+ const out = exec("git", ["credential", "fill"], "protocol=https\nhost=dev.azure.com\n\n");
59
+ const pw = /^password=(.*)$/m.exec(out)?.[1]?.trim();
60
+ if (pw)
61
+ return (cached = basic(pw));
62
+ }
63
+ catch {
64
+ /* fall through */
65
+ }
66
+ throw new AihubError("not signed in to Azure DevOps: run 'az login' or set AIHUB_ADO_PAT");
67
+ };
68
+ }
@@ -0,0 +1,119 @@
1
+ import { parse } from "yaml";
2
+ import { repoClient } from "./context.js";
3
+ import { AihubError } from "./errors.js";
4
+ import { resolvePr } from "./pr.js";
5
+ import { readUtf8 } from "./team.js";
6
+ const OPEN = new Set(["active", "pending", ""]);
7
+ export const REPLY_STATUSES = ["fixed", "wontFix", "closed", "active"];
8
+ const CONTEXT = 2;
9
+ export async function getThreads(client, prId, sourceCommit, includeResolved) {
10
+ const threads = await client.list(`${client.repoPath()}/pullrequests/${prId}/threads`);
11
+ const files = new Map();
12
+ const out = [];
13
+ for (const t of threads) {
14
+ if (t.isDeleted)
15
+ continue;
16
+ const comments = (t.comments ?? []).filter((c) => !c.isDeleted && (c.commentType ?? "text") !== "system");
17
+ if (!comments.length)
18
+ continue;
19
+ const status = t.status ?? "active";
20
+ if (!includeResolved && !OPEN.has(status))
21
+ continue;
22
+ const file = t.threadContext?.filePath;
23
+ const line = t.threadContext?.rightFileStart?.line;
24
+ let code;
25
+ if (file && line && sourceCommit) {
26
+ if (!files.has(file))
27
+ files.set(file, await fetchLines(client, file, sourceCommit));
28
+ const lines = files.get(file);
29
+ if (lines) {
30
+ const end = t.threadContext?.rightFileEnd?.line ?? line;
31
+ code = [];
32
+ for (let n = Math.max(1, line - CONTEXT); n <= Math.min(lines.length, end + CONTEXT); n++)
33
+ code.push({ n, text: lines[n - 1] });
34
+ }
35
+ }
36
+ out.push({
37
+ threadId: t.id,
38
+ status,
39
+ file,
40
+ line,
41
+ code,
42
+ comments: comments.map((c) => ({ id: c.id, author: c.author?.displayName ?? "?", text: (c.content ?? "").trim() })),
43
+ });
44
+ }
45
+ return out;
46
+ }
47
+ async function fetchLines(client, path, commit) {
48
+ try {
49
+ const text = await client.getText(`${client.repoPath()}/items`, {
50
+ path,
51
+ "versionDescriptor.version": commit,
52
+ "versionDescriptor.versionType": "commit",
53
+ $format: "text",
54
+ });
55
+ return text.replace(/^/, "").replace(/\r\n/g, "\n").split("\n");
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ export function formatThreads(prId, threads) {
62
+ if (!threads.length)
63
+ return `!${prId}: no open comment threads`;
64
+ const lines = [`!${prId}: ${threads.length} thread${threads.length === 1 ? "" : "s"}`];
65
+ for (const t of threads) {
66
+ const where = t.file ? `${t.file}${t.line ? `:${t.line}` : ""}` : "(general)";
67
+ const [first, ...rest] = t.comments;
68
+ lines.push(`[${t.threadId}] ${where} (${t.status}) ${first.author}: ${oneLine(first.text)}`);
69
+ if (t.code)
70
+ for (const c of t.code)
71
+ lines.push(` ${c.n === t.line ? ">" : " "} ${String(c.n).padStart(4)} ${c.text}`);
72
+ for (const r of rest)
73
+ lines.push(` - ${r.author}: ${oneLine(r.text)}`);
74
+ }
75
+ return lines.join("\n");
76
+ }
77
+ const oneLine = (s) => s.replace(/\s*\n\s*/g, " / ");
78
+ export async function commentsGet(ctx, o) {
79
+ const { root, client } = repoClient(ctx);
80
+ const pr = await resolvePr(ctx, client, root, o.pr);
81
+ const threads = await getThreads(client, pr.pullRequestId, pr.lastMergeSourceCommit?.commitId, !!o.includeResolved);
82
+ return o.json ? JSON.stringify({ pr: pr.pullRequestId, threads }) : formatThreads(pr.pullRequestId, threads);
83
+ }
84
+ export function parseReplies(yamlText) {
85
+ const doc = parse(yamlText);
86
+ const list = Array.isArray(doc) ? doc : doc?.replies;
87
+ if (!Array.isArray(list))
88
+ throw new AihubError("replies file must be a yaml list of {threadId, text, status}");
89
+ return list.map((r, i) => {
90
+ const threadId = Number(r.threadId);
91
+ if (!Number.isInteger(threadId) || threadId <= 0)
92
+ throw new AihubError(`replies[${i}]: threadId is missing or not a number`);
93
+ const status = r.status === undefined || r.status === null ? undefined : String(r.status);
94
+ if (status && !REPLY_STATUSES.includes(status)) {
95
+ throw new AihubError(`replies[${i}]: status '${status}' must be one of ${REPLY_STATUSES.join("|")}`);
96
+ }
97
+ const text = r.text === undefined || r.text === null ? undefined : String(r.text).trim();
98
+ if (!text && !status)
99
+ throw new AihubError(`replies[${i}]: needs text and/or status`);
100
+ return { threadId, text: text || undefined, status: status };
101
+ });
102
+ }
103
+ export async function commentsReply(ctx, o) {
104
+ const replies = parseReplies(readUtf8(o.repliesFile));
105
+ const { root, client } = repoClient(ctx);
106
+ const pr = await resolvePr(ctx, client, root, o.pr);
107
+ const base = `${client.repoPath()}/pullrequests/${pr.pullRequestId}/threads`;
108
+ const done = [];
109
+ for (const r of replies) {
110
+ if (r.text)
111
+ await client.post(`${base}/${r.threadId}/comments`, { content: r.text, parentCommentId: 1, commentType: "text" });
112
+ if (r.status)
113
+ await client.patch(`${base}/${r.threadId}`, { status: r.status });
114
+ done.push(`${r.threadId}${r.status ? `=${r.status}` : ""}`);
115
+ }
116
+ return o.json
117
+ ? JSON.stringify({ pr: pr.pullRequestId, replied: replies.map((r) => r.threadId) })
118
+ : `!${pr.pullRequestId}: ${replies.length} repl${replies.length === 1 ? "y" : "ies"} posted (${done.join(", ")})`;
119
+ }
@@ -0,0 +1,9 @@
1
+ import { AdoClient, parseRemote } from "./ado.js";
2
+ import { makeAuth } from "./auth.js";
3
+ import { remoteUrl, repoRoot } from "./git.js";
4
+ export function repoClient(ctx) {
5
+ const root = repoRoot(ctx.cwd);
6
+ const remote = parseRemote(remoteUrl(root));
7
+ const auth = makeAuth({ env: ctx.env, exec: ctx.exec, cacheFile: ctx.tokenCache });
8
+ return { root, client: new AdoClient(remote, auth, ctx.fetch) };
9
+ }
@@ -0,0 +1,7 @@
1
+ /** An error whose message is shown to the user as-is (one line, with the fix). */
2
+ export class AihubError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "AihubError";
6
+ }
7
+ }
@@ -0,0 +1,79 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { AihubError } from "./errors.js";
3
+ export function git(cwd, args, opts = {}) {
4
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
5
+ if (r.error)
6
+ throw new AihubError(`git is not available: ${r.error.message}`);
7
+ if (r.status !== 0) {
8
+ if (opts.allowFail)
9
+ return "";
10
+ throw new AihubError(`git ${args.join(" ")} failed: ${(r.stderr || "").trim().split("\n")[0]}`);
11
+ }
12
+ return r.stdout.replace(/\r\n/g, "\n").trimEnd();
13
+ }
14
+ export function remoteUrl(cwd, remote = "origin") {
15
+ // raw config value: `git remote get-url` would expand insteadOf rewrites
16
+ const url = git(cwd, ["config", "--get", `remote.${remote}.url`], { allowFail: true }).trim();
17
+ if (!url)
18
+ throw new AihubError(`no git remote '${remote}' here; run inside a clone of the Azure DevOps repository`);
19
+ return url;
20
+ }
21
+ export function currentBranch(cwd) {
22
+ const b = git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]).trim();
23
+ if (b === "HEAD")
24
+ throw new AihubError("detached HEAD; check out a branch first");
25
+ return b;
26
+ }
27
+ export function repoRoot(cwd) {
28
+ return git(cwd, ["rev-parse", "--show-toplevel"]).trim();
29
+ }
30
+ /** origin's default branch name from origin/HEAD, or "" when unknown. */
31
+ export function originDefaultBranch(cwd) {
32
+ const ref = git(cwd, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], { allowFail: true }).trim();
33
+ return ref.replace(/^origin\//, "");
34
+ }
35
+ export function hasRef(cwd, ref) {
36
+ return git(cwd, ["rev-parse", "--verify", "--quiet", ref], { allowFail: true }).trim() !== "";
37
+ }
38
+ export function mergeBase(cwd, target) {
39
+ const ref = hasRef(cwd, `origin/${target}`) ? `origin/${target}` : target;
40
+ return git(cwd, ["merge-base", "HEAD", ref], { allowFail: true }).trim();
41
+ }
42
+ /** Commits on HEAD since the merge-base with the target, oldest first. */
43
+ export function commitsSince(cwd, base) {
44
+ if (!base)
45
+ return [];
46
+ const out = git(cwd, ["log", "--reverse", "--format=%h%x09%s", `${base}..HEAD`], { allowFail: true });
47
+ return out
48
+ .split("\n")
49
+ .filter(Boolean)
50
+ .map((l) => {
51
+ const [sha, ...rest] = l.split("\t");
52
+ return { sha, subject: rest.join("\t") };
53
+ });
54
+ }
55
+ /** File content at origin/<branch> (falls back to local branch), or undefined. */
56
+ export function showFile(cwd, branch, path) {
57
+ for (const ref of [`origin/${branch}`, branch]) {
58
+ if (!hasRef(cwd, ref))
59
+ continue;
60
+ const r = spawnSync("git", ["show", `${ref}:${path}`], { cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
61
+ if (r.status === 0)
62
+ return r.stdout.replace(/^/, "");
63
+ }
64
+ return undefined;
65
+ }
66
+ /** Push the branch when origin does not have it or is behind. Returns true if a push happened. */
67
+ export function pushIfNeeded(cwd, branch) {
68
+ const remoteSha = git(cwd, ["ls-remote", "--heads", "origin", branch], { allowFail: true }).split(/\s+/)[0];
69
+ const local = git(cwd, ["rev-parse", "HEAD"]).trim();
70
+ if (remoteSha === local)
71
+ return false;
72
+ git(cwd, ["push", "--set-upstream", "origin", `HEAD:refs/heads/${branch}`]);
73
+ return true;
74
+ }
75
+ /** Work item id from branch names like feature/1234-slug, bugfix/1234_x, 1234-x. */
76
+ export function workItemFromBranch(branch) {
77
+ const m = /(?:^|\/)(\d{1,9})(?=[-_/]|$)/.exec(branch);
78
+ return m ? Number(m[1]) : undefined;
79
+ }
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,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,41 @@
1
+ import { AihubError } from "./lib/errors.js";
2
+ import * as comments from "./commands/comments.js";
3
+ import * as pr from "./commands/pr.js";
4
+ /**
5
+ * Command registry. To add a command: create src/commands/<name>.ts exporting
6
+ * `run(argv, ctx)` and add one line here. Commands print through ctx.out and
7
+ * throw AihubError for user-facing failures.
8
+ */
9
+ export const commands = {
10
+ pr: pr.run,
11
+ comments: comments.run,
12
+ };
13
+ export const VERSION = "0.0.0";
14
+ /** Returns the process exit code. */
15
+ export async function main(argv, ctx, registry = commands) {
16
+ const [name, ...rest] = argv;
17
+ if (!name || name === "--help" || name === "-h" || name === "help") {
18
+ ctx.out(`aihub ${VERSION}: Azure DevOps team workflows in one call. Commands: ${Object.keys(registry).join(", ")}.`);
19
+ return 0;
20
+ }
21
+ if (name === "--version" || name === "-v") {
22
+ ctx.out(VERSION);
23
+ return 0;
24
+ }
25
+ const fn = registry[name];
26
+ if (!fn) {
27
+ ctx.err(`aihub: unknown command '${name}'. Commands: ${Object.keys(registry).join(", ")}.`);
28
+ return 2;
29
+ }
30
+ try {
31
+ await fn(rest, ctx);
32
+ return 0;
33
+ }
34
+ catch (e) {
35
+ if (e instanceof AihubError)
36
+ ctx.err(`aihub: ${e.message}`);
37
+ else
38
+ ctx.err(`aihub: unexpected error: ${e.message}`);
39
+ return 1;
40
+ }
41
+ }
@@ -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();
@@ -0,0 +1,70 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { describe, expect, it } from "vitest";
5
+ import { COMMANDS, commandFileName, expectedCommand, lintSkills, parseFrontMatter } from "./lintSkills.js";
6
+ const repoSkills = path.resolve(import.meta.dirname, "../../../skills");
7
+ function body(extra = "") {
8
+ const para = "Run the command and report the printed link. Never ask about template sections. ".repeat(12);
9
+ return `# T\n\n## When\n${para}\n## Steps\nx\n## What the CLI fills\ny\n## If it fails\nz\n${extra}`;
10
+ }
11
+ function pack(skill, text) {
12
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "lint-"));
13
+ fs.mkdirSync(path.join(root, "skills", skill), { recursive: true });
14
+ fs.mkdirSync(path.join(root, "commands"), { recursive: true });
15
+ fs.writeFileSync(path.join(root, "skills", skill, "SKILL.md"), text);
16
+ return path.join(root, "skills");
17
+ }
18
+ const good = (extra = "") => `---\nname: demo\ndescription: "Use when testing"\n---\n${body(extra)}`;
19
+ const lint = (dir) => lintSkills(dir).filter((e) => !e.includes("commands") && !e.includes("skill \"") && !e.includes(".md: missing"));
20
+ describe("lintSkills", () => {
21
+ it("accepts a valid skill", () => {
22
+ expect(lint(pack("demo", good()))).toEqual([]);
23
+ });
24
+ it("requires Use when", () => {
25
+ const t = good().replace("Use when testing", "Does things");
26
+ expect(lint(pack("demo", t)).join()).toMatch(/Use when/);
27
+ });
28
+ it("requires name equal to folder", () => {
29
+ expect(lint(pack("other", good())).join()).toMatch(/must equal folder/);
30
+ });
31
+ it("checks the token budget", () => {
32
+ expect(lint(pack("demo", good("x".repeat(4000)))).join()).toMatch(/max 500/);
33
+ });
34
+ it("flags broken links, absolute paths and forbidden names", () => {
35
+ const e = lint(pack("demo", good("[a](nope.md) C:\\Users\\x IQBS"))).join("\n");
36
+ expect(e).toMatch(/link does not resolve/);
37
+ expect(e).toMatch(/absolute path/);
38
+ expect(e).toMatch(/forbidden name "iqbs"/);
39
+ });
40
+ it("accepts a configurable forbidden list", () => {
41
+ const dir = pack("demo", good("Acme"));
42
+ expect(lintSkills(dir, { forbidden: ["acme"] }).join()).toMatch(/forbidden name "acme"/);
43
+ });
44
+ it("does not treat https links as absolute paths", () => {
45
+ expect(lint(pack("demo", good("[x](https://example.com/a)")))).toEqual([]);
46
+ });
47
+ it("parses front matter", () => {
48
+ expect(parseFrontMatter(good())?.data.name).toBe("demo");
49
+ });
50
+ it("detects commands that drift from the generated text", () => {
51
+ const dir = pack("demo", good());
52
+ const cmds = path.join(dir, "..", "commands", "opencode");
53
+ fs.mkdirSync(cmds, { recursive: true });
54
+ fs.writeFileSync(path.join(cmds, "pr.md"), "edited");
55
+ expect(lintSkills(dir).join("\n")).toMatch(/pr.md: does not match|skill "pr-create" does not exist/);
56
+ });
57
+ });
58
+ describe("the real pack", () => {
59
+ it("lints clean", () => {
60
+ expect(lintSkills(repoSkills)).toEqual([]);
61
+ });
62
+ it("has command files equal to the generated text", () => {
63
+ for (const kind of ["opencode", "copilot"]) {
64
+ for (const c of COMMANDS) {
65
+ const f = path.join(repoSkills, "..", "commands", kind, commandFileName(kind, c));
66
+ expect(fs.readFileSync(f, "utf8").replace(/\r\n/g, "\n")).toBe(expectedCommand(kind, c));
67
+ }
68
+ }
69
+ });
70
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferronhooi/aihub",
3
- "version": "0.0.1",
3
+ "version": "0.1.0-next.2",
4
4
  "description": "One small CLI for Azure DevOps team workflows used by coding agents (stories, pull requests, reviews, cherry-picks).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,5 +26,14 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "yaml": "^2.6.1"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "https://github.com/MyDataIntelligence/aihub",
33
+ "directory": "cli"
34
+ },
35
+ "homepage": "https://github.com/MyDataIntelligence/aihub#readme",
36
+ "bugs": {
37
+ "url": "https://github.com/MyDataIntelligence/aihub/issues"
29
38
  }
30
39
  }