Merge remote-tracking branch 'origin/main' into feat/pipeline-driven-ship-commands

# Conflicts:
#	server/__tests__/lanes-cli.test.js
This commit is contained in:
2026-08-25 11:17:33 +07:00
12 changed files with 542 additions and 13 deletions
+125
View File
@@ -0,0 +1,125 @@
/**
* @file Tests for server/lib/ci-status.js against a fake `gh` binary that
* returns canned `run list`/`run view` JSON for each scenario this module
* has to classify: no run yet, an in-progress run, a green run, and a red
* run — plus branch-vs-sha ref detection.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-ci-status-"));
const { ciStatus } = require("../lib/ci-status");
/**
* Fake `gh` that branches on the subcommand: `run list` returns `listJson`,
* `run view` returns `viewJson`. Also records every invocation's args (one
* line per call, space-joined) to `$CALLS_LOG` so a test can assert which
* flag (--branch vs --commit) was used.
*/
function stubGh(listJson, viewJson) {
const bin = path.join(ROOT, `bin-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.mkdirSync(bin, { recursive: true });
const callsLog = path.join(bin, "calls.log");
fs.writeFileSync(callsLog, "");
const script = `#!/usr/bin/env bash
echo "$@" >> "${callsLog}"
if [ "$1" = "run" ] && [ "$2" = "list" ]; then
cat <<'EOF'
${JSON.stringify(listJson)}
EOF
exit 0
fi
if [ "$1" = "run" ] && [ "$2" = "view" ]; then
cat <<'EOF'
${JSON.stringify(viewJson)}
EOF
exit 0
fi
echo "unexpected gh invocation: $@" >&2
exit 1
`;
fs.writeFileSync(path.join(bin, "gh"), script);
fs.chmodSync(path.join(bin, "gh"), 0o755);
const originalPath = process.env.PATH;
process.env.PATH = `${bin}${path.delimiter}${originalPath}`;
return {
calls: () => fs.readFileSync(callsLog, "utf8").trim().split("\n").filter(Boolean),
restore: () => {
process.env.PATH = originalPath;
},
};
}
after(() => fs.rmSync(ROOT, { recursive: true, force: true }));
describe("ciStatus()", () => {
it("reports pending when no run exists yet for the ref", async () => {
const stub = stubGh([], {});
try {
const result = await ciStatus(ROOT, "development");
assert.deepEqual(result, { state: "pending", ref: "development", checks: [] });
} finally {
stub.restore();
}
});
it("reports pending when the latest run is still in progress", async () => {
const stub = stubGh([{ databaseId: 1, status: "in_progress", conclusion: null }], {
jobs: [{ name: "server-tests", status: "in_progress", conclusion: null, url: null }],
});
try {
const result = await ciStatus(ROOT, "development");
assert.equal(result.state, "pending");
} finally {
stub.restore();
}
});
it("reports success when the latest run completed clean", async () => {
const stub = stubGh([{ databaseId: 2, status: "completed", conclusion: "success" }], {
jobs: [
{ name: "server-tests", status: "completed", conclusion: "success", url: "https://x/1" },
{ name: "client-tests", status: "completed", conclusion: "skipped", url: "https://x/2" },
],
});
try {
const result = await ciStatus(ROOT, "development");
assert.equal(result.state, "success");
assert.equal(result.checks.length, 2);
} finally {
stub.restore();
}
});
it("reports failure when any job failed", async () => {
const stub = stubGh([{ databaseId: 3, status: "completed", conclusion: "failure" }], {
jobs: [
{ name: "server-tests", status: "completed", conclusion: "failure", url: "https://x/3" },
],
});
try {
const result = await ciStatus(ROOT, "development");
assert.equal(result.state, "failure");
assert.equal(result.checks[0].conclusion, "failure");
} finally {
stub.restore();
}
});
it("uses --commit for a sha-shaped ref and --branch otherwise", async () => {
const stub = stubGh([], {});
try {
await ciStatus(ROOT, "a1b2c3d");
await ciStatus(ROOT, "feat/some-slug");
const calls = stub.calls().filter((line) => line.startsWith("run list"));
assert.match(calls[0], /--commit a1b2c3d/);
assert.match(calls[1], /--branch feat\/some-slug/);
} finally {
stub.restore();
}
});
});
+65
View File
@@ -0,0 +1,65 @@
/**
* @file Tests for server/lib/gh.js's execFile wrapper against real fake `gh`
* scripts on PATH — the same fixture style server/__tests__/lane-lifecycle.test.js
* uses for a fake `claude` binary, since this codebase's server tests use real
* subprocesses instead of mocking child_process.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-gh-"));
const { gh } = require("../lib/gh");
/** Puts a fake `gh` script on PATH for the duration of one test. */
function stubGh(scriptBody) {
const bin = path.join(ROOT, `bin-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.mkdirSync(bin, { recursive: true });
const bin_gh = path.join(bin, "gh");
fs.writeFileSync(bin_gh, `#!/usr/bin/env bash\n${scriptBody}\n`);
fs.chmodSync(bin_gh, 0o755);
const originalPath = process.env.PATH;
process.env.PATH = `${bin}${path.delimiter}${originalPath}`;
return () => {
process.env.PATH = originalPath;
};
}
after(() => fs.rmSync(ROOT, { recursive: true, force: true }));
describe("gh()", () => {
it("returns stdout on success", async () => {
const restore = stubGh('echo "$@" >&2\necho \'{"ok":true}\'');
try {
const result = await gh(ROOT, ["run", "list"]);
assert.match(result.stdout, /"ok":true/);
} finally {
restore();
}
});
it("throws with .gh details on a non-zero exit", async () => {
const restore = stubGh('echo "boom" >&2\nexit 7');
try {
await assert.rejects(
() => gh(ROOT, ["run", "list"]),
(err) => err.gh.code === 7 && /boom/.test(err.gh.stderr)
);
} finally {
restore();
}
});
it("throws ENOGH when gh is not on PATH", async () => {
const originalPath = process.env.PATH;
process.env.PATH = ROOT; // a directory with no gh binary in it
try {
await assert.rejects(() => gh(ROOT, ["run", "list"]), { code: "ENOGH" });
} finally {
process.env.PATH = originalPath;
}
});
});
+17 -1
View File
@@ -22,13 +22,29 @@ const { installAgents } = require("../lib/lane-agents");
after(() => fs.rmSync(SUITE_ROOT, { recursive: true, force: true }));
// Strip GIT_* vars a parent git hook (e.g. the pre-commit hook running this
// very suite) sets in its own environment — those leak to every child
// process and override an explicit `cwd`, so without this `git init` here
// operates on the outer repo's .git instead of this fixture's throwaway one.
// Same scrub `lanes-cli.test.js` and `worktree.js`'s own git() helper use.
const GIT_ENV = { ...process.env };
delete GIT_ENV.GIT_DIR;
delete GIT_ENV.GIT_WORK_TREE;
delete GIT_ENV.GIT_INDEX_FILE;
delete GIT_ENV.GIT_COMMON_DIR;
delete GIT_ENV.GIT_OBJECT_DIRECTORY;
delete GIT_ENV.GIT_ALTERNATE_OBJECT_DIRECTORIES;
delete GIT_ENV.GIT_PREFIX;
delete GIT_ENV.GIT_NAMESPACE;
delete GIT_ENV.GIT_CONFIG_PARAMETERS;
let laneSeq = 0;
/** Create a real git repo dir (used as a lane's cwd). */
function makeRepoDir() {
const cwd = path.join(SUITE_ROOT, `repo-${++laneSeq}`);
fs.mkdirSync(cwd, { recursive: true });
execFileSync("git", ["init", "--initial-branch=main"], { cwd, stdio: "pipe" });
execFileSync("git", ["init", "--initial-branch=main"], { cwd, stdio: "pipe", env: GIT_ENV });
return cwd;
}
+60
View File
@@ -9,6 +9,7 @@ const assert = require("node:assert/strict");
const path = require("path");
const os = require("os");
const http = require("http");
const fs = require("fs");
const { WebSocket } = require("ws");
const TEST_DB = path.join(os.tmpdir(), `dashboard-lanes-api-${Date.now()}-${process.pid}.db`);
@@ -928,3 +929,62 @@ describe("detection attributes work to the lane the work touched", () => {
await request("DELETE", `/api/lanes/${session.body.lane.id}`);
});
});
describe("GET /:id/ci/status", () => {
let laneId;
let laneCwd;
let restorePath;
let bin;
before(async () => {
laneCwd = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-ci-status-route-"));
const r = await request("POST", "/api/lanes", { title: "CI status lane", cwd: laneCwd });
laneId = r.body.lane.id;
bin = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-ci-status-bin-"));
fs.writeFileSync(
path.join(bin, "gh"),
`#!/usr/bin/env bash
if [ "$1" = "run" ] && [ "$2" = "list" ]; then
echo '[{"databaseId":1,"status":"completed","conclusion":"success"}]'
exit 0
fi
if [ "$1" = "run" ] && [ "$2" = "view" ]; then
echo '{"jobs":[{"name":"tests","status":"completed","conclusion":"success","url":"https://x/1"}]}'
exit 0
fi
exit 1
`
);
fs.chmodSync(path.join(bin, "gh"), 0o755);
const originalPath = process.env.PATH;
process.env.PATH = `${bin}${path.delimiter}${originalPath}`;
restorePath = () => {
process.env.PATH = originalPath;
};
});
after(() => {
if (restorePath) restorePath();
fs.rmSync(laneCwd, { recursive: true, force: true });
fs.rmSync(bin, { recursive: true, force: true });
});
it("404s for an unknown lane", async () => {
const r = await request("GET", "/api/lanes/999999/ci/status?ref=development");
assert.equal(r.status, 404);
});
it("400s when ref is missing", async () => {
const r = await request("GET", `/api/lanes/${laneId}/ci/status`);
assert.equal(r.status, 400);
assert.equal(r.body.error.code, "EBADREF");
});
it("returns the derived state for a real ref", async () => {
const r = await request("GET", `/api/lanes/${laneId}/ci/status?ref=development`);
assert.equal(r.status, 200);
assert.equal(r.body.state, "success");
assert.equal(r.body.checks[0].name, "tests");
});
});
+80 -2
View File
@@ -126,11 +126,11 @@ function get(urlPath) {
// spawnSync would stall the event loop and the CLI child's request to
// 127.0.0.1 would never be served — a deadlock that looks like a network
// sandbox blocking loopback.
function cli(args, cwd) {
function cli(args, cwd, extraEnv = {}) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [CLI, ...args], {
cwd,
env: { ...process.env, CLAUDE_DASHBOARD_PORT: String(server.address().port) },
env: { ...process.env, CLAUDE_DASHBOARD_PORT: String(server.address().port), ...extraEnv },
});
let stdout = "";
let stderr = "";
@@ -573,3 +573,81 @@ describe("ccam ship-full / ccam ship-quick", () => {
assert.match(q.stderr, /usage: ccam ship-quick/);
});
});
describe("ccam lanes ci status", () => {
let restorePath;
let bin;
before(() => {
bin = fs.mkdtempSync(path.join(os.tmpdir(), "ccam-ci-status-cli-bin-"));
fs.writeFileSync(
path.join(bin, "gh"),
`#!/usr/bin/env bash
if [ "$1" = "run" ] && [ "$2" = "list" ]; then
if [ "$CI_STATUS_FIXTURE" = "failure" ]; then
echo '[{"databaseId":1,"status":"completed","conclusion":"failure"}]'
elif [ "$CI_STATUS_FIXTURE" = "pending" ]; then
echo '[]'
else
echo '[{"databaseId":1,"status":"completed","conclusion":"success"}]'
fi
exit 0
fi
if [ "$1" = "run" ] && [ "$2" = "view" ]; then
if [ "$CI_STATUS_FIXTURE" = "failure" ]; then
echo '{"jobs":[{"name":"tests","status":"completed","conclusion":"failure","url":"https://x/1"}]}'
else
echo '{"jobs":[{"name":"tests","status":"completed","conclusion":"success","url":"https://x/1"}]}'
fi
exit 0
fi
exit 1
`
);
fs.chmodSync(path.join(bin, "gh"), 0o755);
const originalPath = process.env.PATH;
process.env.PATH = `${bin}${path.delimiter}${originalPath}`;
restorePath = () => {
process.env.PATH = originalPath;
};
});
after(() => {
if (restorePath) restorePath();
fs.rmSync(bin, { recursive: true, force: true });
});
it("exits 0 and prints success state", async () => {
const r = await cli(["lanes", "ci", "status", "development"], LANE_DIR);
assert.equal(r.status, 0);
assert.match(r.stdout, /"state": "success"/);
});
it("exits 1 on a failed run", async () => {
const orig = process.env.CI_STATUS_FIXTURE;
try {
process.env.CI_STATUS_FIXTURE = "failure";
const r = await cli(["lanes", "ci", "status", "development"], LANE_DIR, {
CI_STATUS_FIXTURE: "failure",
});
assert.equal(r.status, 1);
assert.match(r.stdout, /"state": "failure"/);
} finally {
process.env.CI_STATUS_FIXTURE = orig;
}
});
it("exits 3 when no run exists yet", async () => {
const orig = process.env.CI_STATUS_FIXTURE;
try {
process.env.CI_STATUS_FIXTURE = "pending";
const r = await cli(["lanes", "ci", "status", "development"], LANE_DIR, {
CI_STATUS_FIXTURE: "pending",
});
assert.equal(r.status, 3);
assert.match(r.stdout, /"state": "pending"/);
} finally {
process.env.CI_STATUS_FIXTURE = orig;
}
});
});
+61
View File
@@ -0,0 +1,61 @@
/**
* @file Turns a GitHub Actions run for one ref into a single derived fact —
* {state, checks} — for ship-feature-lane's Stage 13 CI-wait. Deliberately a
* snapshot, not a poll loop: the driving skill owns the wait/retry decision
* (docs/LANES.md "Orchestration: what CCAM does NOT do"), this module only
* reports what gh already knows.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { gh } = require("./gh");
/** A 7-40 char hex string reads as a commit sha; anything else is a branch name. */
const SHA_RE = /^[0-9a-f]{7,40}$/i;
/**
* @param {string} cwd - The lane's repo directory (gh resolves the GitHub
* repo from this directory's git remote).
* @param {string} ref - A branch name or commit sha.
* @returns {Promise<{state: "success"|"failure"|"pending", ref: string, checks: Array}>}
*/
async function ciStatus(cwd, ref) {
const refFlag = SHA_RE.test(ref) ? "--commit" : "--branch";
const { stdout: listOut } = await gh(cwd, [
"run",
"list",
refFlag,
ref,
"--json",
"databaseId,status,conclusion",
"--limit",
"1",
]);
const runs = JSON.parse(listOut);
if (runs.length === 0) {
return { state: "pending", ref, checks: [] };
}
const run = runs[0];
if (run.status !== "completed") {
return { state: "pending", ref, checks: [] };
}
const { stdout: viewOut } = await gh(cwd, [
"run",
"view",
String(run.databaseId),
"--json",
"jobs",
]);
const { jobs } = JSON.parse(viewOut);
const checks = jobs.map((job) => ({
name: job.name,
conclusion: job.conclusion || job.status,
url: job.url || null,
}));
const FAILING = new Set(["failure", "cancelled", "timed_out", "action_required"]);
const state = checks.some((c) => FAILING.has(c.conclusion)) ? "failure" : "success";
return { state, ref, checks };
}
module.exports = { ciStatus };
+36
View File
@@ -0,0 +1,36 @@
/**
* @file Thin execFile wrapper around the GitHub CLI (`gh`), used by
* server/lib/ci-status.js to read Actions run state. Mirrors worktree.js's
* git() helper's shape (cwd-scoped, throws with structured .gh details on
* failure) but has no env-scrubbing to do — gh doesn't read GIT_* variables.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { execFile } = require("node:child_process");
const { promisify } = require("node:util");
const execFileAsync = promisify(execFile);
/**
* Run `gh <args>` in `cwd`. Resolves `{ stdout, stderr }` on a zero exit.
* On failure, throws an Error with `.gh = { args, code, stderr }` — `.code`
* is `"ENOGH"` when the binary itself is missing, otherwise the process's
* exit code.
*
* @param {string} cwd
* @param {string[]} args
* @returns {Promise<{stdout: string, stderr: string}>}
*/
async function gh(cwd, args) {
try {
const result = await execFileAsync("gh", args, { cwd, maxBuffer: 8 * 1024 * 1024 });
return { stdout: result.stdout, stderr: result.stderr };
} catch (err) {
const error = new Error(`gh ${args[0]} failed`);
error.code = err.code === "ENOENT" ? "ENOGH" : err.code;
error.gh = { args, code: err.code, stderr: err.stderr || "" };
throw error;
}
}
module.exports = { gh };
+22
View File
@@ -50,6 +50,7 @@ const {
} = require("../lib/lane-runtime");
const { reapOrphanMcp, capOversizedLogs } = require("../lib/lane-gc");
const { detectNode, scaffoldProfile } = require("../lib/lane-detect");
const { ciStatus } = require("../lib/ci-status");
const router = Router();
const MAX_WORKTREE_DIRECTORY_ATTEMPTS = 50;
@@ -520,6 +521,27 @@ router.get("/:id/git", async (req, res) => {
}
});
/**
* A single GitHub Actions status snapshot for one ref (branch or commit sha)
* in the lane's repo — NOT a poll loop. ship-feature-lane's Stage 13 owns
* the wait/retry decision (docs/LANES.md "Orchestration: what CCAM does NOT
* do"); this route only reports what `gh` currently knows. Read-only, no
* same-origin guard, same reasoning as GET /:id/git.
*/
router.get("/:id/ci/status", async (req, res) => {
const lane = laneOr404(req, res);
if (!lane) return;
const ref = typeof req.query.ref === "string" ? req.query.ref.trim() : "";
if (!ref) {
return res.status(400).json({ error: { code: "EBADREF", message: "ref is required" } });
}
try {
res.json(await ciStatus(lane.cwd, ref));
} catch (err) {
sendRuntimeError(res, err);
}
});
/**
* Create a dashboard-managed worktree lane. Git work happens after the 202
* response because provisioning a large repository can take seconds.