Skip to content
← 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.

FollowFork

Files

fingerprint.ts

331 lines · 13.8 KB · TypeScript
/**
 * Pure rules for the factory health error feed: error families, fingerprints,
 * skip rules, caps, and status transitions. No kody:runtime, so it is
 * unit-testable. Ported from the run-error triage reference design, minus
 * Discord and agent spawning.
 */

/** Kody id of this package: its own failed runs never become fingerprints. */
export const SELF_KODY_ID = 'kody-factory'

/** Org used when no event, setting, or hosted URL names one. */
export const DEFAULT_ORG = 'kody'

/** Max Patch wakes per clock hour. */
export const MAX_WAKES_PER_HOUR = 3
/** New fingerprints in one hour above this pause wakes for that hour. */
export const FINGERPRINT_ANOMALY_THRESHOLD = 15
/** Raw error events in one hour above this pause wakes for that hour. */
export const EVENT_ANOMALY_THRESHOLD = 80
/** A wake with no recorded outcome is marked failed after this long. */
export const LEASE_STALE_MS = 2 * 60 * 60 * 1000
/** A finished fingerprint is only re-queued after this cooldown. */
export const RETRIAGE_COOLDOWN_MS = 24 * 60 * 60 * 1000
/** Linked runs kept per fingerprint. */
export const MAX_LINKED_RUNS = 20

export const OUTCOMES = ['fixed', 'recommendation', 'noise'] as const
export type HealthOutcome = (typeof OUTCOMES)[number]

/**
 * queued: waiting for triage. claimed: a wake is being sent. woken: Patch has it.
 * fixed / recommendation / noise: recorded outcomes. failed: a wake got no outcome.
 * skipped_execute: closed without a wake because the run came from an agent execute call.
 */
export const STATUSES = [
	'queued',
	'claimed',
	'woken',
	'fixed',
	'recommendation',
	'noise',
	'failed',
	'skipped_execute',
] as const
export type HealthStatus = (typeof STATUSES)[number]

export const IN_FLIGHT_STATUSES: ReadonlySet<string> = new Set(['queued', 'claimed', 'woken'])
/** Outcomes that mean "do not wake again for this family". */
export const SKIP_WAKE_OUTCOMES: ReadonlySet<string> = new Set(['fixed', 'recommendation', 'noise'])

export type RunSnippet = {
	id?: string | null
	surface?: string | null
	name?: string | null
	package_id?: string | null
	kody_id?: string | null
	job_id?: string | null
	error_name?: string | null
	error_message?: string | null
	started_at?: string | null
	/** Present on runList / runGet; `run.error.recorded` omits it. */
	metadata?: Record<string, unknown> | null
}

export function hourBucket(date = new Date()): string {
	return date.toISOString().slice(0, 13)
}

export function toLowerKebabCase(value: unknown): string {
	return String(value ?? '')
		.toLowerCase()
		.replace(/[^a-z0-9]+/g, '-')
		.replace(/^-+|-+$/g, '')
}

