import assert from 'node:assert/strict' import { registerHooks } from 'node:module' import { test } from 'node:test' // No network: credential('model') returns a canned jev answer; github is injected per test. const STUB = ` const store = globalThis.__factoryStore ??= new Map(); export const packageStorage = () => ({ async get(k) { return store.get(k) ?? null }, async set(k, v) { store.set(k, JSON.stringify(v)) }, }); export const packageContext = { appBasePath: '/apps/factory/' }; export async function credential(key) { if (key === 'model') return { name: 'model', fetch: async () => Response.json({ result: { answers: { autopilot: { choice: 'autopilot_ok', confidence: 0.9 } } } }) }; if (key === 'github' && globalThis.__githubFetch) return { name: 'github', fetch: globalThis.__githubFetch }; throw new Error('credential not mapped'); } export async function credentials() { return [] } ` registerHooks({ resolve(spec, ctx, next) { if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true } return next(spec, ctx) }, }) const g = globalThis as unknown as { __githubFetch?: (u: string) => Promise; __factoryStore: Map } const { sweep } = await import('./orchestrator.ts') const { upsertProject } = await import('../projects/config.ts') const { patchSettings, loadSettings } = await import('../lib/settings.ts') const { default: create } = await import('../exports/create.ts') const { default: linkPr } = await import('../exports/link-pr.ts') const { default: recordOutcome } = await import('../exports/record-outcome.ts') const { default: sync } = await import('../exports/sync.ts') const { ingestSignals } = await import('../signals/intake.ts') const { prReferencesIssue } = await import('./overlap.ts') const { inPilotScope } = await import('./scope.ts') const { loadJson, saveJson, storageKeys } = await import('../lib/storage.ts') const { emptyLedger } = await import('./work-item.ts') type Ledger = import('./work-item.ts').Ledger const ledger = () => loadJson(storageKeys.LEDGER_KEY, emptyLedger()) const item = async (id: string) => (await ledger()).items[id]! const NO_GH = { github: null } await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'kody-hq__kody', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] }) await upsertProject({ id: 'other', displayName: 'Other', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'o__x', repoRef: 'o/x', host: 'github', enabled: true }] }) await patchSettings({ cloudflareAccountId: 'abcdef0123456789abcdef0123456789' }) const issueSignal = (n: number, repo = 'kody-hq/kody', projectId = 'kody') => ({ id: `sig_${n}`, projectId, source: 'github-issues' as const, externalId: String(n), fingerprint: `github-issue:${repo}:${n}`, title: `Issue ${n}`, body: '', severity: 'medium' as const, labels: ['P2'], links: [], repoRef: repo, receivedAt: new Date().toISOString(), }) test('pilot scope defaults to nothing; sweep and sync touch no project until it is set', async () => { assert.deepEqual((await loadSettings()).pilotScope, { mode: 'allowlist', projectIds: [], repoRefs: [] }) const { item: w } = await create({ projectId: 'other', title: 'out of scope' }) const r = await sweep({}, NO_GH) assert.ok(r.outOfScope.includes(w.id)) assert.equal((await item(w.id)).state, 'intake') const s = await sync({}, { fetch: async () => { throw new Error('no network') } }) assert.equal(s.repos.length, 0) assert.ok(s.skippedRepos.every((x) => /pilot scope/.test(x.reason))) assert.equal(inPilotScope({ mode: 'allowlist', projectIds: ['kody'], repoRefs: ['kody-hq/kody'] }, 'kody', 'kody-hq/other'), false) await patchSettings({ pilotScope: { mode: 'allowlist', projectIds: ['kody'], repoRefs: ['kody-hq/kody'] } }) }) test('fingerprint dedupe blocks re-intake in every state, including shipped and dropped', async () => { const first = await ingestSignals([issueSignal(500)]) const id = first.created[0]!.id for (const state of ['needs-kent', 'shipped', 'dropped'] as const) { const l = await ledger(); l.items[id]!.state = state; await saveJson(storageKeys.LEDGER_KEY, l) const again = await ingestSignals([issueSignal(500)]) assert.equal(again.created.length, 0, state) assert.equal(again.deduped[0]!.workItemId, id) } }) test('PR reference matching', () => { assert.ok(prReferencesIssue({ title: 'Fix x', body: 'Closes #12' }, 'kody-hq/kody', 12)) assert.ok(prReferencesIssue({ title: 'x', body: 'see https://github.com/kody-hq/kody/issues/12' }, 'kody-hq/kody', 12)) assert.ok(prReferencesIssue({ title: 'kody-hq/kody#12', body: '' }, 'kody-hq/kody', 12)) assert.ok(!prReferencesIssue({ title: 'Fix #123', body: '' }, 'kody-hq/kody', 12)) assert.ok(!prReferencesIssue({ title: 'x', body: 'other/repo#12' }, 'kody-hq/kody', 12)) }) test('backfill marks issues with an open PR and does not ingest them', async () => { const calls: string[] = [] const fetchFn = async (u: string) => { calls.push(u) if (u.includes('/pulls')) return Response.json([{ number: 77, html_url: 'https://github.com/kody-hq/kody/pull/77', title: 'Fix it', body: 'Fixes #41' }]) return Response.json([{ number: 41, title: 'Has PR', labels: [], html_url: 'https://github.com/kody-hq/kody/issues/41' }, { number: 42, title: 'No PR', labels: [] }]) } const r = await sync({ dryRun: false }, { fetch: fetchFn }) assert.equal(calls.filter((c) => c.includes('/pulls')).length, 1, 'one PR list per repo') const has = r.issues.find((i) => i.number === 41)! assert.equal(has.status, 'open-pr') assert.equal(has.prUrl, 'https://github.com/kody-hq/kody/pull/77') assert.equal(r.totals.created, 1) }) test('sweep suppresses a start when an open PR or active session overlaps, and links it', async () => { await patchSettings({ shadowMode: false }) const l = await ledger() const ids = (await ingestSignals([issueSignal(60), issueSignal(61)])).created.map((c) => c.id) const l2 = await ledger() for (const id of ids) l2.items[id]!.state = 'planned' // 61 already has another in-flight item (running) on the same issue. l2.items['wi_running61'] = { ...l2.items[ids[1]!]!, id: 'wi_running61', fingerprint: 'github-issue:kody-hq/kody:61-dup', state: 'running', runId: 'run_x', links: [{ kind: 'session', url: 'https://app.devin.ai/sessions/abc', at: '' }] } await saveJson(storageKeys.LEDGER_KEY, l2) void l const gh = async (u: string) => Response.json(u.includes('/pulls') ? [{ number: 9, html_url: 'https://github.com/kody-hq/kody/pull/9', title: 'x', body: 'Closes #60' }] : []) const r = await sweep({}, { github: gh }) const s60 = r.suppressed.find((s) => s.workItemId === ids[0])! assert.equal(s60.kind, 'open-pr') const s61 = r.suppressed.find((s) => s.workItemId === ids[1])! assert.equal(s61.kind, 'active-session') assert.equal(s61.url, 'https://app.devin.ai/sessions/abc') const i60 = await item(ids[0]!) assert.equal(i60.state, 'planned') assert.equal(i60.links!.find((x) => x.reason === 'overlap:open-pr')!.url, 'https://github.com/kody-hq/kody/pull/9') const again = await sweep({}, { github: gh }) assert.equal((await item(ids[0]!)).events.filter((e) => /suppressed/.test(e.reason)).length, 1, 'no duplicate events') void again const l3 = await ledger(); for (const id of [...ids, 'wi_running61']) l3.items[id]!.state = 'dropped'; await saveJson(storageKeys.LEDGER_KEY, l3) await patchSettings({ shadowMode: true }) }) test('sweep drops planned items whose source issue is closed instead of starting them', async () => { await patchSettings({ shadowMode: false }) const ids = (await ingestSignals([issueSignal(70), issueSignal(71)])).created.map((c) => c.id) try { const l = await ledger() for (const id of ids) l.items[id]!.state = 'planned' // 70: close already recorded on the item (webhook noted it while planned). l.items[ids[0]!]!.events.push({ at: '', from: 'planned', to: 'planned', reason: 'source issue closed (closed)', actor: 'system', meta: { externalState: 'closed' } }) await saveJson(storageKeys.LEDGER_KEY, l) // 71: close was never recorded, but GitHub says closed. const gh = async (u: string) => Response.json(u.includes('/pulls') ? [] : { state: 'closed' }) const r = await sweep({ limit: 1 }, { github: gh }) assert.equal(r.started.length, 0, 'never starts a closed issue') assert.equal((await item(ids[0]!)).state, 'dropped') assert.equal((await item(ids[1]!)).state, 'dropped') assert.ok(r.advanced.some((a) => a.id === ids[1] && /closed before start/.test(a.reason))) } finally { const l2 = await ledger(); for (const id of ids) l2.items[id]!.state = 'dropped'; await saveJson(storageKeys.LEDGER_KEY, l2) await patchSettings({ shadowMode: true }) } }) test('a running item whose PR merged on GitHub ships, frees the slot, and starts the main watch', async () => { await patchSettings({ shadowMode: false }) const { item: w } = await create({ projectId: 'kody', title: 'merge watch' }) try { const l = await ledger() l.items[w.id] = { ...l.items[w.id]!, state: 'running', runId: 'solo_noop_x', pr: { url: 'https://github.com/kody-hq/kody/pull/77', number: 77, reviewState: 'approved', ready: true, updatedAt: '' } } await saveJson(storageKeys.LEDGER_KEY, l) const sha = 'c'.repeat(40) const gh = async (u: string) => u.endsWith('/pulls/77') ? Response.json({ merged: true, merge_commit_sha: sha }) : u.includes('/pulls') ? Response.json([]) : u.includes(`/commits/${sha}/check-runs`) ? Response.json({ check_runs: [{ status: 'completed', conclusion: 'success' }] }) : Response.json({}) const r = await sweep({}, { github: gh }) const it = await item(w.id) assert.equal(it.state, 'shipped') assert.equal(it.pr!.merged!.attestedBy, 'github-api') assert.equal(it.pr!.merged!.mergeCommit, sha) assert.ok(r.advanced.some((a) => a.id === w.id && a.to === 'shipped')) assert.equal(it.postMerge!.phase, 'green', 'same tick reads the merge commit checks') } finally { const l2 = await ledger(); l2.items[w.id]!.state = 'dropped'; await saveJson(storageKeys.LEDGER_KEY, l2) await patchSettings({ shadowMode: true }) } }) test('record-outcome with a merge commit ships and starts the watch', async () => { const { item: w } = await create({ projectId: 'kody', title: 'record watch' }) const r = await recordOutcome({ workItemId: w.id, state: 'succeeded', merged: true, attestedBy: 'kent', mergeCommit: 'd'.repeat(40), artifacts: [{ kind: 'pr', url: 'https://github.com/kody-hq/kody/pull/78' }], dryRun: true }) assert.equal(r.item.state, 'shipped') assert.equal(r.item.postMerge!.phase, 'watching') const l = await ledger(); l.items[w.id]!.state = 'dropped'; await saveJson(storageKeys.LEDGER_KEY, l) }) test('merge needs attestation: record-outcome and link-pr validate', async () => { const { item: w } = await create({ projectId: 'kody', title: 'attest' }) await assert.rejects(recordOutcome({ workItemId: w.id, state: 'succeeded', merged: true }), /attestedBy/) await assert.rejects(recordOutcome({ workItemId: w.id, state: 'succeeded', merged: true, attestedBy: 'kent' }), /PR/) await assert.rejects(linkPr({ workItemId: w.id, prUrl: 'https://github.com/o/x/pull/1' }), /kody-hq\/kody/) await assert.rejects(linkPr({ workItemId: w.id, prUrl: 'https://evil.example/pull/1' }), /prUrl/) const r = await recordOutcome({ workItemId: w.id, state: 'succeeded', merged: true, attestedBy: 'kent', artifacts: [{ kind: 'pr', url: 'https://github.com/kody-hq/kody/pull/5' }] }) assert.equal(r.item.state, 'shipped') assert.equal(r.item.pr!.merged!.attestedBy, 'kent') const l = await ledger(); l.items[w.id]!.state = 'dropped'; await saveJson(storageKeys.LEDGER_KEY, l) }) test('full mock lifecycle: intake → triaged → planned → (shadow holds) → running → verifying → shipped on attested merge', async () => { const { item: w } = await create({ projectId: 'kody', title: 'Lifecycle work', priority: 1 }) const step = async () => { await sweep({}, NO_GH); return (await item(w.id)).state } assert.equal(await step(), 'triaged') assert.equal(await step(), 'planned') assert.equal(await step(), 'planned', 'shadow mode never starts a run') assert.match((await item(w.id)).events.at(-1)!.reason, /shadow\/dry: would start single-agent/) await patchSettings({ shadowMode: false }) assert.equal(await step(), 'running') const running = await item(w.id) assert.match(running.runId ?? '', /^solo_noop_/) assert.match(running.events.at(-1)!.reason, /started single-agent/) assert.equal(await step(), 'verifying') assert.equal(await step(), 'verifying', 'summary text alone never ships') await linkPr({ workItemId: w.id, prUrl: 'https://github.com/kody-hq/kody/pull/321', reviewState: 'approved', ready: true }) assert.equal(await step(), 'verifying', 'approved but not merged') await linkPr({ workItemId: w.id, prUrl: 'https://github.com/kody-hq/kody/pull/321', merged: { by: 'human', attestedBy: 'kent', mergeCommit: 'abc1234' } }) assert.equal(await step(), 'shipped') const done = await item(w.id) assert.equal(done.pr!.reviewState, 'approved') assert.ok(done.links!.some((l) => l.kind === 'pr' && l.url.endsWith('/pull/321'))) await patchSettings({ shadowMode: true }) })