codeburn/src/sync/cli.ts
Resham Joshi 2fc62f7876
0.9.25: correctness, energy, menu bar and installer fixes (#1511)
* 0.9.25: correctness + provider fixes, energy guard, logo, default DMG

CLI/engine fixes: local-model savings count reasoning; ZCode reasoning billed;
codex-credits version-boundary tiering; GLM alias repointed to z.ai discounted rate;
openclaw/pi/qwen timestamp mtime fallback; hermes delta timestamp;
sqlite/warp/hermes busy+permission reclassified as failed (no sealed empty);
codex-cache dev+ino; cursor-cache WAL; antigravity server TTL; quota timeout+
grokbot footer+claude near-expiry; serve RSS guard env+hysteresis; CSV export
subfolder; providers pane fixed window; Warp credit-based cost.
Desktop/menubar: unified flame logo; default DMG; docs signed+notarized.

* menubar: one running instance, self-relaunch on language change

The single-instance guard only retired strictly older copies, so two login
items starting in the same instant both survived, and a copy whose bundle
identity did not survive install was never seen at all. The decision is now
total (newest launch wins, ties break on pid) and peers are matched on bundle
id or executable name. --keep-both opts one launch out.

Language changes no longer have the desktop app quit and reopen the menu bar,
which made macOS attribute the new process to the desktop app and re-ask for
the data-access grant. The menu bar relaunches itself via the existing remote
command key; older menu bars that do not watch the key fall back to the old
path after 5s.

* desktop: export toast shows the saved path; resource buckets on app_close

The export toast showed the folder that was picked, not the dated subfolder
the files land in. The handler already parsed the CLI's saved line; it now
returns that path and the toast uses it.

app_close carries cpu/mem (and serveCpu/serveMem when serve reported) as bucket
labels, sampled on the existing flush interval. serve adds cpuSec and peak rssMb
to its answer frames. Unmeasured figures are omitted, never sent as zero.

* menubar guard never leaves zero instances; installer replaces in place; JSON export into folder

Guard: an unreadable launch date on either side could make two copies retire
each other. Unreadable peers now count only when their pid is lower, and a copy
that cannot read its own date retires lower pids only, so a disagreement keeps
at least one instance.

Installer: an existing bundle in /Applications or ~/Applications is replaced
where it lives instead of a second copy being added. The old bundle is moved
aside and restored on any failure; a cross-volume move falls back to a copy that
is re-verified with codesign. An unwritable location is never escalated: the
install goes to ~/Applications and the leftover is named.

Export: -o pointing at an existing folder writes the JSON inside it. Short
sessions omit the cpu buckets. setLanguage reopens the menu bar if its own
relaunch never comes back. AppRelaunch passes the bundle path as an argument.

* menubar guard orders by kernel start time; installer opens the copy that exists and recovers a killed install

Guard: launch dates could be unreadable and pid order can disagree with start
order after pid reuse, so two copies could still retire each other. Ordering now
uses the kernel-reported process start time, which both sides read identically.
A copy whose start time cannot be read is left out, so the worst case is two
menu bars, never none.

Installer: with the only copy in an unwritable /Applications, a plain run tried
to open a path that did not exist. It now opens the installed copy. A placement
killed mid-way is recovered on the next run, a concurrent install is refused,
and a failed restore names where the previous bundle is. Process matching uses
the exact executable name.

Export: a trailing separator names a folder. Telemetry cpu is measured from
telemetry start.

* installer: a recycled pid can no longer block installs; language change waits for the replacement process

An aside left by an earlier install counted as an active install whenever its
pid was live, so once that pid was reused every install was refused for good.
It now also has to be recent (ctime within 10 minutes), a pid we may not signal
is not ours, the refusal names the file, and an orphan that cannot be cleared is
reported instead of aborting the install.

setLanguage confirmed the relaunch with a matcher the dying process still
satisfied, so the reopen fallback never fired. It now waits for a pid that was
not running before.

* desktop: only the headline refreshes live; act, yield and the optimize scan move to slower tiers

An open window ran act report (a fresh CLI process each time), yield and an
optimize scan on every refresh. The headline poll now passes --no-optimize and
takes the snapshot path; act report refreshes on mount, on manual refresh and
every 10 minutes, yield every 5. The optimize scan runs at most once a day per
query scope, is stored in userData with its time, and is forced fresh by the
Optimize page or a manual refresh. Figures that are not live show their age,
and no stored scan means no savings clause rather than a zero.

On battery the live interval doubles; the chosen cadence stays the base.

* desktop: a stored optimize scan is only valid on the day it was computed; cadence changes no longer refetch

The scan cache is keyed on the argv, which says 'today' or '30days', not a date,
so yesterday's scan was served as today's. It is now reused only on the same
local day. Stored findings in Signals carry their age, a failed scan shows the
error instead of scanning forever, and the cold-boot label uses the time the app
received the payload.

usePolled fetched immediately whenever its interval changed, so every power
transition (and launching on battery) refetched every live hook and could spawn
an extra act report. Fetching and timer arming are now separate effects.
Optimize's yield is on the same 5 minute tier as Overview.

* desktop: re-ask for the optimize scan on the first render of a new local day

An app left open across midnight kept yesterday's stored savings under Today,
because the scan was only requested on mount, scope change or manual refresh.
The local day is now one of the hook's triggers; the previous day's figure is
dropped while the new scan runs.

* serve: a menubar poll is never answered from the status snapshot

Inside its settle window the status snapshot returns the pre-change payload on
purpose. The resident serve process then memoized that answer as clean, so after
a single write followed by quiet the headline stayed on the old figure until the
next write or the five minute memo cap. The snapshot is for one-shot runs; the
resident process already holds the parsed state, so it now skips it.

* tests stop writing the real serve pid file; superseded caches are swept; installer notes reach the desktop card

ServeConnection takes its pid file as a parameter, so the Swift tests no longer
share ~/.cache/codeburn/menubar-serve.pid with a running menu bar, and the
reaper only signals a record that is a serve --stdio command.

Superseded session-cache, codex-results and cursor-results files (100MB+ each)
are removed once untouched for 14 days, at most once a day. daily-cache and the
hermes ledger are never swept: they carry sealed days a version bump adopts.

The menu bar installer's leftover-copy advice is emitted as a marked line under
CODEBURN_PROGRESS and shown on the desktop card. The skipped-refresh NSLog is
debug only. The app's vitest workers turn off Node's built-in web storage.

* menubar: anonymous usage statistics, under the same consent as the desktop and the Windows tray

The Swift menu bar sent nothing, so every codeburn-menubar row was a Windows
tray. It now follows the desktop's telemetry.v1.json when that exists (read
only: same install id, same on/off, onboarded required) and otherwise keeps its
own state with the same region default (off in EU/EEA/UK/CH and when the region
is unknown). Settings gains one Privacy toggle, disabled when the desktop owns
the choice. Events use the tray's names; the daily usage snapshot is the CLI's
block passed through a sanitizer and is left to the desktop when it is the
consent source. Debug builds never send.

