// Milestone 1: the Hub. Polls GitLab for ajuan, queues events, runs the reviewer per event and // publishes templated comments (to a local outbox in shadow mode). See docs/SPEC.md → M1. import { mkdirSync, writeFileSync, readFileSync } from 'node:fs'; import path from 'node:path'; import type { MrInfo, MrRef, MrSummary, Note } from './gitlab.ts'; import type { TurnResult } from './codex.ts'; import type { ReviewOutcome, Reviewer, Session } from './review.ts'; import type { Checked } from './contract.ts'; import { Store, type Ajuan, type OutboxItem, type QueuedEvent, type Release, type ReleaseChanges } from './store.ts'; import { latestTag, nextTag, releaseNotes, tagProblem } from './release.ts'; import { verdictComment, errorComment, replyComment, rereviewComment, devopsComment, needsDevops, decisionComment, gasComment, closeComment, ajuanNote, VERDICT_MARKER, type Stamp } from './render.ts'; export type HubConfig = { mode: 'shadow' | 'live'; pollSeconds: number; label: string; projects: string[]; // The bot's GitLab username once it exists; its own notes are ignored and `@` is a mention. botUsername: string | null; // How a merge deploys, per project and target branch: 'merge' (the target branch's push // pipeline, the default) or 'tag' (a later release tag's pipeline). A plain value covers every branch. deployBy?: Record>; // Gas (M3). 'dry' runs every check and stops before the merge; 'live' merges with the merge token. gas?: { mode: 'dry' | 'live'; graceSeconds: number }; // Notifications to the approver (M3). Without a Telegram chat they only go to the Hub's log. notify?: { telegramChatId: string | null; boardUrl: string; remindHours: number }; // Deploy setup belongs to devops: these GitLab users are tagged when a bad or todo finding // cites one of `rules` or points at a deploy file (CI, Dockerfile, compose, manifests). devops?: { users: string[]; rules?: string[] }; }; type DeployBy = 'merge' | 'tag'; const DEVOPS_RULES = ['R9', 'R13']; const GAS_DEFAULT = { mode: 'dry' as const, graceSeconds: 15 }; const NOTIFY_DEFAULT = { telegramChatId: null, boardUrl: 'http://localhost:4810', remindHours: 4 }; // Pipelines are checked at most this often; a deploy that has not finished after DEPLOY_LIMIT is reported. const DEPLOY_CHECK_MS = 30_000; const DEPLOY_LIMIT_MS = 3 * 3600_000; const NO_PIPELINE_MS = 15 * 60_000; // Everything the Hub needs from the outside world, so tests can replace it. export type Ports = { gitlab: { listLabelledMrs(project: string, label: string): Promise; mrSummary(ref: MrRef): Promise; listNotes(ref: MrRef, afterId: number): Promise; postNote(ref: MrRef, body: string): Promise; updateNote(ref: MrRef, noteId: number, body: string): Promise; recheckMergeStatus(ref: MrRef): Promise; mergeMr(ref: MrRef, sha: string): Promise<{ mergeSha: string | null; state: string }>; closeMr(ref: MrRef): Promise<{ state: string }>; pipelineFor(project: string, sha: string | null, ref: string): Promise<{ id: number; status: string; webUrl: string } | null>; releaseTagFor(project: string, mergeSha: string): Promise<{ name: string; sha: string } | null>; releaseBase(project: string, branch: string): Promise<{ head: string; tags: Array<{ name: string; sha: string }> }>; releaseChanges(project: string, branch: string, from: string | null, to: string): Promise; createTag(project: string, name: string, sha: string, message: string): Promise<{ name: string; sha: string }>; }; // Null: no channel configured; notifications are only logged. notifier: { send(text: string): Promise } | null; reviewer: { rubricVersion(): string; prepare(ref: MrRef, workDir: string): Promise; connect(mr: MrInfo, workDir: string, threadId: string | null): Promise; review(s: Session, previousSha: string | null): Promise; ask(s: Session, question: string): Promise; }; }; const MAX_ATTEMPTS = 3; // GitLab statuses that mean "not computed yet", not "no": Gas asks for a recheck and waits. const PENDING_MERGE_STATUS = new Set(['unchecked', 'checking', 'preparing', 'approvals_syncing']); const MERGE_STATUS_WAIT_MS = 2 * 60_000; const RECHECK_EVERY_MS = 30_000; export class Hub { readonly store: Store; readonly config: HubConfig; readonly reviewer: Reviewer; readonly ports: Ports; readonly workRoot: string; readonly log: (line: string) => void; private lastDeployCheck = 0; // When each waiting Gas last asked GitLab to recompute mergeability (in memory; a restart just asks again). private rechecked = new Map(); private notifyRetryAt = 0; constructor(store: Store, config: HubConfig, reviewer: Reviewer, ports: Ports, workRoot: string, log: (line: string) => void = () => {}) { this.store = store; this.config = config; this.reviewer = reviewer; this.ports = ports; this.workRoot = workRoot; this.log = log; } private get gasConfig() { return { ...GAS_DEFAULT, ...this.config.gas }; } private get notifyConfig() { return { ...NOTIFY_DEFAULT, ...this.config.notify }; } private label(a: Ajuan): string { return `${a.project.split('/').pop()} !${a.iid}`; } // One line for the approver plus a link to the ajuan on the board; sent once per key. private notify(key: string, a: Ajuan, text: string) { this.store.notify(key, a.id, `${text}\n${this.notifyConfig.boardUrl}/#a${a.id}`); } private ref(a: Ajuan): MrRef { return { host: 'gitlab.com', projectPath: a.project, iid: a.iid }; } workDir(a: Ajuan): string { return path.join(this.workRoot, 'ajuan', `${a.project.replace(/\//g, '__')}-${a.iid}`); } private mentionPattern(): RegExp { const names = [this.reviewer.name, this.config.botUsername].filter(Boolean).map((n) => n!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); return new RegExp(`@(${names.join('|')})\\b`, 'i'); } private isOwnNote(n: Note): boolean { return n.system || n.body.includes(VERDICT_MARKER) || (!!this.config.botUsername && n.author === this.config.botUsername); } // Starting point for mentions: only notes written after the ajuan exists count. private async latestNoteId(ref: MrRef): Promise { const notes = await this.ports.gitlab.listNotes(ref, 0); return notes.reduce((m, n) => Math.max(m, n.id), 0); } async add(ref: MrRef, source: Ajuan['source'] = 'manual'): Promise { const m = await this.ports.gitlab.mrSummary(ref); const { ajuan, created } = this.store.upsertAjuan({ project: m.projectPath, iid: m.iid, webUrl: m.webUrl, title: m.title, sha: m.sha, author: m.author, targetBranch: m.targetBranch }, await this.latestNoteId(ref), source); if (created) this.log(`ajuan baru: ${m.projectPath} !${m.iid}`); else if (ajuan.status === 'closed' && m.state === 'opened') this.reopen(ajuan, m.sha); return this.store.ajuanById(ajuan.id); } private reopen(a: Ajuan, sha: string) { this.store.update(a.id, { status: 'queued', head_sha: sha, closed_state: null }); this.store.enqueue(a.id, 'opened', { sha }); this.log(`ajuan dibuka lagi: ${a.project} !${a.iid}`); } // Reconcile GitLab into the store: new labelled MRs, new heads, closed MRs, mentions. async poll(): Promise { for (const project of this.config.projects) { for (const m of await this.ports.gitlab.listLabelledMrs(project, this.config.label)) { const known = this.store.ajuan(m.projectPath, m.iid); if (!known) await this.add({ host: 'gitlab.com', projectPath: m.projectPath, iid: m.iid }, 'label'); else if (known.status === 'closed') this.reopen(known, m.sha); } } for (const a of this.store.openAjuan()) { const ref = this.ref(a); const m = await this.ports.gitlab.mrSummary(ref); const labelGone = a.source === 'label' && !m.labels.includes(this.config.label); if (m.state !== 'opened' || labelGone) { if (!this.store.hasPending(a.id, 'closed')) this.store.enqueue(a.id, 'closed', { state: m.state, labelGone, mergeSha: m.mergeSha ?? null }); continue; } if (m.sha !== a.head_sha) { this.store.update(a.id, { head_sha: m.sha }); this.newCommitClearsDecision(a); if (!this.store.hasPending(a.id, 'new_commit') && !this.store.hasPending(a.id, 'opened')) this.store.enqueue(a.id, 'new_commit', { sha: m.sha }); this.log(`commit baru: ${a.project} !${a.iid} → ${m.sha.slice(0, 8)}`); } const notes = await this.ports.gitlab.listNotes(ref, a.last_note_id); const mention = this.mentionPattern(); for (const n of notes) { if (!this.isOwnNote(n) && mention.test(n.body)) { this.store.enqueue(a.id, 'mention', { question: n.body, author: n.author, noteId: n.id }); this.log(`mention: ${a.project} !${a.iid} dari @${n.author}`); } } if (notes.length) this.store.update(a.id, { last_note_id: Math.max(...notes.map((n) => n.id)) }); } } // A new commit is a new ajuan for the approver: Tunda and Tolak lapse, and a Gas still in its // grace period is dropped. A Gas the Hub already took is refused by its own commit check. private newCommitClearsDecision(a: Ajuan) { if (!a.decision || !this.store.cancelActions(a.id, 'dibatalkan: commit baru')) return; this.store.update(a.id, { decision: null, decision_by: null, decision_at: null, decision_note: null, deploy_state: a.deploy_state === 'dry' ? null : a.deploy_state }); if (a.decision === 'gas') this.notify(`gas-dropped:${a.id}:${a.decision_at}`, a, `↩️ Gas ${this.label(a)} batal: ada commit baru, ${this.reviewer.name} review ulang.`); this.log(`${a.project} !${a.iid}: keputusan ${a.decision} gugur karena commit baru`); } // Works through the queue in order. Returns the number of events finished. async drain(): Promise { let done = 0; for (let ev = this.store.nextEvent(); ev; ev = this.store.nextEvent()) { if (!(await this.process(ev))) break; done++; } return done; } // Returns false when the event failed and stays queued for a later try. async process(ev: QueuedEvent): Promise { const a = this.store.ajuanById(ev.ajuan_id); this.store.startEvent(ev.id); try { const result = await this.handle(ev, a); this.store.finishEvent(ev.id, result); this.log(`${a.project} !${a.iid} ${ev.kind}: ${result}`); this.writeNote(this.store.ajuanById(a.id)); return true; } catch (e: any) { const msg = String(e?.message ?? e).slice(0, 300); this.log(`${a.project} !${a.iid} ${ev.kind} gagal (percobaan ${ev.attempts + 1}): ${msg}`); if (ev.attempts + 1 < MAX_ATTEMPTS) return false; this.store.finishEvent(ev.id, `failed: ${msg}`); if (ev.kind === 'opened' || ev.kind === 'new_commit' || ev.kind === 'recheck') { this.store.update(a.id, { status: 'reviewer_error' }); await this.publishVerdict(this.store.ajuanById(a.id), errorComment('reviewer_error', this.stamp(a, null), [msg])); this.notify(`error:${a.id}:${a.head_sha}`, a, `⚪ ${this.label(a)} perlu dicek manual: ${this.reviewer.name} gagal.`); } this.writeNote(this.store.ajuanById(a.id)); return true; } } private devopsFor(c: Checked): string[] { const d = this.config.devops; return d?.users.length && needsDevops(c, d.rules ?? DEVOPS_RULES) ? d.users : []; } private stamp(a: Ajuan, s: Session | null, sha?: string): Stamp { return { reviewer: this.reviewer.name, sha: sha ?? a.reviewed_sha ?? a.head_sha, model: s?.model ?? this.reviewer.model ?? 'default', effort: this.reviewer.effort, rubricVersion: s?.rubricVersion ?? '-' }; } private async handle(ev: QueuedEvent, a: Ajuan): Promise { if (ev.kind === 'closed') { // Merged in GitLab without Labuh's Gas (the manual path still works): follow its deploy too. const merged = !ev.payload.labelGone && ev.payload.state === 'merged'; this.store.update(a.id, { status: 'closed', closed_state: ev.payload.labelGone ? 'unlabelled' : ev.payload.state, ...(merged && !a.merge_sha ? this.afterMerge(a, ev.payload.mergeSha ?? null) : {}), }); return ev.payload.labelGone ? 'label dilepas' : `MR ${ev.payload.state}`; } if (a.status === 'closed') return 'dilewati: ajuan sudah selesai'; if (ev.kind === 'mention') return this.answer(ev, a); return this.reviewAjuan(a); } private async reviewAjuan(a: Ajuan): Promise { if (a.tokens >= this.reviewer.budgetTokensPerAjuan) { if (a.status !== 'over_budget') { this.store.update(a.id, { status: 'over_budget' }); await this.publishVerdict(a, errorComment('over_budget', this.stamp(a, null))); this.notify(`budget:${a.id}`, a, `⚪ ${this.label(a)} perlu dicek manual: jatah token ${this.reviewer.name} habis.`); } return 'jatah token habis'; } const workDir = this.workDir(a); mkdirSync(workDir, { recursive: true }); const mr = await this.ports.reviewer.prepare(this.ref(a), workDir); // The same commit is reviewed again only after an error or when the rubric changed. const rubric = this.ports.reviewer.rubricVersion(); if (mr.sha === a.reviewed_sha && a.status !== 'reviewer_error' && a.rubric_version === rubric) return `sudah direview di ${mr.sha.slice(0, 8)}`; this.store.update(a.id, { status: 'reviewing', head_sha: mr.sha, title: mr.title, target_branch: mr.targetBranch }); const s = await this.ports.reviewer.connect(mr, workDir, a.thread_id); try { // Saved before the turn, so a restart resumes this thread instead of starting over. this.store.update(a.id, { thread_id: s.threadId }); const previous = a.thread_id && a.reviewed_sha ? a.reviewed_sha : null; const out = await this.ports.reviewer.review(s, previous); const tokens = Math.max(a.tokens, s.usage?.totalTokens ?? 0); if (!out.ok) { this.store.update(a.id, { status: 'reviewer_error', tokens }); await this.publishVerdict(this.store.ajuanById(a.id), errorComment('reviewer_error', this.stamp(a, s, mr.sha), out.errors)); this.notify(`error:${a.id}:${mr.sha}`, a, `⚪ ${this.label(a)} perlu dicek manual: ${this.reviewer.name} gagal memberi hasil yang valid.`); return `reviewer error setelah ${out.attempts} percobaan`; } const devops = this.devopsFor(out.checked); // Devops is told once when deploy findings appear, not again on every push while they stay. const before = a.verdict_json ? (JSON.parse(a.verdict_json) as Checked) : null; const tellDevops = devops.length > 0 && !(before && this.devopsFor(before).length); const hadVerdictNote = this.store.outbox(a.id).some((o) => o.kind === 'verdict'); this.store.update(a.id, { status: out.checked.verdict, reviewed_sha: mr.sha, rubric_version: s.rubricVersion, verdict_json: JSON.stringify(out.checked), tokens }); await this.publishVerdict(this.store.ajuanById(a.id), verdictComment(out.checked, this.stamp(a, s, mr.sha), devops)); const noteId = this.store.outbox(a.id).find((o) => o.kind === 'verdict')?.note_id; const verdictUrl = noteId ? `${a.web_url}#note_${noteId}` : null; if (previous) { await this.publishReply(a, rereviewComment(out.checked, { sha: mr.sha, author: a.author, reviewer: this.reviewer.name, verdictUrl, rubricChanged: previous === mr.sha, devops: tellDevops ? devops : [] })); } else if (tellDevops && hadVerdictNote) { // An edited verdict note notifies nobody, so the mention goes in a note of its own. await this.publishReply(a, devopsComment(devops, verdictUrl)); } if (out.checked.verdict === 'go') this.notify(`ready:${a.id}:${mr.sha}`, a, `🟢 ${this.label(a)} siap gas: ${out.checked.reason}`); return `${out.checked.verdict} di ${mr.sha.slice(0, 8)}${out.attempts > 1 ? ' (percobaan ke-2)' : ''}`; } finally { s.client.close(); } } private async answer(ev: QueuedEvent, a: Ajuan): Promise { const question = { author: ev.payload.author ?? '', noteId: ev.payload.noteId ?? null }; if (!a.thread_id || !a.reviewed_sha) { await this.publishReply(a, replyComment('Review belum selesai. Pertanyaan ini dijawab setelah verdict pertama keluar; tanya lagi nanti.', question, this.stamp(a, null))); return 'belum ada review'; } if (a.tokens >= this.reviewer.budgetTokensPerAjuan) return 'jatah token habis'; const workDir = this.workDir(a); const mr = await this.ports.reviewer.prepare(this.ref(a), workDir); const s = await this.ports.reviewer.connect(mr, workDir, a.thread_id); try { const turn = await this.ports.reviewer.ask(s, ev.payload.question); this.store.update(a.id, { tokens: Math.max(a.tokens, s.usage?.totalTokens ?? 0) }); await this.publishReply(a, replyComment(turn.finalText || '(tidak ada jawaban)', question, this.stamp(a, s))); return 'dijawab'; } finally { s.client.close(); } } // ---- M3: board actions, deploys, reminders, notifications ---- // Runs every few seconds next to the review loop, so a Gas never waits behind a long review. async tick(now = Date.now()): Promise { await this.runActions(now); await this.runReleases(now); if (now - this.lastDeployCheck >= DEPLOY_CHECK_MS) { this.lastDeployCheck = now; await this.trackDeploys(now); } this.remind(now); if (now >= this.notifyRetryAt) await this.sendNotifications(now); } private async runActions(now: number) { const grace = this.gasConfig.graceSeconds * 1000; for (const ev of this.store.pendingActions()) { // Still undoable. An action claimed before a restart (attempts > 0) is finished now. if (ev.attempts === 0 && now - ev.payload.at < grace) continue; if (ev.attempts === 0 && !this.store.claimAction(ev.id)) continue; const a = this.store.ajuanById(ev.ajuan_id); try { const result = ev.kind === 'gas' ? await this.gas(a, ev, now) : ev.kind === 'close' ? await this.close(a, ev) : await this.announce(a, ev); if (result === null) continue; // still waiting on GitLab; the claimed event runs again next tick this.rechecked.delete(ev.id); this.store.finishEvent(ev.id, result); this.log(`${a.project} !${a.iid} ${ev.kind}: ${result}`); } catch (e: any) { // Not retried: a merge that failed is for the approver to look at and Gas again. this.rechecked.delete(ev.id); const msg = String(e?.message ?? e).slice(0, 300); this.store.finishEvent(ev.id, `failed: ${msg}`); this.log(`${a.project} !${a.iid} ${ev.kind} gagal: ${msg}`); if (ev.kind === 'gas') { this.clearDecision(a); this.notify(`gas-failed:${ev.id}`, a, `❗ Gas ${this.label(a)} gagal: ${msg.slice(0, 160)}`); } if (ev.kind === 'close') this.notify(`close-failed:${ev.id}`, a, `❗ Tutup MR ${this.label(a)} gagal: ${msg.slice(0, 160)}`); } this.writeNote(this.store.ajuanById(a.id)); } } private clearDecision(a: Ajuan) { this.store.update(a.id, { decision: null, decision_by: null, decision_at: null, decision_note: null }); } // Every check runs again against GitLab at the moment of the merge; the board's view may be old. // Null: GitLab has not computed mergeability yet; try again on the next tick. private async gas(a: Ajuan, ev: QueuedEvent, now: number): Promise { const ref = this.ref(a); const m = await this.ports.gitlab.mrSummary(ref); const by = ev.payload.by as string; if (m.state === 'merged' && ev.attempts > 0) return this.merged(a, m.mergeSha ?? null, by, now); // merged before a restart const refuse = (why: string) => { this.clearDecision(a); this.notify(`gas-refused:${ev.id}`, a, `✋ Gas ${this.label(a)} tidak dijalankan: ${why}.`); return `ditolak: ${why}`; }; if (a.decision !== 'gas') return 'dilewati: keputusan sudah berubah'; if (m.state !== 'opened') return refuse(`MR ${m.state}`); if (a.status !== 'go') return refuse(`verdict sekarang ${a.status}`); if (m.sha !== a.reviewed_sha || ev.payload.sha !== a.reviewed_sha) return refuse('ada commit baru setelah review'); if (m.pipelineStatus && m.pipelineStatus !== 'success') return refuse(`pipeline MR ${m.pipelineStatus}`); if (m.mergeStatus && PENDING_MERGE_STATUS.has(m.mergeStatus)) { const waited = now - ev.payload.at - this.gasConfig.graceSeconds * 1000; if (waited >= MERGE_STATUS_WAIT_MS) return refuse(`GitLab masih ${m.mergeStatus} setelah ${MERGE_STATUS_WAIT_MS / 60_000} menit`); if (now - (this.rechecked.get(ev.id) ?? 0) >= RECHECK_EVERY_MS) { this.rechecked.set(ev.id, now); await this.ports.gitlab.recheckMergeStatus(ref); this.log(`${a.project} !${a.iid} gas: GitLab ${m.mergeStatus}, minta cek ulang`); } return null; } if (m.mergeStatus && m.mergeStatus !== 'mergeable') return refuse(`GitLab bilang ${m.mergeStatus}`); if (this.gasConfig.mode !== 'live') { this.store.update(a.id, { deploy_state: 'dry' }); this.notify(`gas:${ev.id}`, a, `🧪 Gas uji coba ${this.label(a)} dari @${by}: semua cek lolos, tidak di-merge.`); return 'uji coba: semua cek lolos, tidak di-merge'; } const r = await this.ports.gitlab.mergeMr(ref, a.reviewed_sha!); if (r.state !== 'merged') throw new Error(`GitLab menjawab state ${r.state}`); return this.merged(a, r.mergeSha, by, now); } private byTag(a: Ajuan): boolean { const d = this.config.deployBy?.[a.project]; return (typeof d === 'string' ? d : d?.[a.target_branch ?? '']) === 'tag'; } // What to watch after a merge: the target branch's pipeline, or the next release tag. private afterMerge(a: Ajuan, mergeSha: string | null, now = Date.now()): Partial { if (!mergeSha) return { merge_sha: null, deploy_state: 'no_pipeline' }; if (this.byTag(a)) return { merge_sha: mergeSha, deploy_state: 'awaiting_release', deploy_ref: null, deploy_at: null }; return { merge_sha: mergeSha, deploy_state: 'deploying', deploy_ref: a.target_branch, deploy_at: new Date(now).toISOString() }; } private async merged(a: Ajuan, mergeSha: string | null, by: string, now: number): Promise { this.store.update(a.id, { status: 'closed', closed_state: 'merged', ...this.afterMerge(a, mergeSha, now) }); await this.publishReply(a, gasComment(by, mergeSha, this.byTag(a))); const next = this.byTag(a) ? 'deploy jalan setelah tag rilis dibuat' : 'deploy jalan'; this.notify(`gas:${a.id}:${mergeSha}`, a, `🚢 Gas ${this.label(a)} dari @${by}: di-merge${mergeSha ? ` ${mergeSha.slice(0, 8)}` : ''} ke ${a.target_branch ?? '?'}, ${next}.`); return `di-merge ${mergeSha?.slice(0, 8) ?? '(tanpa sha)'}`; } // A rejected MR closed on the approver's word. The comment goes first, so the MR says why. private async close(a: Ajuan, ev: QueuedEvent): Promise { if (a.decision !== 'tolak') return 'dilewati: keputusan sudah berubah'; const m = await this.ports.gitlab.mrSummary(this.ref(a)); if (m.state !== 'opened') return `dilewati: MR ${m.state}`; if (this.gasConfig.mode !== 'live') return 'uji coba: MR tidak ditutup'; await this.publishReply(a, closeComment(ev.payload.by)); const r = await this.ports.gitlab.closeMr(this.ref(a)); if (r.state !== 'closed') throw new Error(`GitLab menjawab state ${r.state}`); this.store.update(a.id, { status: 'closed', closed_state: 'closed' }); return 'MR ditutup'; } private async announce(a: Ajuan, ev: QueuedEvent): Promise { await this.publishReply(a, decisionComment(ev.payload)); // The team hears about a Tolak; Tunda and undo stay in the MR thread. if (ev.payload.decision === 'tolak') this.notify(`tolak:${ev.id}`, a, `⛔ ${this.label(a)} ditolak @${ev.payload.by}${ev.payload.note ? `: ${String(ev.payload.note).slice(0, 120)}` : '.'}`); return `diumumkan: ${ev.payload.decision}`; } // "Berlabuh": the pipeline that deploys the merge — on the target branch, or on the first // release tag that holds it. Waiting for a tag has no time limit; the team tags when it releases. private async trackDeploys(now: number) { for (const a of this.store.allAjuan().filter((x) => x.deploy_state === 'awaiting_release')) { try { const tag = await this.ports.gitlab.releaseTagFor(a.project, a.merge_sha!); if (!tag) continue; this.store.update(a.id, { deploy_state: 'deploying', deploy_ref: tag.name, deploy_at: new Date(now).toISOString() }); this.notify(`release:${a.id}:${tag.name}`, a, `🏷️ ${this.label(a)} masuk rilis ${tag.name}, deploy jalan.`); this.log(`${a.project} !${a.iid} masuk rilis ${tag.name}`); } catch (e: any) { this.log(`${a.project} !${a.iid} cek tag rilis gagal: ${String(e?.message ?? e).slice(0, 200)}`); } } await this.proposeReleases(); for (const a of this.store.allAjuan().filter((x) => x.deploy_state === 'deploying')) { try { const onTag = !!a.deploy_ref && a.deploy_ref !== a.target_branch; const p = await this.ports.gitlab.pipelineFor(a.project, onTag ? null : a.merge_sha!, a.deploy_ref ?? a.target_branch ?? ''); const since = now - Date.parse(a.deploy_at ?? a.status_at ?? a.updated_at); if (!p) { if (since > NO_PIPELINE_MS) { this.store.update(a.id, { deploy_state: 'no_pipeline' }); this.notify(`deploy:${a.id}`, a, `❓ ${this.label(a)} sudah di-merge tapi tidak ada pipeline deploy setelah 15 menit.`); } continue; } if (p.id !== a.deploy_pipeline) this.store.update(a.id, { deploy_pipeline: p.id, deploy_url: p.webUrl }); if (p.status === 'success') { this.store.update(a.id, { deploy_state: 'deployed' }); this.notify(`deploy:${a.id}`, a, `⚓ ${this.label(a)} berlabuh: pipeline deploy hijau.`); } else if (['failed', 'canceled', 'skipped'].includes(p.status) || since > DEPLOY_LIMIT_MS) { this.store.update(a.id, { deploy_state: 'failed' }); this.notify(`deploy:${a.id}`, a, `🚨 Deploy ${this.label(a)} gagal (pipeline ${p.status}). ${p.webUrl}`); } else continue; this.log(`${a.project} !${a.iid} deploy: ${p.status}`); this.writeNote(this.store.ajuanById(a.id)); } catch (e: any) { this.log(`${a.project} !${a.iid} cek pipeline gagal: ${String(e?.message ?? e).slice(0, 200)}`); } } } // ---- Releases (src/release.ts) ---- // One proposal per branch with merged ajuan still waiting for a tag. It names the branch head; // when the branch moves before anyone confirms, the proposal is replaced by a fresh one. private async proposeReleases() { const waiting = new Map(); for (const a of this.store.allAjuan().filter((x) => x.deploy_state === 'awaiting_release' && x.target_branch)) { const key = `${a.project}\n${a.target_branch}`; waiting.set(key, [...(waiting.get(key) ?? []), a]); } for (const [key, list] of waiting) { const [project, branch] = key.split('\n'); const open = this.store.openRelease(project, branch); if (open && open.state !== 'proposed') continue; try { const base = await this.ports.gitlab.releaseBase(project, branch); if (open?.sha === base.head) continue; const from = latestTag(base.tags.map((t) => t.name)); const changes = await this.ports.gitlab.releaseChanges(project, branch, from, base.head); if (open) this.store.updateRelease(open.id, { state: 'superseded', result: 'branch bergerak' }); const r = this.store.addRelease({ project, branch, sha: base.head, from_tag: from, proposed_tag: nextTag(from), changes }); const n = changes.mrs.length + changes.commits.length; this.notify(`release-proposed:${r.id}`, list[0], `🏷️ Usulan rilis ${project.split('/').pop()} ${r.proposed_tag} (${branch}, ${n} perubahan) nunggu persetujuan di board.`); this.log(`${project} ${branch}: usulan rilis ${r.proposed_tag} di ${base.head.slice(0, 8)}`); } catch (e: any) { this.log(`${project} ${branch}: usulan rilis gagal: ${String(e?.message ?? e).slice(0, 200)}`); } } } // Confirmed releases past their grace period. A release taken before a restart ('tagging') is finished now. private async runReleases(now: number) { const grace = this.gasConfig.graceSeconds * 1000; for (const r of this.store.releasesIn('queued', 'tagging')) { if (r.state === 'queued' && (now - (r.queued_at ?? now) < grace || !this.store.claimRelease(r.id))) continue; const anchor = this.store.allAjuan().find((a) => a.project === r.project && a.target_branch === r.branch && a.deploy_state === 'awaiting_release'); const name = `${r.project.split('/').pop()} ${r.tag}`; try { const result = await this.release(r); this.log(`${r.project} rilis ${r.tag}: ${result}`); if (anchor && result.startsWith('uji coba')) this.notify(`release:${r.id}:dry`, anchor, `🧪 Rilis uji coba ${name} dari @${r.by}: semua cek lolos, tag tidak dibuat.`); if (anchor && result.startsWith('ditolak')) this.notify(`release:${r.id}:refused`, anchor, `✋ Rilis ${name} tidak dijalankan: ${result.replace(/^ditolak: /, '')}.`); } catch (e: any) { // Not retried: the approver looks at it and confirms again. const msg = String(e?.message ?? e).slice(0, 300); this.store.updateRelease(r.id, { state: 'proposed', tag: null, by: null, queued_at: null, result: `gagal: ${msg}` }); this.log(`${r.project} rilis ${r.tag} gagal: ${msg}`); if (anchor) this.notify(`release:${r.id}:failed:${now}`, anchor, `❗ Rilis ${name} gagal: ${msg.slice(0, 160)}`); } } } // Everything is checked again against GitLab: the branch must still be at the proposed commit, // and the tag must be new and later than every release tag. private async release(r: Release): Promise { const base = await this.ports.gitlab.releaseBase(r.project, r.branch); const tag = r.tag!; const same = base.tags.find((t) => t.name === tag); if (same && same.sha === r.sha) { // Created before a restart. this.store.updateRelease(r.id, { state: 'tagged', result: `tag ${tag} dibuat` }); return `tag ${tag} sudah ada`; } const refuse = (why: string, state: Release['state'] = 'proposed') => { this.store.updateRelease(r.id, { state, tag: null, by: null, queued_at: null, result: `ditolak: ${why}` }); return `ditolak: ${why}`; }; if (base.head !== r.sha) return refuse(`${r.branch} sudah bergerak ke ${base.head.slice(0, 8)}; usulan baru menyusul`, 'superseded'); const problem = tagProblem(tag, base.tags.map((t) => t.name)); if (problem) return refuse(problem.replace(/\.$/, '')); if (this.gasConfig.mode !== 'live') { this.store.updateRelease(r.id, { state: 'proposed', tag: null, by: null, queued_at: null, result: 'uji coba: semua cek lolos, tag tidak dibuat' }); return 'uji coba: semua cek lolos'; } await this.ports.gitlab.createTag(r.project, tag, r.sha, releaseNotes(tag, r.changes, r.from_tag, r.by ?? '?')); this.store.updateRelease(r.id, { state: 'tagged', result: `tag ${tag} dibuat` }); return `tag ${tag} dibuat di ${r.sha.slice(0, 8)}`; } // An ajuan ready to Gas with no decision reminds the approver every `remindHours`. private remind(now: number) { const every = this.notifyConfig.remindHours * 3600_000; for (const a of this.store.openAjuan()) { if (a.status !== 'go' || a.decision || a.head_sha !== a.reviewed_sha) continue; const n = Math.floor((now - Date.parse(a.status_at ?? a.updated_at)) / every); if (n >= 1) this.notify(`remind:${a.id}:${a.reviewed_sha}:${n}`, a, `⏰ ${this.label(a)} sudah ${n * this.notifyConfig.remindHours} jam siap gas.`); } } private async sendNotifications(now: number) { for (const n of this.store.unsentNotifications()) { if (!this.ports.notifier) { this.log(`notif: ${n.text.split('\n')[0]}`); this.store.markNotified(n.id); continue; } try { await this.ports.notifier.send(n.text); this.store.markNotified(n.id); } catch (e: any) { const msg = String(e?.message ?? e).slice(0, 200); this.store.markNotified(n.id, msg); this.log(`notif gagal, coba lagi 1 menit lagi: ${msg}`); this.notifyRetryAt = now + 60_000; return; } } } // Shadow mode keeps every comment local. Live mode posts as the bot: the verdict comment is // found by its marker and edited, so a restart never posts a second one. private async publishVerdict(a: Ajuan, body: string) { if (this.config.mode === 'shadow') { this.writeOutbox(a, this.store.putVerdictComment(a.id, body, 'shadow')); return; } const item = this.store.putVerdictComment(a.id, body, 'pending'); const ref = this.ref(a); let noteId = item.note_id; if (!noteId) { const existing = (await this.ports.gitlab.listNotes(ref, 0)).find((n) => n.body.includes(VERDICT_MARKER) && n.author === this.config.botUsername); noteId = existing?.id ?? null; } if (noteId) await this.ports.gitlab.updateNote(ref, noteId, body); else noteId = await this.ports.gitlab.postNote(ref, body); this.store.markPosted(item.id, noteId); } private async publishReply(a: Ajuan, body: string) { if (this.config.mode === 'shadow') { this.writeOutbox(a, this.store.addReply(a.id, body, 'shadow')); return; } const item = this.store.addReply(a.id, body, 'pending'); this.store.markPosted(item.id, await this.ports.gitlab.postNote(this.ref(a), body)); } private writeOutbox(a: Ajuan, item: OutboxItem) { const dir = path.join(this.workRoot, 'outbox'); mkdirSync(dir, { recursive: true }); const name = `${a.project.replace(/\//g, '__')}-${a.iid}-${item.kind === 'verdict' ? 'verdict' : `reply-${item.id}`}.md`; writeFileSync(path.join(dir, name), item.body + '\n'); } // Local draft of the vault note; the vault itself is written only through the decided // integrator (plan decision 3). writeNote(a: Ajuan) { const dir = path.join(this.workRoot, 'notes'); mkdirSync(dir, { recursive: true }); const verdict: Checked | null = a.verdict_json ? JSON.parse(a.verdict_json) : null; writeFileSync(path.join(dir, `${a.project.replace(/\//g, '__')}-${a.iid}.md`), ajuanNote(a, verdict, this.store.events(a.id), this.reviewer.name)); } } export function loadHubConfig(root: string): HubConfig { return JSON.parse(readFileSync(path.join(root, 'hub.json'), 'utf8')); }