Merge pull request #1153 from getagentseal/feat/consent-scheduler

feat(sync): consent-once auto-sync with acceptance fingerprint, receipts, and kill switch (CB-4)
This commit is contained in:
Resham Joshi 2026-08-28 07:08:35 -07:00 • committed by GitHub
commit 3b4d3fd665
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 1149 additions and 2 deletions

View file

@ -21,10 +21,91 @@ import {
CALLBACK_PORTS,
} from './auth.js'
import { createCredentialStore } from './credentials.js'
import { readSyncConfig, writeSyncConfig, deleteSyncConfig, updateLastSync } from './config.js'
import { readSyncConfig, writeSyncConfig, deleteSyncConfig, updateLastSync, receiptsPath, readReceipts, appendReceipt } from './config.js'
import { collectUnsentCalls, collectUnsentAttribution, sendBatches, sendAttributionBatches, batchCalls, MAX_PER_PUSH, MAX_ATTRIBUTION_PER_PUSH, type PushResult } from './push.js'
import { batchAttributionItems, wireProjectName } from './otlp.js'
import { batchAttributionItems, wireProjectName, CORE_SYNC_ATTRIBUTE_KEYS } from './otlp.js'
import { loadPlugins, declaredSyncAttributes, type PluginLoad } from '../plugins/loader.js'
import {
computeAcceptanceFingerprint,
buildDisclosure,
CORE_SYNC_FIELD_MEANINGS,
detectFingerprintChanges,
type FingerprintInput,
type DisclosureInput,
type Receipt,
buildReceipt,
} from './consent.js'
import { installSchedule, removeSchedule } from './schedule-installer.js'
// Helper for executing the push after data collection
interface ExecutePushInput {
config: NonNullable<Awaited<ReturnType<typeof readSyncConfig>>>
unsent: Awaited<ReturnType<typeof collectUnsentCalls>>['unsent']
attributionUnsent: Awaited<ReturnType<typeof collectUnsentAttribution>>['unsent']
pluginAttributeKeys: ReadonlySet<string>
coverageThrough?: string
tokens: { access_token: string }
silent?: boolean
}
async function executePush(input: ExecutePushInput): Promise<{ result: PushResult; attrResult: PushResult | null; attrFacts: number }> {
const { config, unsent, attributionUnsent, pluginAttributeKeys, coverageThrough, tokens, silent } = input
const log = silent ? () => {} : (msg: string) => process.stderr.write(`${msg}\n`)
const discoveryDoc = await fetchDiscoveryDoc(config.baseUrl)
const endpoint = `${config.baseUrl}${config.tracesPath}`
let result: PushResult = { outcome: 'complete', totalSent: 0, totalRejected: 0, totalCostSent: 0 }
if (unsent.length > 0) {
const toPush = unsent.slice(0, MAX_PER_PUSH)
const batches = batchCalls(toPush, discoveryDoc.max_batch_size)
result = await sendBatches({
endpoint,
accessToken: tokens.access_token,
batches,
...(coverageThrough ? { coverageThrough } : {}),
pluginAttributes: { keys: pluginAttributeKeys, values: [] },
log,
})
}
let attrResult: PushResult | null = null
let attrFacts = 0
if (attributionUnsent.length > 0 && result.outcome === 'complete') {
const attrToPush = attributionUnsent.slice(0, MAX_ATTRIBUTION_PER_PUSH)
const attrBatches = batchAttributionItems(attrToPush, discoveryDoc.max_batch_size)
attrResult = await sendAttributionBatches({
endpoint,
accessToken: tokens.access_token,
batches: attrBatches,
log,
})
attrFacts = attrResult.outcome === 'complete' ? attrResult.totalSent : 0
}
if (result.outcome === 'complete') {
updateLastSync()
}
return { result, attrResult, attrFacts }
}
// Helper to build FingerprintInput for acceptance checking
function buildAcceptanceFingerprintInput(
config: NonNullable<Awaited<ReturnType<typeof readSyncConfig>>>,
allKeys: string[],
workMatching: boolean,
cadence: 'daily' | 'hourly',
): FingerprintInput {
return {
org: config.clientId,
destination: config.baseUrl,
outboundFields: allKeys,
workMatching,
scopeSinceDays: 7,
cadence,
}
}
export function registerSyncCommands(program: Command): void {
const sync = program
@ -475,4 +556,287 @@ export function registerSyncCommands(program: Command): void {
process.exit(1)
}
})
// --- auto (parent) ---
const auto = sync
.command('auto')
.description('Manage automatic scheduled pushes')
// --- auto enable ---
auto
.command('enable')
.description('Enable automatic scheduled pushes (requires --accept to proceed)')
.option('--cadence <cadence>', 'Schedule frequency: daily or hourly', 'daily')
.option('--attribution', 'Also send work-matching data (session-to-commit links)')
.option('--accept', 'Accept the disclosure and enable automatic sync')
.action(async (opts: { cadence?: string; attribution?: boolean; accept?: boolean }) => {
const config = readSyncConfig()
if (!config) {
process.stderr.write('Sync not configured. Run `codeburn sync setup <url>` first.\n')
process.exit(1)
}
const cadence = opts.cadence as 'daily' | 'hourly'
if (cadence !== 'daily' && cadence !== 'hourly') {
process.stderr.write('Invalid --cadence. Use: daily or hourly\n')
process.exit(1)
}
try {
const pluginLoads: PluginLoad[] = await loadPlugins()
const pluginKeys = declaredSyncAttributes(pluginLoads)
const allKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS)
.concat(Array.from(pluginKeys.keys()))
.sort()
const fieldList = allKeys.map(key => {
const plugin = pluginKeys.get(key)
const disclosure = plugin?.disclosure ?? CORE_SYNC_FIELD_MEANINGS.get(key) ?? '(no description)'
return { key, disclosure }
})
const workMatching = opts.attribution ?? false
const fingerprintInput = buildAcceptanceFingerprintInput(config, allKeys, workMatching, cadence)
const fingerprint = computeAcceptanceFingerprint(fingerprintInput)
const disclosureInput: DisclosureInput = {
destination: config.clientId,
destinationUrl: config.baseUrl,
cadence,
outboundFields: fieldList,
workMatching,
scopeSinceDays: 7,
}
const disclosure = buildDisclosure(disclosureInput)
process.stdout.write(disclosure + '\n\n')
if (!opts.accept) {
process.stderr.write('Re-run with --accept to consent to exactly this.\n')
process.exit(1)
}
config.auto = {
accepted: {
fingerprint,
acceptedAt: new Date().toISOString(),
cadence,
disclosure,
attribution: workMatching,
input: fingerprintInput,
},
killed: false,
}
delete config.auto.killed
writeSyncConfig(config)
try {
await installSchedule(cadence, process.argv[1])
process.stdout.write(`Automatic sync enabled (${cadence}). Fingerprint: ${fingerprint}\n`)
} catch (schedErr) {
process.stderr.write(`Warning: ${(schedErr as Error).message}\n`)
process.stderr.write(`Acceptance was stored and will take effect, but the schedule could not be installed.\n`)
process.stderr.write(`Run: codeburn sync auto enable --cadence ${cadence} --attribution${opts.attribution ? '' : ''}\n`)
process.stderr.write(`Or install manually: launchctl load ~/Library/LaunchAgents/com.codeburn.sync-auto.plist\n`)
process.exit(1)
}
} catch (err) {
process.stderr.write(`${(err as Error).message}\n`)
process.exit(1)
}
})
// --- auto disable ---
auto
.command('disable')
.description('Disable automatic scheduled pushes (kill switch)')
.action(async () => {
const config = readSyncConfig()
if (!config) {
process.stderr.write('Sync not configured.\n')
return
}
if (!config.auto?.accepted) {
process.stdout.write('Automatic sync was not enabled.\n')
return
}
config.auto.killed = true
writeSyncConfig(config)
try {
await removeSchedule()
} catch {
// Best effort
}
process.stdout.write('Automatic sync disabled.\n')
})
// --- auto status ---
auto
.command('status')
.description('Show automatic sync status and recent receipts')
.action(async () => {
const config = readSyncConfig()
if (!config?.auto?.accepted) {
process.stdout.write('Automatic sync is not configured.\n')
return
}
const accepted = config.auto.accepted
process.stdout.write(`Accepted fingerprint: ${accepted.fingerprint}\n`)
process.stdout.write(`Accepted at: ${accepted.acceptedAt}\n`)
process.stdout.write(`Cadence: ${accepted.cadence}\n`)
// Recompute fingerprint to check for changes
try {
const pluginLoads: PluginLoad[] = await loadPlugins()
const pluginKeys = declaredSyncAttributes(pluginLoads)
const allKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS)
.concat(Array.from(pluginKeys.keys()))
.sort()
const fingerprintInput = buildAcceptanceFingerprintInput(config, allKeys, accepted.attribution, accepted.cadence)
const currentFingerprint = computeAcceptanceFingerprint(fingerprintInput)
if (currentFingerprint === accepted.fingerprint) {
process.stdout.write('Current fingerprint: MATCHES\n')
} else {
const changed = detectFingerprintChanges(accepted.input, fingerprintInput)
process.stdout.write(`Current fingerprint: DIFFERS (${changed.join(', ')})\n`)
}
} catch {
process.stdout.write('Current fingerprint: unable to recompute\n')
}
process.stdout.write(`Killed: ${config.auto.killed ? 'yes' : 'no'}\n`)
const receipts = readReceipts(5)
if (receipts.length > 0) {
process.stdout.write('\nLast 5 receipts:\n')
for (const r of receipts) {
process.stdout.write(` ${r.at} - ${r.result}\n`)
}
}
})
// --- auto run ---
auto
.command('run')
.description('Run automatic push (invoked by scheduler)')
.action(async () => {
const config = readSyncConfig()
const at = new Date().toISOString()
if (config?.auto?.killed) {
appendReceipt(buildReceipt(at, undefined, { result: 'killed' }))
return
}
if (!config?.auto?.accepted) {
appendReceipt(buildReceipt(at, undefined, { result: 'not-accepted' }))
return
}
const accepted = config.auto.accepted
try {
// Recompute fingerprint
const pluginLoads: PluginLoad[] = await loadPlugins()
const pluginKeys = declaredSyncAttributes(pluginLoads)
const allKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS)
.concat(Array.from(pluginKeys.keys()))
.sort()
const fingerprintInput = buildAcceptanceFingerprintInput(config, allKeys, accepted.attribution, accepted.cadence)
const currentFingerprint = computeAcceptanceFingerprint(fingerprintInput)
if (currentFingerprint !== accepted.fingerprint) {
const changed = detectFingerprintChanges(accepted.input, fingerprintInput)
appendReceipt(buildReceipt(
at,
currentFingerprint,
{ result: 'acceptance-required', changed }
))
return
}
// Collect data - 7 day window. Sent-ledger prevents duplicates across runs,
// so daily/hourly rescans don't lose anything.
const { parseAllSessions } = await import('../parser.js')
const { getDateRange } = await import('../cli-date.js')
const range = getDateRange('week').range
const projects = (await parseAllSessions(range))
.map(p => ({ ...p, project: wireProjectName(p.projectPath, p.project) }))
const { readPlans } = await import('../config.js')
const plans = await readPlans()
const { loadDailyCache } = await import('../daily-cache.js')
const dailyCache = await loadDailyCache()
const coverageThrough = dailyCache.complete === true && dailyCache.watermarkTrusted === true && dailyCache.lastComputedDate
? dailyCache.lastComputedDate
: undefined
const { unsent } = collectUnsentCalls(projects, Date.now(), { plans })
if (unsent.length === 0) {
appendReceipt(buildReceipt(at, currentFingerprint, { result: 'pushed', spans: 0 }))
return
}
const store = createCredentialStore()
const rt = store.retrieve()
if (!rt) {
appendReceipt(buildReceipt(at, currentFingerprint, { result: 'error', reason: 'no auth token' }))
return
}
const oidc = await fetchOidcConfig(config.issuer)
const tokens = await refreshToken(oidc.token_endpoint, rt, config.clientId)
if (tokens.refresh_token && tokens.refresh_token !== rt) {
store.store(tokens.refresh_token)
}
// Collect attribution if enabled
let attributionUnsent: Awaited<ReturnType<typeof collectUnsentAttribution>>['unsent'] = []
if (accepted.attribution) {
const { computeAttributionRecords } = await import('../yield.js')
const records = computeAttributionRecords(projects, range, process.cwd())
const collected = collectUnsentAttribution(records)
attributionUnsent = collected.unsent
}
// Use shared push helper
const pluginAttributeKeys: ReadonlySet<string> = new Set(pluginKeys.keys())
const { result, attrFacts } = await executePush({
config,
unsent,
attributionUnsent,
pluginAttributeKeys,
coverageThrough,
tokens,
silent: true,
})
if (result.outcome === 'complete') {
const receipt: Record<string, unknown> = { result: 'pushed', spans: result.totalSent }
if (attrFacts > 0) {
receipt.attributionFacts = attrFacts
}
appendReceipt(buildReceipt(at, currentFingerprint, receipt as any))
} else {
appendReceipt(buildReceipt(at, currentFingerprint, { result: 'error', reason: result.outcome }))
}
} catch (err) {
appendReceipt(buildReceipt(
at,
undefined,
{ result: 'error', reason: err instanceof Error ? err.message : String(err) }
))
}
})
}

