@ferronhooi/aihub 0.1.0-next.5 → 0.1.0-next.6

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.
@@ -2,7 +2,9 @@ import { parseArgs } from "node:util";
2
2
  import { changedFiles } from "../lib/changes.js";
3
3
  import { repoClient } from "../lib/context.js";
4
4
  import { AihubError } from "../lib/errors.js";
5
- import { followBuild, formatNeeded, queueRobot, robotConfig, robotNeeded, summarize } from "../lib/robot.js";
5
+ import { formatIntegrate, integrate } from "../lib/integrate.js";
6
+ import { currentBranch } from "../lib/git.js";
7
+ import { followBuild, formatNeeded, queueRobot, formatTargets, resolveTarget, robotConfig, robotDefinitionId, robotNeeded, summarize } from "../lib/robot.js";
6
8
  import { loadTeam } from "../lib/team.js";
7
9
  export async function run(argv, ctx) {
8
10
  const [sub, ...rest] = argv;
@@ -17,17 +19,23 @@ export async function run(argv, ctx) {
17
19
  include: { type: "string" },
18
20
  pipeline: { type: "string" },
19
21
  "no-wait": { type: "boolean" },
22
+ "no-merge": { type: "boolean" },
23
+ on: { type: "string" },
20
24
  },
21
25
  }).values;
22
26
  }
23
27
  catch (e) {
24
28
  throw new AihubError(e.message);
25
29
  }
26
- if (sub !== "needed" && sub !== "run")
27
- throw new AihubError("usage: aihub robot needed|run [flags]");
30
+ if (sub !== "needed" && sub !== "run" && sub !== "targets")
31
+ throw new AihubError("usage: aihub robot needed|run|targets [flags]");
28
32
  const { root, client } = repoClient(ctx);
29
33
  const team = loadTeam(root);
30
34
  const cfg = robotConfig(team);
