import { loadJson, saveJson } from '../lib/storage.ts' import { nowIso } from '../core/work-item.ts' import { updateClaims, cap } from '../lib/update-helpers.ts' const CLAIMS_KEY = 'factory:claims:v1' export type Claim = { id: string kind: 'work' | 'plan' agent: string claimedAt: string expiresAt: string } export type ClaimStore = { claims: Record } export async function loadClaims(): Promise { return loadJson(CLAIMS_KEY, { claims: {} }) } /** * Claim a card so other agents see it is owned. Claims expire after ttlMinutes. * * @example * import claim from 'kody:@kody/kody-factory/claim' * await claim({ id: 'wi_abc', kind: 'work', agent: 'patch', ttlMinutes: 30 }) */ export default async function claim(input: { id: string kind: 'work' | 'plan' agent: string ttlMinutes?: number dryRun?: boolean }) { if (!input?.id) throw new Error('claim: id is required') if (!input.agent) throw new Error('claim: agent is required') const agent = cap(input.agent, 100) || 'unknown' const now = Date.now() const ttl = Math.max(0, Math.min((input.ttlMinutes ?? 60), 1440)) * 60_000 const store = await loadClaims() const existing = store.claims[input.id] if (existing && Date.parse(existing.expiresAt) > now && existing.agent !== agent) { return { claimed: false, heldBy: existing.agent, expiresAt: existing.expiresAt } } const record: Claim = { id: input.id, kind: input.kind ?? 'work', agent, claimedAt: nowIso(), expiresAt: new Date(now + ttl).toISOString(), } if (input.dryRun) return { claimed: true, claim: record, persisted: false } await updateClaims((s) => ({ claims: { ...s.claims, [input.id]: record } })) return { claimed: true, claim: record, persisted: true } } /** * Release a claim on a card. * * @example * import release from 'kody:@kody/kody-factory/release' * await release({ id: 'wi_abc', agent: 'patch' }) */ export async function release(input: { id: string; agent?: string; dryRun?: boolean }) { if (!input?.id) throw new Error('release: id is required') const store = await loadClaims() const existing = store.claims[input.id] if (!existing) return { released: true, was: null } if (input.agent && existing.agent !== input.agent) { return { released: false, heldBy: existing.agent } } if (input.dryRun) return { released: true, was: existing, persisted: false } await updateClaims((s) => { const next = { ...s.claims } delete next[input.id] return { claims: next } }) return { released: true, was: existing, persisted: true } }