View file

@ -8,12 +8,15 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from '
import { join } from 'path'
import { homedir } from 'os'
import type { AutoSyncConfig } from './consent.js'
export interface SyncConfig {
baseUrl: string
clientId: string
tracesPath: string
issuer: string
lastSync?: string
auto?: AutoSyncConfig
}
function configDir(): string {
@ -24,6 +27,10 @@ function configPath(): string {
return join(configDir(), 'sync.json')
}
export function receiptsPath(): string {
return join(configDir(), 'receipts.jsonl')
}
export function readSyncConfig(): SyncConfig | null {
const path = configPath()
if (!existsSync(path)) return null
@ -42,6 +49,7 @@ export function readSyncConfig(): SyncConfig | null {
tracesPath: typeof data.tracesPath === 'string' ? data.tracesPath : '/v1/traces',
issuer: typeof data.issuer === 'string' ? data.issuer : '',
lastSync: typeof data.lastSync === 'string' ? data.lastSync : undefined,
auto: typeof data.auto === 'object' && data.auto ? (data.auto as AutoSyncConfig) : undefined,
}
} catch {
return null
@ -64,3 +72,28 @@ export function updateLastSync(): void {
export function deleteSyncConfig(): void {
try { unlinkSync(configPath()) } catch { /* may not exist */ }
}
export function readReceipts(limit?: number): Array<Record<string, unknown>> {
const path = receiptsPath()
if (!existsSync(path)) return []
try {
const raw = readFileSync(path, 'utf-8')
const lines = raw.trim().split('\n').filter(Boolean)
const entries = lines.map(line => JSON.parse(line) as Record<string, unknown>)
if (limit && limit > 0) return entries.slice(-limit)
return entries
} catch {
return []
}
}
export function appendReceipt(receipt: Record<string, unknown>): void {
const dir = configDir()
mkdirSync(dir, { recursive: true })
const path = receiptsPath()
// Ensure directory exists immediately before write (handles race conditions)
mkdirSync(dir, { recursive: true })
const line = JSON.stringify(receipt) + '\n'
writeFileSync(path, line, { flag: 'a' })
}

184
src/sync/consent.ts Normal file
View file

@ -0,0 +1,184 @@
/**
* codeburn sync - consent-once auto-sync with fingerprint and receipts.
*
* Manages acceptance fingerprints, disclosure building, and receipt tracking
* for automatic scheduled pushes.
*/
import { createHash } from 'crypto'
export const WIRE_CONTRACT_VERSION = 'v2'
export const CORE_SYNC_FIELD_MEANINGS: ReadonlyMap<string, string> = new Map([
['ai.provider', 'which AI service handled the call'],
['ai.model', 'which AI model handled the call'],
['ai.input_tokens', 'tokens sent to the model'],
['ai.output_tokens', 'tokens returned by the model'],
['ai.cost_usd', 'the cost of the call in US dollars'],
['ai.speed', 'how many output tokens per second'],
['ai.project', 'directory name of the project'],
['ai.tools', 'tools available to the model'],
['ai.cost_estimated', 'whether cost was estimated or billed'],
['ai.work_unit_id', 'internal task identifier (only when work matching is on)'],
['ai.session_role', 'type of usage (development, production, etc.)'],
['ai.lineage_evidence', 'evidence linking the session to a task (only when work matching is on)'],
['ai.cache_read_tokens', 'tokens read from cache'],
['ai.cache_write_tokens', 'tokens written to cache'],
['ai.call_count', 'how many API requests in the session'],
['ai.session_duration_ms', 'how long the session lasted in milliseconds'],
['ai.subscription_covered', 'whether usage is covered by subscription'],
['codeburn.device_id', 'a stable random identifier for this device'],
['codeburn.coverage_through', 'date through which usage has been analyzed'],
['codeburn.attribution_methodology', 'how session-to-task links were inferred'],
['git.repo', 'repository name (only when work matching is on)'],
['git.sha', 'commit hash (only when work matching is on)'],
['git.commit_count', 'number of commits in the session (only when work matching is on)'],
['git.in_main', 'whether commits were to the main branch (only when work matching is on)'],
['git.was_reverted', 'whether work was reverted (only when work matching is on)'],
['git.pr_links', 'pull request URLs (only when work matching is on)'],
])
export interface FingerprintInput {
org: string
destination: string
outboundFields: string[]
workMatching: boolean
scopeSinceDays: number | null
cadence: 'daily' | 'hourly'
}
export function computeAcceptanceFingerprint(input: FingerprintInput): string {
const canonical = {
org: input.org,
destination: input.destination,
contractVersion: WIRE_CONTRACT_VERSION,
outboundFields: [...input.outboundFields].sort(),
workMatching: input.workMatching,
scopeSinceDays: input.scopeSinceDays,
cadence: input.cadence,
}
const json = JSON.stringify(canonical)
return createHash('sha256').update(json).digest('hex')
}
export interface DisclosureInput {
destination: string
destinationUrl: string
cadence: 'daily' | 'hourly'
outboundFields: Array<{ key: string; disclosure: string }>
workMatching: boolean
scopeSinceDays: number | null
}
export function buildDisclosure(input: DisclosureInput): string {
const cadenceText = input.cadence === 'daily' ? 'once per day' : 'once per hour'
const scopeText = input.scopeSinceDays === null
? 'full history (up to 6 months)'
: input.scopeSinceDays === 0
? 'today only'
: `last ${input.scopeSinceDays} days`
const workMatchingText = input.workMatching
? 'on - session-to-commit links are sent'
: 'off'
const fieldsList = input.outboundFields.length > 0
? input.outboundFields
.map(f => ` ${f.key}: ${f.disclosure}`)
.join('\n')
: ' (no fields)'
return [
`Destination: ${input.destination}`,
`URL: ${input.destinationUrl}`,
`Cadence: ${cadenceText}`,
`Scope: ${scopeText}`,
`Work matching: ${workMatchingText}`,
'',
'Data sent to the endpoint:',
fieldsList,
'',
'Data that stays local:',
' raw prompts (never sent)',
' file paths (only project basename sent)',
' provider configuration files',
'',
'You can stop automatic sync at any time with: codeburn sync auto disable',
'Any change to what would be sent requires your acceptance again before an automatic push runs.',
].join('\n')
}
export interface AcceptanceRecord {
fingerprint: string
acceptedAt: string
cadence: 'daily' | 'hourly'
disclosure: string
attribution: boolean
input?: FingerprintInput
}
export interface AutoSyncConfig {
accepted?: AcceptanceRecord
killed?: boolean
lastRun?: {
at: string
result: string
}
}
export type ReceiptResult =
| { result: 'killed' }
| { result: 'not-accepted' }
| { result: 'acceptance-required'; changed: string[] }
| { result: 'pushed'; spans: number }
| { result: 'error'; reason: string }
export interface Receipt {
at: string
fingerprint?: string
result: string
[key: string]: unknown
}
export function buildReceipt(at: string, fingerprint: string | undefined, data: ReceiptResult): Receipt {
return {
at,
...(fingerprint && { fingerprint }),
...data,
}
}
export function detectFingerprintChanges(stored: FingerprintInput | undefined, current: FingerprintInput): string[] {
if (!stored) return ['unknown']
const changes: string[] = []
if (stored.destination !== current.destination) {
changes.push('destination')
}
if (stored.cadence !== current.cadence) {
changes.push('cadence')
}
if (stored.scopeSinceDays !== current.scopeSinceDays) {
changes.push('scope')
}
if (stored.workMatching !== current.workMatching) {
changes.push('work matching')
}
const storedFields = new Set(stored.outboundFields)
const currentFields = new Set(current.outboundFields)
const added = Array.from(currentFields).filter(f => !storedFields.has(f)).sort()
const removed = Array.from(storedFields).filter(f => !currentFields.has(f)).sort()
if (added.length > 0 || removed.length > 0) {
const parts: string[] = []
if (added.length > 0) parts.push(`added: ${added.join(', ')}`)
if (removed.length > 0) parts.push(`removed: ${removed.join(', ')}`)
changes.push(`field set (${parts.join(' / ')})`)
}
return changes.length > 0 ? changes : ['unknown']
}

View file

@ -0,0 +1,121 @@
/**
* codeburn sync - schedule installer for automatic pushes.
*
* Manages LaunchAgent plist on macOS for scheduled sync auto runs.
* On other platforms, prints the crontab line to add manually.
*/
import { platform } from 'os'
import { homedir } from 'os'
import { join } from 'path'
import { writeFileSync, unlinkSync, existsSync, mkdirSync } from 'fs'
import { spawn } from 'child_process'
const SCHEDULE_AGENT_NAME = 'com.codeburn.sync-auto'
const SCHEDULE_INTERVAL_DAILY = 86400
const SCHEDULE_INTERVAL_HOURLY = 3600
function launchAgentDir(): string {
return join(homedir(), 'Library', 'LaunchAgents')
}
function launchAgentPath(): string {
return join(launchAgentDir(), `${SCHEDULE_AGENT_NAME}.plist`)
}
function buildLaunchAgentPlist(
cadence: 'daily' | 'hourly',
codeburn_path: string,
): string {
const interval = cadence === 'daily' ? SCHEDULE_INTERVAL_DAILY : SCHEDULE_INTERVAL_HOURLY
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>${SCHEDULE_AGENT_NAME}</string>
<key>ProgramArguments</key>
<array>
<string>${codeburn_path}</string>
<string>sync</string>
<string>auto</string>
<string>run</string>
</array>
<key>StartInterval</key>
<integer>${interval}</integer>
<key>StandardErrorPath</key>
<string>/dev/null</string>
<key>StandardOutPath</key>
<string>/dev/null</string>
</dict>
</plist>
`
}
export async function installSchedule(
cadence: 'daily' | 'hourly',
codeburnPath: string,
): Promise<void> {
if (platform() !== 'darwin') {
const cronExpression = cadence === 'daily'
? '0 0 * * *'
: '0 * * * *'
process.stderr.write(`macOS is not detected. To schedule automatic syncs, add to crontab:\n`)
process.stderr.write(` ${cronExpression} ${codeburnPath} sync auto run\n`)
return
}
const plistContent = buildLaunchAgentPlist(cadence, codeburnPath)
const plistPath = launchAgentPath()
const agentDir = launchAgentDir()
try {
// Ensure LaunchAgents directory exists
mkdirSync(agentDir, { recursive: true })
// Write the plist
writeFileSync(plistPath, plistContent, { mode: 0o644 })
// Load the agent (unload first if it's already loaded)
try {
await runCommand('/bin/launchctl', ['unload', plistPath])
} catch {
// May not be loaded yet
}
await runCommand('/bin/launchctl', ['load', plistPath])
} catch (err) {
throw new Error(`Failed to install schedule: ${err instanceof Error ? err.message : String(err)}`)
}
}
export async function removeSchedule(): Promise<void> {
if (platform() !== 'darwin') return
const plistPath = launchAgentPath()
try {
await runCommand('/bin/launchctl', ['unload', plistPath])
} catch {
// May not be loaded
}
try {
unlinkSync(plistPath)
} catch {
// May not exist
}
}
function runCommand(command: string, args: string[]): Promise<void> {
return new Promise((resolve, reject) => {
const proc = spawn(command, args, { stdio: 'pipe' })
let stderr = ''
proc.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString()
})
proc.on('error', reject)
proc.on('close', (code) => {
if (code === 0) resolve()
else reject(new Error(`${command} exited with status ${code}${stderr ? `: ${stderr.trim()}` : ''}`))
})
})
}

445
tests/sync-consent.test.ts Normal file
View file

@ -0,0 +1,445 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { mkdtemp, rm, writeFile, readFile, mkdir } from 'fs/promises'
import { join } from 'path'
import { tmpdir } from 'os'
import {
computeAcceptanceFingerprint,
buildDisclosure,
CORE_SYNC_FIELD_MEANINGS,
detectFingerprintChanges,
type FingerprintInput,
type DisclosureInput,
} from '../src/sync/consent.js'
import { readSyncConfig, writeSyncConfig, readReceipts, appendReceipt } from '../src/sync/config.js'
import { CORE_SYNC_ATTRIBUTE_KEYS } from '../src/sync/otlp.js'
describe('Fingerprint', () => {
it('is deterministic - same input produces same hash', () => {
const input: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd', 'ai.model'],
workMatching: true,
scopeSinceDays: 7,
cadence: 'daily',
}
const fp1 = computeAcceptanceFingerprint(input)
const fp2 = computeAcceptanceFingerprint(input)
expect(fp1).toBe(fp2)
expect(fp1).toMatch(/^[a-f0-9]{64}$/)
})
it('differs when org changes', () => {
const base: FingerprintInput = {
org: 'org1',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd'],
workMatching: true,
scopeSinceDays: null,
cadence: 'daily',
}
const changed = { ...base, org: 'org2' }
const fp1 = computeAcceptanceFingerprint(base)
const fp2 = computeAcceptanceFingerprint(changed)
expect(fp1).not.toBe(fp2)
})
it('differs when destination changes', () => {
const base: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint1.example.com',
outboundFields: ['ai.cost_usd'],
workMatching: true,
scopeSinceDays: null,
cadence: 'daily',
}
const changed = { ...base, destination: 'https://endpoint2.example.com' }
const fp1 = computeAcceptanceFingerprint(base)
const fp2 = computeAcceptanceFingerprint(changed)
expect(fp1).not.toBe(fp2)
})
it('differs when fields change', () => {
const base: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd', 'ai.model'],
workMatching: true,
scopeSinceDays: null,
cadence: 'daily',
}
const changed = { ...base, outboundFields: ['ai.cost_usd', 'ai.model', 'git.repo'] }
const fp1 = computeAcceptanceFingerprint(base)
const fp2 = computeAcceptanceFingerprint(changed)
expect(fp1).not.toBe(fp2)
})
it('differs when workMatching changes', () => {
const base: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd'],
workMatching: true,
scopeSinceDays: null,
cadence: 'daily',
}
const changed = { ...base, workMatching: false }
const fp1 = computeAcceptanceFingerprint(base)
const fp2 = computeAcceptanceFingerprint(changed)
expect(fp1).not.toBe(fp2)
})
it('differs when scopeSinceDays changes', () => {
const base: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd'],
workMatching: true,
scopeSinceDays: null,
cadence: 'daily',
}
const changed = { ...base, scopeSinceDays: 7 }
const fp1 = computeAcceptanceFingerprint(base)
const fp2 = computeAcceptanceFingerprint(changed)
expect(fp1).not.toBe(fp2)
})
it('differs when cadence changes', () => {
const base: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd'],
workMatching: true,
scopeSinceDays: null,
cadence: 'daily',
}
const changed = { ...base, cadence: 'hourly' }
const fp1 = computeAcceptanceFingerprint(base)
const fp2 = computeAcceptanceFingerprint(changed)
expect(fp1).not.toBe(fp2)
})
})
describe('Disclosure', () => {
it('builds readable disclosure text', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [
{ key: 'ai.cost_usd', disclosure: 'Dollar cost of API calls' },
{ key: 'ai.model', disclosure: 'AI model name' },
],
workMatching: true,
scopeSinceDays: null,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('test-org')
expect(disclosure).toContain('https://endpoint.example.com')
expect(disclosure).toContain('once per day')
expect(disclosure).toContain('ai.cost_usd')
expect(disclosure).toContain('ai.model')
expect(disclosure).toContain('raw prompts')
expect(disclosure).toContain('file paths')
expect(disclosure).toContain('codeburn sync auto disable')
})
it('states hourly cadence correctly', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'hourly',
outboundFields: [],
workMatching: true,
scopeSinceDays: null,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('once per hour')
})
it('states scope correctly for null (full history)', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [],
workMatching: true,
scopeSinceDays: null,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('full history')
})
it('states scope correctly for 0 (today only)', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [],
workMatching: true,
scopeSinceDays: 0,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('today only')
})
it('states scope correctly for days', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [],
workMatching: true,
scopeSinceDays: 7,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('last 7 days')
})
it('core field meanings map contains all core attribute keys', () => {
const meaningsKeys = new Set(CORE_SYNC_FIELD_MEANINGS.keys())
for (const key of CORE_SYNC_ATTRIBUTE_KEYS) {
expect(meaningsKeys.has(key)).toBe(true)
}
})
it('disclosure contains no empty field meanings', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [
{ key: 'ai.cost_usd', disclosure: 'the cost of the call in US dollars' },
{ key: 'ai.model', disclosure: 'which AI model handled the call' },
{ key: 'custom.field', disclosure: 'custom plugin field' },
],
workMatching: false,
scopeSinceDays: 7,
}
const disclosure = buildDisclosure(input)
// Check that no field line (starting with spaces) ends with ":" and nothing after
const lines = disclosure.split('\n')
for (const line of lines) {
if (line.startsWith(' ') && line.includes(':')) {
// Field line: should have content after the colon
expect(line).not.toMatch(/:\s*$/)
}
}
})
it('includes work-matching line when enabled', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [],
workMatching: true,
scopeSinceDays: 7,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('Work matching: on - session-to-commit links are sent')
})
it('includes work-matching line when disabled', () => {
const input: DisclosureInput = {
destination: 'test-org',
destinationUrl: 'https://endpoint.example.com',
cadence: 'daily',
outboundFields: [],
workMatching: false,
scopeSinceDays: 7,
}
const disclosure = buildDisclosure(input)
expect(disclosure).toContain('Work matching: off')
})
it('detects removed field set changes', () => {
const storedInput: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd', 'ai.model', 'plugin.custom'],
workMatching: false,
scopeSinceDays: 7,
cadence: 'daily',
}
const currentInput: FingerprintInput = {
org: 'test-org',
destination: 'https://endpoint.example.com',
outboundFields: ['ai.cost_usd', 'ai.model'],
workMatching: false,
scopeSinceDays: 7,
cadence: 'daily',
}
const changes = detectFingerprintChanges(storedInput, currentInput)
expect(changes[0]).toContain('field set')
expect(changes[0]).toContain('removed: plugin.custom')
})
})
describe('Config with auto block', () => {
let tmpDir: string
beforeEach(async () => {
tmpDir = await mkdtemp(join(tmpdir(), 'codeburn-test-'))
process.env.HOME = tmpDir
})
afterEach(async () => {
await rm(tmpDir, { recursive: true, force: true })
})
it('round-trips auto block through config with attribution', async () => {
const configDir = join(tmpDir, '.config', 'codeburn')
await mkdir(configDir, { recursive: true })
const config = {
baseUrl: 'https://endpoint.example.com',
clientId: 'test-client',
tracesPath: '/v1/traces',
issuer: 'https://issuer.example.com',
auto: {
accepted: {
fingerprint: 'abc123',
acceptedAt: new Date().toISOString(),
cadence: 'daily' as const,
disclosure: 'Test disclosure',
attribution: true,
},
killed: false,
},
}
writeSyncConfig(config)
const loaded = readSyncConfig()
expect(loaded?.auto?.accepted?.fingerprint).toBe('abc123')
expect(loaded?.auto?.accepted?.cadence).toBe('daily')
expect(loaded?.auto?.accepted?.attribution).toBe(true)
expect(loaded?.auto?.killed).toBe(false)
})
it('status recompute matches original fingerprint when attribution choice stored', () => {
// Simulate what enable does: compute fingerprint with 7-day scope and stored attribution choice
const fields = ['ai.cost_usd', 'ai.model', 'git.repo']
const attribution = false // User did NOT request --attribution
const cadence = 'daily' as const
const enableInput: FingerprintInput = {
org: 'test-client',
destination: 'https://endpoint.example.com',
outboundFields: fields,
workMatching: attribution,
scopeSinceDays: 7,
cadence,
}
const storedFingerprint = computeAcceptanceFingerprint(enableInput)
// Now simulate what status does: recompute with same config
const statusInput: FingerprintInput = {
org: 'test-client',
destination: 'https://endpoint.example.com',
outboundFields: fields,
workMatching: attribution, // Same as what was stored
scopeSinceDays: 7, // Same as what was stored
cadence,
}
const recomputedFingerprint = computeAcceptanceFingerprint(statusInput)
expect(recomputedFingerprint).toBe(storedFingerprint)
})
it('handles missing auto block', () => {
const configDir = join(tmpDir, '.config', 'codeburn')
mkdir(configDir, { recursive: true })
const config = {
baseUrl: 'https://endpoint.example.com',
clientId: 'test-client',
tracesPath: '/v1/traces',
issuer: 'https://issuer.example.com',
}
writeSyncConfig(config)
const loaded = readSyncConfig()
expect(loaded?.auto).toBeUndefined()
})
})
describe('Receipts', () => {
let tmpDir: string
beforeEach(async () => {
tmpDir = await mkdtemp(join(tmpdir(), 'codeburn-test-'))
process.env.HOME = tmpDir
})
afterEach(async () => {
await rm(tmpDir, { recursive: true, force: true })
})
it('appends receipts to JSONL file', () => {
const configDir = join(tmpDir, '.config', 'codeburn')
mkdir(configDir, { recursive: true })
const receipt1 = { at: '2024-01-01T00:00:00Z', result: 'pushed', spans: 10 }
const receipt2 = { at: '2024-01-02T00:00:00Z', result: 'killed' }
appendReceipt(receipt1)
appendReceipt(receipt2)
const receipts = readReceipts()
expect(receipts).toHaveLength(2)
expect(receipts[0]?.result).toBe('pushed')
expect(receipts[1]?.result).toBe('killed')
})
it('reads last N receipts', () => {
const configDir = join(tmpDir, '.config', 'codeburn')
mkdir(configDir, { recursive: true })
for (let i = 0; i < 10; i++) {
appendReceipt({ at: `2024-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`, result: 'pushed' })
}
const last5 = readReceipts(5)
expect(last5).toHaveLength(5)
expect(last5[0]?.at).toContain('01-06')
expect(last5[4]?.at).toContain('01-10')
})
it('returns empty array when receipts file does not exist', () => {
const receipts = readReceipts()
expect(receipts).toEqual([])
})
it('creates directory if missing when appending receipt', () => {
// Don't pre-create configDir - test that appendReceipt creates it
process.env.HOME = tmpDir
const receipt = { at: '2024-01-01T00:00:00Z', result: 'pushed', spans: 5 }
appendReceipt(receipt)
const receipts = readReceipts()
expect(receipts).toHaveLength(1)
expect(receipts[0]?.result).toBe('pushed')
})
})