A resident CLI that gets disabled for the run now says so in the log.

* menubar statistics: private network session, abandoned batch on opt-out, a desktop No survives the desktop going away

The sender used URLSession.shared, so a server or CDN cookie and the default
User-Agent rode along and would have outlived an opt-out. It now owns an
ephemeral session with no cookies, no cache, a fixed agent string and no
redirects. A batch that is out when the toggle goes off is dropped rather than
re-queued under the fresh id. The desktop's answer is recorded locally, so a
missing or damaged state file never falls back to the region default, and the
standalone id is persisted when minted. The toggle stays usable as a local off
switch under desktop consent. Copy states what this app actually sends.

* vercel gateway spend is shown on its own row and kept out of totals by default

The gateway reports daily aggregates per model, with nothing to match against
the local tools that were pointed at it, so every headline counted that traffic
twice. Totals now leave the gateway slice out when all providers are shown; the
row keeps its full amount and is marked not in total, --provider vercel-gateway
is unchanged, and codeburn gateway-totals include folds it back in. The daily
cache still stores the slice, so the choice applies retroactively. Reports with
no gateway credential are byte-identical.

The gateway's request_count now feeds the call count instead of each daily row
counting as one call. Hermes: a mid-session price change lands on the day it is
observed and sealed days are never rewritten; stated in the code and changelog.

* gateway exclusion applies to every report through the parse, and the detail panels follow the headline

The first pass narrowed only the day totals, so By tool, top models, top
projects, activities, status json projects and any project-filtered table still
carried gateway spend next to a headline that did not, and By tool shares could
pass 100%. The rule now lives in parseAllSessions: with all providers in scope
and the opt-in off, aggregate-only sessions are dropped after the memo, and the
callers that derive cached days opt out so stored slices are unchanged.
day.projects is reduced like models. The gateway stays visible once, as a
labelled not-in-total row with no share, and standalone reports note the
excluded amount on stderr so machine output is unchanged.

* dashboard: the background history index follows the gateway exclusion too

The index keeps the whole corpus so it can fill the daily cache, but its
per-period projection handed that unfiltered list to the project, model and
activity panels, so they regained gateway spend once the index landed.

* ci: a hung lock suite fails in 90s and retries once with a warning; slow Windows tests get measured limits

The cache-lock step failed 6 of the last 60 runs with no output for five minutes
after the vitest banner; passing runs take 12-18s on every Node version. Each
attempt is now capped at 90s and retried once, with a warning whenever that
happens. On windows-latest a single CLI spawn takes 1.4-12s, so the four-spawn
status snapshot test and the c6 parser suite get limits taken from those runs,
each with its reason. Both test jobs print their ten slowest cases.

* desktop: Privacy & data uses the same rows as the rest of Settings

The pane mixed two static claims with two controls in its own layout. It now
uses the about-row pattern every other pane uses: title and hint on the left,
one control on the right. The claims became the subtitle. Rows: anonymous usage
statistics (toggle, link to what is sent), device sharing state with Manage,
local report snapshots with Clear, export with Open export.

* desktop: Privacy & data keeps one bounded column and rows that never squeeze

