From d92ddd71f4d40e84b7a4d5bc9f5d20152b49d19b Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 28 Aug 2026 00:54:14 -0700 Subject: [PATCH 1/5] feat(sync): consent-once auto-sync with acceptance fingerprint, receipts, and kill switch (CB-4) Reused menubar-installer pattern for schedule installer. On non-darwin, prints crontab line to add manually. Auto block is optional in sync config; add-only and never migrates existing installs. --- src/sync/cli.ts | 312 +++++++++++++++++++++++++++++++- src/sync/config.ts | 31 ++++ src/sync/consent.ts | 113 ++++++++++++ src/sync/schedule-installer.ts | 117 ++++++++++++ tests/sync-consent.test.ts | 314 +++++++++++++++++++++++++++++++++ 5 files changed, 885 insertions(+), 2 deletions(-) create mode 100644 src/sync/consent.ts create mode 100644 src/sync/schedule-installer.ts create mode 100644 tests/sync-consent.test.ts diff --git a/src/sync/cli.ts b/src/sync/cli.ts index 5ac5a49e..d2f700d7 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -21,10 +21,19 @@ 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, + type FingerprintInput, + type DisclosureInput, + type Receipt, + buildReceipt, +} from './consent.js' +import { installSchedule, removeSchedule } from './schedule-installer.js' export function registerSyncCommands(program: Command): void { const sync = program @@ -475,4 +484,303 @@ 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 ', 'Schedule frequency: daily or hourly', 'daily') + .option('--accept', 'Accept the disclosure and enable automatic sync') + .action(async (opts: { cadence?: string; accept?: boolean }) => { + const config = readSyncConfig() + if (!config) { + process.stderr.write('Sync not configured. Run `codeburn sync setup ` 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) + return { key, disclosure: plugin?.disclosure ?? '' } + }) + + const fingerprintInput: FingerprintInput = { + org: config.clientId, + destination: config.baseUrl, + outboundFields: allKeys, + workMatching: true, + scopeSinceDays: null, + cadence, + } + + const fingerprint = computeAcceptanceFingerprint(fingerprintInput) + + const disclosureInput: DisclosureInput = { + destination: config.clientId, + destinationUrl: config.baseUrl, + cadence, + outboundFields: fieldList, + workMatching: true, + scopeSinceDays: null, + } + + 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, + }, + killed: false, + } + delete config.auto.killed + writeSyncConfig(config) + + await installSchedule(cadence, process.argv[1]) + + process.stdout.write(`Automatic sync enabled (${cadence}). Fingerprint: ${fingerprint}\n`) + } 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: FingerprintInput = { + org: config.clientId, + destination: config.baseUrl, + outboundFields: allKeys, + workMatching: true, + scopeSinceDays: null, + cadence: accepted.cadence, + } + + const currentFingerprint = computeAcceptanceFingerprint(fingerprintInput) + if (currentFingerprint === accepted.fingerprint) { + process.stdout.write('Current fingerprint: MATCHES\n') + } else { + // Detect what changed + const changed: string[] = [] + const coreCount = Array.from(CORE_SYNC_ATTRIBUTE_KEYS).length + if (allKeys.length !== coreCount + pluginKeys.size) { + changed.push('field set') + } + if (config.baseUrl !== config.baseUrl) { + changed.push('destination') + } + 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: FingerprintInput = { + org: config.clientId, + destination: config.baseUrl, + outboundFields: allKeys, + workMatching: true, + scopeSinceDays: null, + cadence: accepted.cadence, + } + + const currentFingerprint = computeAcceptanceFingerprint(fingerprintInput) + + if (currentFingerprint !== accepted.fingerprint) { + // Detect what changed + const changed: string[] = [] + const baseCoreKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS).sort() + if (JSON.stringify(allKeys) !== JSON.stringify(baseCoreKeys)) { + changed.push('field set') + } + appendReceipt(buildReceipt( + at, + currentFingerprint, + { result: 'acceptance-required', changed: changed.length > 0 ? changed : ['unknown'] } + )) + return + } + + // Run the same push path as sync push + 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 { allCalls, 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) + } + + const discoveryDoc = await fetchDiscoveryDoc(config.baseUrl) + const endpoint = `${config.baseUrl}${config.tracesPath}` + + const toPush = unsent.slice(0, MAX_PER_PUSH) + const batches = batchCalls(toPush, discoveryDoc.max_batch_size) + + const pluginAttributeKeys: ReadonlySet = new Set(pluginKeys.keys()) + const result: PushResult = await sendBatches({ + endpoint, + accessToken: tokens.access_token, + batches, + ...(coverageThrough ? { coverageThrough } : {}), + pluginAttributes: { keys: pluginAttributeKeys, values: [] }, + log: () => {}, // Silent mode + }) + + if (result.outcome === 'complete') { + updateLastSync() + appendReceipt(buildReceipt(at, currentFingerprint, { result: 'pushed', spans: result.totalSent })) + } 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) } + )) + } + }) } diff --git a/src/sync/config.ts b/src/sync/config.ts index 6ddfcec0..04c6469e 100644 --- a/src/sync/config.ts +++ b/src/sync/config.ts @@ -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,26 @@ export function updateLastSync(): void { export function deleteSyncConfig(): void { try { unlinkSync(configPath()) } catch { /* may not exist */ } } + +export function readReceipts(limit?: number): Array> { + 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) + if (limit && limit > 0) return entries.slice(-limit) + return entries + } catch { + return [] + } +} + +export function appendReceipt(receipt: Record): void { + const dir = configDir() + mkdirSync(dir, { recursive: true }) + const path = receiptsPath() + const line = JSON.stringify(receipt) + '\n' + writeFileSync(path, line, { flag: 'a' }) +} diff --git a/src/sync/consent.ts b/src/sync/consent.ts new file mode 100644 index 00000000..200a812d --- /dev/null +++ b/src/sync/consent.ts @@ -0,0 +1,113 @@ +/** + * 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 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 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}`, + '', + '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 +} + +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, + } +} diff --git a/src/sync/schedule-installer.ts b/src/sync/schedule-installer.ts new file mode 100644 index 00000000..fac699a8 --- /dev/null +++ b/src/sync/schedule-installer.ts @@ -0,0 +1,117 @@ +/** + * 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 } 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 ` + + + + Label + ${SCHEDULE_AGENT_NAME} + ProgramArguments + + ${codeburn_path} + sync + auto + run + + StartInterval + ${interval} + StandardErrorPath + /dev/null + StandardOutPath + /dev/null + + +` +} + +export async function installSchedule( + cadence: 'daily' | 'hourly', + codeburnPath: string, +): Promise { + 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() + + try { + // 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 { + 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 { + 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()}` : ''}`)) + }) + }) +} diff --git a/tests/sync-consent.test.ts b/tests/sync-consent.test.ts new file mode 100644 index 00000000..ed562284 --- /dev/null +++ b/tests/sync-consent.test.ts @@ -0,0 +1,314 @@ +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, + type FingerprintInput, + type DisclosureInput, +} from '../src/sync/consent.js' +import { readSyncConfig, writeSyncConfig, readReceipts, appendReceipt } from '../src/sync/config.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') + }) +}) + +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', 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', + }, + killed: false, + }, + } + + writeSyncConfig(config) + const loaded = readSyncConfig() + + expect(loaded?.auto?.accepted?.fingerprint).toBe('abc123') + expect(loaded?.auto?.accepted?.cadence).toBe('daily') + expect(loaded?.auto?.killed).toBe(false) + }) + + 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([]) + }) +}) From 05e4b7cbc10b7c8a6d4663bbcda0f763ef113838 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 28 Aug 2026 01:00:54 -0700 Subject: [PATCH 2/5] fix(sync): honest 7-day scope and stored work-matching choice in acceptance; shared push helper --- src/sync/cli.ts | 111 ++++++++++++++++++++++++++------- src/sync/config.ts | 2 + src/sync/consent.ts | 3 +- src/sync/schedule-installer.ts | 2 +- tests/sync-consent.test.ts | 16 ++++- 5 files changed, 108 insertions(+), 26 deletions(-) diff --git a/src/sync/cli.ts b/src/sync/cli.ts index d2f700d7..4276f02f 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -35,6 +35,59 @@ import { } from './consent.js' import { installSchedule, removeSchedule } from './schedule-installer.js' +// Helper for executing the push after data collection +interface ExecutePushInput { + config: NonNullable>> + unsent: Awaited>['unsent'] + attributionUnsent: Awaited>['unsent'] + pluginAttributeKeys: ReadonlySet + 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 } +} + export function registerSyncCommands(program: Command): void { const sync = program .command('sync') @@ -495,8 +548,9 @@ export function registerSyncCommands(program: Command): void { .command('enable') .description('Enable automatic scheduled pushes (requires --accept to proceed)') .option('--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; accept?: boolean }) => { + .action(async (opts: { cadence?: string; attribution?: boolean; accept?: boolean }) => { const config = readSyncConfig() if (!config) { process.stderr.write('Sync not configured. Run `codeburn sync setup ` first.\n') @@ -521,12 +575,13 @@ export function registerSyncCommands(program: Command): void { return { key, disclosure: plugin?.disclosure ?? '' } }) + const workMatching = opts.attribution ?? false const fingerprintInput: FingerprintInput = { org: config.clientId, destination: config.baseUrl, outboundFields: allKeys, - workMatching: true, - scopeSinceDays: null, + workMatching, + scopeSinceDays: 7, cadence, } @@ -537,8 +592,8 @@ export function registerSyncCommands(program: Command): void { destinationUrl: config.baseUrl, cadence, outboundFields: fieldList, - workMatching: true, - scopeSinceDays: null, + workMatching, + scopeSinceDays: 7, } const disclosure = buildDisclosure(disclosureInput) @@ -555,6 +610,7 @@ export function registerSyncCommands(program: Command): void { acceptedAt: new Date().toISOString(), cadence, disclosure, + attribution: workMatching, }, killed: false, } @@ -693,8 +749,8 @@ export function registerSyncCommands(program: Command): void { org: config.clientId, destination: config.baseUrl, outboundFields: allKeys, - workMatching: true, - scopeSinceDays: null, + workMatching: accepted.attribution, + scopeSinceDays: 7, cadence: accepted.cadence, } @@ -715,7 +771,8 @@ export function registerSyncCommands(program: Command): void { return } - // Run the same push path as sync push + // 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') @@ -732,7 +789,7 @@ export function registerSyncCommands(program: Command): void { ? dailyCache.lastComputedDate : undefined - const { allCalls, unsent } = collectUnsentCalls(projects, Date.now(), { plans }) + const { unsent } = collectUnsentCalls(projects, Date.now(), { plans }) if (unsent.length === 0) { appendReceipt(buildReceipt(at, currentFingerprint, { result: 'pushed', spans: 0 })) @@ -753,25 +810,33 @@ export function registerSyncCommands(program: Command): void { store.store(tokens.refresh_token) } - const discoveryDoc = await fetchDiscoveryDoc(config.baseUrl) - const endpoint = `${config.baseUrl}${config.tracesPath}` - - const toPush = unsent.slice(0, MAX_PER_PUSH) - const batches = batchCalls(toPush, discoveryDoc.max_batch_size) + // Collect attribution if enabled + let attributionUnsent: Awaited>['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 = new Set(pluginKeys.keys()) - const result: PushResult = await sendBatches({ - endpoint, - accessToken: tokens.access_token, - batches, - ...(coverageThrough ? { coverageThrough } : {}), - pluginAttributes: { keys: pluginAttributeKeys, values: [] }, - log: () => {}, // Silent mode + const { result, attrFacts } = await executePush({ + config, + unsent, + attributionUnsent, + pluginAttributeKeys, + coverageThrough, + tokens, + silent: true, }) if (result.outcome === 'complete') { - updateLastSync() - appendReceipt(buildReceipt(at, currentFingerprint, { result: 'pushed', spans: result.totalSent })) + const receipt: Record = { 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 })) } diff --git a/src/sync/config.ts b/src/sync/config.ts index 04c6469e..4862a4f0 100644 --- a/src/sync/config.ts +++ b/src/sync/config.ts @@ -92,6 +92,8 @@ export function appendReceipt(receipt: Record): 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' }) } diff --git a/src/sync/consent.ts b/src/sync/consent.ts index 200a812d..79780d7c 100644 --- a/src/sync/consent.ts +++ b/src/sync/consent.ts @@ -1,5 +1,5 @@ /** - * codeburn sync — consent-once auto-sync with fingerprint and receipts. + * codeburn sync - consent-once auto-sync with fingerprint and receipts. * * Manages acceptance fingerprints, disclosure building, and receipt tracking * for automatic scheduled pushes. @@ -79,6 +79,7 @@ export interface AcceptanceRecord { acceptedAt: string cadence: 'daily' | 'hourly' disclosure: string + attribution: boolean } export interface AutoSyncConfig { diff --git a/src/sync/schedule-installer.ts b/src/sync/schedule-installer.ts index fac699a8..50ff5a20 100644 --- a/src/sync/schedule-installer.ts +++ b/src/sync/schedule-installer.ts @@ -1,5 +1,5 @@ /** - * codeburn sync — schedule installer for automatic pushes. + * 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. diff --git a/tests/sync-consent.test.ts b/tests/sync-consent.test.ts index ed562284..515977e1 100644 --- a/tests/sync-consent.test.ts +++ b/tests/sync-consent.test.ts @@ -219,7 +219,7 @@ describe('Config with auto block', () => { await rm(tmpDir, { recursive: true, force: true }) }) - it('round-trips auto block through config', async () => { + it('round-trips auto block through config with attribution', async () => { const configDir = join(tmpDir, '.config', 'codeburn') await mkdir(configDir, { recursive: true }) @@ -234,6 +234,7 @@ describe('Config with auto block', () => { acceptedAt: new Date().toISOString(), cadence: 'daily' as const, disclosure: 'Test disclosure', + attribution: true, }, killed: false, }, @@ -244,6 +245,7 @@ describe('Config with auto block', () => { 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) }) @@ -311,4 +313,16 @@ describe('Receipts', () => { 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') + }) }) From 1e3a7228c8786638622cc8fa480ca906c6357177 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 28 Aug 2026 01:04:44 -0700 Subject: [PATCH 3/5] fix(sync): status recomputes the acceptance fingerprint with the same input as run --- src/sync/cli.ts | 54 ++++++++++++++++---------------------- tests/sync-consent.test.ts | 30 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 32 deletions(-) diff --git a/src/sync/cli.ts b/src/sync/cli.ts index 4276f02f..3c869249 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -88,6 +88,23 @@ async function executePush(input: ExecutePushInput): Promise<{ result: PushResul return { result, attrResult, attrFacts } } +// Helper to build FingerprintInput for acceptance checking +function buildAcceptanceFingerprintInput( + config: NonNullable>>, + 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 .command('sync') @@ -576,15 +593,7 @@ export function registerSyncCommands(program: Command): void { }) const workMatching = opts.attribution ?? false - const fingerprintInput: FingerprintInput = { - org: config.clientId, - destination: config.baseUrl, - outboundFields: allKeys, - workMatching, - scopeSinceDays: 7, - cadence, - } - + const fingerprintInput = buildAcceptanceFingerprintInput(config, allKeys, workMatching, cadence) const fingerprint = computeAcceptanceFingerprint(fingerprintInput) const disclosureInput: DisclosureInput = { @@ -678,28 +687,17 @@ export function registerSyncCommands(program: Command): void { .concat(Array.from(pluginKeys.keys())) .sort() - const fingerprintInput: FingerprintInput = { - org: config.clientId, - destination: config.baseUrl, - outboundFields: allKeys, - workMatching: true, - scopeSinceDays: null, - cadence: accepted.cadence, - } - + 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 { // Detect what changed const changed: string[] = [] - const coreCount = Array.from(CORE_SYNC_ATTRIBUTE_KEYS).length - if (allKeys.length !== coreCount + pluginKeys.size) { + const baseCoreKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS).sort() + if (JSON.stringify(allKeys) !== JSON.stringify(baseCoreKeys)) { changed.push('field set') } - if (config.baseUrl !== config.baseUrl) { - changed.push('destination') - } process.stdout.write(`Current fingerprint: DIFFERS (${changed.join(', ')})\n`) } } catch { @@ -745,15 +743,7 @@ export function registerSyncCommands(program: Command): void { .concat(Array.from(pluginKeys.keys())) .sort() - const fingerprintInput: FingerprintInput = { - org: config.clientId, - destination: config.baseUrl, - outboundFields: allKeys, - workMatching: accepted.attribution, - scopeSinceDays: 7, - cadence: accepted.cadence, - } - + const fingerprintInput = buildAcceptanceFingerprintInput(config, allKeys, accepted.attribution, accepted.cadence) const currentFingerprint = computeAcceptanceFingerprint(fingerprintInput) if (currentFingerprint !== accepted.fingerprint) { diff --git a/tests/sync-consent.test.ts b/tests/sync-consent.test.ts index 515977e1..91d188db 100644 --- a/tests/sync-consent.test.ts +++ b/tests/sync-consent.test.ts @@ -249,6 +249,36 @@ describe('Config with auto block', () => { 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 }) From a9c5d8b6eca0214771f259354cc049b40a5f4e94 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 28 Aug 2026 01:08:06 -0700 Subject: [PATCH 4/5] fix(sync): plain-language meanings for every core field in the consent disclosure --- src/sync/cli.ts | 4 +++- src/sync/consent.ts | 29 +++++++++++++++++++++++++++++ tests/sync-consent.test.ts | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/sync/cli.ts b/src/sync/cli.ts index 3c869249..f16f023e 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -28,6 +28,7 @@ import { loadPlugins, declaredSyncAttributes, type PluginLoad } from '../plugins import { computeAcceptanceFingerprint, buildDisclosure, + CORE_SYNC_FIELD_MEANINGS, type FingerprintInput, type DisclosureInput, type Receipt, @@ -589,7 +590,8 @@ export function registerSyncCommands(program: Command): void { const fieldList = allKeys.map(key => { const plugin = pluginKeys.get(key) - return { key, disclosure: plugin?.disclosure ?? '' } + const disclosure = plugin?.disclosure ?? CORE_SYNC_FIELD_MEANINGS.get(key) ?? '(no description)' + return { key, disclosure } }) const workMatching = opts.attribution ?? false diff --git a/src/sync/consent.ts b/src/sync/consent.ts index 79780d7c..3e978357 100644 --- a/src/sync/consent.ts +++ b/src/sync/consent.ts @@ -9,6 +9,35 @@ import { createHash } from 'crypto' export const WIRE_CONTRACT_VERSION = 'v2' +export const CORE_SYNC_FIELD_MEANINGS: ReadonlyMap = 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 diff --git a/tests/sync-consent.test.ts b/tests/sync-consent.test.ts index 91d188db..26cd2b43 100644 --- a/tests/sync-consent.test.ts +++ b/tests/sync-consent.test.ts @@ -6,10 +6,12 @@ import { tmpdir } from 'os' import { computeAcceptanceFingerprint, buildDisclosure, + CORE_SYNC_FIELD_MEANINGS, 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', () => { @@ -205,6 +207,38 @@ describe('Disclosure', () => { 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*$/) + } + } + }) }) describe('Config with auto block', () => { From 9616bbd0f5bbb1c2b211f9edcedddfd3a3da2a27 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Fri, 28 Aug 2026 01:26:48 -0700 Subject: [PATCH 5/5] fix(sync): fresh-machine schedule install, work-matching disclosure line, named drift causes --- src/sync/cli.ts | 31 ++++++++++---------- src/sync/consent.ts | 41 ++++++++++++++++++++++++++ src/sync/schedule-installer.ts | 6 +++- tests/sync-consent.test.ts | 53 ++++++++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 17 deletions(-) diff --git a/src/sync/cli.ts b/src/sync/cli.ts index f16f023e..c31f0134 100644 --- a/src/sync/cli.ts +++ b/src/sync/cli.ts @@ -29,6 +29,7 @@ import { computeAcceptanceFingerprint, buildDisclosure, CORE_SYNC_FIELD_MEANINGS, + detectFingerprintChanges, type FingerprintInput, type DisclosureInput, type Receipt, @@ -622,15 +623,23 @@ export function registerSyncCommands(program: Command): void { cadence, disclosure, attribution: workMatching, + input: fingerprintInput, }, killed: false, } delete config.auto.killed writeSyncConfig(config) - await installSchedule(cadence, process.argv[1]) - - process.stdout.write(`Automatic sync enabled (${cadence}). Fingerprint: ${fingerprint}\n`) + 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) @@ -694,12 +703,7 @@ export function registerSyncCommands(program: Command): void { if (currentFingerprint === accepted.fingerprint) { process.stdout.write('Current fingerprint: MATCHES\n') } else { - // Detect what changed - const changed: string[] = [] - const baseCoreKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS).sort() - if (JSON.stringify(allKeys) !== JSON.stringify(baseCoreKeys)) { - changed.push('field set') - } + const changed = detectFingerprintChanges(accepted.input, fingerprintInput) process.stdout.write(`Current fingerprint: DIFFERS (${changed.join(', ')})\n`) } } catch { @@ -749,16 +753,11 @@ export function registerSyncCommands(program: Command): void { const currentFingerprint = computeAcceptanceFingerprint(fingerprintInput) if (currentFingerprint !== accepted.fingerprint) { - // Detect what changed - const changed: string[] = [] - const baseCoreKeys = Array.from(CORE_SYNC_ATTRIBUTE_KEYS).sort() - if (JSON.stringify(allKeys) !== JSON.stringify(baseCoreKeys)) { - changed.push('field set') - } + const changed = detectFingerprintChanges(accepted.input, fingerprintInput) appendReceipt(buildReceipt( at, currentFingerprint, - { result: 'acceptance-required', changed: changed.length > 0 ? changed : ['unknown'] } + { result: 'acceptance-required', changed } )) return } diff --git a/src/sync/consent.ts b/src/sync/consent.ts index 3e978357..ad06ba6b 100644 --- a/src/sync/consent.ts +++ b/src/sync/consent.ts @@ -77,6 +77,9 @@ export function buildDisclosure(input: DisclosureInput): string { : 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 @@ -89,6 +92,7 @@ export function buildDisclosure(input: DisclosureInput): string { `URL: ${input.destinationUrl}`, `Cadence: ${cadenceText}`, `Scope: ${scopeText}`, + `Work matching: ${workMatchingText}`, '', 'Data sent to the endpoint:', fieldsList, @@ -109,6 +113,7 @@ export interface AcceptanceRecord { cadence: 'daily' | 'hourly' disclosure: string attribution: boolean + input?: FingerprintInput } export interface AutoSyncConfig { @@ -141,3 +146,39 @@ export function buildReceipt(at: string, fingerprint: string | undefined, data: ...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'] +} diff --git a/src/sync/schedule-installer.ts b/src/sync/schedule-installer.ts index 50ff5a20..d23933b7 100644 --- a/src/sync/schedule-installer.ts +++ b/src/sync/schedule-installer.ts @@ -8,7 +8,7 @@ import { platform } from 'os' import { homedir } from 'os' import { join } from 'path' -import { writeFileSync, unlinkSync, existsSync } from 'fs' +import { writeFileSync, unlinkSync, existsSync, mkdirSync } from 'fs' import { spawn } from 'child_process' const SCHEDULE_AGENT_NAME = 'com.codeburn.sync-auto' @@ -67,8 +67,12 @@ export async function installSchedule( 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 }) diff --git a/tests/sync-consent.test.ts b/tests/sync-consent.test.ts index 26cd2b43..0e26aed1 100644 --- a/tests/sync-consent.test.ts +++ b/tests/sync-consent.test.ts @@ -7,6 +7,7 @@ import { computeAcceptanceFingerprint, buildDisclosure, CORE_SYNC_FIELD_MEANINGS, + detectFingerprintChanges, type FingerprintInput, type DisclosureInput, } from '../src/sync/consent.js' @@ -239,6 +240,58 @@ describe('Disclosure', () => { } } }) + + 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', () => {