Files
labuh/test/hub.test.ts
Adnan Zahir 112923640d 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>
2026-11-06 19:39:58 +07:00

602 lines
30 KiB
TypeScript

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');
});