← Public packages
@kody/kody-factory
Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.
Files
/**
* Friction papercuts as factory cards. A target repo that belongs to a
* factory project (or a Kody package target, filed under
* `frictionCards.packageProjectId`) becomes an intake card tagged
* `source:friction`, `kind:friction`, `repo:` or `pkg:`, and `area:` when
* clear. The day sweep leaves friction cards alone; the nightly card run
* groups and works them. P0 and security friction is routed at once by the
* card routes.
*
* Dedupe: an open card with the same project, target, and title gets a
* "seen again" note (and a priority raise when the new filing is higher).
* A shipped or dropped match files a new card.
*/
import { loadJson, saveJson, storageKeys } from '../lib/storage.ts'
import { loadSettings } from '../lib/settings.ts'
import { appBaseUrl, cardLink } from '../lib/links.ts'
import { emptyLedger, newWorkItemId, nowIso, type Ledger, type WorkItem, type WorkItemPriority } from '../core/work-item.ts'
import { rankOf } from '../core/priority-queue.ts'
import { loadProjects } from '../projects/config.ts'
import { afterCardTriaged, afterCardsCreated } from '../cards/lifecycle.ts'
import { schemeTags, withTags } from '../cards/tags.ts'
import { buildFrictionBody, frictionKindLabels, isSameFrictionBody, normalizeFrictionKind, normalizeFrictionTitle, type FrictionKind } from './shared.ts'
import type { FrictionTarget } from './qualify.ts'
export type FrictionCardPlace = { projectId: string; repoRef: string | null; pkg: string | null; targetKey: string }
export type FrictionCardInput = {
title: string
body?: string
whatHappened?: string
whatYouWanted?: string
howToReproduce?: string
cost?: string
preliminaryInvestigation?: string
relevantFiles?: Array<string>
kind?: FrictionKind
/** Optional priority (0 highest). P0 is routed at once. */
priority?: WorkItemPriority
/** Security friction is routed at once. */
security?: boolean
/** Optional area tags (platform, packages, ui, billing, security, mcp, cli, docs, dev-tooling, ops, perf). */
areas?: Array<string>
}
export type FrictionCardResult =
| { action: 'filed'; cardId: string; url: string; title: string; card: WorkItem; dryRun?: boolean }
| { action: 'reused'; cardId: string; url: string; title: string; noted: boolean; raised: boolean; seenCount: number; dryRun?: boolean }
const AREAS = new Set(['platform', 'packages', 'ui', 'billing', 'security', 'mcp', 'cli', 'docs', 'dev-tooling', 'ops', 'perf'])
/** Light area guess from the text. Security is never guessed: pass `security: true`. */
export function guessAreas(text: string): string[] {
const t = text.toLowerCase()
const out: string[] = []
if (/\bmcp\b/.test(t)) out.push('mcp')
if (/\bcli\b|npx @kodycodes\/cli|kody (api|execute|package)\b/.test(t)) out.push('cli')
if (/\bdocs?\b|readme|agents\.md/.test(t)) out.push('docs')
if (/pre-push|\bknip\b|flaky|\bci\b|workflow/.test(t)) out.push('dev-tooling')
if (/\bbilling\b|\bcredits?\b|stripe/.test(t)) out.push('billing')
if (/\bslow\b|latency|timeout|cold start|\bperf/.test(t)) out.push('perf')
return out.slice(0, 3)
}
export function frictionFingerprint(place: FrictionCardPlace, title: string): string {
return `friction:${place.projectId}:${place.targetKey.toLowerCase()}:${normalizeFrictionTitle(title).toLowerCase()}`
}
/**
* Where a friction target lands on the board, or null to keep the GitHub
* issue path (repo not in any enabled project, or friction cards off).
*/
export async function frictionCardPlace(target: FrictionTarget): Promise<FrictionCardPlace | null> {
const settings = await loadSettings()
if (!settings.frictionCards.enabled) return null
const projects = Object.values((await loadProjects()).projects).filter((p) => p.enabled)
if (target.host === 'kody') {
const pkg = String(target.repo).trim()
const project = projects.find((p) => p.id === settings.frictionCards.packageProjectId)
if (!project) return null
return { projectId: project.id, repoRef: null, pkg, targetKey: `pkg:${pkg}` }
}
const repo = String(target.repo).trim().toLowerCase()
for (const p of projects) {
const hit = p.repos.find((r) => r.enabled && r.repoRef.toLowerCase() === repo) ?? (p.repoRef?.toLowerCase() === repo ? { repoRef: p.repoRef } : null)
if (hit) return { projectId: p.id, repoRef: hit.repoRef, pkg: null, targetKey: `repo:${hit.repoRef}` }
}
return null
}
function isOpen(item: WorkItem) {
return item.state !== 'shipped' && item.state !== 'dropped'
}
export function frictionCardLabels(input: FrictionCardInput, place: FrictionCardPlace): string[] {
const kind = normalizeFrictionKind(input.kind)
const base = ['friction', ...frictionKindLabels(kind).filter((l) => l !== 'friction')]
const text = [input.title, input.body, input.whatHappened, input.cost].filter(Boolean).join('\n')
const areas = [...(input.areas ?? []).map((a) => String(a).toLowerCase()).filter((a) => AREAS.has(a)), ...guessAreas(text), ...(place.pkg ? ['packages'] : []), ...(input.security ? ['security'] : [])]
return withTags(schemeTags({ source: 'friction', labels: base, repoRef: place.repoRef, pkg: place.pkg }), [
'kind:friction',
kind === 'wasteful-context' ? 'kind:friction:wasteful-context' : null,
input.security ? 'kind:security' : null,
...areas.map((a) => `area:${a}`),
])
}
/** File one friction papercut as a card (or note it on the open match). */
export async function fileFrictionCard(input: FrictionCardInput, place: FrictionCardPlace, opts: { dryRun?: boolean } = {}): Promise<FrictionCardResult> {
const title = normalizeFrictionTitle(input.title)
const body = buildFrictionBody(input)
const fingerprint = frictionFingerprint(place, title)
const priority: WorkItemPriority = typeof input.priority === 'number' && [0, 1, 2, 3].includes(input.priority) ? input.priority : null
const base = await appBaseUrl()
const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
const existing = Object.values(ledger.items).find((i) => i.fingerprint === fingerprint && isOpen(i))
const at = nowIso()
if (existing) {
const seenCount = existing.events.filter((e) => e.reason === 'friction seen again').length + 1
const noted = !isSameFrictionBody(body, existing.body)
const raised = priority !== null && (existing.priority === null || priority < existing.priority)
const labels = withTags(existing.labels, frictionCardLabels(input, place))
const next: WorkItem = {
...existing,
labels,
...(raised ? { priority, rank: rankOf(priority, existing.needsKent) } : {}),
updatedAt: at,
events: [...existing.events, { at, from: existing.state, to: existing.state, reason: 'friction seen again', actor: 'agent', meta: { seenCount, ...(noted ? { note: body.slice(0, 2000) } : {}), ...(raised ? { priority } : {}) } }],
}
const url = cardLink(base, existing.id)
if (opts.dryRun) return { action: 'reused', cardId: existing.id, url, title, noted, raised, seenCount, dryRun: true }
const fresh = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
fresh.items[existing.id] = next
await saveJson(storageKeys.LEDGER_KEY, fresh)
if (raised || labels.join('\n') !== existing.labels.join('\n')) {
await afterCardTriaged([{ before: { state: existing.state, priority: existing.priority, needsKent: existing.needsKent, labels: existing.labels }, after: next, reason: 'friction seen again' }])
}
return { action: 'reused', cardId: existing.id, url, title, noted, raised, seenCount }
}
const item: WorkItem = {
id: newWorkItemId(),
projectId: place.projectId,
title,
body,
state: 'intake',
priority,
needsKent: false,
rank: rankOf(priority, false),
source: 'friction',
externalId: null,
fingerprint,
signalIds: [],
labels: frictionCardLabels(input, place),
repoRef: place.repoRef,
planCardId: null,
runId: null,
createdAt: at,
updatedAt: at,
events: [{ at, from: null, to: 'intake', reason: 'friction filed', actor: 'agent', meta: { target: place.targetKey } }],
shadow: false,
}
const url = cardLink(base, item.id)
if (opts.dryRun) return { action: 'filed', cardId: item.id, url, title, card: item, dryRun: true }
const fresh = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
fresh.items[item.id] = item
await saveJson(storageKeys.LEDGER_KEY, fresh)
await afterCardsCreated([item])
return { action: 'filed', cardId: item.id, url, title, card: item }
}