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

update-helpers.ts

65 lines · 2.1 KB · TypeScript
/**
 * Shared helpers for safe ledger, plan store, and claim store updates.
 * Each re-reads from storage immediately before saving and replaces only
 * the target record, so a concurrent sweep write is not clobbered.
 */
import { loadJson, saveJson, storageKeys } from './storage.ts'
import { emptyLedger, type Ledger, type WorkItem } from '../core/work-item.ts'
import { emptyPlanStore, PLANS_KEY, type Plan, type PlanStore } from '../core/plan.ts'
import type { ClaimStore } from '../exports/claim.ts'

const CLAIMS_KEY = 'factory:claims:v1'

const VALID_ACTORS = new Set(['agent', 'human', 'system'])

export type EventActor = 'agent' | 'human' | 'system'

export function normalizeActor(raw: string | undefined): EventActor {
	if (raw && VALID_ACTORS.has(raw)) return raw as EventActor
	return 'human'
}

export function actorMeta(raw: string | undefined): Record<string, unknown> | undefined {
	if (!raw || VALID_ACTORS.has(raw)) return undefined
	return { actorName: String(raw).slice(0, 100) }
}

export function cap(s: string | undefined | null, max: number): string {
	if (!s) return ''
	return s.length <= max ? s : s.slice(0, max)
}

export async function updateLedgerItem(
	id: string,
	mutate: (item: WorkItem, ledger: Ledger) => WorkItem,
): Promise<WorkItem> {
	const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
	const item = ledger.items[id]
	if (!item) throw new Error(`work item not found: ${id}`)
	const next = mutate(item, ledger)
	ledger.items[id] = next
	await saveJson(storageKeys.LEDGER_KEY, ledger)
	return next
}

export async function updatePlanItem(
	id: string,
	mutate: (plan: Plan, store: PlanStore) => Plan,
): Promise<Plan> {
	const store = await loadJson<PlanStore>(PLANS_KEY, emptyPlanStore())
	const plan = store.plans[id]
	if (!plan) throw new Error(`plan not found: ${id}`)
	const next = mutate(plan, store)
	store.plans[id] = next
	await saveJson(PLANS_KEY, store)
	return next
}

export async function updateClaims(
	mutate: (store: ClaimStore) => ClaimStore,
): Promise<ClaimStore> {
	const store = await loadJson<ClaimStore>(CLAIMS_KEY, { claims: {} })
	const next = mutate(store)
	await saveJson(CLAIMS_KEY, next)
	return next
}