export function truncate(text: unknown, maxLength: number): string {
	const value = String(text ?? '')
	return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`
}

export const PACKAGE_CALLER_VALIDATION_FAMILY = 'package-caller-validation'

export function isPackageCallerValidation(text: string): boolean {
	const raw = String(text ?? '')
	if (!raw) return false
	if (
		/available event types/i.test(raw) ||
		/call list-event-types/i.test(raw) ||
		/could not resolve that event type/i.test(raw) ||
		/requires (?:id or )?eventtypeid/i.test(raw) ||
		/requires eventtypeslug/i.test(raw) ||
		/event type with id .+ not found/i.test(raw) ||
		/create-webhook requires/i.test(raw)
	) {
		return true
	}
	const kebab = toLowerKebabCase(raw)
	return (
		kebab.includes('available-event-types') ||
		kebab.includes('could-not-resolve-that-event-type') ||
		kebab.includes('requires-eventtypeid') ||
		kebab.includes('requires-id-or-eventtypeid') ||
		kebab.includes('create-webhook-requires') ||
		(kebab.includes('event-type-with-id') && kebab.includes('not-found'))
	)
}

function knownFamilyFrom(text: string): string | null {
	const m = String(text ?? '')
	if (isPackageCallerValidation(m)) return PACKAGE_CALLER_VALIDATION_FAMILY
	if (/Execution timed out after \d+(?:s|ms)/i.test(m)) return 'execution-timed-out'
	if (/The platform interrupted this run before completion/i.test(m)) return 'platform-interrupted'
	if (m.includes('Cannot read properties of undefined')) return 'cannot-read-properties-of-undefined'
	if (m.includes('Cannot read properties of null')) return 'cannot-read-properties-of-null'
	if (m.includes('Dynamic worker concurrency limit exceeded')) return 'dynamic-worker-concurrency-limit-exceeded'
	if (m.includes('Plan limit reached') && m.includes('repo sessions')) return 'repo-session-plan-limit'
	if (m.includes('Durable Object reset because its code was updated')) return 'durable-object-code-reset'
	if (m.includes('packageContext is not a function')) return 'package-context-not-function'
	if (m.includes('HTTP Error: 500')) return 'http-500'
	if (m.includes('stale running TTL')) return 'stale-ttl-interrupted'
	if (m.includes('REPO_SESSION_INDEX')) return 'repo-session-index-unbound'
	if (m.includes('Network connection lost')) return 'network-lost'
	if (m.startsWith('internal error; reference')) return 'internal-error'
	if (m.includes('Plain repo') && m.includes('not found')) return 'plain-repo-not-found'
	if (m.includes('packageStorage() cannot access')) return 'package-storage-context'
	if (m.includes('RPC stub used after being disposed')) return 'rpc-disposed'
	return null
}

function innerErrorsFrom(message: string): string[] {
	const found: string[] = []
	for (const match of message.matchAll(/"error"\s*:\s*"((?:\\.|[^"\\])*)"/g)) {
		found.push(match[1]!.replaceAll('\\"', '"'))
	}
	return found
}

/** Stable family for `Something failed: {json with instance keys}` wrappers. */
export function wrapperFamilyOf(text: string): string | null {
	const raw = String(text || '')
	const messageMatch = raw.match(/^(.{3,80}?)\s+failed:\s*\{/i)
	if (messageMatch) return toLowerKebabCase(`${messageMatch[1]} failed`)
	const kebab = toLowerKebabCase(raw)
	const keyVariant = kebab.match(/^([a-z0-9]+(?:-[a-z0-9]+)*)-failed-key-/)
	if (keyVariant) return `${keyVariant[1]}-failed`
	return null
}

export function normalizeErrorFamily(message: string | null | undefined): string {
	const m = String(message ?? '')
	const fromFull = knownFamilyFrom(m)
	if (fromFull) return fromFull
	for (const inner of innerErrorsFrom(m)) {
		const known = knownFamilyFrom(inner)
		if (known) return known
	}
	const wrapper = wrapperFamilyOf(m)
	if (wrapper) return wrapper
	const cleaned = m
		.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<id>')
		.replace(/reference = [a-z0-9]+/gi, 'reference = <id>')
		.replace(/\{[\s\S]*$/, '')
		.replace(/\d+/g, 'N')
		.slice(0, 80)
	return toLowerKebabCase(cleaned) || 'unknown'
}

/** Collapse stored family variants so sibling matching sees one issue. */
export function coarseErrorFamily(familyOrMessage: string): string {
	const raw = String(familyOrMessage || '')
	const family = raw.includes(' ') ? normalizeErrorFamily(raw) : toLowerKebabCase(raw)
	if (isPackageCallerValidation(raw) || isPackageCallerValidation(family)) {
		return PACKAGE_CALLER_VALIDATION_FAMILY
	}
	if (family === 'timeout-90s' || family.startsWith('execution-timed-out') || family.startsWith('timeout-')) {
		return 'execution-timed-out'
	}
	for (const prefix of [
		'cannot-read-properties-of-undefined',
		'cannot-read-properties-of-null',
		'dynamic-worker-concurrency-limit-exceeded',
		'durable-object-code-reset',
	]) {
		if (family.startsWith(prefix)) return prefix
	}
	if (family === 'platform-interrupted' || family.startsWith('the-platform-interrupted-this-run')) {
		return 'platform-interrupted'
	}
	if (family === 'internal-error' || family.startsWith('internal-error-')) return 'internal-error'
	return wrapperFamilyOf(raw) || wrapperFamilyOf(family) || family
}

export type FamilyMatchInput = { error_family: string; sample_message?: string | null }

/** All coarse families a stored row can match under, including wrappers. */
export function matchFamiliesFor(record: FamilyMatchInput): Set<string> {
	const families = new Set<string>()
	const add = (value: string | null | undefined) => {
		if (!value) return
		families.add(coarseErrorFamily(value))
		const wrapper = wrapperFamilyOf(value)
		if (wrapper) families.add(wrapper)
		if (value.includes(' ') || value.includes('{')) families.add(normalizeErrorFamily(value))
	}
	add(record.error_family)
	add(record.sample_message || '')
	return families
}

export function matchFamiliesOverlap(left: FamilyMatchInput, right: FamilyMatchInput): boolean {
	const rightFamilies = matchFamiliesFor(right)
	for (const family of matchFamiliesFor(left)) {
		if (rightFamilies.has(family)) return true
	}
	return false
}

export function ownerFor(run: RunSnippet): string {
	return run.kody_id || run.package_id || run.name || 'ad-hoc'
}

export function normalizeOrg(org: unknown): string {
	return toLowerKebabCase(org) || DEFAULT_ORG
}

/** `<org>:<surface>:<owner>:<family>`. The org prefix keeps ids from colliding across orgs. */
export function fingerprintFor(org: string, run: RunSnippet): string {
	return `${normalizeOrg(org)}:${run.surface || 'unknown'}:${ownerFor(run)}:${normalizeErrorFamily(run.error_message)}`
}

/** Org slug from a trusted Activity link such as `https://kody.codes/@kody/-/activity/<id>`. */
export function orgFromActivityUrl(url: unknown): string | null {
	const match = /\/@([a-z0-9][a-z0-9-]*)\/-\/activity\//i.exec(String(url ?? ''))
	return match ? match[1]!.toLowerCase() : null
}

export function activityUrlFor(origin: string, org: string, runId: string | null | undefined): string | null {
	if (!runId) return null
	return `${origin.replace(/\/+$/, '')}/@${normalizeOrg(org)}/-/activity/${encodeURIComponent(runId)}`
}

function metadataString(run: Pick<RunSnippet, 'metadata'>, key: string): string | null {
	const value = run.metadata?.[key]
	return typeof value === 'string' && value ? value : null
}

/** Unsaved `workflows.create` from MCP execute (name `inline-code`, no package). */
export function isUnsavedInlineWorkflow(run: RunSnippet): boolean {
	if ((run.surface || '') !== 'workflow') return false
	if (run.package_id || run.kody_id) return false
	if ((run.name || '') !== 'inline-code') return false
	const sourceType = metadataString(run, 'sourceType')
	return sourceType === 'inline' || sourceType == null
}

/** Agent MCP `execute`, a package run invoked from that execute, or its inline workflow. */
export function isAgentExecuteOrigin(run: RunSnippet): boolean {
	if ((run.surface || '') === 'execute') return true
	if (metadataString(run, 'source') === 'execute') return true
	return isUnsavedInlineWorkflow(run)
}

export const AGENT_EXECUTE_NOTE =
	'Ignored by factory health: agent MCP execute origin. The calling agent already saw the error; standing package, job, and subscription failures stay open.'
export const PLATFORM_WEATHER_NOTE =
	'Resolved by factory health: platform isolate weather (skills retriever interrupt, observer timeout, worker cap, or system-email status interrupt). Standing noise.'
export const STANDING_NOISE_NOTE = 'Resolved by factory health: this fingerprint is recorded as noise.'

export function isPlatformInterrupted(run: Pick<RunSnippet, 'error_name' | 'error_message'>): boolean {
	if (String(run.error_name || '') === 'platform_interrupted') return true
	return /The platform interrupted this run before completion/i.test(String(run.error_message || ''))
}

/** Skills retriever isolate weather and system-email /api/status interrupts. */
export function isPlatformWeather(run: RunSnippet): boolean {
	const surface = run.surface || ''
	const kodyId = run.kody_id || ''
	const name = run.name || ''
	const message = String(run.error_message || '')
	if (surface === 'retriever' && (kodyId === 'skills' || name === 'skills')) {
		if (isPlatformInterrupted(run)) return true
		if (message.includes('Dynamic worker concurrency limit exceeded')) return true
		if (/Execution timed out after \d+ms/i.test(message)) return true
	}
	const systemEmailStatus =
		surface === 'app_fetch' && kodyId === 'system-email' && (name === '/api/status' || name === 'api/status')
	return Boolean(systemEmailStatus && isPlatformInterrupted(run))
}

export function isSelfPackageRun(run: RunSnippet, selfPackageId?: string | null): boolean {
	if (run.kody_id === SELF_KODY_ID) return true
	return Boolean(selfPackageId && run.package_id === selfPackageId)
}

export type SkipReason = 'agent-execute' | 'self-package' | 'smoke-test'

/** Runs that never become fingerprints. Platform weather is tracked, as standing noise. */
export function skipReason(run: RunSnippet, selfPackageId?: string | null): SkipReason | null {
	if (isAgentExecuteOrigin(run)) return 'agent-execute'
	if (isSelfPackageRun(run, selfPackageId)) return 'self-package'
	const family = normalizeErrorFamily(run.error_message)
	if (family.includes('smoke-test') || coarseErrorFamily(family).includes('smoke-test')) return 'smoke-test'
	return null
}

/** Status after one more matching error event. In-flight and noise never move. */
export function nextStatusAfterEvent(input: {
	status: string
	completedAt: string | null
	runStartedAt?: string | null
	now?: number
}): string {
	if (input.status === 'skipped_execute') return 'queued'
	if (IN_FLIGHT_STATUSES.has(input.status)) return input.status
	if (input.status === 'noise') return input.status
	const now = input.now ?? Date.now()
	const completedAt = input.completedAt ? Date.parse(input.completedAt) : 0
	if (completedAt && now - completedAt < RETRIAGE_COOLDOWN_MS) return input.status
	const runStarted = input.runStartedAt ? Date.parse(input.runStartedAt) : now
	if (completedAt && !Number.isNaN(runStarted) && runStarted <= completedAt) return input.status
	return 'queued'
}

/** Soft triage applied to matching Activity rows once an outcome is recorded. */
export function softTriageForOutcome(outcome: string | null | undefined): 'resolved' | null {
	return outcome === 'fixed' || outcome === 'noise' ? 'resolved' : null
}

export function anomalyTripped(counts: { fingerprints: number; events: number }): boolean {
	return counts.fingerprints > FINGERPRINT_ANOMALY_THRESHOLD || counts.events > EVENT_ANOMALY_THRESHOLD
}