Files
labuh/test/hub.test.ts

759 lines
37 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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: 'Labuh', 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[],
// Asks for a mergeability recheck; what GitLab answers on the next read (null: it stays as it is).
rechecks: [] as number[],
recheckTo: 'mergeable' as string | null,
};
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 });
},
recheckMergeStatus: async (ref) => {
gl.rechecks.push(ref.iid);
const m = gl.mrs.get(ref.iid)!;
const before = m.mergeStatus ?? 'mergeable';
if (gl.recheckTo) m.mergeStatus = gl.recheckTo;
return before;
},
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: '@labuh 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/);
});
const deployFinding = (kind: 'bad' | 'todo' | 'ok'): Checked => ({
verdict: kind === 'bad' ? 'no_go' : 'go',
reason: 'urutan deploy',
findings: [{ kind, text: 'API naik sebelum migrasi', evidence: [{ type: 'file', path: '.gitlab-ci.yml', line: 118, job_id: null, rule_id: null, label: '.gitlab-ci.yml:118', url: 'https://x' }] }],
postDeploy: [],
dropped: [],
overrides: [],
});
const codeFinding: Checked = {
verdict: 'go',
reason: 'aman',
findings: [{ kind: 'todo', text: 'tambah test', evidence: [{ type: 'rubric', path: null, line: null, job_id: null, rule_id: 'R8', label: 'rubric R8', url: 'file:///r#r8' }] }],
postDeploy: [],
dropped: [],
overrides: [],
};
test('deploy findings tag devops once; code findings and ok checks do not', async () => {
const w = world({ devops: { users: ['ops1', 'ops2'] } });
w.gl.mrs.set(8, { sha: 'a1', state: 'opened', labels: ['labuh'] });
w.script(ok(deployFinding('bad')), ok(deployFinding('todo')), ok(codeFinding), ok(deployFinding('ok')), ok(deployFinding('todo')));
const step = async (sha: string) => {
w.gl.mrs.get(8)!.sha = sha;
await w.hub.poll();
await w.hub.drain();
const out = w.store.outbox(w.store.ajuan(PROJECT, 8)!.id);
return { verdict: out.find((o) => o.kind === 'verdict')!.body, replies: out.filter((o) => o.kind === 'reply').map((o) => o.body) };
};
let r = await step('a1');
assert.match(r.verdict, /Untuk devops @ops1 @ops2/, 'a bad finding on a CI file tags devops in the new verdict note');
r = await step('a2');
assert.match(r.verdict, /Untuk devops/);
assert.doesNotMatch(r.replies[0], /@ops1/, 'still a deploy finding: devops is not tagged again');
r = await step('a3');
assert.doesNotMatch(r.verdict, /Untuk devops/, 'a code-only todo leaves devops out');
r = await step('a4');
assert.doesNotMatch(r.verdict, /Untuk devops/, 'an ok check on a CI file is not a deploy finding');
r = await step('a5');
assert.match(r.replies.at(-1)!, /Untuk devops @ops1 @ops2/, 'a deploy finding that comes back tags devops in the re-review note');
});
test('a rubric R13 citation tags devops; without devops users nothing is added', async () => {
const r13: Checked = { ...codeFinding, findings: [{ ...codeFinding.findings[0], evidence: [{ ...codeFinding.findings[0].evidence[0], rule_id: 'R13', label: 'rubric R13' }] }] };
const w = world({ devops: { users: ['ops1'] } });
w.gl.mrs.set(9, { sha: 'b1', state: 'opened', labels: ['labuh'] });
w.script(ok(r13));
await w.hub.poll();
await w.hub.drain();
assert.match(w.store.outbox(w.store.ajuan(PROJECT, 9)!.id).find((o) => o.kind === 'verdict')!.body, /Untuk devops @ops1/);
const plain = world();
plain.gl.mrs.set(9, { sha: 'b1', state: 'opened', labels: ['labuh'] });
plain.script(ok(deployFinding('bad')));
await plain.hub.poll();
await plain.hub.drain();
assert.doesNotMatch(plain.store.outbox(plain.store.ajuan(PROJECT, 9)!.id).find((o) => o.kind === 'verdict')!.body, /devops/);
});
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 — @labuh`, author: 'someone', system: false, createdAt: '' },
{ id: 11, body: 'added 1 commit @labuh', author: 'dev', system: true, createdAt: '' },
{ id: 12, body: '@Labuh kenapa ini tahan?', author: 'dev', system: false, createdAt: '' },
]);
await w.hub.poll();
await w.hub.drain();
assert.deepEqual(w.calls.ask, ['@Labuh 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: 'labuh_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('Gas waits while GitLab has not computed mergeability, asking it to recheck', async () => {
const { w, a } = await readyAjuan();
w.gl.mrs.get(20)!.mergeStatus = 'unchecked';
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
await w.hub.tick(T0 + 16_000);
assert.deepEqual(w.gl.rechecks, [20], 'asks GitLab once');
assert.deepEqual(w.gl.merges, [], 'does not merge on the first pass');
assert.equal(w.store.ajuanById(a.id).decision, 'gas', 'keeps the decision while waiting');
assert.ok(!w.gl.sent.some((t) => t.includes('tidak dijalankan')));
await w.hub.tick(T0 + 21_000);
assert.deepEqual(w.gl.merges, [{ iid: 20, sha: 'g1' }]);
assert.deepEqual(w.gl.rechecks, [20]);
});
test('Gas gives up when GitLab stays unchecked, re-asking every 30 seconds', async () => {
const { w, a } = await readyAjuan();
w.gl.mrs.get(20)!.mergeStatus = 'unchecked';
w.gl.recheckTo = null;
decide(w.store, a.id, 'gas', 'sen', { sha: 'g1' }, T0);
for (let t = T0 + 16_000; t < T0 + 15_000 + 120_000; t += 5_000) await w.hub.tick(t);
assert.equal(w.gl.rechecks.length, 4);
assert.equal(w.store.ajuanById(a.id).decision, 'gas');
await w.hub.tick(T0 + 15_000 + 120_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 masih unchecked setelah 2 menit')));
});
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');
});
// lti-api !1388 (2026-11-09): 9router answered "high demand" and Codex ended both turns
// `failed` with no message. Labuh read the empty text as invalid JSON, told the model its
// verdict was rejected, and gave up at once with a misleading comment.
const unavailable = () => {
const e = new Error('Model tidak bisa dihubungi: We’re currently experiencing high demand');
e.name = 'ReviewerUnavailable';
throw e;
};
test('a turn the provider failed is not a rejected verdict: review stops after one turn', 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: '', usage: null, commands: [], refused: [], error: { message: 'We’re currently experiencing high demand', info: 'internal_server_error' } };
},
},
} as unknown as Session;
await assert.rejects(review(s), (e: any) => e.name === 'ReviewerUnavailable' && /high demand/.test(e.message));
assert.equal(turns.length, 1, 'no "Labuh rejected your verdict" turn follows');
});
test('provider failures make the queue wait and retry, then the review lands', async () => {
const w = world();
w.gl.mrs.set(21, { sha: 'abab1111', state: 'opened', labels: ['labuh'] });
w.script(unavailable, unavailable, ok(checked('go', 'Aman')));
await w.hub.poll();
const t0 = Date.now();
assert.equal(await w.hub.drain(t0), 0);
assert.equal(await w.hub.drain(t0 + 60_000), 0, 'still waiting out the first 2 minutes');
assert.equal(w.calls.review.length, 1, 'no review call while waiting');
assert.equal(await w.hub.drain(t0 + 2 * 60_000), 0, 'second failure: now waits 4 minutes');
assert.equal(await w.hub.drain(t0 + 5 * 60_000), 0);
assert.equal(await w.hub.drain(t0 + 6 * 60_000), 1);
assert.equal(w.store.ajuan(PROJECT, 21)!.status, 'go');
assert.equal(w.store.outbox(w.store.ajuan(PROJECT, 21)!.id).filter((o) => /Perlu dicek manual/.test(o.body)).length, 0, 'no error comment on the way');
});
test('a provider down for about an hour ends in a manual check that says so', async () => {
const w = world();
w.gl.mrs.set(22, { sha: 'cdcd2222', state: 'opened', labels: ['labuh'] });
w.script(unavailable, unavailable, unavailable, unavailable, unavailable, unavailable);
await w.hub.poll();
let t = Date.now();
for (let i = 0; i < 6; i++, t += 33 * 60_000) await w.hub.drain(t);
const a = w.store.ajuan(PROJECT, 22)!;
assert.equal(w.calls.review.length, 6);
assert.equal(a.status, 'reviewer_error');
const body = w.store.outbox(a.id)[0].body;
assert.match(body, /tidak bisa dihubungi/);
assert.doesNotMatch(body, /not valid JSON/);
assert.equal(w.store.nextEvent(), undefined);
});