/** * Nightly friction clustering job (before the nightly card run). Groups open * friction cards into clusters with deterministic keyword grouping and tags * each card `cluster:` (replacing an older cluster tag), so the board * and the nightly run see related papercuts together. Creates no cards. * `dryRun: true` reports the clusters without writing. */ import { clusterFrictionSignals, type FrictionSignal } from '../board/friction-cluster.ts' import { loadJson, saveJson, storageKeys } from '../lib/storage.ts' import { emptyLedger, nowIso, type Ledger } from '../core/work-item.ts' import { isFrictionCard } from '../cards/tags.ts' export default async function frictionClusterJob(params?: { dryRun?: boolean }) { const dryRun = params?.dryRun === true const ledger = await loadJson(storageKeys.LEDGER_KEY, emptyLedger()) const items = Object.values(ledger.items) const frictionItems = items.filter( (i) => isFrictionCard(i) && (i.state === 'intake' || i.state === 'triaged'), ) const signals: FrictionSignal[] = frictionItems.map((item) => { const issueNumber = item.fingerprint.includes(':') ? Number(item.fingerprint.split(':').pop()) || 0 : 0 return { id: item.id, title: item.title, body: item.body, labels: item.labels, number: issueNumber || Math.abs(hashCode(item.id)), repoRef: item.repoRef ?? '', createdAt: item.createdAt, htmlUrl: item.links?.find((l) => l.kind === 'issue')?.url ?? '', } }) const result = clusterFrictionSignals(signals) let tagged = 0 if (!dryRun && result.clusters.length > 0) { const fresh = await loadJson(storageKeys.LEDGER_KEY, emptyLedger()) const at = nowIso() for (const cluster of result.clusters) { const tag = `cluster:${cluster.slug}`.slice(0, 80) for (const sig of cluster.signals) { const item = fresh.items[sig.id] if (!item || item.labels.includes(tag)) continue fresh.items[sig.id] = { ...item, labels: [...item.labels.filter((l) => !l.startsWith('cluster:')), tag], updatedAt: at } tagged++ } } if (tagged > 0) await saveJson(storageKeys.LEDGER_KEY, fresh) } return { dryRun, tagged, signalsProcessed: signals.length, clustersFound: result.clusters.length, deferred: result.deferred.length, method: result.method, clusters: result.clusters.map((c) => ({ slug: c.slug, name: c.name, areas: c.areas, signalCount: c.signals.length, signalIds: c.signals.map((s) => s.id), })), } } function hashCode(s: string): number { let h = 0 for (let i = 0; i < s.length; i++) { h = (Math.imul(31, h) + s.charCodeAt(i)) | 0 } return h >>> 0 }