The card stretched with the window, stranding each control hundreds of pixels
from its text. This pane's heading, subtitle and card now share a 760px column
and one text measure. Rows stack on their own width, because the window can
never be narrow enough for the old viewport rule to fire; row buttons do not
wrap. The what-is-sent link sits on its own line, and the snapshot and export
descriptions fit their measure and say this machine.

* menubar tests clean up their scratch defaults and leave the real Keychain alone

Four test files never removed their UserDefaults suites and the rest removed the
domain but left the plist, so thousands of files piled up in
~/Library/Preferences. A shared helper forgets a suite and deletes its file, and
every test that makes a suite now uses it. cfprefsd still rewrites an empty plist
when the test process exits, so a run leaves about a hundred 42-byte files with
no test data in them. The real-Keychain round trip only runs with
CODEBURN_TEST_REAL_KEYCHAIN=1.

* desktop: the resident parser retires after 15 idle minutes and restarts on demand

The renderer stops polling while the window is hidden, but the serve child stayed
resident with its parsed cache, one to two GB on a large corpus. After 15 minutes
without a request it is stopped the way a settings restart stops it, without
spending the unexpected-death budget, and the next request starts a new resident
through the existing lazy path, never a one-shot. CODEBURN_SERVE_IDLE_MS tunes or
disables it.

* desktop: every settings pane keeps a bounded column, and dark buttons have an edge

Cards stretched with the window, so on a wide display controls sat up to 1300px
from their labels and intro lines ran past 140 characters. All panes now share
one left-aligned column (760px, 980px for projects, aliases and pricing, which
hold wide rows) and one text measure. Rows stack on their own width instead of a
viewport rule the 900px minimum window could never reach, and a long path in
Projects no longer overflows the pane.

In dark mode the secondary button matched or sat below its surface, and was
invisible on the plugin install dialog. It gets a face and a border from two new
tokens; light is unchanged. The onboarding consent label matches Settings.

* desktop: this device shows its fingerprint on its own line

The local name and the fingerprint are two adjacent inline spans, so they read as
one run of text.

* menubar: the resident parser retires after 15 idle minutes and restarts on demand

The menu bar kept its serve child, and the parsed cache with it, for the whole
run, even with the popover closed and nothing changing. After 15 minutes without
a request the child is retired without counting as a death, and the next request
starts a new resident through ensureStarted, never the one-shot fallback, whose
snapshot settle window would make the figure lag a whole tick. The window sits
above the longest gap between real requests, so a child stays warm while work is
happening. CodeBurnServeIdleSeconds tunes or disables it.

* serve: a poll re-checks only what the watcher saw change, and shard writes are coalesced

With a session being written, every poll re-listed about 2,400 directories and
re-fingerprinted about 6,000 transcripts, then rewrote the whole current-month
shard (49MB on a large corpus) and read it back on the next poll. The resident
process now reuses the previous listing and fingerprints for paths its root
watcher proves untouched, and falls back to the full sweep whenever the watcher
is missing, unhealthy, overflowed, armed after the sweep, does not cover the
path, the memo is older than 4.5 minutes, or the process was suspended. Shard
publication is held for up to 90s and flushed when stdin closes; a held write is
dropped rather than written over something another process published. One-shot
runs are unchanged. Active poll cost 0.71 to 0.33 CPU-s at a 30s cadence;
time-to-reflect unchanged at about 1.2s across append, new dir, new file, delete,
rename-over, in-flight, watcher overflow and unhealthy watcher.

Changelog: state the telemetry default as it is in this version.

* a retired parser gets to publish its held shards, and durable providers are never held

Both apps retired the serve child with SIGTERM before its stdin-close flush could
run, so every retire discarded the coalesced window. They now close stdin, give
the child a bounded grace to publish and exit, and signal it only if it is still
running; a settings restart does the same. Measured: flushed 0/5 before, 5/5
after, for both clients.

copilot's cache entries are the only record once Copilot prunes its own files, so
a held window that was dropped (retire, crash, kill -9) before the source was
pruned lost that spend for good. A window that a durable provider dirtied is
published on the poll that parsed it, as before coalescing existed. The RSS guard
publishes a held window before it clears the caches instead of discarding it.

* serve: release the lifetime parse after the fill, and make the collection real

The RSS guard dropped its memos and then called globalThis.gc, which exists only
under --expose-gc; no launcher passes it, so the collection had never run and the
freed pages never went back. On a cold start the resident idled at 2.2GB with
364MB of live heap: clearing every memo moved RSS by 0MB, a collection alone by
700MB.

After the background fill has sealed its summaries the process now publishes any
held shard window, drops the memos it can re-read from disk (the cold start had
loaded the cache with scope 'all', which then served every later poll), and
collects; it collects again a minute later for as long as a pass returns 64MB,
at most four times. Cold idle 2198MB to 700MB, warm 900MB to 781MB. Reports are
leaf-identical cold and warm, time-to-reflect unchanged, a released month scope
reloads in 0.3-0.5s.

* warp: the billed cost reaches reports and survives the cache

