@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
@@ -0,0 +1,118 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { parse } from "yaml";
5
+ import { parseRemote } from "./ado.js";
6
+ import { defaultExec, ADO_RESOURCE } from "./auth.js";
7
+ import { CLIENTS, clientDirs } from "./clients.js";
8
+ import { originDefaultBranch, remoteUrl, repoRoot, showFile } from "./git.js";
9
+ import { packRoot } from "./pack.js";
10
+ import { requiredPaths, validateTeam } from "./schema.js";
11
+ import { defaultTargetFor, loadTeam, readUtf8, TEAM_FILE } from "./team.js";
12
+ import { resolveTemplate } from "./templates.js";
13
+ const ok = (name, detail) => ({ name, status: "OK", detail });
14
+ const fix = (name, detail, how) => ({ name, status: "FIX", detail, fix: how });
15
+ /** Never prompts: a credential helper that wants a terminal fails instead of hanging. */
16
+ const quietExec = (cmd, args, input) => {
17
+ if (cmd !== "git")
18
+ return defaultExec(cmd, args, input);
19
+ const r = spawnSync(cmd, args, {
20
+ encoding: "utf8",
21
+ input,
22
+ timeout: 10000,
23
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" },
24
+ });
25
+ if (r.error || r.status !== 0)
26
+ throw new Error(r.error?.message ?? (r.stderr || "").trim());
27
+ return r.stdout;
28
+ };
29
+ function checkAuth(ctx) {
30
+ const how = "run 'az login', set AIHUB_ADO_PAT, or sign in once with git (git credential manager)";
31
+ const pat = ctx.env.AIHUB_ADO_PAT ? "AIHUB_ADO_PAT" : ctx.env.AZURE_DEVOPS_EXT_PAT ? "AZURE_DEVOPS_EXT_PAT" : "";
32
+ if (pat)
33
+ return ok("auth", `PAT from environment (${pat})`);
34
+ const exec = ctx.exec ?? quietExec;
35
+ try {
36
+ const j = JSON.parse(exec("az", ["account", "get-access-token", "--resource", ADO_RESOURCE, "--output", "json"]));
37
+ if (j.accessToken)
38
+ return ok("auth", "Azure CLI token (az login)");
39
+ }
40
+ catch {
41
+ /* next method */
42
+ }
43
+ try {
44
+ if (/^password=.+$/m.test(exec("git", ["credential", "fill"], "protocol=https\nhost=dev.azure.com\n\n"))) {
45
+ return ok("auth", "git credential");
46
+ }
47
+ }
48
+ catch {
49
+ /* none */
50
+ }
51
+ return fix("auth", "no way to sign in to Azure DevOps works", how);
52
+ }
53
+ export function runChecks(ctx) {
54
+ const checks = [];
55
+ const major = Number(process.versions.node.split(".")[0]);
56
+ checks.push(major >= 18
57
+ ? ok("node", `v${process.versions.node}`)
58
+ : fix("node", `v${process.versions.node} is too old (needs 18 or newer)`, "install Node 18 or newer from nodejs.org"));
59
+ const g = spawnSync("git", ["--version"], { encoding: "utf8" });
60
+ checks.push(g.status === 0 ? ok("git", g.stdout.trim()) : fix("git", "git is not available", "install git and make sure it is on the PATH"));
61
+ let root;
62
+ try {
63
+ root = repoRoot(ctx.cwd);
64
+ }
65
+ catch {
66
+ checks.push(fix("repository", "not inside a git repository", "cd into a clone of your team repository"));
67
+ }
68
+ let repoName = "";
69
+ if (root) {
70
+ try {
71
+ const r = parseRemote(remoteUrl(root));
72
+ repoName = r.repo;
73
+ checks.push(ok("remote", `${r.org}/${r.project}/${r.repo}`));
74
+ }
75
+ catch (e) {
76
+ checks.push(fix("remote", e.message, "set origin to the Azure DevOps clone URL: git remote set-url origin <url>"));
77
+ }
78
+ }
79
+ checks.push(checkAuth(ctx));
80
+ if (root) {
81
+ const teamPath = join(root, TEAM_FILE);
82
+ if (!existsSync(teamPath)) {
83
+ checks.push(fix("team.yaml", `${TEAM_FILE} not found`, "run 'aihub init' (opens a pull request with the team pack)"));
84
+ }
85
+ else {
86
+ try {
87
+ const data = parse(readUtf8(teamPath));
88
+ const schemaFile = join(packRoot(), "skills", "_shared", "references", "team.schema.yaml");
89
+ const problems = validateTeam(data, requiredPaths(readFileSync(schemaFile, "utf8")));
90
+ checks.push(problems.length
91
+ ? fix("team.yaml", problems.join("; "), `edit ${TEAM_FILE} (see docs/team-yaml.md) and open a pull request`)
92
+ : ok("team.yaml", `${TEAM_FILE} is valid`));
93
+ }
94
+ catch (e) {
95
+ checks.push(fix("team.yaml", `cannot be read: ${e.message.split("\n")[0]}`, `repair ${TEAM_FILE} (valid YAML) or recreate it with 'aihub init'`));
96
+ }
97
+ }
98
+ const team = loadTeam(root);
99
+ const target = defaultTargetFor(team, repoName) || originDefaultBranch(root) || "main";
100
+ const tpl = resolveTemplate(target, { readRef: (b, p) => showFile(root, b, p), localRoot: root });
101
+ checks.push(tpl
102
+ ? ok("pr-template", `${tpl.path} (${tpl.from === "ref" ? `on origin/${target}` : "in the working tree only"})`)
103
+ : fix("pr-template", "no pull request template found", "run 'aihub init' or add .azuredevops/pull_request_template.md"));
104
+ }
105
+ for (const c of CLIENTS) {
106
+ const places = [
107
+ { label: "global", dir: clientDirs(c, ctx.env, { global: true }).skills },
108
+ ...(root ? [{ label: "project", dir: clientDirs(c, ctx.env, { global: false, root }).skills }] : []),
109
+ ].filter((p) => existsSync(join(p.dir, "start-here", "SKILL.md")));
110
+ checks.push(places.length
111
+ ? ok(`skills:${c}`, places.map((p) => `${p.label} (${p.dir})`).join(", "))
112
+ : fix(`skills:${c}`, "aihub skills not installed", `aihub skills install --client ${c} --global`));
113
+ }
114
+ return checks;
115
+ }
116
+ export function formatChecks(checks) {
117
+ return checks.map((c) => `${c.status.padEnd(4)} ${c.name}: ${c.detail}${c.fix ? ` -> ${c.fix}` : ""}`);
118
+ }
@@ -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
+ }
@@ -0,0 +1,157 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { stringify } from "yaml";
5
+ import { parseRemote } from "./ado.js";
6
+ import { AihubError } from "./errors.js";
7
+ import { git, hasRef, originDefaultBranch, pushIfNeeded, remoteUrl, repoRoot, showFile } from "./git.js";
8
+ import { listFiles, packRoot, readPackFile } from "./pack.js";
9
+ import { createPr } from "./pr.js";
10
+ import { TEAM_FILE } from "./team.js";
11
+ import { resolveTemplate } from "./templates.js";
12
+ export const PACK_BRANCH = "chore/aihub-team-pack";
13
+ export const STORY_TEMPLATE = ".agents/skills/_shared/assets/story-template.md";
14
+ export const COMMIT_TEMPLATE = ".agents/skills/_shared/assets/commit-template.txt";
15
+ export const PR_TEMPLATE = ".azuredevops/pull_request_template.md";
16
+ export function parseLanguage(v) {
17
+ if (!v)
18
+ return "en";
19
+ if (v === "nl" || v === "en")
20
+ return v;
21
+ throw new AihubError(`--language must be nl or en, not '${v}'`);
22
+ }
23
+ function teamYaml(o) {
24
+ const data = {
25
+ version: 1,
26
+ language: o.language,
27
+ azureDevOps: { organization: o.org, project: o.project },
28
+ repositories: [{ name: o.repo, defaultTarget: o.target, releaseBranches: ["release/*"] }],
29
+ pullRequest: {
30
+ template: o.prTemplate,
31
+ title: "{storyId}: {storyTitle}",
32
+ emptySection: o.language === "nl" ? "n.v.t." : "-",
33
+ },
34
+ workItems: { storyType: "User Story", storyTemplate: STORY_TEMPLATE },
35
+ branches: { feature: "feature/{storyId}-{slug}", protected: [o.target, "release/*"] },
36
+ };
37
+ const head = "# Team file proposed by 'aihub init': check every value and change it through a pull request.\n" +
38
+ "# Schema: skills/_shared/references/team.schema.yaml in the aihub pack; see docs/team-yaml.md.\n";
39
+ return head + stringify(data, { lineWidth: 0 });
40
+ }
41
+ /** Where Azure DevOps already finds a PR template for the target branch, or undefined. */
42
+ export function existingPrTemplate(root, target) {
43
+ return resolveTemplate(target, { readRef: (b, p) => showFile(root, b, p), localRoot: root })?.path;
44
+ }
45
+ /** Everything `aihub init` would like to have in the repository (before skipping what exists). */
46
+ export function planFiles(root, o) {
47
+ const pack = packRoot();
48
+ const assets = join(pack, "skills", "_shared", "assets");
49
+ const nl = o.language === "nl";
50
+ const asset = (name, nlName) => readPackFile(join(assets, nl ? nlName : name));
51
+ const found = existingPrTemplate(root, o.target);
52
+ const plan = [
53
+ { path: TEAM_FILE, content: teamYaml({ ...o, prTemplate: found && !found.includes("/branches/") ? found : PR_TEMPLATE }) },
54
+ { path: STORY_TEMPLATE, content: asset("story-template.md", "story-template.nl.md") },
55
+ { path: COMMIT_TEMPLATE, content: asset("commit-template.txt", "commit-template.nl.txt") },
56
+ ];
57
+ if (!found)
58
+ plan.push({ path: PR_TEMPLATE, content: asset("pull_request_template.md", "pull_request_template.nl.md") });
59
+ for (const f of listFiles(join(pack, "commands", "opencode"))) {
60
+ plan.push({ path: `.opencode/command/${f}`, content: readPackFile(join(pack, "commands", "opencode", f)) });
61
+ }
62
+ for (const f of listFiles(join(pack, "commands", "copilot"))) {
63
+ plan.push({ path: `.github/prompts/${f}`, content: readPackFile(join(pack, "commands", "copilot", f)) });
64
+ }
65
+ return { plan, skips: found ? { [PR_TEMPLATE]: `a pull request template already exists (${found})` } : {} };
66
+ }
67
+ /** Write planned files that do not exist yet; never touches an existing file. */
68
+ export function writePlanned(root, plan, skipExtra = {}) {
69
+ const res = { created: [], skipped: [] };
70
+ for (const [path, reason] of Object.entries(skipExtra))
71
+ res.skipped.push({ path, reason });
72
+ for (const p of plan) {
73
+ const abs = join(root, p.path);
74
+ if (existsSync(abs)) {
75
+ res.skipped.push({ path: p.path, reason: "exists" });
76
+ continue;
77
+ }
78
+ mkdirSync(dirname(abs), { recursive: true });
79
+ writeFileSync(abs, p.content, "utf8");
80
+ res.created.push(p.path);
81
+ }
82
+ return res;
83
+ }
84
+ function prBody(language, r) {
85
+ const nl = language === "nl";
86
+ const list = (xs) => (xs.length ? xs.map((x) => `- \`${x}\``).join("\n") : nl ? "- geen" : "- none");
87
+ return [
88
+ `## ${nl ? "Beschrijving" : "Description"}`,
89
+ "",
90
+ nl
91
+ ? "Voorstel van `aihub init` voor het teampakket: teambestand, sjablonen en slash-commando's. Bestaande bestanden zijn niet aangepast. Controleer de waarden in `team.yaml` voor het mergen."
92
+ : "Proposal from `aihub init` for the team pack: team file, templates and slash commands. Existing files were not changed. Check the values in `team.yaml` before merging.",
93
+ "",
94
+ nl ? "Aangemaakt:" : "Created:",
95
+ list(r.created),
96
+ "",
97
+ nl ? "Overgeslagen (bestond al):" : "Skipped (already existed):",
98
+ list(r.skipped.map((s) => s.path)),
99
+ "",
100
+ ].join("\n");
101
+ }
102
+ export async function runInit(ctx, o) {
103
+ const language = parseLanguage(o.language);
104
+ const root = repoRoot(resolve(ctx.cwd, o.repo ?? "."));
105
+ const remote = parseRemote(remoteUrl(root));
106
+ const target = originDefaultBranch(root) || "main";
107
+ const info = { org: remote.org, project: remote.project, repo: remote.repo, target, language };
108
+ if (o.noPr) {
109
+ const p = planFiles(root, info);
110
+ return writePlanned(root, p.plan, p.skips);
111
+ }
112
+ const original = git(root, ["rev-parse", "--abbrev-ref", "HEAD"]).trim();
113
+ if (hasRef(root, `refs/heads/${PACK_BRANCH}`) || git(root, ["ls-remote", "--heads", "origin", PACK_BRANCH], { allowFail: true }).trim()) {
114
+ throw new AihubError(`branch '${PACK_BRANCH}' already exists; merge or delete it first, or run 'aihub init --no-pr'`);
115
+ }
116
+ git(root, ["switch", "-c", PACK_BRANCH, hasRef(root, `origin/${target}`) ? `origin/${target}` : "HEAD"]);
117
+ const back = () => {
118
+ if (original !== "HEAD")
119
+ git(root, ["switch", original], { allowFail: true });
120
+ };
121
+ try {
122
+ const p = planFiles(root, info);
123
+ const result = writePlanned(root, p.plan, p.skips);
124
+ result.branch = PACK_BRANCH;
125
+ if (!result.created.length) {
126
+ back();
127
+ git(root, ["branch", "-D", PACK_BRANCH], { allowFail: true });
128
+ result.branch = undefined;
129
+ return result;
130
+ }
131
+ git(root, ["add", "--", ...result.created]);
132
+ git(root, ["commit", "-m", "chore: aihub team pack", "--", ...result.created]);
133
+ pushIfNeeded(root, PACK_BRANCH);
134
+ const bodyFile = join(mkdtempSync(join(tmpdir(), "aihub-init-")), "body.md");
135
+ writeFileSync(bodyFile, prBody(language, result), "utf8");
136
+ result.pr = await createPr({ ...ctx, cwd: root }, { title: "chore: aihub team pack", bodyFile, target });
137
+ back();
138
+ return result;
139
+ }
140
+ catch (e) {
141
+ back();
142
+ throw e;
143
+ }
144
+ }
145
+ export function reportInit(r) {
146
+ const lines = [
147
+ ...r.created.map((p) => `created ${p}`),
148
+ ...r.skipped.map((s) => `skipped ${s.path} (${s.reason})`),
149
+ ];
150
+ if (!r.created.length)
151
+ lines.push("nothing to create: the team pack is already in place");
152
+ if (r.pr)
153
+ lines.push(r.pr);
154
+ else if (r.created.length && !r.branch)
155
+ lines.push("files written, no pull request (--no-pr): review, commit and push them yourself");
156
+ return lines;
157
+ }
@@ -0,0 +1,141 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { clientDirs, CLIENTS } from "./clients.js";
4
+ import { cliVersion, listFiles, packRoot, readPackFile, sha256, stamp } from "./pack.js";
5
+ export const MANIFEST = ".aihub-manifest.json";
6
+ function readManifest(dir) {
7
+ try {
8
+ const m = JSON.parse(readFileSync(join(dir, MANIFEST), "utf8"));
9
+ return { version: m.version, files: m.files ?? {} };
10
+ }
11
+ catch {
12
+ return { version: "", files: {} };
13
+ }
14
+ }
15
+ const readNorm = (p) => readFileSync(p, "utf8").replace(/\r\n/g, "\n");
16
+ /**
17
+ * Write entries into dir. Files that are not ours (no manifest record) or that the user changed (checksum differs from
18
+ * what we wrote) are never overwritten. Idempotent. Files we installed earlier that left the pack are removed when unmodified.
19
+ */
20
+ export function installEntries(dir, entries, version) {
21
+ const man = readManifest(dir);
22
+ const results = [];
23
+ const next = {};
24
+ for (const e of entries) {
25
+ const abs = join(dir, e.rel);
26
+ const want = sha256(e.content);
27
+ if (!existsSync(abs)) {
28
+ mkdirSync(dirname(abs), { recursive: true });
29
+ writeFileSync(abs, e.content, "utf8");
30
+ next[e.rel] = want;
31
+ results.push({ action: "created", path: abs });
32
+ continue;
33
+ }
34
+ const cur = sha256(readNorm(abs));
35
+ if (cur === want) {
36
+ next[e.rel] = want;
37
+ results.push({ action: "unchanged", path: abs });
38
+ }
39
+ else if (man.files[e.rel] === cur) {
40
+ writeFileSync(abs, e.content, "utf8");
41
+ next[e.rel] = want;
42
+ results.push({ action: "updated", path: abs });
43
+ }
44
+ else {
45
+ if (man.files[e.rel])
46
+ next[e.rel] = man.files[e.rel];
47
+ results.push({ action: "skipped", path: abs, reason: man.files[e.rel] ? "changed by the user" : "exists and is not an aihub file" });
48
+ }
49
+ }
50
+ for (const [rel, sum] of Object.entries(man.files)) {
51
+ if (entries.some((e) => e.rel === rel))
52
+ continue;
53
+ const abs = join(dir, rel);
54
+ if (!existsSync(abs))
55
+ continue;
56
+ if (sha256(readNorm(abs)) === sum) {
57
+ unlinkSync(abs);
58
+ results.push({ action: "removed", path: abs, reason: "no longer in the pack" });
59
+ }
60
+ else
61
+ next[rel] = sum;
62
+ }
63
+ if (Object.keys(next).length) {
64
+ mkdirSync(dir, { recursive: true });
65
+ writeFileSync(join(dir, MANIFEST), JSON.stringify({ version, files: next }, null, 2) + "\n", "utf8");
66
+ }
67
+ pruneEmpty(dir, dir);
68
+ return results;
69
+ }
70
+ /** Remove only the files aihub wrote and the user did not change. */
71
+ export function uninstallDir(dir) {
72
+ const man = readManifest(dir);
73
+ const results = [];
74
+ const keep = {};
75
+ for (const [rel, sum] of Object.entries(man.files)) {
76
+ const abs = join(dir, rel);
77
+ if (!existsSync(abs))
78
+ continue;
79
+ if (sha256(readNorm(abs)) === sum) {
80
+ unlinkSync(abs);
81
+ results.push({ action: "removed", path: abs });
82
+ }
83
+ else {
84
+ keep[rel] = sum;
85
+ results.push({ action: "skipped", path: abs, reason: "changed by the user" });
86
+ }
87
+ }
88
+ const mf = join(dir, MANIFEST);
89
+ if (Object.keys(keep).length)
90
+ writeFileSync(mf, JSON.stringify({ version: man.version, files: keep }, null, 2) + "\n", "utf8");
91
+ else if (existsSync(mf))
92
+ unlinkSync(mf);
93
+ pruneEmpty(dir, dir);
94
+ return results;
95
+ }
96
+ /** Delete empty directories below dir and dir itself when it ends up empty. */
97
+ function pruneEmpty(dir, top) {
98
+ if (!existsSync(dir))
99
+ return;
100
+ for (const n of readdirSync(dir, { withFileTypes: true }))
101
+ if (n.isDirectory())
102
+ pruneEmpty(join(dir, n.name), top);
103
+ if (readdirSync(dir).length === 0)
104
+ rmdirSync(dir);
105
+ }
106
+ export function skillEntries(version = cliVersion()) {
107
+ const src = join(packRoot(), "skills");
108
+ return listFiles(src).map((rel) => ({ rel, content: stamp(rel, readPackFile(join(src, rel)), version) }));
109
+ }
110
+ export function commandEntries(source, version = cliVersion()) {
111
+ const src = join(packRoot(), "commands", source);
112
+ return listFiles(src).map((rel) => ({ rel, content: stamp(rel, readPackFile(join(src, rel)), version) }));
113
+ }
114
+ export function parseClients(value) {
115
+ if (!value || value === "all")
116
+ return [...CLIENTS];
117
+ if (CLIENTS.includes(value))
118
+ return [value];
119
+ throw new Error(`unknown client '${value}'; use opencode, github-copilot, codex or all`);
120
+ }
121
+ export function installClients(clients, env, opts) {
122
+ const version = cliVersion();
123
+ const out = [];
124
+ for (const c of clients) {
125
+ const d = clientDirs(c, env, opts);
126
+ out.push({ client: c, dir: d.skills, results: installEntries(d.skills, skillEntries(version), version) });
127
+ if (d.commands)
128
+ out.push({ client: c, dir: d.commands.dir, results: installEntries(d.commands.dir, commandEntries(d.commands.source, version), version) });
129
+ }
130
+ return out;
131
+ }
132
+ export function uninstallClients(clients, env, opts) {
133
+ const out = [];
134
+ for (const c of clients) {
135
+ const d = clientDirs(c, env, opts);
136
+ out.push({ client: c, dir: d.skills, results: uninstallDir(d.skills) });
137
+ if (d.commands)
138
+ out.push({ client: c, dir: d.commands.dir, results: uninstallDir(d.commands.dir) });
139
+ }
140
+ return out;
141
+ }
@@ -0,0 +1,48 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { AihubError } from "./errors.js";
6
+ const here = dirname(fileURLToPath(import.meta.url));
7
+ /** Directory that holds the bundled `skills/` and `commands/` (the repo root in a checkout, cli/pack in the npm package). */
8
+ export function packRoot() {
9
+ for (const c of [join(here, "..", "..", ".."), join(here, "..", "..", "pack")]) {
10
+ if (existsSync(join(c, "skills")) && existsSync(join(c, "commands")))
11
+ return c;
12
+ }
13
+ throw new AihubError("the bundled skills are missing from this installation; reinstall with 'npm i -g @ferronhooi/aihub'");
14
+ }
15
+ export function cliVersion() {
16
+ try {
17
+ return JSON.parse(readFileSync(join(here, "..", "..", "package.json"), "utf8")).version;
18
+ }
19
+ catch {
20
+ return "0.0.0";
21
+ }
22
+ }
23
+ export const sha256 = (s) => createHash("sha256").update(s, "utf8").digest("hex");
24
+ /** Relative POSIX paths of all files below dir, sorted. */
25
+ export function listFiles(dir, base = dir) {
26
+ const out = [];
27
+ for (const name of readdirSync(dir).sort()) {
28
+ const p = join(dir, name);
29
+ if (statSync(p).isDirectory())
30
+ out.push(...listFiles(p, base));
31
+ else
32
+ out.push(p.slice(base.length + 1).replace(/\\/g, "/"));
33
+ }
34
+ return out;
35
+ }
36
+ export const readPackFile = (path) => readFileSync(path, "utf8").replace(/^/, "").replace(/\r\n/g, "\n");
37
+ /**
38
+ * Mark a file as installed by aihub: `<!-- aihub <version> -->` in markdown (after the front matter, which must stay
39
+ * first), `# aihub <version>` in other text files.
40
+ */
41
+ export function stamp(rel, content, version) {
42
+ const isMd = rel.endsWith(".md");
43
+ const mark = isMd ? `<!-- aihub ${version} -->` : `# aihub ${version}`;
44
+ const fm = /^---\n[\s\S]*?\n---\n/.exec(content);
45
+ if (isMd && fm)
46
+ return `${fm[0]}${mark}\n${content.slice(fm[0].length)}`;
47
+ return `${mark}\n${content}`;
48
+ }