mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
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.
This commit is contained in:
parent
c01b7be4b0
commit
d92ddd71f4
5 changed files with 885 additions and 2 deletions
312
src/sync/cli.ts
312
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 <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 <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)
|
||||
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<string> = 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) }
|
||||
))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<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()
|
||||
const line = JSON.stringify(receipt) + '\n'
|
||||
writeFileSync(path, line, { flag: 'a' })
|
||||
}
|
||||
|
|
|
|||
113
src/sync/consent.ts
Normal file
113
src/sync/consent.ts
Normal file
|
|
@ -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,
|
||||
}
|
||||
}
|
||||
117
src/sync/schedule-installer.ts
Normal file
117
src/sync/schedule-installer.ts
Normal file
|
|
@ -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 `<?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()
|
||||
|
||||
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<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()}` : ''}`))
|
||||
})
|
||||
})
|
||||
}
|
||||
314
tests/sync-consent.test.ts
Normal file
314
tests/sync-consent.test.ts
Normal file
|
|
@ -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([])
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue