0.1.0: first release — review, harbour, Gas, deploys and releases
- Pandu reviews every MR labelled `labuh` through Codex app-server and answers in a fixed shape; the Hub checks each piece of evidence, applies hard rules the model cannot override, retries once, and posts the comments itself. - The board shows the harbour: lanes per environment, Dicek / Siap gas / Beres, two fixed berth rows, boats that glide; GitLab sign-in, approvers from board.json, works on a phone. - Gas, Tunda, Tolak and Tutup MR with 15 seconds to undo; the Hub checks GitLab again and merges the reviewed commit only, then follows the deploy. - Branches that deploy from tags get a proposed version and changelog; the approver confirms the number and the Hub creates the annotated tag. - Telegram notifications, reminders, dry mode for rehearsals. - Hosting: one image, three containers. The reviewer runs in its own container with no GitLab token and read-only checkouts, reached by the Hub over a token-guarded WebSocket; every command it asks for still passes the Hub's allowlist. Configuration and state live in LABUH_HOME. - AGPL-3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
254
test/board.test.ts
Normal file
254
test/board.test.ts
Normal file
@@ -0,0 +1,254 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { Store } from '../src/store.ts';
|
||||
import { viewAjuan, visible, laneOf, type BoardConfig, type Viewer } from '../src/boardview.ts';
|
||||
import { createBoard } from '../src/board.ts';
|
||||
|
||||
const cfg: BoardConfig = {
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
publicUrl: 'http://localhost:4810',
|
||||
gitlabClientId: null,
|
||||
approvers: ['sen'],
|
||||
lanes: [
|
||||
{ name: 'Prod', branches: ['production', 'main'] },
|
||||
{ name: 'Staging', branches: ['development'] },
|
||||
],
|
||||
doneHours: 24,
|
||||
};
|
||||
const sen: Viewer = { username: 'sen', name: 'Sen', approver: true, projects: ['g/api'] };
|
||||
const dev: Viewer = { username: 'raka', name: 'Raka', approver: false, projects: ['g/api'] };
|
||||
|
||||
function seeded() {
|
||||
const store = new Store(path.join(mkdtempSync(path.join(os.tmpdir(), 'labuh-board-')), 'db.sqlite'));
|
||||
const add = (iid: number, fields: object) => {
|
||||
const { ajuan } = store.upsertAjuan({ project: 'g/api', iid, webUrl: `https://gitlab.com/g/api/-/merge_requests/${iid}`, title: `MR ${iid}`, sha: 'h1', author: 'raka', targetBranch: 'production' });
|
||||
store.update(ajuan.id, fields as any);
|
||||
return store.ajuanById(ajuan.id);
|
||||
};
|
||||
const verdict = (v: string) => JSON.stringify({ verdict: v, reason: 'alasan', findings: [{ kind: 'bad', text: 'urutan migrasi', evidence: [{ label: 'a.go:3', url: 'https://gitlab.com/g/api/-/blob/h1/a.go#L3' }, { label: 'rubric R9', url: 'file:///x/rubric.md#r9' }] }], postDeploy: [], dropped: [], overrides: [] });
|
||||
return { store, add, verdict };
|
||||
}
|
||||
|
||||
test('statuses map to zones; a moved head shows as being checked again', () => {
|
||||
const { store, add, verdict } = seeded();
|
||||
const held = add(1, { status: 'no_go', reviewed_sha: 'h1', verdict_json: verdict('no_go') });
|
||||
const v = viewAjuan(held, store.events(held.id), cfg, sen);
|
||||
assert.equal(v.status, 'fix');
|
||||
assert.equal(v.zone, 'cek');
|
||||
assert.equal(v.lane, 'Prod');
|
||||
assert.equal(v.reason, 'alasan');
|
||||
assert.deepEqual(v.findings[0].evidence.map((e) => e.url), ['https://gitlab.com/g/api/-/blob/h1/a.go#L3', '/rubric#r9']);
|
||||
assert.equal(v.needsYou, false, 'a held ajuan does not need the approver');
|
||||
assert.equal(viewAjuan(held, [], cfg, dev).needsYou, true, 'but it needs its author');
|
||||
|
||||
const moved = add(2, { status: 'go', reviewed_sha: 'h0', head_sha: 'h1', verdict_json: verdict('go') });
|
||||
const m = viewAjuan(moved, [], cfg, sen);
|
||||
assert.equal(m.status, 'checking');
|
||||
assert.deepEqual(m.findings, [], 'an old verdict is not shown as current');
|
||||
|
||||
const ready = add(3, { status: 'go', reviewed_sha: 'h1', verdict_json: verdict('go') });
|
||||
assert.equal(viewAjuan(ready, [], cfg, sen).zone, 'siap');
|
||||
assert.equal(viewAjuan(ready, [], cfg, sen).needsYou, true);
|
||||
assert.equal(laneOf('feature/x', cfg), 'Lainnya');
|
||||
});
|
||||
|
||||
test('only readable projects, open ajuan and merges from the last day are visible', () => {
|
||||
const { add } = seeded();
|
||||
const open = add(1, { status: 'reviewing' });
|
||||
const merged = add(2, { status: 'closed', closed_state: 'merged' });
|
||||
const closed = add(3, { status: 'closed', closed_state: 'closed' });
|
||||
assert.equal(visible(open, cfg, sen), true);
|
||||
assert.equal(visible(merged, cfg, sen), true);
|
||||
assert.equal(visible(merged, cfg, sen, Date.now() + 25 * 3600_000), false);
|
||||
assert.equal(visible(closed, cfg, sen), false);
|
||||
assert.equal(visible(open, cfg, { ...sen, projects: ['other/repo'] }), false);
|
||||
});
|
||||
|
||||
test('the timeline reads as people talk', () => {
|
||||
const { store, add } = seeded();
|
||||
const a = add(1, { status: 'no_go' });
|
||||
const opened = store.nextEvent()!;
|
||||
store.finishEvent(opened.id, 'no_go di h1abcdef');
|
||||
store.enqueue(a.id, 'mention', {});
|
||||
store.finishEvent(store.nextEvent()!.id, 'dijawab');
|
||||
const v = viewAjuan(store.ajuanById(a.id), store.events(a.id), cfg, sen);
|
||||
assert.deepEqual(v.timeline.map((t) => t.text), ['Diajukan raka; Pandu: tahan', 'Ditanya; Pandu jawab di MR']);
|
||||
});
|
||||
|
||||
async function serve(store: Store, c: BoardConfig, devUser?: string) {
|
||||
const server = createBoard(store, c, ['g/api'], { devUser });
|
||||
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
|
||||
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
return { base, close: () => new Promise((r) => server.close(r)) };
|
||||
}
|
||||
|
||||
test('without a session the board shows sign-in and the API refuses', async () => {
|
||||
const { store, add } = seeded();
|
||||
add(1, { status: 'reviewing' });
|
||||
const s = await serve(store, cfg);
|
||||
try {
|
||||
const page = await fetch(`${s.base}/`);
|
||||
assert.equal(page.status, 401);
|
||||
assert.match(await page.text(), /Masuk dengan GitLab/);
|
||||
assert.match(page.headers.get('content-security-policy')!, /script-src 'self'/);
|
||||
assert.equal((await fetch(`${s.base}/api/board`)).status, 401);
|
||||
assert.equal((await fetch(`${s.base}/rubric`)).status, 401);
|
||||
const login = await fetch(`${s.base}/auth/login`, { redirect: 'manual' });
|
||||
assert.equal(login.status, 503, 'no OAuth app configured yet');
|
||||
const cb = await fetch(`${s.base}/auth/callback?code=x&state=forged`);
|
||||
assert.equal(cb.status, 400, 'an unknown state is refused');
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('the OAuth redirect uses PKCE and read_api', async () => {
|
||||
const { store } = seeded();
|
||||
const s = await serve(store, { ...cfg, gitlabClientId: 'client-1' });
|
||||
try {
|
||||
const r = await fetch(`${s.base}/auth/login`, { redirect: 'manual' });
|
||||
const to = new URL(r.headers.get('location')!);
|
||||
assert.equal(to.origin + to.pathname, 'https://gitlab.com/oauth/authorize');
|
||||
assert.equal(to.searchParams.get('scope'), 'read_api');
|
||||
assert.equal(to.searchParams.get('code_challenge_method'), 'S256');
|
||||
assert.equal(to.searchParams.get('redirect_uri'), 'http://localhost:4810/auth/callback');
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('the local dev user works only when bound to 127.0.0.1', async () => {
|
||||
const { store, add, verdict } = seeded();
|
||||
add(1, { status: 'no_go', reviewed_sha: 'h1', verdict_json: verdict('no_go') });
|
||||
const local = await serve(store, cfg, 'sen');
|
||||
try {
|
||||
const r = await fetch(`${local.base}/api/board`);
|
||||
assert.equal(r.status, 200);
|
||||
const body = await r.json();
|
||||
assert.equal(body.viewer.approver, true);
|
||||
assert.equal(body.ajuan.length, 1);
|
||||
assert.equal(body.ajuan[0].findings[0].evidence[1].url, '/rubric#r9');
|
||||
const rubric = await fetch(`${local.base}/rubric`);
|
||||
assert.match(await rubric.text(), /id="r9"/);
|
||||
} finally {
|
||||
await local.close();
|
||||
}
|
||||
const exposed = await serve(store, { ...cfg, host: '0.0.0.0' }, 'sen');
|
||||
try {
|
||||
assert.equal((await fetch(`${exposed.base}/api/board`)).status, 401);
|
||||
} finally {
|
||||
await exposed.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('decisions and deploys move the boat: Gas waits in Siap gas, sailing and failed sit in Beres', () => {
|
||||
const { store, add, verdict } = seeded();
|
||||
const base = { status: 'go', reviewed_sha: 'h1', verdict_json: verdict('go') };
|
||||
const zone = (a: any, act?: any) => viewAjuan(a, [], cfg, sen, act);
|
||||
const gas = add(1, { ...base, decision: 'gas', decision_by: 'sen' });
|
||||
const v = zone(gas, { taken: false, gasQueuedAt: 1000, graceSeconds: 15, allowed: ['undo'], dry: false });
|
||||
assert.deepEqual([v.status, v.zone, v.gasAt, v.actions], ['gas', 'siap', 16000, ['undo']]);
|
||||
assert.deepEqual(viewAjuan(gas, [], cfg, dev, { taken: false, gasQueuedAt: 1000, graceSeconds: 15, allowed: ['undo'], dry: false }).actions, [], 'developers get no actions');
|
||||
assert.deepEqual([zone(add(2, { ...base, decision: 'tunda', decision_by: 'sen', decision_note: 'jam sibuk' })).zone], ['cek']);
|
||||
assert.match(zone(store.ajuan('g/api', 2)!).reason, /Ditunda @sen: “jam sibuk”/);
|
||||
assert.equal(zone(add(3, { ...base, decision: 'tolak', decision_by: 'sen' })).status, 'rejected');
|
||||
const sailing = zone(add(4, { ...base, status: 'closed', closed_state: 'merged', deploy_state: 'deploying' }));
|
||||
assert.deepEqual([sailing.status, sailing.zone], ['sailing', 'beres']);
|
||||
const failed = zone(add(5, { ...base, status: 'closed', closed_state: 'merged', deploy_state: 'failed' }));
|
||||
assert.deepEqual([failed.status, failed.needsYou], ['failed', true]);
|
||||
// A new commit outranks an old decision on the board.
|
||||
assert.equal(zone(add(6, { ...base, head_sha: 'h2', decision: 'gas' })).status, 'checking');
|
||||
});
|
||||
|
||||
test('only an approver, same origin and JSON, can act; Gas is recorded for the Hub', async () => {
|
||||
const { store, add, verdict } = seeded();
|
||||
const a = add(1, { status: 'go', reviewed_sha: 'h1', verdict_json: verdict('go') });
|
||||
const post = (base: string, body: object, headers: Record<string, string> = { Origin: 'http://localhost:4810', 'Content-Type': 'application/json' }) =>
|
||||
fetch(`${base}/api/ajuan/${a.id}/action`, { method: 'POST', headers, body: JSON.stringify(body) });
|
||||
|
||||
const asDev = await serve(store, cfg, 'raka');
|
||||
try {
|
||||
assert.equal((await post(asDev.base, { action: 'gas', sha: 'h1' })).status, 403);
|
||||
} finally {
|
||||
await asDev.close();
|
||||
}
|
||||
const s = await serve(store, cfg, 'sen');
|
||||
try {
|
||||
assert.equal((await post(s.base, { action: 'gas', sha: 'h1' }, { Origin: 'https://evil.example', 'Content-Type': 'application/json' })).status, 403);
|
||||
assert.equal((await post(s.base, { action: 'gas', sha: 'h1' }, { Origin: 'http://localhost:4810', 'Content-Type': 'text/plain' })).status, 403);
|
||||
assert.equal((await post(s.base, { action: 'merge-now' })).status, 400);
|
||||
const stale = await post(s.base, { action: 'gas', sha: 'h0' });
|
||||
assert.equal(stale.status, 409);
|
||||
assert.match((await stale.json()).error, /commit baru/);
|
||||
assert.equal((await post(s.base, { action: 'gas', sha: 'h1' })).status, 200);
|
||||
assert.equal(store.ajuanById(a.id).decision, 'gas');
|
||||
assert.deepEqual(store.pendingActions(a.id).map((e) => [e.kind, e.payload.by, e.payload.sha]), [['gas', 'sen', 'h1']]);
|
||||
const board = await (await fetch(`${s.base}/api/board`)).json();
|
||||
assert.deepEqual(board.ajuan[0].actions, ['undo']);
|
||||
assert.ok(board.ajuan[0].gasAt > Date.now());
|
||||
assert.equal((await post(s.base, { action: 'undo' })).status, 200);
|
||||
assert.equal(store.pendingActions(a.id).length, 0);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('a session ends when the Hub starts watching a project it never checked', async () => {
|
||||
const { store } = seeded();
|
||||
const { createHash } = await import('node:crypto');
|
||||
const s = await serve(store, cfg);
|
||||
try {
|
||||
// Signed in when only g/api was watched: still valid.
|
||||
store.db.prepare("INSERT INTO board_sessions (id, username, name, approver, projects, checked, expires_at) VALUES (?, 'sen', 'Sen', 1, '[\"g/api\"]', '[\"g/api\"]', ?)").run(createHash('sha256').update('old').digest('hex'), Date.now() + 3600_000);
|
||||
assert.equal((await fetch(`${s.base}/api/board`, { headers: { cookie: 'labuh_session=old' } })).status, 200);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
const more = createBoard(store, cfg, ['g/api', 'g/web']);
|
||||
await new Promise<void>((r) => more.listen(0, '127.0.0.1', r));
|
||||
try {
|
||||
const base = `http://127.0.0.1:${(more.address() as AddressInfo).port}`;
|
||||
assert.equal((await fetch(`${base}/api/board`, { headers: { cookie: 'labuh_session=old' } })).status, 401, 'g/web was never checked for this session');
|
||||
} finally {
|
||||
await new Promise((r) => more.close(r));
|
||||
}
|
||||
});
|
||||
|
||||
test('the release proposal shows on merged ajuan; only an approver can confirm it, with a valid tag', async () => {
|
||||
const { store, add } = seeded();
|
||||
const a = add(1, { status: 'closed', closed_state: 'merged', merge_sha: 'm1', deploy_state: 'awaiting_release' });
|
||||
const r = store.addRelease({ project: 'g/api', branch: 'production', sha: 'm1', from_tag: 'v2.0.9', proposed_tag: 'v2.0.10', changes: { mrs: [{ iid: 1, title: 'MR 1', author: 'raka' }], commits: [] } });
|
||||
const post = (base: string, body: object, origin = 'http://localhost:4810') =>
|
||||
fetch(`${base}/api/release/${r.id}/action`, { method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||
|
||||
const asDev = await serve(store, cfg, 'raka');
|
||||
try {
|
||||
const board = await (await fetch(`${asDev.base}/api/board`)).json();
|
||||
assert.equal(board.ajuan[0].release.proposedTag, 'v2.0.10');
|
||||
assert.deepEqual(board.ajuan[0].release.actions, []);
|
||||
assert.equal((await post(asDev.base, { action: 'release', tag: 'v2.0.10' })).status, 403);
|
||||
} finally {
|
||||
await asDev.close();
|
||||
}
|
||||
const s = await serve(store, cfg, 'sen');
|
||||
try {
|
||||
assert.equal((await post(s.base, { action: 'release', tag: 'v2.0.10' }, 'https://evil.example')).status, 403);
|
||||
const bad = await post(s.base, { action: 'release', tag: 'v2.0.5' });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.match((await bad.json()).error, /lebih baru dari v2\.0\.9/);
|
||||
assert.equal((await post(s.base, { action: 'release', tag: 'v2.1.0' })).status, 200);
|
||||
const board = await (await fetch(`${s.base}/api/board`)).json();
|
||||
assert.deepEqual([board.ajuan[0].release.state, board.ajuan[0].release.tag, board.ajuan[0].release.actions], ['queued', 'v2.1.0', ['undo']]);
|
||||
assert.ok(board.ajuan[0].release.at > Date.now());
|
||||
assert.equal((await post(s.base, { action: 'undo' })).status, 200);
|
||||
assert.equal(store.releaseById(r.id)!.state, 'proposed');
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
assert.equal(a.deploy_state, 'awaiting_release');
|
||||
});
|
||||
101
test/contract.test.ts
Normal file
101
test/contract.test.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { shapeErrors, check, rubricIds, type Verdict } from '../src/contract.ts';
|
||||
import { decideCommand } from '../src/policy.ts';
|
||||
|
||||
const ev = (o: object) => ({ type: 'file', path: null, line: null, job_id: null, rule_id: null, ...o });
|
||||
|
||||
test('allowlist keeps the reviewer read-only', () => {
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'rg -n hpp_lama src | head -20'").allow, true);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'git log --oneline -5'").allow, true);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'curl -sI https://example.com'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'git push origin main'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'cat a > b'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'sed -i s/a/b/ f'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'find . -name x -delete'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'ls && rm -rf /'").allow, false);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc "rg -n 'DeleteAndUnlink|DeleteIfUnused|2026, 11, 6' internal"`).allow, true);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'git branch -a --contains HEAD'").allow, true);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'git branch evil'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'git branch -D main'").allow, false);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc "echo \\"$(id)\\""`).allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'rg --pre ./x foo'").allow, false);
|
||||
assert.equal(decideCommand("/bin/zsh -lc 'sleep 1 & ls'").allow, false);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc 'git diff HEAD''^ HEAD --name-status && rg --files -g '"'.gitlab-ci.yml' -g '*deploy*'"`).allow, true);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc 'ls '"'x'"' && curl '"'https://e.com'"`).allow, false);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc "rg -n 'a|b' src"`).allow, true);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc 'rg -n x docs README* 2>/dev/null; ls 2>&1'`).allow, true);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc 'cat a 2>/tmp/x'`).allow, false);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc "nl -ba a.yml | sed -n '1,240p'; rg -n \\"hatchery|supplier\\" app | head -80"`).allow, true);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc "rg -n \\"x\\"; curl \\"https://e.com\\""`).allow, false);
|
||||
assert.equal(decideCommand(`/bin/zsh -lc 'cat a >/dev/nullx'`).allow, false);
|
||||
});
|
||||
|
||||
test('allowlist keeps reads inside the checkout and allowed knowledge', () => {
|
||||
const base = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'labuh-scope-')));
|
||||
const work = path.join(base, 'work');
|
||||
const repo = path.join(work, 'repo');
|
||||
const vault = path.join(base, 'vault');
|
||||
for (const d of [path.join(repo, 'src'), path.join(repo, '.git'), path.join(vault, 'Repositories', 'x'), path.join(vault, 'Credentials'), path.join(base, 'outside')]) mkdirSync(d, { recursive: true });
|
||||
writeFileSync(path.join(vault, 'Credentials', 'k.md'), 'secret');
|
||||
writeFileSync(path.join(base, 'outside', 'm.txt'), 'marker');
|
||||
symlinkSync(path.join(base, 'outside', 'm.txt'), path.join(repo, 'link.txt'));
|
||||
const scope = { cwd: repo, allow: [work, path.join(vault, 'Repositories')], deny: [path.join(repo, '.git'), path.join(vault, 'Credentials')] };
|
||||
const ok = (c: string, s = scope) => decideCommand(`/bin/zsh -lc '${c}'`, s).allow;
|
||||
|
||||
assert.equal(ok('rg -n foo src'), true);
|
||||
assert.equal(ok('cat ../mr.diff'), true);
|
||||
assert.equal(ok(`rg -n deploy ${vault}/Repositories/x`), true);
|
||||
assert.equal(ok('cat ~/.ssh/id_ed25519'), false);
|
||||
assert.equal(ok(`cat ${vault}/Credentials/k.md`), false);
|
||||
assert.equal(ok(`cat ${vault}/Repositories/../Credentials/k.md`), false);
|
||||
assert.equal(ok('cat ../../outside/m.txt'), false);
|
||||
assert.equal(ok('cat ../../../../etc/hosts'), false);
|
||||
assert.equal(ok(`rg -n foo ${base}/outside`), false);
|
||||
assert.equal(ok(`rg --files --glob=${base}/outside`), false);
|
||||
assert.equal(ok('cat link.txt'), false);
|
||||
assert.equal(ok('cat .git/config'), false);
|
||||
assert.equal(ok('cat $HOME/.ssh/id_rsa'), false);
|
||||
assert.equal(ok('grep -R foo .'), false);
|
||||
assert.equal(ok('ls', { ...scope, cwd: path.join(base, 'outside') }), false);
|
||||
});
|
||||
|
||||
test('shape: go with a bad finding is rejected', () => {
|
||||
const v = { verdict: 'go', reason: 'ok', post_deploy: [], findings: [{ kind: 'bad', text: 'x', evidence: [ev({ type: 'rubric', rule_id: 'R1' })] }] };
|
||||
assert.match(shapeErrors(JSON.stringify(v)).errors.join(), /go but a finding is bad/);
|
||||
});
|
||||
|
||||
test('shape: long text and missing evidence are rejected', () => {
|
||||
const v = { verdict: 'no_go', reason: 'x'.repeat(81), post_deploy: [], findings: [{ kind: 'bad', text: 'x', evidence: [] }] };
|
||||
const errs = shapeErrors(JSON.stringify(v)).errors.join('\n');
|
||||
assert.match(errs, /limit is 80/);
|
||||
assert.match(errs, /no evidence/);
|
||||
});
|
||||
|
||||
test('evidence must exist; ok without evidence is dropped; failing pipeline holds go', async () => {
|
||||
const repo = mkdtempSync(path.join(os.tmpdir(), 'labuh-'));
|
||||
writeFileSync(path.join(repo, 'a.py'), 'one\ntwo\nthree\n');
|
||||
const ctx = {
|
||||
repoDir: repo, blobBase: 'https://gitlab.com/x/-/blob/abc', sha: 'abc',
|
||||
rubricIds: rubricIds('## R1 · Rollback\n## R2 · Data\n'), rubricUrl: (id: string) => `rubric#${id}`,
|
||||
pipeline: { status: 'failed' }, pipelineIds: [7],
|
||||
loadJob: async (id: number) => (id === 1 ? { pipelineId: 7, name: 'test', webUrl: 'job/1' } : null),
|
||||
};
|
||||
const good: Verdict = { verdict: 'go', reason: 'Aman', post_deploy: [], findings: [
|
||||
{ kind: 'ok', text: 'tes ada', evidence: [ev({ type: 'pipeline', job_id: 1 })] },
|
||||
{ kind: 'ok', text: 'karangan', evidence: [ev({ path: 'nope.py', line: 3 })] },
|
||||
] };
|
||||
const r = await check(good, ctx);
|
||||
assert.equal(r.checked!.findings.length, 1);
|
||||
assert.equal(r.checked!.dropped.length, 1);
|
||||
assert.equal(r.checked!.verdict, 'waiting');
|
||||
|
||||
const bad: Verdict = { verdict: 'no_go', reason: 'Tahan', post_deploy: [], findings: [{ kind: 'bad', text: 'baris palsu', evidence: [ev({ path: 'a.py', line: 99 })] }] };
|
||||
assert.match((await check(bad, ctx)).errors.join(), /outside the file/);
|
||||
|
||||
const escape: Verdict = { verdict: 'no_go', reason: 'Tahan', post_deploy: [], findings: [{ kind: 'bad', text: 'keluar repo', evidence: [ev({ path: '../../etc/hosts', line: 1 })] }] };
|
||||
assert.match((await check(escape, ctx)).errors.join(), /does not exist/);
|
||||
});
|
||||
601
test/hub.test.ts
Normal file
601
test/hub.test.ts
Normal file
@@ -0,0 +1,601 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store } from '../src/store.ts';
|
||||
import { Hub, type HubConfig, type Ports } from '../src/hub.ts';
|
||||
import { review, type Reviewer, type Session } from '../src/review.ts';
|
||||
import { VERDICT_MARKER } from '../src/render.ts';
|
||||
import { decide, allowedActions } from '../src/decide.ts';
|
||||
import { decideRelease, nextTag, latestTag, tagProblem } from '../src/release.ts';
|
||||
import { viewAjuan } from '../src/boardview.ts';
|
||||
import type { Note } from '../src/gitlab.ts';
|
||||
import type { Checked } from '../src/contract.ts';
|
||||
|
||||
const reviewer: Reviewer = { name: 'Pandu', codexBin: '', model: 'm', effort: 'medium', rubric: 'rubric/rubric.md', budgetTokensPerAjuan: 1000, pricingPer1MTokens: null, knowledge: null };
|
||||
const PROJECT = 'acme/api';
|
||||
const checked = (verdict: Checked['verdict'], reason: string): Checked => ({
|
||||
verdict,
|
||||
reason,
|
||||
findings: verdict === 'no_go' ? [{ kind: 'bad', text: 'urutan migrasi', evidence: [{ label: '.gitlab-ci.yml:167', url: 'https://gitlab.com/x/-/blob/s/.gitlab-ci.yml#L167' }, { label: 'rubric R9', url: 'file:///r#r9' }] as any }] : [],
|
||||
postDeploy: [],
|
||||
dropped: [],
|
||||
overrides: [],
|
||||
});
|
||||
|
||||
// A fake GitLab and reviewer with a script of what each call returns.
|
||||
function world(config: Partial<HubConfig> = {}) {
|
||||
const gl = {
|
||||
mrs: new Map<number, { sha: string; state: string; labels: string[]; mergeStatus?: string; pipelineStatus?: string | null; mergeSha?: string }>(),
|
||||
notes: new Map<number, Note[]>(),
|
||||
posted: [] as Array<{ iid: number; id: number; body: string; edit: boolean }>,
|
||||
// Keyed by commit sha, or by tag name for a tag's pipeline.
|
||||
pipelines: new Map<string, { id: number; status: string; webUrl: string }>(),
|
||||
tags: new Map<string, { name: string; sha: string }>(),
|
||||
merges: [] as Array<{ iid: number; sha: string }>,
|
||||
sent: [] as string[],
|
||||
sendFails: 0,
|
||||
rubric: 'abc',
|
||||
// The release side of the repo: branch head, existing tags, what changed, tags Labuh made.
|
||||
head: 'merge-g1',
|
||||
tagList: [] as Array<{ name: string; sha: string }>,
|
||||
changes: { mrs: [], commits: [] } as { mrs: Array<{ iid: number; title: string; author: string }>; commits: Array<{ sha: string; title: string }> },
|
||||
created: [] as Array<{ name: string; sha: string; message: string }>,
|
||||
closed: [] as number[],
|
||||
};
|
||||
const calls = { connect: [] as Array<string | null>, review: [] as Array<string | null>, ask: [] as string[] };
|
||||
let outcomes: Array<() => any> = [];
|
||||
let nextThread = 1;
|
||||
const summary = (iid: number) => {
|
||||
const m = gl.mrs.get(iid)!;
|
||||
return { projectPath: PROJECT, iid, sha: m.sha, state: m.state, title: `MR ${iid}`, webUrl: `https://gitlab.com/${PROJECT}/-/merge_requests/${iid}`, labels: m.labels, author: 'dev', targetBranch: 'production', mergeSha: m.mergeSha ?? null, mergeStatus: m.mergeStatus ?? 'mergeable', pipelineStatus: m.pipelineStatus ?? null };
|
||||
};
|
||||
const ports: Ports = {
|
||||
gitlab: {
|
||||
listLabelledMrs: async (_p, label) => [...gl.mrs.keys()].filter((i) => gl.mrs.get(i)!.state === 'opened' && gl.mrs.get(i)!.labels.includes(label)).map(summary),
|
||||
mrSummary: async (ref) => summary(ref.iid),
|
||||
listNotes: async (ref, after) => (gl.notes.get(ref.iid) ?? []).filter((n) => n.id > after),
|
||||
postNote: async (ref, body) => {
|
||||
const id = 9000 + gl.posted.length;
|
||||
gl.posted.push({ iid: ref.iid, id, body, edit: false });
|
||||
return id;
|
||||
},
|
||||
updateNote: async (ref, id, body) => {
|
||||
gl.posted.push({ iid: ref.iid, id, body, edit: true });
|
||||
},
|
||||
mergeMr: async (ref, sha) => {
|
||||
const m = gl.mrs.get(ref.iid)!;
|
||||
if (m.sha !== sha) throw new Error('409 SHA does not match HEAD of source branch');
|
||||
gl.merges.push({ iid: ref.iid, sha });
|
||||
m.state = 'merged';
|
||||
m.mergeSha = `merge-${sha}`;
|
||||
return { mergeSha: m.mergeSha, state: 'merged' };
|
||||
},
|
||||
closeMr: async (ref) => {
|
||||
gl.closed.push(ref.iid);
|
||||
gl.mrs.get(ref.iid)!.state = 'closed';
|
||||
return { state: 'closed' };
|
||||
},
|
||||
pipelineFor: async (_p, sha, ref) => gl.pipelines.get(sha ?? ref) ?? null,
|
||||
releaseTagFor: async (_p, mergeSha) => gl.tags.get(mergeSha) ?? null,
|
||||
releaseBase: async () => ({ head: gl.head, tags: gl.tagList }),
|
||||
releaseChanges: async () => gl.changes,
|
||||
createTag: async (_p, name, sha, message) => {
|
||||
gl.created.push({ name, sha, message });
|
||||
gl.tagList.unshift({ name, sha });
|
||||
gl.tags.set(sha, { name, sha });
|
||||
return { name, sha };
|
||||
},
|
||||
},
|
||||
notifier: {
|
||||
send: async (text) => {
|
||||
if (gl.sendFails > 0) {
|
||||
gl.sendFails--;
|
||||
throw new Error('Telegram sendMessage: Bad Gateway');
|
||||
}
|
||||
gl.sent.push(text);
|
||||
},
|
||||
},
|
||||
reviewer: {
|
||||
rubricVersion: () => gl.rubric,
|
||||
prepare: async (ref) => ({ ...summary(ref.iid), projectId: 1, sshUrl: '', description: '', author: 'dev', sourceBranch: 'a', pipeline: null, pipelineIds: [], commits: [], diffs: [] }) as any,
|
||||
connect: async (mr, workDir, threadId) => {
|
||||
calls.connect.push(threadId);
|
||||
return { mr, reviewer, threadId: threadId ?? `t${nextThread++}`, threadPath: null, model: 'm', rubricVersion: gl.rubric, workDir, usage: { totalTokens: 100 } as any, log: [], client: { close() {} } as any } as Session;
|
||||
},
|
||||
review: async (s, previous) => {
|
||||
calls.review.push(previous);
|
||||
return outcomes.shift()!();
|
||||
},
|
||||
ask: async (_s, q) => {
|
||||
calls.ask.push(q);
|
||||
return { finalText: 'Karena migrasi jalan setelah API naik.', usage: null, commands: [], refused: [] };
|
||||
},
|
||||
},
|
||||
};
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'labuh-hub-'));
|
||||
const store = new Store(path.join(root, 'db.sqlite'));
|
||||
const hub = new Hub(store, { mode: 'shadow', pollSeconds: 1, label: 'labuh', projects: [PROJECT], botUsername: null, ...config }, reviewer, ports, root);
|
||||
return { gl, calls, hub, store, root, script: (...o: Array<() => any>) => (outcomes = o) };
|
||||
}
|
||||
|
||||
const ok = (c: Checked) => () => ({ ok: true, checked: c, attempts: 1, turns: [] });
|
||||
|
||||
test('labelled MR is reviewed once, a new commit updates the same comment in the same thread', async () => {
|
||||
const w = world();
|
||||
w.gl.mrs.set(5, { sha: 'aaaa1111', state: 'opened', labels: ['labuh'] });
|
||||
w.gl.notes.set(5, [{ id: 1, body: '@pandu old question before Labuh', author: 'dev', system: false, createdAt: '' }]);
|
||||
w.script(ok(checked('no_go', 'API naik sebelum migrasi')), ok(checked('go', 'Urutan sudah benar')));
|
||||
|
||||
await w.hub.poll();
|
||||
await w.hub.poll(); // a second poll adds nothing
|
||||
assert.equal(await w.hub.drain(), 1);
|
||||
let a = w.store.ajuan(PROJECT, 5)!;
|
||||
assert.equal(a.status, 'no_go');
|
||||
assert.equal(a.reviewed_sha, 'aaaa1111');
|
||||
assert.deepEqual(w.calls.connect, [null]);
|
||||
assert.deepEqual(w.calls.ask, [], 'mentions written before the ajuan existed are not answered');
|
||||
|
||||
w.gl.mrs.get(5)!.sha = 'bbbb2222';
|
||||
await w.hub.poll();
|
||||
assert.equal(await w.hub.drain(), 1);
|
||||
a = w.store.ajuan(PROJECT, 5)!;
|
||||
assert.equal(a.status, 'go');
|
||||
assert.deepEqual(w.calls.connect, [null, 't1'], 'the new commit resumes the same thread');
|
||||
assert.deepEqual(w.calls.review, [null, 'aaaa1111'], 'the re-review knows the previous commit');
|
||||
|
||||
const verdicts = w.store.outbox(a.id).filter((o) => o.kind === 'verdict');
|
||||
assert.equal(verdicts.length, 1);
|
||||
const replies = w.store.outbox(a.id).filter((o) => o.kind === 'reply');
|
||||
assert.equal(replies.length, 1, 'only the re-review leaves a new note');
|
||||
assert.match(replies[0].body, /^@dev Review ulang commit `bbbb2222`: 🟢 Aman\. Detail di verdict di atas\./);
|
||||
assert.match(verdicts[0].body, /🟢 Aman — Urutan sudah benar/);
|
||||
assert.match(verdicts[0].body, /commit `bbbb2222`/);
|
||||
assert.ok(readdirSync(path.join(w.root, 'outbox')).includes('acme__api-5-verdict.md'));
|
||||
const note = readFileSync(path.join(w.root, 'notes', 'acme__api-5.md'), 'utf8');
|
||||
assert.match(note, /Commit terakhir direview: bbbb2222/);
|
||||
assert.match(note, /new_commit: go di bbbb2222/);
|
||||
});
|
||||
|
||||
test('mentions are answered in the thread without changing the verdict; own notes are ignored', async () => {
|
||||
const w = world();
|
||||
w.gl.mrs.set(6, { sha: 'cccc3333', state: 'opened', labels: ['labuh'] });
|
||||
w.script(ok(checked('no_go', 'API naik sebelum migrasi')));
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
w.gl.notes.set(6, [
|
||||
{ id: 10, body: `${VERDICT_MARKER}\n### 🔴 Tahan — @pandu`, author: 'someone', system: false, createdAt: '' },
|
||||
{ id: 11, body: 'added 1 commit @pandu', author: 'dev', system: true, createdAt: '' },
|
||||
{ id: 12, body: '@Pandu kenapa ini tahan?', author: 'dev', system: false, createdAt: '' },
|
||||
]);
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
assert.deepEqual(w.calls.ask, ['@Pandu kenapa ini tahan?']);
|
||||
const a = w.store.ajuan(PROJECT, 6)!;
|
||||
assert.equal(a.status, 'no_go');
|
||||
const reply = w.store.outbox(a.id).find((o) => o.kind === 'reply')!;
|
||||
assert.match(reply.body, /^@dev Karena migrasi/);
|
||||
assert.match(reply.body, /tidak mengubah verdict/);
|
||||
});
|
||||
|
||||
test('two invalid outputs end in reviewer error after exactly one retry', async () => {
|
||||
const turns: string[] = [];
|
||||
const s = {
|
||||
mr: { webUrl: 'https://gitlab.com/x', sha: 's', pipeline: null, pipelineIds: [], projectId: 1, diffs: [], commits: [], labels: [] },
|
||||
reviewer,
|
||||
threadId: 't',
|
||||
workDir: mkdtempSync(path.join(os.tmpdir(), 'labuh-rev-')),
|
||||
usage: null,
|
||||
client: {
|
||||
runTurn: async (_t: string, prompt: string) => {
|
||||
turns.push(prompt);
|
||||
return { finalText: '{"verdict":"maybe"}', usage: null, commands: [], refused: [] };
|
||||
},
|
||||
},
|
||||
} as unknown as Session;
|
||||
const out = await review(s);
|
||||
assert.equal(out.ok, false);
|
||||
assert.equal(out.attempts, 2);
|
||||
assert.equal(turns.length, 2);
|
||||
assert.match(turns[1], /Labuh rejected your verdict/);
|
||||
|
||||
const w = world();
|
||||
w.gl.mrs.set(7, { sha: 'dddd4444', state: 'opened', labels: ['labuh'] });
|
||||
w.script(() => out);
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
const a = w.store.ajuan(PROJECT, 7)!;
|
||||
assert.equal(a.status, 'reviewer_error');
|
||||
assert.match(w.store.outbox(a.id)[0].body, /Perlu dicek manual/);
|
||||
});
|
||||
|
||||
test('a crash mid-review resumes the saved thread and finishes once', async () => {
|
||||
const w = world();
|
||||
w.gl.mrs.set(8, { sha: 'eeee5555', state: 'opened', labels: ['labuh'] });
|
||||
w.script(
|
||||
() => {
|
||||
throw new Error('codex app-server exited (null)');
|
||||
},
|
||||
ok(checked('go', 'Aman')),
|
||||
);
|
||||
await w.hub.poll();
|
||||
assert.equal(await w.hub.drain(), 0, 'the failed event stays queued');
|
||||
assert.equal(w.store.nextEvent()!.attempts, 1);
|
||||
assert.equal(await w.hub.drain(), 1);
|
||||
assert.deepEqual(w.calls.connect, [null, 't1'], 'the restart resumes the thread saved before the turn');
|
||||
assert.equal(w.store.ajuan(PROJECT, 8)!.status, 'go');
|
||||
assert.equal(w.store.nextEvent(), undefined);
|
||||
});
|
||||
|
||||
test('an event that keeps failing gives up after three tries', async () => {
|
||||
const w = world();
|
||||
w.gl.mrs.set(9, { sha: 'ffff6666', state: 'opened', labels: ['labuh'] });
|
||||
const boom = () => {
|
||||
throw new Error('glab: 502');
|
||||
};
|
||||
w.script(boom, boom, boom);
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
await w.hub.drain();
|
||||
await w.hub.drain();
|
||||
assert.equal(w.store.ajuan(PROJECT, 9)!.status, 'reviewer_error');
|
||||
assert.equal(w.store.nextEvent(), undefined);
|
||||
});
|
||||
|
||||
test('merged MRs and removed labels close the ajuan; budget stops further reviews', async () => {
|
||||
const w = world();
|
||||
w.gl.mrs.set(11, { sha: 'a1', state: 'opened', labels: ['labuh'] });
|
||||
w.gl.mrs.set(12, { sha: 'b1', state: 'opened', labels: ['labuh'] });
|
||||
w.script(ok(checked('go', 'Aman')), ok(checked('go', 'Aman')));
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
w.gl.mrs.get(11)!.state = 'merged';
|
||||
w.gl.mrs.get(12)!.labels = [];
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
assert.equal(w.store.ajuan(PROJECT, 11)!.status, 'closed');
|
||||
assert.equal(w.store.ajuan(PROJECT, 12)!.status, 'closed');
|
||||
|
||||
const b = world();
|
||||
b.gl.mrs.set(13, { sha: 'c1', state: 'opened', labels: ['labuh'] });
|
||||
await b.hub.poll();
|
||||
b.store.update(b.store.ajuan(PROJECT, 13)!.id, { tokens: 5000 });
|
||||
await b.hub.drain();
|
||||
assert.equal(b.store.ajuan(PROJECT, 13)!.status, 'over_budget');
|
||||
assert.deepEqual(b.calls.review, []);
|
||||
});
|
||||
|
||||
test('live mode posts one verdict comment and edits it afterwards', async () => {
|
||||
const w = world({ mode: 'live', botUsername: 'pandu_bot' });
|
||||
w.gl.mrs.set(14, { sha: 'a1', state: 'opened', labels: ['labuh'] });
|
||||
w.script(ok(checked('no_go', 'Tahan')), ok(checked('go', 'Aman')));
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
w.gl.mrs.get(14)!.sha = 'a2';
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
assert.deepEqual(w.gl.posted.map((p) => [p.id, p.edit]), [[9000, false], [9000, true], [9002, false]]);
|
||||
assert.match(w.gl.posted[2].body, /Review ulang commit `a2`: 🟢 Aman\. Detail di \[verdict\]\(https:\/\/gitlab.com\/acme\/api\/-\/merge_requests\/14#note_9000\)/);
|
||||
assert.ok(!w.gl.posted[0].body.includes('file:///'), 'local links never reach GitLab');
|
||||
});
|
||||
|
||||
test('operator-added MRs are kept without a label', async () => {
|
||||
const w = world();
|
||||
w.gl.mrs.set(15, { sha: 'a1', state: 'opened', labels: [] });
|
||||
w.script(ok(checked('go', 'Aman')));
|
||||
await w.hub.add({ host: 'gitlab.com', projectPath: PROJECT, iid: 15 });
|
||||
await w.hub.drain();
|
||||
await w.hub.poll();
|
||||
assert.equal(w.store.ajuan(PROJECT, 15)!.status, 'go');
|
||||
assert.equal(w.store.nextEvent(), undefined);
|
||||
});
|
||||
|
||||
// ---- Milestone 3 ----
|
||||
|
||||
const T0 = Date.parse('2026-11-06T08:00:00Z');
|
||||
|
||||
async function readyAjuan(config: Partial<HubConfig> = {}, iid = 20) {
|
||||
const w = world({ gas: { mode: 'live', graceSeconds: 15 }, ...config });
|
||||
w.gl.mrs.set(iid, { sha: 'g1', state: 'opened', labels: ['labuh'] });
|
||||
w.script(ok(checked('go', 'Aman')));
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
return { w, a: w.store.ajuan(PROJECT, iid)! };
|
||||
}
|
||||
|
||||
test('Gas waits out its grace period, merges the reviewed commit and follows the deploy until it docks', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
assert.deepEqual(allowedActions(a, false), ['gas', 'tunda', 'tolak']);
|
||||
assert.equal(decide(w.store, a.id, 'gas', 'sen', { sha: 'old' }, T0).ok, false, 'a Gas on a stale view is refused');
|
||||
assert.equal(decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0).ok, true);
|
||||
|
||||
await w.hub.tick(T0 + 5_000);
|
||||
assert.deepEqual(w.gl.merges, [], 'nothing merges during the grace period');
|
||||
await w.hub.tick(T0 + 16_000);
|
||||
assert.deepEqual(w.gl.merges, [{ iid: 20, sha: 'g1' }]);
|
||||
let now = w.store.ajuanById(a.id);
|
||||
assert.equal(now.status, 'closed');
|
||||
assert.equal(now.deploy_state, 'deploying');
|
||||
assert.equal(decide(w.store, a.id, 'undo', 'sen', {}, T0 + 17_000).ok, false, 'a merge cannot be undone');
|
||||
assert.match(w.store.outbox(a.id).find((o) => o.kind === 'reply')!.body, /Gas dari @sen lewat Labuh/);
|
||||
|
||||
w.gl.pipelines.set('merge-g1', { id: 77, status: 'running', webUrl: 'https://gitlab.com/p/77' });
|
||||
await w.hub.tick(T0 + 60_000);
|
||||
assert.equal(w.store.ajuanById(a.id).deploy_state, 'deploying');
|
||||
w.gl.pipelines.get('merge-g1')!.status = 'success';
|
||||
await w.hub.tick(T0 + 61_000);
|
||||
assert.equal(w.store.ajuanById(a.id).deploy_state, 'deploying', 'pipelines are checked at most every 30 seconds');
|
||||
await w.hub.tick(T0 + 95_000);
|
||||
now = w.store.ajuanById(a.id);
|
||||
assert.equal(now.deploy_state, 'deployed');
|
||||
assert.equal(now.deploy_pipeline, 77);
|
||||
assert.equal(w.gl.sent.filter((t) => t.includes('berlabuh')).length, 1);
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('🚢 Gas api !20 dari @sen: di-merge merge-g1 ke production')));
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('🟢 api !20 siap gas') && t.endsWith('/#a1')));
|
||||
});
|
||||
|
||||
test('undo inside the grace period drops the Gas; a new commit drops it too', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
|
||||
assert.equal(decide(w.store, a.id, 'undo', 'sen', {}, T0 + 3_000).ok, true);
|
||||
await w.hub.tick(T0 + 20_000);
|
||||
assert.deepEqual(w.gl.merges, []);
|
||||
assert.equal(w.store.ajuanById(a.id).decision, null);
|
||||
|
||||
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0 + 30_000);
|
||||
w.gl.mrs.get(20)!.sha = 'g2';
|
||||
await w.hub.poll();
|
||||
assert.equal(w.store.ajuanById(a.id).decision, null);
|
||||
await w.hub.tick(T0 + 60_000);
|
||||
assert.deepEqual(w.gl.merges, []);
|
||||
assert.ok(w.gl.sent.some((t) => t.includes('Gas api !20 batal: ada commit baru')));
|
||||
});
|
||||
|
||||
test('the Hub checks GitLab again before merging, and dry mode stops before the merge', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
w.gl.mrs.get(20)!.mergeStatus = 'conflict';
|
||||
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
|
||||
await w.hub.tick(T0 + 16_000);
|
||||
assert.deepEqual(w.gl.merges, []);
|
||||
assert.equal(w.store.ajuanById(a.id).decision, null);
|
||||
assert.ok(w.gl.sent.some((t) => t.includes('tidak dijalankan: GitLab bilang conflict')));
|
||||
|
||||
const dry = await readyAjuan({ gas: { mode: 'dry', graceSeconds: 15 } }, 21);
|
||||
decide(dry.w.store, dry.a.id, 'gas', 'sen', { sha: 'g1' }, T0);
|
||||
await dry.w.hub.tick(T0 + 16_000);
|
||||
assert.deepEqual(dry.w.gl.merges, []);
|
||||
const after = dry.w.store.ajuanById(dry.a.id);
|
||||
assert.equal(after.deploy_state, 'dry');
|
||||
assert.equal(after.status, 'go');
|
||||
await dry.w.hub.tick(T0 + 17_000);
|
||||
assert.ok(dry.w.gl.sent.some((t) => t.startsWith('🧪 Gas uji coba api !21')));
|
||||
assert.equal(decide(dry.w.store, dry.a.id, 'undo', 'sen', {}, T0 + 20_000).ok, true, 'a dry Gas can be undone');
|
||||
});
|
||||
|
||||
test('Tunda and Tolak reach the MR after the grace period; undo takes them back there', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
decide(w.store, a.id, 'tunda', 'sen', { note: 'tunggu jam sepi' }, T0);
|
||||
assert.deepEqual(allowedActions(w.store.ajuanById(a.id), false), ['gas', 'undo', 'tolak']);
|
||||
await w.hub.tick(T0 + 16_000);
|
||||
const replies = () => w.store.outbox(a.id).filter((o) => o.kind === 'reply').map((o) => o.body);
|
||||
assert.match(replies()[0], /Ditunda oleh @sen/);
|
||||
assert.match(replies()[0], /tunggu jam sepi/);
|
||||
decide(w.store, a.id, 'undo', 'sen', {}, T0 + 20_000);
|
||||
await w.hub.tick(T0 + 40_000);
|
||||
assert.match(replies()[1], /membatalkan tunda/);
|
||||
|
||||
decide(w.store, a.id, 'tolak', 'sen', {}, T0 + 50_000);
|
||||
decide(w.store, a.id, 'undo', 'sen', {}, T0 + 52_000);
|
||||
await w.hub.tick(T0 + 80_000);
|
||||
assert.equal(replies().length, 2, 'a Tolak undone inside the grace period never reaches the MR');
|
||||
decide(w.store, a.id, 'tolak', 'sen', { note: 'endpoint masih dipakai' }, T0 + 90_000);
|
||||
await w.hub.tick(T0 + 110_000);
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('⛔ api !20 ditolak @sen: endpoint masih dipakai')));
|
||||
assert.ok(!w.gl.sent.some((t) => t.includes('Ditunda')), 'Tunda stays in the MR');
|
||||
});
|
||||
|
||||
test('failed deploys, reminders and a flaky Telegram', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
const status_at = w.store.ajuanById(a.id).status_at!;
|
||||
w.gl.sendFails = 1;
|
||||
await w.hub.tick(Date.parse(status_at) + 1_000);
|
||||
assert.equal(w.gl.sent.length, 0, 'the first send failed');
|
||||
await w.hub.tick(Date.parse(status_at) + 30_000);
|
||||
assert.equal(w.gl.sent.length, 0, 'retried only after a minute');
|
||||
await w.hub.tick(Date.parse(status_at) + 62_000);
|
||||
assert.equal(w.gl.sent.length, 1);
|
||||
await w.hub.tick(Date.parse(status_at) + 4 * 3600_000 + 120_000);
|
||||
await w.hub.tick(Date.parse(status_at) + 4 * 3600_000 + 240_000);
|
||||
assert.equal(w.gl.sent.filter((t) => t.includes('sudah 4 jam siap gas')).length, 1);
|
||||
|
||||
// Merged by hand in GitLab: Labuh follows its deploy as well.
|
||||
w.gl.mrs.get(20)!.state = 'merged';
|
||||
w.gl.mrs.get(20)!.mergeSha = 'm9';
|
||||
await w.hub.poll();
|
||||
await w.hub.drain();
|
||||
w.gl.pipelines.set('m9', { id: 90, status: 'failed', webUrl: 'https://gitlab.com/p/90' });
|
||||
await w.hub.tick(Date.parse(status_at) + 6 * 3600_000);
|
||||
assert.equal(w.store.ajuanById(a.id).deploy_state, 'failed');
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('🚨 Deploy api !20 gagal')));
|
||||
});
|
||||
|
||||
test('a changed rubric re-reviews the same commit in the same thread; an unchanged one does not', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
w.store.enqueue(a.id, 'recheck', {});
|
||||
await w.hub.drain();
|
||||
assert.deepEqual(w.calls.review, [null], 'same commit, same rubric: skipped');
|
||||
w.gl.rubric = 'def';
|
||||
w.script(ok(checked('no_go', 'R12')));
|
||||
w.store.enqueue(a.id, 'recheck', {});
|
||||
await w.hub.drain();
|
||||
assert.deepEqual(w.calls.review, [null, 'g1'], 'the re-review is told the commit it already saw');
|
||||
assert.deepEqual(w.calls.connect, [null, 't1']);
|
||||
const now = w.store.ajuanById(a.id);
|
||||
assert.equal(now.status, 'no_go');
|
||||
assert.equal(now.rubric_version, 'def');
|
||||
assert.match(w.store.outbox(a.id).filter((o) => o.kind === 'reply').pop()!.body, /Rubrik berubah; review ulang commit `g1`: 🔴 Tahan \(1 harus dibenahi\)/);
|
||||
});
|
||||
|
||||
test('a repo that deploys by tag waits for the release tag, then follows its pipeline', async () => {
|
||||
const { w, a } = await readyAjuan({ deployBy: { [PROJECT]: { production: 'tag' } } });
|
||||
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
|
||||
await w.hub.tick(T0 + 16_000);
|
||||
let now = w.store.ajuanById(a.id);
|
||||
assert.equal(now.deploy_state, 'awaiting_release');
|
||||
assert.ok(w.gl.sent.some((t) => t.includes('deploy jalan setelah tag rilis dibuat')));
|
||||
assert.match(w.store.outbox(a.id).find((o) => o.kind === 'reply')!.body, /setelah tag rilis dibuat/);
|
||||
|
||||
// A push pipeline on the branch is not the deploy, and no tag for hours is not a failure.
|
||||
w.gl.pipelines.set('merge-g1', { id: 70, status: 'success', webUrl: 'https://gitlab.com/p/70' });
|
||||
await w.hub.tick(T0 + 10 * 3600_000);
|
||||
assert.equal(w.store.ajuanById(a.id).deploy_state, 'awaiting_release');
|
||||
|
||||
w.gl.tags.set('merge-g1', { name: 'v1.4.0', sha: 'tagsha' });
|
||||
await w.hub.tick(T0 + 11 * 3600_000);
|
||||
now = w.store.ajuanById(a.id);
|
||||
assert.deepEqual([now.deploy_state, now.deploy_ref], ['deploying', 'v1.4.0']);
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('🏷️ api !20 masuk rilis v1.4.0')));
|
||||
|
||||
w.gl.pipelines.set('v1.4.0', { id: 80, status: 'success', webUrl: 'https://gitlab.com/p/80' });
|
||||
await w.hub.tick(T0 + 12 * 3600_000);
|
||||
now = w.store.ajuanById(a.id);
|
||||
assert.deepEqual([now.deploy_state, now.deploy_pipeline], ['deployed', 80]);
|
||||
});
|
||||
|
||||
test('the deploy mode is per target branch: staging deploys on merge even where production waits for a tag', async () => {
|
||||
const { w, a } = await readyAjuan({ deployBy: { [PROJECT]: { production: 'tag' } } });
|
||||
w.store.update(a.id, { target_branch: 'staging' });
|
||||
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
|
||||
await w.hub.tick(T0 + 16_000);
|
||||
const now = w.store.ajuanById(a.id);
|
||||
assert.deepEqual([now.deploy_state, now.deploy_ref], ['deploying', 'staging']);
|
||||
});
|
||||
|
||||
// ---- Releases for tag-deployed branches ----
|
||||
|
||||
const BOARD = { host: '127.0.0.1', port: 0, publicUrl: 'http://localhost', gitlabClientId: null, approvers: ['sen'], lanes: [{ name: 'Prod', branches: ['production'] }], doneHours: 12 };
|
||||
const viewer = (approver: boolean) => ({ username: approver ? 'sen' : 'dev', name: '', approver, projects: [PROJECT] });
|
||||
|
||||
test('tag numbers: versions compare as numbers and the proposal is the next patch', () => {
|
||||
assert.equal(latestTag(['v1.4.9', 'backup/x', 'v1.4.10', 'v1.3.99']), 'v1.4.10');
|
||||
assert.equal(nextTag('v1.4.10'), 'v1.4.11');
|
||||
assert.equal(nextTag(null), 'v0.1.0');
|
||||
assert.match(tagProblem('1.5.0', ['v1.4.10'])!, /vX\.Y\.Z/);
|
||||
assert.match(tagProblem('v1.4.10', ['v1.4.10'])!, /sudah ada/);
|
||||
assert.match(tagProblem('v1.4.2', ['v1.4.10'])!, /lebih baru dari v1\.4\.10/);
|
||||
assert.equal(tagProblem('v1.5.0', ['v1.4.10']), null);
|
||||
});
|
||||
|
||||
async function awaitingRelease() {
|
||||
const { w, a } = await readyAjuan({ deployBy: { [PROJECT]: { production: 'tag' } }, gas: { mode: 'live', graceSeconds: 15 } });
|
||||
w.gl.tagList = [{ name: 'v1.4.10', sha: 't10' }, { name: 'v1.4.9', sha: 't9' }];
|
||||
w.gl.changes = { mrs: [{ iid: 20, title: 'Fix recording', author: 'dev' }], commits: [{ sha: 'direct1234567', title: 'hotfix config' }] };
|
||||
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
|
||||
await w.hub.tick(T0 + 16_000); // merges, then proposes
|
||||
return { w, a: w.store.ajuanById(a.id) };
|
||||
}
|
||||
|
||||
test('a merge waiting for a tag gets a release proposal with its changelog, confirmed on the board and tagged after the grace period', async () => {
|
||||
const { w, a } = await awaitingRelease();
|
||||
assert.equal(a.deploy_state, 'awaiting_release');
|
||||
const r = w.store.openRelease(PROJECT, 'production')!;
|
||||
assert.deepEqual([r.state, r.sha, r.from_tag, r.proposed_tag], ['proposed', 'merge-g1', 'v1.4.10', 'v1.4.11']);
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('🏷️ Usulan rilis api v1.4.11 (production, 2 perubahan)')));
|
||||
|
||||
// The board: approvers may release, developers only see it.
|
||||
const events = w.store.events(a.id);
|
||||
const asSen = viewAjuan(a, events, BOARD, viewer(true), undefined, r);
|
||||
assert.deepEqual(asSen.release!.actions, ['release']);
|
||||
assert.equal(asSen.needsYou, true);
|
||||
assert.match(asSen.reason, /usul rilis v1\.4\.11/);
|
||||
assert.deepEqual(viewAjuan(a, events, BOARD, viewer(false), undefined, r).release!.actions, []);
|
||||
|
||||
// The approver may change the number, within the pattern and above the last tag.
|
||||
assert.equal(decideRelease(w.store, r.id, 'release', 'sen', 'v1.4.10', T0 + 60_000).ok, false);
|
||||
assert.equal(decideRelease(w.store, r.id, 'release', 'sen', 'v1.5.0', T0 + 60_000).ok, true);
|
||||
assert.equal(decideRelease(w.store, r.id, 'undo', 'sen', undefined, T0 + 61_000).ok, true, 'undo inside the grace period');
|
||||
assert.equal(w.store.releaseById(r.id)!.state, 'proposed');
|
||||
assert.equal(decideRelease(w.store, r.id, 'release', 'sen', 'v1.5.0', T0 + 62_000).ok, true);
|
||||
|
||||
await w.hub.tick(T0 + 70_000);
|
||||
assert.deepEqual(w.gl.created, [], 'nothing is tagged during the grace period');
|
||||
await w.hub.tick(T0 + 78_000);
|
||||
assert.equal(w.gl.created.length, 1);
|
||||
const tag = w.gl.created[0];
|
||||
assert.deepEqual([tag.name, tag.sha], ['v1.5.0', 'merge-g1']);
|
||||
assert.match(tag.message, /^v1\.5\.0 \(sejak v1\.4\.10\)/);
|
||||
assert.match(tag.message, /- Fix recording \(!20, @dev\)/);
|
||||
assert.match(tag.message, /Commit langsung, tanpa MR:\n- direct12 hotfix config/);
|
||||
assert.match(tag.message, /disetujui @sen/);
|
||||
assert.equal(w.store.releaseById(r.id)!.state, 'tagged');
|
||||
assert.equal(decideRelease(w.store, r.id, 'undo', 'sen', undefined, T0 + 79_000).ok, false, 'a tag cannot be undone');
|
||||
|
||||
// The existing release tracking picks the new tag up and follows its pipeline.
|
||||
await w.hub.tick(T0 + 120_000);
|
||||
const now = w.store.ajuanById(a.id);
|
||||
assert.deepEqual([now.deploy_state, now.deploy_ref], ['deploying', 'v1.5.0']);
|
||||
assert.equal(w.store.openRelease(PROJECT, 'production'), undefined, 'no second proposal');
|
||||
});
|
||||
|
||||
test('a release is refused when the branch moved or the tag appeared meanwhile; dry mode makes no tag', async () => {
|
||||
const { w } = await awaitingRelease();
|
||||
const r = w.store.openRelease(PROJECT, 'production')!;
|
||||
decideRelease(w.store, r.id, 'release', 'sen', 'v1.4.11', T0 + 60_000);
|
||||
w.gl.head = 'pushed-later';
|
||||
await w.hub.tick(T0 + 80_000);
|
||||
assert.deepEqual(w.gl.created, []);
|
||||
assert.equal(w.store.releaseById(r.id)!.state, 'superseded');
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('✋ Rilis api v1.4.11 tidak dijalankan: production sudah bergerak')));
|
||||
// The next deploy check proposes again, from the new head.
|
||||
await w.hub.tick(T0 + 120_000);
|
||||
const fresh = w.store.openRelease(PROJECT, 'production')!;
|
||||
assert.deepEqual([fresh.state, fresh.sha], ['proposed', 'pushed-later']);
|
||||
|
||||
decideRelease(w.store, fresh.id, 'release', 'sen', 'v1.4.11', T0 + 130_000);
|
||||
w.gl.tagList.unshift({ name: 'v1.4.11', sha: 'someone-else' });
|
||||
await w.hub.tick(T0 + 150_000);
|
||||
assert.deepEqual(w.gl.created, []);
|
||||
assert.match(w.store.releaseById(fresh.id)!.result!, /sudah ada/);
|
||||
assert.equal(w.store.releaseById(fresh.id)!.state, 'proposed');
|
||||
|
||||
(w.hub.config.gas as any).mode = 'dry';
|
||||
decideRelease(w.store, fresh.id, 'release', 'sen', 'v1.4.12', T0 + 160_000);
|
||||
await w.hub.tick(T0 + 180_000);
|
||||
assert.deepEqual(w.gl.created, [], 'dry mode never tags');
|
||||
assert.deepEqual([w.store.releaseById(fresh.id)!.state, w.store.releaseById(fresh.id)!.result], ['proposed', 'uji coba: semua cek lolos, tag tidak dibuat']);
|
||||
assert.ok(w.gl.sent.some((t) => t.startsWith('🧪 Rilis uji coba api v1.4.12')));
|
||||
});
|
||||
|
||||
test('a rejected MR can be closed after the grace period; undo drops only the close', async () => {
|
||||
const { w, a } = await readyAjuan();
|
||||
decide(w.store, a.id, 'tolak', 'sen', { note: 'masih dipakai FE' }, T0);
|
||||
assert.deepEqual(allowedActions(w.store.ajuanById(a.id), false), ['close', 'undo']);
|
||||
assert.equal(decide(w.store, a.id, 'close', 'sen', {}, T0 + 1_000).ok, true);
|
||||
assert.deepEqual(allowedActions(w.store.ajuanById(a.id), false, true), ['undo']);
|
||||
|
||||
// Undo while the close waits: the Tolak stays and is still announced.
|
||||
assert.equal(decide(w.store, a.id, 'undo', 'sen', {}, T0 + 2_000).ok, true);
|
||||
assert.equal(w.store.ajuanById(a.id).decision, 'tolak');
|
||||
await w.hub.tick(T0 + 20_000);
|
||||
assert.deepEqual(w.gl.closed, []);
|
||||
assert.match(w.store.outbox(a.id).filter((o) => o.kind === 'reply')[0].body, /Ditolak oleh @sen/);
|
||||
|
||||
decide(w.store, a.id, 'close', 'sen', {}, T0 + 30_000);
|
||||
await w.hub.tick(T0 + 40_000);
|
||||
assert.deepEqual(w.gl.closed, [], 'nothing closes during the grace period');
|
||||
await w.hub.tick(T0 + 46_000);
|
||||
assert.deepEqual(w.gl.closed, [20]);
|
||||
const now = w.store.ajuanById(a.id);
|
||||
assert.deepEqual([now.status, now.closed_state], ['closed', 'closed']);
|
||||
assert.match(w.store.outbox(a.id).filter((o) => o.kind === 'reply').at(-1)!.body, /ditutup oleh @sen lewat Labuh/);
|
||||
assert.equal(decide(w.store, a.id, 'undo', 'sen', {}, T0 + 47_000).ok, false);
|
||||
|
||||
// Dry mode checks and leaves the MR open.
|
||||
const dry = await readyAjuan({ gas: { mode: 'dry', graceSeconds: 15 } }, 21);
|
||||
decide(dry.w.store, dry.a.id, 'tolak', 'sen', {}, T0);
|
||||
decide(dry.w.store, dry.a.id, 'close', 'sen', {}, T0);
|
||||
await dry.w.hub.tick(T0 + 16_000);
|
||||
assert.deepEqual(dry.w.gl.closed, []);
|
||||
assert.equal(dry.w.store.ajuanById(dry.a.id).status, 'go');
|
||||
});
|
||||
Reference in New Issue
Block a user