The provider derived a dollar cost from Warp's own billing record (provider cents,
charged usage, or credits), but warp was missing from the reported-cost
pass-through, so the cached call kept no cost and every report, cold or warm,
priced the conversation from its tokens. A fixture billed at $1.22 reported
$0.15. A call whose cost came from a billing record now keeps it; a call that
only has the token floor stores none and is still re-priced when prices change.

Warp entries re-parse once (provider parse version), and the daily cache moves to
v34 so days whose Warp source still exists re-derive; call counts do not move, so
nothing is double counted or dropped.

* openclaw and pi: a reported cost survives the cache like every other reported cost

Both providers read the cost their tool recorded for a message, and both were
missing from the reported-cost pass-through, so reports priced every call from
tokens instead. Fixtures reported $0.011 against $0.056 (openclaw) and $0.013
against $0.410 (pi). A call with a reported cost now keeps it; a call with none,
or an explicit zero, stores none and is still re-priced when prices change. omp
had been added to the list in #1150 and pi, the same parser, was never revisited.

The provider list is one named set, the unreachable providerCallToTurn is gone,
and both providers re-parse once; the v34 daily cache re-derives their days with
call counts unchanged.

* test: pin parse count per report and per resident poll
2026-09-21 00:16:21 +02:00

926 lines
39 KiB
TypeScript