35
+ if (sub === "targets") {
36
+ ctx.out(formatTargets(cfg));
37
+ return;
38
+ }
31
39
  if (sub === "needed") {
32
40
  const c = changedFiles(root, team, { branch: v.branch, target: v.target });
33
41
  ctx.out(formatNeeded(robotNeeded(c.files, cfg), cfg, c.branch));
@@ -36,13 +44,21 @@ export async function run(argv, ctx) {
36
44
  const pipeline = v.pipeline ?? cfg.pipeline;
37
45
  if (!pipeline)
38
46
  throw new AihubError("no Robot pipeline: set robot.pipeline in team.yaml or pass --pipeline <name>");
39
- const branch = cfg.integrationBranch;
40
- if (!branch)
41
- throw new AihubError("robot.integrationBranch is not set in team.yaml; the Robot pipeline runs on that branch");
47
+ const target = resolveTarget(cfg, client.remote.repo, v.on);
48
+ if (!target)
49
+ throw new AihubError("no Robot target: set robot.targets (and robot.defaultTarget) or robot.integrationBranch in team.yaml, or pass --on <name|branch>");
50
+ const { branch, requires } = target;
42
51
  if (v.suite && cfg.suites.length && !cfg.suites.some((s) => s.name === v.suite)) {
43
52
  throw new AihubError(`unknown suite '${v.suite}'; team.yaml suites: ${cfg.suites.map((s) => s.name).join(", ")}`);
44
53
  }
45
- const b = await queueRobot(client, { pipeline, branch, suite: v.suite, include: v.include });
54
+ const definitionId = await robotDefinitionId(client, pipeline);
55
+ if (target.merge && !v["no-merge"]) {
56
+ const feature = currentBranch(root);
57
+ if (feature === branch)
58
+ throw new AihubError(`you are on the integration branch '${branch}'; check out the feature branch or pass --no-merge`);
59
+ ctx.out(formatIntegrate(feature, integrate(root, { feature, integration: branch, requires })));
60
+ }
61
+ const b = await queueRobot(client, { definitionId, branch, suite: v.suite, include: v.include });
46
62
  ctx.out(`queued ${pipeline} build ${b.id} on ${branch}${v.suite ? ` (suite ${v.suite})` : ""}${v.include ? ` (include ${v.include})` : ""}`);
47
63
  if (v["no-wait"])
48
64
  return;
@@ -0,0 +1,80 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { AihubError } from "./errors.js";
6
+ import { git, pushIfNeeded } from "./git.js";
7
+ function tryGit(cwd, args) {
8
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
9
+ return { ok: r.status === 0, out: (r.stdout ?? "").replace(/\r\n/g, "\n").trim(), err: (r.stderr ?? "").trim() };
10
+ }
11
+ /**
12
+ * Merge the feature branch (and `requires` branches that are behind) into the integration branch inside a
13
+ * temporary worktree, then push the integration branch. The user's checkout is never touched. On a conflict
14
+ * nothing is pushed.
15
+ */
16
+ export function integrate(root, opts) {
17
+ const { feature, integration } = opts;
18
+ const requires = (opts.requires ?? []).filter((b) => b !== integration && b !== feature);
19
+ pushIfNeeded(root, feature); // the integration branch must only contain commits that exist on the remote
20
+ git(root, ["fetch", "--prune", "origin"]);
21
+ const base = tryGit(root, ["rev-parse", "--verify", "--quiet", `origin/${integration}`]);
22
+ if (!base.ok)
23
+ throw new AihubError(`integration branch '${integration}' does not exist on origin; check robot.integrationBranch in team.yaml`);
24
+ for (const b of [feature, ...requires]) {
25
+ if (!tryGit(root, ["rev-parse", "--verify", "--quiet", `origin/${b}`]).ok)
26
+ throw new AihubError(`branch '${b}' does not exist on origin`);
27
+ }
28
+ const dir = mkdtempSync(join(tmpdir(), "aihub-integrate-"));
29
+ const wt = join(dir, "wt");
30
+ try {
31
+ git(root, ["worktree", "add", "--detach", wt, `origin/${integration}`]);
32
+ const merged = [];
33
+ // requires first so the feature lands on top of them
34
+ for (const b of [...requires, feature]) {
35
+ if (tryGit(wt, ["merge-base", "--is-ancestor", `origin/${b}`, "HEAD"]).ok)
36
+ continue;
37
+ const m = tryGit(wt, ["merge", "--no-edit", "--no-ff", "-m", `Merge ${b} into ${integration}`, `origin/${b}`]);
38
+ if (!m.ok) {
39
+ const files = tryGit(wt, ["diff", "--name-only", "--diff-filter=U"]).out.split("\n").filter(Boolean);
40
+ tryGit(wt, ["merge", "--abort"]);
41
+ if (!files.length)
42
+ throw new AihubError(`merging ${b} into ${integration} failed: ${(m.err || m.out).split("\n")[0]}; nothing was pushed`);
43
+ throw new AihubError(`merge conflict merging ${b} into ${integration} in: ${files.join(", ")}; nothing was pushed. Resolve it on your branch first (merge ${integration} into it).`);
44
+ }
45
+ merged.push(b);
46
+ }
47
+ const log = tryGit(wt, ["log", "--no-merges", "--reverse", "--format=%h%x09%s", `origin/${integration}..HEAD`]).out;
48
+ const commits = log
49
+ .split("\n")
50
+ .filter(Boolean)
51
+ .map((l) => {
52
+ const [sha, ...rest] = l.split("\t");
53
+ return { sha, subject: rest.join("\t") };
54
+ });
55
+ const changed = tryGit(wt, ["rev-parse", "HEAD"]).out !== tryGit(wt, ["rev-parse", `origin/${integration}`]).out;
56
+ if (changed) {
57
+ const p = tryGit(wt, ["push", "origin", `HEAD:refs/heads/${integration}`]);
58
+ if (!p.ok)
59
+ throw new AihubError(`pushing ${integration} failed: ${p.err.split("\n")[0]}`);
60
+ }
61
+ return { integration, merged, commits, pushed: changed };
62
+ }
63
+ finally {
64
+ tryGit(root, ["worktree", "remove", "--force", wt]);
65
+ try {
66
+ rmSync(dir, { recursive: true, force: true });
67
+ }
68
+ catch {
69
+ /* temp cleanup is best effort */
70
+ }
71
+ }
72
+ }
73
+ export function formatIntegrate(feature, r) {
74
+ if (!r.pushed)
75
+ return `${r.integration} already contains ${feature}: nothing to merge`;
76
+ const lines = [`merged ${r.merged.join(", ")} into ${r.integration} and pushed it; ${r.commits.length} commit${r.commits.length === 1 ? "" : "s"} went in:`];
77
+ for (const c of r.commits)
78
+ lines.push(` ${c.sha} ${c.subject}`);
79
+ return lines.join("\n");
80
+ }
package/dist/lib/robot.js CHANGED
@@ -1,9 +1,50 @@
1
1
  import { AihubError } from "./errors.js";
2
2
  import { anyGlob } from "./glob.js";
3
+ /** `--on` (target name or plain branch), else robot.defaultTarget, else the legacy integration branch (merged). */
4
+ export function resolveTarget(cfg, repo, on) {
5
+ const targets = cfg.targets ?? {};
6
+ const find = (n) => Object.entries(targets).find(([k]) => k.toLowerCase() === n.toLowerCase());
7
+ const make = (name, t) => ({
8
+ name,
9
+ branch: t.branch,
10
+ merge: t.mergeMyBranchFirst ?? false,
11
+ requires: t.mustAlreadyContain ?? [],
12
+ });
13
+ if (on) {
14
+ const hit = find(on);
15
+ return hit ? make(hit[0], hit[1]) : { name: on, branch: on, merge: false, requires: [] };
16
+ }
17
+ if (cfg.defaultTarget) {
18
+ const hit = find(cfg.defaultTarget);
19
+ if (!hit)
20
+ throw new AihubError(`robot.defaultTarget '${cfg.defaultTarget}' is not in robot.targets (${Object.keys(targets).join(", ") || "none"})`);
21
+ return make(hit[0], hit[1]);
22
+ }
23
+ const legacy = resolveIntegration(cfg, repo);
24
+ return legacy.branch ? { name: "integration", branch: legacy.branch, merge: true, requires: legacy.requires } : undefined;
25
+ }
26
+ export function formatTargets(cfg) {
27
+ const entries = Object.entries(cfg.targets ?? {});
28
+ if (!entries.length)
29
+ return cfg.integrationBranch ? `robot targets: integration -> ${cfg.integrationBranch} (merges the feature branch first)` : "robot targets: none in team.yaml robot.targets";
30
+ const lines = ["robot targets:"];
31
+ for (const [name, t] of entries) {
32
+ const req = t.mustAlreadyContain?.length ? `; must already contain ${t.mustAlreadyContain.join(", ")}` : "";
33
+ lines.push(`- ${name} -> ${t.branch} (${t.mergeMyBranchFirst ? "merges the feature branch first" : "runs the branch as is"}${req})${name === cfg.defaultTarget ? " [default]" : ""}`);
34
+ }
35
+ lines.push("use: aihub robot run --on <name|branch>");
36
+ return lines.join("\n");
37
+ }
38
+ export function resolveIntegration(cfg, repo) {
39
+ const list = cfg.integrationBranches ?? [];
40
+ const hit = list.find((e) => e.repository && repo && e.repository.toLowerCase() === repo.toLowerCase()) ?? list.find((e) => !e.repository);
41
+ const branch = hit?.branch ?? cfg.integrationBranch;
42
+ return { branch, requires: hit?.requires ?? cfg.integrationRequires ?? [] };
43
+ }
3
44
  export function robotConfig(team) {
4
45
  const r = team.robot ?? {};
5
46
  const suites = (r.suites ?? []).filter((s) => !!s?.name && Array.isArray(s.paths));
6
- return { pipeline: r.pipeline, integrationBranch: r.integrationBranch, suites };
47
+ return { pipeline: r.pipeline, integrationBranch: r.integrationBranch, integrationBranches: r.integrationBranches, integrationRequires: r.integrationRequires, targets: r.targets, defaultTarget: r.defaultTarget, suites };
7
48
  }
8
49
  export function robotNeeded(files, cfg) {
9
50
  const out = [];
@@ -30,18 +71,21 @@ export function formatNeeded(needs, cfg, branch) {
30
71
  lines.push(`run: aihub robot run --suite ${needs[0].suite}`);
31
72
  return lines.join("\n");
32
73
  }
33
- export async function queueRobot(c, opts) {
34
- const defs = await c.get("build/definitions", { name: opts.pipeline });
35
- const def = (defs.value ?? []).find((d) => d.name.toLowerCase() === opts.pipeline.toLowerCase());
74
+ export async function robotDefinitionId(c, pipeline) {
75
+ const defs = await c.get("build/definitions", { name: pipeline });
76
+ const def = (defs.value ?? []).find((d) => d.name.toLowerCase() === pipeline.toLowerCase());
36
77
  if (!def)
37
- throw new AihubError(`pipeline '${opts.pipeline}' not found in Azure DevOps; check robot.pipeline in team.yaml or pass --pipeline`);
78
+ throw new AihubError(`pipeline '${pipeline}' not found in Azure DevOps; check robot.pipeline in team.yaml or pass --pipeline`);
79
+ return def.id;
80
+ }
81
+ export async function queueRobot(c, opts) {
38
82
  const templateParameters = {};
39
83
  if (opts.suite)
40
84
  templateParameters.suite = opts.suite;
41
85
  if (opts.include)
42
86
  templateParameters.include = opts.include;
43
87
  return c.post("build/builds", {
44
- definition: { id: def.id },
88
+ definition: { id: opts.definitionId },
45
89
  sourceBranch: opts.branch.startsWith("refs/") ? opts.branch : `refs/heads/${opts.branch}`,
46
90
  ...(Object.keys(templateParameters).length ? { templateParameters } : {}),
47
91
  });
@@ -6,7 +6,7 @@
6
6
  version: 1 # integer, schema version (required)
7
7
  language: en # content language of stories, PRs, comments, e.g. en or nl (required)
8
8
 
9
- azureDevOps:
9
+ azureDevOps: # where the CLI talks to (required)
10
10
  organization: <organization> # Azure DevOps organization name (required)
11
11
  project: <project> # project name (required)
12
12
 
@@ -16,24 +16,24 @@ repositories: # list (required, at least one)
16
16
  defaultTarget: main # branch a new PR targets (required)
17
17
  releaseBranches: [] # release branch patterns or names, e.g. ["release/*"] (optional)
18
18
 
19
- pullRequest:
19
+ pullRequest: # pull request settings (required)
20
20
  template: .azuredevops/pull_request_template.md # path in the repo to the PR template (required)
21
21
  title: "{storyId}: {storyTitle}" # title pattern; placeholders {storyId} {storyTitle} {branch} (optional)
22
22
  emptySection: "-" # text the CLI writes into a template section left empty (optional)
23
23
 
24
- workItems:
24
+ workItems: # work item settings (required)
25
25
  storyType: User Story # work item type used for stories (required)
26
26
  storyTemplate: .agents/skills/_shared/assets/story-template.md # story template path (required)
27
27
 
28
- branches:
28
+ branches: # branch rules (required)
29
29
  feature: "feature/{storyId}-{slug}" # pattern for feature branches (required)
30
30
  protected: # branches the CLI never pushes to or force-updates (optional)
31
31
  - main
32
32
  - release/*
33
33
 
34
- cherryPick:
34
+ cherryPick: # cherry-pick settings (optional)
35
35
  groups: # named sets of target branches, usable as --to <group> (optional)
36
- supported: ["release/1.2", "release/1.3"]
36
+ supported: ["release/1.2", "release/1.3"] # example group name and its target branches (optional)
37
37
 
38
38
  pipelines: # pipelines to follow per repository (optional)
39
39
  - repository: <repository> # repository name this pipeline belongs to
@@ -41,7 +41,7 @@ pipelines: # pipelines to follow per repository (optiona
41
41
  required: true # true when a red run blocks the PR
42
42
 
43
43
  fabric: # Fabric workspaces for `aihub fabric` (optional)
44
- workspaces:
44
+ workspaces: # list of workspaces the CLI may know about
45
45
  - name: <workspace> # workspace display name, e.g. DEV-test-project (optional)
46
46
  id: <guid> # workspace id (optional; looked up by name when absent)
47
47
  environment: dev # dev | feature | test | acc | prd (optional); acc and prd are never run by the CLI
@@ -49,8 +49,16 @@ fabric: # Fabric workspaces for `aihub fabric` (optio
49
49
 
50
50
  robot: # Robot integration tests for `aihub robot` (optional)
51
51
  pipeline: <pipeline> # Azure DevOps pipeline that runs the Robot suites (optional; needed for robot run)
52
- integrationBranch: <branch> # branch the pipeline runs on (optional; needed for robot run)
52
+ defaultTarget: <target> # name in targets used when robot run has no --on (optional)
53
+ targets: # named places to run Robot, e.g. feature and staging (optional)
54
+ <target>: # the name you say: "draai Robot op <target>"
55
+ branch: <branch> # branch the pipeline runs on (optional)
56
+ mergeMyBranchFirst: true # true: merge my current branch into this branch and push it first; false: run it as is (optional)
57
+ mustAlreadyContain: [] # branches that must already be merged into this branch, e.g. ["staging"] (optional)
58
+ integrationBranch: <branch> # older form: one branch that gets my branch merged, used without targets (optional)
59
+ integrationBranches: [] # older form per repository: [{ repository, branch, requires }] (optional)
60
+ integrationRequires: [] # older form: branches the integration branch must already contain (optional)
53
61
  suites: # list; a suite belongs to a flow (optional; needed for robot needed)
54
- - name: <suite> # suite name passed to the pipeline as parameter `suite`
55
- paths: [] # path patterns of the flow, e.g. ["src/flows/orders/**"]
62
+ - name: <suite> # suite name passed to the pipeline as parameter `suite` (optional)
63
+ paths: [] # path patterns of the flow, e.g. ["src/flows/orders/**"] (optional)
56
64
  tests: [] # path patterns of the suite's Robot files, e.g. ["tests/robot/orders/**"] (optional)
@@ -15,11 +15,11 @@ aihub fabric plan
15
15
  aihub fabric run --item nb_load_orders --wait
16
16
  ```
17
17
 
18
- 2. Robot: check first, then run only when needed:
18
+ 2. Robot: check first, then run only when needed. The target comes from the sentence: "test op staging" is `--on staging`, "draai Robot op feature" is `--on feature`. No target named: use the team default, do not ask. Run merges your branch into a merge target first and stops on a conflict:
19
19
 
20
20
  ```sh
21
21
  aihub robot needed
22
- aihub robot run --suite orders
22
+ aihub robot run --on staging --suite orders
23
23
  ```
24
24
 
25
25
  3. Parameters: `--params-file params.json` (Fabric), `--include <tag>` (Robot).
@@ -30,6 +30,6 @@ aihub robot run --suite orders
30
30
  Changed items versus the target, the workspace by branch rule, item and job ids, the pipeline and branch from the team file. Do not ask for ids.
31
31
 
32
32
  ## If it fails
33
- Not signed in: `az login` or `aihub doctor`. Item not found: check the plan. Never run ACC or PRD: the developer does that; the CLI refuses them. Details: [Fabric and Robot reference](references/fabric-robot.md).
33
+ Merge conflict: nothing was pushed; merge the target into your branch and fix it. `aihub robot targets` lists the targets; `--no-merge` skips the merge. Not signed in: `az login` or `aihub doctor`. Item not found: check the plan. Never run ACC or PRD: the developer does that; the CLI refuses them. Details: [Fabric and Robot reference](references/fabric-robot.md).
34
34
 
35
35
  Rules: direct task, 0 questions. A new Robot test is only needed for a new or changed flow.
@@ -8,7 +8,8 @@
8
8
  | `aihub fabric run --item N [--workspace W] [--params-file F] [--wait]` | Starts a notebook or pipeline job; with `--wait` polls and prints status and the failure reason. |
9
9
  | `aihub fabric status --item N --job ID [--workspace W]` | Status of one job. |
10
10
  | `aihub robot needed [--branch B]` | Which suites cover a changed flow, and whether a test changed with it. |
11
- | `aihub robot run [--suite S] [--include tag] [--pipeline P] [--no-wait]` | Queues the team Robot pipeline on the integration branch and prints the results summary. |
11
+ | `aihub robot run [--on target\|branch] [--suite S] [--include tag] [--pipeline P] [--no-merge] [--no-wait]` | With a merge target: merges the current branch (and `mustAlreadyContain` branches that are behind) into the target branch in a temporary worktree, pushes it and lists the commits that went in; a conflict stops with the files and pushes nothing. Then queues the team Robot pipeline on that branch and prints the results summary. |
12
+ | `aihub robot targets` | Lists the named targets and the default. |
12
13
 
13
14
  ## Environments
14
15
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferronhooi/aihub",
3
- "version": "0.1.0-next.5",
3
+ "version": "0.1.0-next.6",
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",