/** * Post a report onto the factory. A report records what an audit or review * found even when nothing needs doing, and can file zero, one, or many cards * that link back to it: * * - Work cards (`needsKent` false) join the queue as New and go through the * normal triage and runner flow. * - Decision cards (`needsKent` true) wait in Needs you; no agent starts on them. * - A card key that matches an open card from an earlier report links that * card instead of filing a duplicate. * * One push per report, and only when it files a new card or flags a finding. * A quiet report is recorded without a push. */ import { afterCardsCreated } from '../cards/lifecycle.ts' import { appBaseUrl, cardLink, hostedBaseUrl, reportLink } from '../lib/links.ts' import { loadJson, saveJson, storageKeys } from '../lib/storage.ts' import { loadSettings } from '../lib/settings.ts' import { tryAcquireLock, releaseLock, sweepTickLockKey } from '../lib/locks.ts' import { emptyLedger, newWorkItemId, nowIso, withLink, type Ledger, type WorkItem } from '../core/work-item.ts' import { rankOf } from '../core/priority-queue.ts' import { loadProjects, primaryRepoRef } from '../projects/config.ts' import { TOPICS, emitHealthEvent, eventKey } from '../events/emit.ts' import { loadRules } from '../notifications/store.ts' import { resolveRules } from '../notifications/types.ts' import { sendPush, type PushSendResult } from '../push/send.ts' import { isNoteworthy, newReportId, normalizeReportInput, reportPath, reportPushBody, shouldPushReport, type FactoryReport, type PostReportInput, type ReportCardRef, } from './model.ts' import { deleteReport, getReport, loadReports, saveReport } from './store.ts' const NAME = 'reports/post' const TERMINAL = new Set(['shipped', 'dropped']) type Deps = { sendPush: typeof sendPush sleep: (ms: number) => Promise } const realDeps: Deps = { sendPush, sleep: (ms) => new Promise((r) => setTimeout(r, ms)) } let deps: Deps = realDeps export function setReportDepsForTests(next: Partial | null) { deps = next ? { ...realDeps, ...next } : realDeps } /** Absolute report URL. Pass `await appBaseUrl()` so `publicBaseUrl` applies. */ export function reportUrl(reportId: string, base?: string): string { return reportLink(base || hostedBaseUrl(), reportId) } /** Open card a report filed earlier under the same source, project, and key. */ export function findOpenReportCard(ledger: Ledger, source: string, projectId: string, key: string): WorkItem | null { const matches = Object.values(ledger.items).filter( (i) => i.reportRef?.source === source && i.reportRef.key === key && i.projectId === projectId && !TERMINAL.has(i.state), ) matches.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) return matches[0] ?? null } /** Hold the sweep tick lock while the ledger is written so a running sweep cannot overwrite new cards. */ async function withLedgerLock(fn: () => Promise): Promise { const holder = `report:${crypto.randomUUID().slice(0, 8)}` let got = false for (let attempt = 0; attempt < 20 && !got; attempt++) { got = await tryAcquireLock(sweepTickLockKey(), holder, 2 * 60_000) if (!got) await deps.sleep(3000) } if (!got) throw new Error(`${NAME}: the sweep is busy; try again in a minute`) try { return await fn() } finally { await releaseLock(sweepTickLockKey(), holder) } } export type PostReportResult = { ok: true dryRun: boolean replayed?: boolean reportId: string reportUrl: string noteworthy: boolean cards: Array report: FactoryReport push: PushSendResult | { skipped: string } } function withCardUrls(report: FactoryReport, base: string) { return report.cards.map((c) => ({ ...c, cardUrl: cardLink(base, c.cardId) })) } export async function postReport(input: PostReportInput): Promise { const n = normalizeReportInput(input) const base = await appBaseUrl() if (n.idempotencyKey) { const prior = Object.values((await loadReports()).reports).find((r) => r.source === n.source && r.idempotencyKey === n.idempotencyKey) if (prior) { return { ok: true, dryRun: n.dryRun, replayed: true, reportId: prior.id, reportUrl: reportUrl(prior.id, base), noteworthy: prior.noteworthy, cards: withCardUrls(prior, base), report: prior, push: { skipped: 'replayed' } } } } let repoDefault: string | null = null if (n.cards.length) { const project = (await loadProjects()).projects[n.projectId!] if (!project) throw new Error(`${NAME}: unknown projectId "${n.projectId}"`) if (!project.enabled) throw new Error(`${NAME}: project "${n.projectId}" is disabled`) repoDefault = primaryRepoRef(project) } const reportId = newReportId() const at = nowIso() const link = reportUrl(reportId, base) const findings = n.findings.map((f) => ({ ...f })) const created: WorkItem[] = [] const fileCards = async (persist: boolean) => { const ledger = await loadJson(storageKeys.LEDGER_KEY, emptyLedger()) const shadow = (await loadSettings()).shadowMode === true const refs: ReportCardRef[] = [] for (const spec of n.cards) { const existing = findOpenReportCard(ledger, n.source, n.projectId!, spec.key) if (existing) { ledger.items[existing.id] = { ...existing, updatedAt: at, links: withLink(existing.links, { kind: 'other', url: link, label: `Report: ${n.title}`.slice(0, 120), reason: 'report:seen-again', at }), events: [...existing.events, { at, from: existing.state, to: existing.state, reason: `seen again in report: ${n.title}`, actor: 'system', meta: { reportId } }], } refs.push({ cardId: existing.id, key: spec.key, title: existing.title, relation: 'existing', state: existing.state, needsKent: existing.needsKent, ...(spec.findingId ? { findingId: spec.findingId } : {}) }) continue } const state = spec.needsKent ? 'needs-kent' : 'intake' const item: WorkItem = { id: newWorkItemId(), projectId: n.projectId!, title: spec.title, body: spec.body, state, priority: spec.priority, needsKent: spec.needsKent, rank: rankOf(spec.priority, spec.needsKent), source: n.source, externalId: null, fingerprint: `report:${n.source}:${n.projectId}:${spec.key}:${reportId}`, signalIds: [], labels: [...new Set(['report', `source:${n.source}`, ...(spec.needsKent ? ['needs-you'] : []), ...spec.labels])], repoRef: spec.repoRef ?? repoDefault, planCardId: null, runId: null, createdAt: at, updatedAt: at, events: [{ at, from: null, to: state, reason: `filed by report: ${n.title}`.slice(0, 300), actor: 'system', meta: { reportId } }], shadow, links: [{ kind: 'other', url: link, label: `Report: ${n.title}`.slice(0, 120), reason: 'report', at }], reportRef: { id: reportId, source: n.source, key: spec.key }, } ledger.items[item.id] = item created.push(item) refs.push({ cardId: item.id, key: spec.key, title: item.title, relation: 'created', state, needsKent: spec.needsKent, ...(spec.findingId ? { findingId: spec.findingId } : {}) }) } if (persist && refs.length) await saveJson(storageKeys.LEDGER_KEY, ledger) return refs } const cards = n.cards.length ? (n.dryRun ? await fileCards(false) : await withLedgerLock(() => fileCards(true))) : [] for (const ref of cards) { if (!ref.findingId) continue const f = findings.find((x) => x.id === ref.findingId) if (f) f.cardId = ref.cardId } const report: FactoryReport = { id: reportId, source: n.source, title: n.title, projectId: n.projectId, period: n.period, summary: n.summary, findings, metrics: n.metrics, links: n.links, cards, noteworthy: false, createdAt: at, idempotencyKey: n.idempotencyKey, push: null, } report.noteworthy = isNoteworthy(report) if (n.dryRun) { return { ok: true, dryRun: true, reportId, reportUrl: link, noteworthy: report.noteworthy, cards: withCardUrls(report, base), report, push: { skipped: 'dry run' } } } let push: PushSendResult | { skipped: string } = { skipped: 'nothing new for the owner' } if (!n.notify) push = { skipped: 'notify: false' } else if (shouldPushReport(report)) { try { const rule = resolveRules(await loadRules(), n.projectId ?? 'default') if (!rule.pushEnabled) push = { skipped: 'push is off for this project' } else push = await deps.sendPush({ kind: 'report', title: `Report: ${n.title}`.slice(0, 120), body: reportPushBody(report), path: reportPath(reportId), tag: `report-${reportId}`, }) } catch (error) { push = { skipped: error instanceof Error ? error.message.slice(0, 200) : 'push failed' } } } report.push = 'sent' in push ? { sent: push.sent } : { sent: 0, skipped: push.skipped } await saveReport(report) // card.created always; push and card-route wakes unless notify is off. await afterCardsCreated(created, { quiet: !n.notify }) await emitHealthEvent(TOPICS.reportPosted, eventKey('report', reportId, 'posted'), { reportId, source: report.source, title: report.title.slice(0, 200), ...(report.projectId ? { projectId: report.projectId } : {}), noteworthy: report.noteworthy, cardIds: report.cards.map((c) => c.cardId), url: link, }) return { ok: true, dryRun: false, reportId, reportUrl: link, noteworthy: report.noteworthy, cards: withCardUrls(report, base), report, push } } export type RemoveReportInput = { reportId: string /** Also delete the cards this report created, but only ones nobody has worked on yet (still New or Needs you, no run, no PR). */ removeCards?: boolean dryRun?: boolean } /** Delete a report (for test data or a bad post). Cards that have been worked on are always kept. */ export async function removeReport(input: RemoveReportInput) { const reportId = typeof input?.reportId === 'string' ? input.reportId.trim() : '' if (!/^rp_[a-z0-9]{16}$/.test(reportId)) throw new Error('reports/remove: reportId must look like rp_…') const report = await getReport(reportId) if (!report) throw new Error(`reports/remove: report not found: ${reportId}`) const removedCards: string[] = [] const keptCards: Array<{ cardId: string; reason: string }> = [] const decide = (ledger: Ledger) => { for (const ref of report.cards) { const item = ledger.items[ref.cardId] if (ref.relation !== 'created') { keptCards.push({ cardId: ref.cardId, reason: 'not created by this report' }); continue } if (!input.removeCards) { keptCards.push({ cardId: ref.cardId, reason: 'removeCards not set' }); continue } if (!item) continue const untouched = (item.state === 'intake' || item.state === 'needs-kent') && !item.runId && !item.pr && item.reportRef?.id === reportId if (!untouched) { keptCards.push({ cardId: ref.cardId, reason: `already ${item.state}` }); continue } removedCards.push(ref.cardId) delete ledger.items[ref.cardId] } } if (input.dryRun) { decide(await loadJson(storageKeys.LEDGER_KEY, emptyLedger())) return { ok: true, dryRun: true, reportId, removedCards, keptCards } } if (input.removeCards && report.cards.length) { await withLedgerLock(async () => { const ledger = await loadJson(storageKeys.LEDGER_KEY, emptyLedger()) decide(ledger) if (removedCards.length) await saveJson(storageKeys.LEDGER_KEY, ledger) }) } else decide(emptyLedger()) await deleteReport(reportId) return { ok: true, dryRun: false, reportId, removedCards, keptCards } }