/**
* codeburn sync — CLI commands.
*
* Registers: sync setup | push | status | logout | reset
*/
import type { Command } from 'commander'
import { randomBytes } from 'crypto'
import { fetchDiscoveryDoc, DiscoveryError } from './discovery.js'
import {
AuthError,
fetchOidcConfig,
generatePkce,
buildAuthUrl,
resolveScopes,
startCallbackServer,
exchangeCode,
refreshToken,
revokeToken,
CALLBACK_PORTS,
} from './auth.js'
import { createCredentialStore } from './credentials.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, CORE_SYNC_ATTRIBUTE_KEYS } from './otlp.js'
import { loadPlugins, declaredSyncAttributes, type PluginLoad } from '../plugins/loader.js'
import { collectPluginEnrichment } from '../plugins/exporter.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
.command('sync')
.description('Sync AI usage telemetry to a remote OTLP endpoint')
// --- setup ---
sync
.command('setup <url>')
.description('Configure sync with a remote endpoint (one-time)')
.action(async (url: string) => {
try {
const baseUrl = url.replace(/\/$/, '')
process.stderr.write(`Fetching discovery doc from ${baseUrl}...\n`)
// 1. Fetch codeburn discovery doc
const discovery = await fetchDiscoveryDoc(baseUrl)
process.stderr.write(` Issuer: ${discovery.issuer}\n`)
process.stderr.write(` Client: ${discovery.client_id}\n`)
// 2. Fetch OIDC configuration from the issuer
const oidc = await fetchOidcConfig(discovery.issuer)
process.stderr.write(` Auth endpoint: ${oidc.authorization_endpoint}\n`)
// 3. Resolve scopes
const scopes = resolveScopes(discovery.scopes, oidc.scopes_supported)
// 4. Generate PKCE
const pkce = generatePkce()
const state = randomBytes(16).toString('hex')
// 5. Start callback server — await the actually-bound port (port
// fallback means it may not be the first in CALLBACK_PORTS)
const { promise: callbackPromise, ready } = startCallbackServer(state)
// If all ports are in use, BOTH `ready` and `callbackPromise` reject.
// Mark callbackPromise as handled so the second rejection can't crash
// the process as an unhandled rejection while we're throwing from
// `await ready`. The later `await callbackPromise` still throws.
callbackPromise.catch(() => {})
const port = await ready
const redirectUri = `http://127.0.0.1:${port}/callback`
// 6. Build auth URL and open browser
const authUrl = buildAuthUrl({
authorization_endpoint: oidc.authorization_endpoint,
client_id: discovery.client_id,
redirect_uri: redirectUri,
scopes,
state,
pkce,
})
process.stderr.write(`\nOpening browser for login...\n`)
process.stderr.write(`If the browser doesn't open, visit:\n ${authUrl}\n\n`)
// Open browser (best-effort, platform-specific).
// execFileSync with args array — authUrl comes from the remote discovery
// doc so it must never be shell-interpolated. Scheme is also validated.
try {
if (!/^https:\/\//.test(authUrl)) {
throw new Error('auth URL must be https')
}
const { execFileSync } = await import('child_process')
if (process.platform === 'darwin') {
execFileSync('open', [authUrl], { stdio: 'ignore' })
} else if (process.platform === 'win32') {
// Do NOT use `cmd /c start` here: cmd.exe treats `&` as a command
// separator, so the auth URL's query string gets truncated at the
// first parameter and the IdP sees a bare /authorize request.
// rundll32's FileProtocolHandler receives the URL as a plain
// process argument with no shell parsing, so `&` survives intact.
execFileSync('rundll32', ['url.dll,FileProtocolHandler', authUrl], { stdio: 'ignore' })
} else {
execFileSync('xdg-open', [authUrl], { stdio: 'ignore' })
}
} catch {
// Browser open failed — user sees the URL above
}
// 7. Wait for callback
process.stderr.write(`Waiting for login (5 min timeout)...\n`)
const callback = await callbackPromise
// 8. Exchange code for tokens
const tokenRedirectUri = `http://127.0.0.1:${callback.port}/callback`
const tokens = await exchangeCode(
oidc.token_endpoint,
callback.code,
pkce.code_verifier,
tokenRedirectUri,
discovery.client_id,
)
if (!tokens.refresh_token) {
process.stderr.write(`Warning: IdP did not return a refresh token. You may need to re-authenticate frequently.\n`)
}
// 9. Store credentials
const store = createCredentialStore()
if (tokens.refresh_token) {
store.store(tokens.refresh_token)
}
// 10. Write config
writeSyncConfig({
baseUrl,
clientId: discovery.client_id,
tracesPath: discovery.traces_path,
issuer: discovery.issuer,
})
process.stderr.write(`\n✓ Sync configured successfully.\n`)
process.stderr.write(` Endpoint: ${baseUrl}\n`)
process.stderr.write(` Token stored in: ${store.method()}\n`)
process.stderr.write(`\nRun \`codeburn sync push\` to send telemetry data.\n`)
} catch (err) {
// Known errors (login timeout, port exhaustion, discovery failures)
// get a clean one-line message instead of a raw Node crash dump.
if (err instanceof AuthError || err instanceof DiscoveryError) {
process.stderr.write(`\nError: ${err.message}\n`)
} else {
process.stderr.write(`\nError: ${(err as Error).stack ?? (err as Error).message}\n`)
}
process.exit(1)
}
})
// --- status ---
sync
.command('status')
.description('Show sync configuration and auth status')
.action(async () => {
const config = readSyncConfig()
if (!config) {
process.stderr.write('Sync not configured. Run `codeburn sync setup <url>` first.\n')
process.exit(1)
}
const store = createCredentialStore()
const token = store.retrieve()
process.stdout.write(`Endpoint: ${config.baseUrl}\n`)
process.stdout.write(`Traces path: ${config.tracesPath}\n`)
process.stdout.write(`Issuer: ${config.issuer}\n`)
process.stdout.write(`Auth: ${token ? 'configured' : 'missing (run sync setup)'}\n`)
process.stdout.write(`Token storage: ${store.method()}\n`)
process.stdout.write(`Last sync: ${config.lastSync ?? 'never'}\n`)
})
// --- logout ---
sync
.command('logout')
.description('Remove stored credentials and revoke token')
.action(async () => {
const config = readSyncConfig()
const store = createCredentialStore()
const token = store.retrieve()
// Revoke if we have a token and know the revocation endpoint
if (token && config) {
try {
const oidc = await fetchOidcConfig(config.issuer)
if (oidc.revocation_endpoint) {
await revokeToken(oidc.revocation_endpoint, token, config.clientId)
process.stderr.write('Token revoked at IdP.\n')
}
} catch {
// Best-effort revocation
}
}
store.delete()
deleteSyncConfig()
process.stderr.write('Sync credentials and config removed.\n')
})
// --- reset ---
sync
.command('reset')
.description('Clear the sent-ledger (next push re-sends all calls in window)')
.option('--confirm', 'Required to confirm reset')
.action(async (opts: { confirm?: boolean }) => {
if (!opts.confirm) {
process.stderr.write('This will clear the sent-ledger, causing the next push to re-send all data.\n')
process.stderr.write('Run with --confirm to proceed.\n')
process.exit(1)
}
const { clearLedger } = await import('./ledger.js')
const removed = clearLedger()
if (removed > 0) {
process.stderr.write(`Ledger cleared (${removed} entries). Next push will re-send all calls in window.\n`)
} else {
process.stderr.write('No ledger entries found (nothing to reset).\n')
}
})
// --- push (placeholder for Step 2) ---
sync
.command('push')
.description('Push unsent telemetry data to the configured endpoint')
.option('--since <period>', 'Time window: today, 7d, 30d, month, all (max 6 months)', '7d')
.option('--dry-run', 'Show what would be sent without sending')
.option('--attribution', 'Also push git attribution spans (session→commit correlation from `codeburn yield`, plus PR links). Sends normalized repo remotes and commit SHAs to the endpoint.')
.action(async (opts: { since: string; dryRun?: boolean; attribution?: boolean }) => {
const config = readSyncConfig()
if (!config) {
process.stderr.write('Sync not configured. Run `codeburn sync setup <url>` first.\n')
process.exit(1)
}
const store = createCredentialStore()
const rt = store.retrieve()
if (!rt) {
process.stderr.write('No auth token found. Run `codeburn sync setup` to authenticate.\n')
process.exit(1)
}
// Refresh token
try {
const oidc = await fetchOidcConfig(config.issuer)
const tokens = await refreshToken(oidc.token_endpoint, rt, config.clientId)
// Store rotated token if present
if (tokens.refresh_token && tokens.refresh_token !== rt) {
store.store(tokens.refresh_token)
}
if (opts.dryRun) {
process.stderr.write(`[dry-run] Auth: valid (Bearer token obtained)\n`)
}
// Collect data
const { parseAllSessions } = await import('../parser.js')
const { getDateRange } = await import('../cli-date.js')
// Map --since to a parser period. Strict: unknown values are an error.
const sinceToPeriod: Record<string, string> = {
'today': 'today',
'7d': 'week', 'week': 'week',
'30d': '30days', '30days': '30days',
'month': 'month',
'all': 'all', // up to 6 months (parser retention limit)
}
const period = sinceToPeriod[opts.since]
if (!period) {
process.stderr.write(`Unknown --since value "${opts.since}". Valid: today, 7d, 30d, month, all.\n`)
process.exit(1)
}
const { range } = getDateRange(period)
// No provider scope, so parseAllSessions applies the shared
// aggregate-only rule: gateway daily aggregates are not pushed unless
// the user opted in. The backend would double count them exactly the
// way a local headline would. Payload schema is unchanged either way.
const projects = (await parseAllSessions(range))
.map(p => ({ ...p, project: wireProjectName(p.projectPath, p.project) }))
// Local-only inputs to the CB-3 fields: configured plans decide
// ai.subscription_covered; the daily-cache watermark stamps
// codeburn.coverage_through (only when a complete parse finalized it).
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
// Flatten + filter against sent-ledger
const { allCalls, unsent, held, frozen } = collectUnsentCalls(projects, Date.now(), { plans })
// Plugin socket: load declared sync attribute keys once for the dry-run
// disclosure and the real-push wire guard. Loader is directory-stat only
// when no plugins are installed, so the no-plugin case is byte-identical
// to before the socket shipped.
const pluginLoads: PluginLoad[] = await loadPlugins()
const pluginKeys = declaredSyncAttributes(pluginLoads)
const pluginAttributeKeys: ReadonlySet<string> = new Set(pluginKeys.keys())
// Attribution records (opt-in): session→commit correlation computed
// locally from the same parsed projects. Reuses the yield engine.
let attributionUnsent: Awaited<ReturnType<typeof collectUnsentAttribution>>['unsent'] = []
let attributionTotal = 0
if (opts.attribution) {
const { computeAttributionRecords } = await import('../yield.js')
const records = computeAttributionRecords(projects, range, process.cwd())
const collected = collectUnsentAttribution(records)
attributionUnsent = collected.unsent
attributionTotal = collected.allItems.length
}
if (opts.dryRun) {
const toPushCount = Math.min(unsent.length, MAX_PER_PUSH)
const cost = unsent.slice(0, MAX_PER_PUSH).reduce((s, c) => s + c.call.costUSD, 0)
process.stderr.write(`[dry-run] Window: ${opts.since} — ${allCalls.length} calls total, ${allCalls.length - unsent.length - held.length - frozen.length} already synced\n`)
if (held.length > 0) {
process.stderr.write(`[dry-run] ${held.length} calls held: their session is still reconciling and its values can still change (#988). They push once it settles.\n`)
}
if (frozen.length > 0) {
process.stderr.write(`[dry-run] ${frozen.length} Copilot calls frozen: their sessions were already synced in the other shape (rollup vs per-request), and a usage span cannot be retracted. See docs/sync/README.md.\n`)
}
process.stderr.write(`[dry-run] Would push ${toPushCount} calls ($${cost.toFixed(2)}) to ${config.baseUrl}${config.tracesPath}\n`)
const toPushList = unsent.slice(0, MAX_PER_PUSH)
const withLineage = toPushList.filter(c => c.session?.workUnitId !== undefined).length
const withCacheTokens = toPushList.filter(c =>
Math.max(c.call.usage.cacheReadInputTokens, c.call.usage.cachedInputTokens) > 0
|| c.call.usage.cacheCreationInputTokens > 0).length
const covered = toPushList.filter(c => c.session?.subscriptionCovered === true).length
const uncovered = toPushList.filter(c => c.session?.subscriptionCovered === false).length
process.stderr.write(`[dry-run] Fields: ${withLineage}/${toPushCount} spans carry lineage (ai.work_unit_id/session_role/lineage_evidence), ${withCacheTokens} carry cache tokens, ai.subscription_covered true on ${covered} / false on ${uncovered} / omitted on ${toPushCount - covered - uncovered}; codeburn.coverage_through: ${coverageThrough ?? 'unavailable'}\n`)
// Plugin socket disclosure (teams issue #3): a member sees every
// loaded plugin and every declared sync attribute, so a plugin
// cannot widen the wire silently. Empty socket => line is omitted.
const loadedPlugins = pluginLoads.filter(l => l.status === 'loaded')
const rejectedPlugins = pluginLoads.filter(l => l.status === 'rejected')
if (loadedPlugins.length > 0 || rejectedPlugins.length > 0) {
const loadedSummary = loadedPlugins.map(l => {
const attrs = l.manifest.capabilities.syncAttributes
return attrs.length > 0
? `${l.manifest.name}@${l.manifest.version} [${attrs.map(a => `${a.key} - ${a.disclosure}`).join('; ')}]`
: `${l.manifest.name}@${l.manifest.version} (no sync attributes declared)`
}).join(' | ')
process.stderr.write(`[dry-run] Plugins loaded: ${loadedPlugins.length} (${loadedSummary})\n`)
if (rejectedPlugins.length > 0) {
const rejectedSummary = rejectedPlugins.map(l => `${l.name} (${l.reason})`).join('; ')
process.stderr.write(`[dry-run] Plugins rejected: ${rejectedPlugins.length} (${rejectedSummary})\n`)
}
}
// Plugin exporter disclosure: show which loaded plugins have exporters
// and what they would contribute
const pluginEnrichmentDry = await collectPluginEnrichment(pluginLoads, toPushList)
const { stat: statFn } = await import('fs/promises')
const exporterPlugins: Array<PluginLoad & { status: 'loaded' }> = []
for (const l of loadedPlugins) {
try {
await statFn(`${l.dir}/exporters/sync.mjs`)
exporterPlugins.push(l as PluginLoad & { status: 'loaded' })
} catch {
// no exporter
}
}
if (exporterPlugins.length > 0) {
const exporterSummary = exporterPlugins.map(l => {
const callCount = pluginEnrichmentDry.perCall.size
const spanCount = pluginEnrichmentDry.extraSpans.length
return `${l.manifest.name} would contribute attributes for ${callCount} calls and ${spanCount} extra spans`
}).join('; ')
process.stderr.write(`[dry-run] Plugin exporters: ${exporterSummary}\n`)
}
if (unsent.length > MAX_PER_PUSH) {
process.stderr.write(`[dry-run] ${unsent.length - MAX_PER_PUSH} more calls exceed the ${MAX_PER_PUSH} safety limit — a second push would be needed\n`)
}
if (opts.attribution) {
const toPushAttr = attributionUnsent.slice(0, MAX_ATTRIBUTION_PER_PUSH)
const commits = toPushAttr.filter(i => i.kind === 'commit').length
const sessions = toPushAttr.filter(i => i.kind === 'session').length
process.stderr.write(`[dry-run] Attribution: ${attributionTotal} facts total, would push ${toPushAttr.length} (${sessions} sessions, ${commits} commits)\n`)
if (attributionUnsent.length > MAX_ATTRIBUTION_PER_PUSH) {
process.stderr.write(`[dry-run] ${attributionUnsent.length - MAX_ATTRIBUTION_PER_PUSH} more attribution facts exceed the ${MAX_ATTRIBUTION_PER_PUSH} safety limit — a second push would be needed\n`)
}
}
return
}
if (unsent.length === 0 && attributionUnsent.length === 0) {
const pendingNote = [
held.length > 0 ? `${held.length} held while their session is still reconciling` : '',
frozen.length > 0 ? `${frozen.length} frozen behind an already-synced rollup` : '',
].filter(Boolean).join(', ')
process.stderr.write(pendingNote
? `Nothing to push yet (${allCalls.length - held.length - frozen.length} calls already synced, ${pendingNote}).\n`
: `Nothing to push (${allCalls.length} calls already synced).\n`)
updateLastSync()
return
}
// Safety valve (not a routine cap — pushes run to completion)
const toPush = unsent.slice(0, MAX_PER_PUSH)
if (unsent.length > MAX_PER_PUSH) {
process.stderr.write(`${unsent.length} unsent calls exceed the ${MAX_PER_PUSH} safety limit. Pushing first ${MAX_PER_PUSH}; run again to continue.\n`)
}
// Batch and send (loops until done; waits out 429 rate limits)
const discoveryDoc = await fetchDiscoveryDoc(config.baseUrl)
const endpoint = `${config.baseUrl}${config.tracesPath}`
let result: PushResult = { outcome: 'complete', totalSent: 0, totalRejected: 0, totalCostSent: 0 }
if (toPush.length > 0) {
const batches = batchCalls(toPush, discoveryDoc.max_batch_size)
// Collect per-call attributes and extra spans from plugin exporters
const pluginEnrichment = await collectPluginEnrichment(pluginLoads, toPush)
result = await sendBatches({
endpoint,
accessToken: tokens.access_token,
batches,
...(coverageThrough ? { coverageThrough } : {}),
// Empty values array is the no-plugin-runtime case: the wire guard
// in otlp.ts drops everything when `values` is empty, so the wire
// is byte-identical until a real plugin supplies attrs.
pluginAttributes: { keys: pluginAttributeKeys, values: [] },
...(pluginEnrichment.perCall.size > 0 || pluginEnrichment.extraSpans.length > 0 ? { pluginEnrichment } : {}),
log: msg => process.stderr.write(`${msg}\n`),
})
}
if (result.outcome === 'auth-rejected') {
process.stderr.write('Auth rejected by server. Run `codeburn sync setup` to re-authenticate.\n')
process.exit(1)
}
if (result.outcome === 'rate-limited') {
process.stderr.write(`Rate limited — gave up after repeated retries. Remaining calls will be sent on the next push.\n`)
}
if (result.outcome === 'server-error') {
process.stderr.write(`Server error (HTTP ${result.httpStatus}). Remaining calls will be sent on the next push.\n`)
}
// Attribution spans ride the same endpoint after the usage push
// completes. Skipped when the usage push hit rate limits or server
// errors — the endpoint is already unhappy; both retry on next push.
let attrResult: PushResult | null = null
if (opts.attribution && attributionUnsent.length > 0) {
if (result.outcome === 'complete') {
// Safety valve, mirroring the usage-call cap
const attrToPush = attributionUnsent.slice(0, MAX_ATTRIBUTION_PER_PUSH)
if (attributionUnsent.length > MAX_ATTRIBUTION_PER_PUSH) {
process.stderr.write(`${attributionUnsent.length} attribution facts exceed the ${MAX_ATTRIBUTION_PER_PUSH} safety limit. Pushing first ${MAX_ATTRIBUTION_PER_PUSH}; run again to continue.\n`)
}
const attrBatches = batchAttributionItems(attrToPush, discoveryDoc.max_batch_size)
attrResult = await sendAttributionBatches({
endpoint,
accessToken: tokens.access_token,
batches: attrBatches,
log: msg => process.stderr.write(`${msg}\n`),
})
if (attrResult.outcome === 'auth-rejected') {
process.stderr.write('Auth rejected by server during attribution push. Run `codeburn sync setup` to re-authenticate.\n')
process.exit(1)
}
if (attrResult.outcome === 'rate-limited') {
process.stderr.write(`Rate limited during attribution push — gave up after repeated retries. Remaining facts will be sent on the next push.\n`)
}
if (attrResult.outcome === 'server-error') {
process.stderr.write(`Server error (HTTP ${attrResult.httpStatus}) during attribution push. Remaining facts will be sent on the next push.\n`)
}
} else {
process.stderr.write(`Skipping attribution push (${attributionUnsent.length} facts) — will retry on next push.\n`)
}
}
// Update lastSync
updateLastSync()
// Summary
process.stderr.write(`\nSynced ${result.totalSent} calls ($${result.totalCostSent.toFixed(2)}) to ${config.baseUrl}\n`)
if (attrResult) {
const attrSuffix = attrResult.outcome !== 'complete'
? ` (push incomplete — remainder retries next push)`
: attrResult.totalRejected > 0 ? `, ${attrResult.totalRejected} rejected (will retry)` : ''
process.stderr.write(` Attribution: ${attrResult.totalSent} facts synced${attrSuffix}\n`)
}
if (result.totalRejected > 0) {
process.stderr.write(` ${result.totalRejected} spans rejected (will retry on next push)\n`)
}
if (unsent.length > MAX_PER_PUSH) {
process.stderr.write(` ${unsent.length - MAX_PER_PUSH} calls remaining (safety limit). Run \`codeburn sync push\` again.\n`)
}
// Non-zero exit when the push did not complete, so cron/scripts can
// detect it. Ledgered progress is kept; next push resumes.
if (result.outcome !== 'complete' || (attrResult !== null && attrResult.outcome !== 'complete')) {
process.exitCode = 1
}
} catch (err) {
process.stderr.write(`${(err as Error).message}\n`)
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.execPath, 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')
.option('--json', 'Output as machine-readable JSON')
.action(async (opts: { json?: boolean }) => {
const config = readSyncConfig()
let currentMatches: boolean | undefined
let changed: string[] = []
const accepted = config?.auto?.accepted
// Recompute fingerprint to check for changes
if (accepted) {
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)
currentMatches = currentFingerprint === accepted.fingerprint
if (!currentMatches) {
changed = detectFingerprintChanges(accepted.input, fingerprintInput)
}
} catch {
currentMatches = undefined
}
}
if (opts.json) {
const result: Record<string, unknown> = {
configured: !!accepted,
killed: config?.auto?.killed ?? false,
}
if (accepted) {
result.accepted = {
fingerprint: accepted.fingerprint,
acceptedAt: accepted.acceptedAt,
cadence: accepted.cadence,
attribution: accepted.attribution,
}
if (currentMatches !== undefined) {
result.currentMatches = currentMatches
if (!currentMatches) {
result.changed = changed
}
}
}
const receipts = readReceipts(5)
result.receipts = receipts
process.stdout.write(JSON.stringify(result, null, 0) + '\n')
return
}
if (!config?.auto?.accepted) {
process.stdout.write('Automatic sync is not configured.\n')
return
}
const acceptedRecord = config.auto.accepted
if (typeof acceptedRecord.fingerprint !== 'string' || typeof acceptedRecord.acceptedAt !== 'string') {
process.stdout.write('Automatic sync acceptance record is damaged. Run: codeburn sync auto enable --cadence <daily|hourly> --accept\n')
process.exit(1)
return
}
process.stdout.write(`Accepted fingerprint: ${acceptedRecord.fingerprint}\n`)
process.stdout.write(`Accepted at: ${acceptedRecord.acceptedAt}\n`)
process.stdout.write(`Cadence: ${acceptedRecord.cadence}\n`)
if (currentMatches === true) {
process.stdout.write('Current fingerprint: MATCHES\n')
} else if (currentMatches === false) {
process.stdout.write(`Current fingerprint: DIFFERS (${changed.join(', ')})\n`)
} else {
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
// No provider scope, so parseAllSessions applies the shared
// aggregate-only rule: gateway daily aggregates are not pushed unless
// the user opted in. The backend would double count them exactly the
// way a local headline would. Payload schema is unchanged either way.
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) }
))
}
})
}