mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 02:39:13 +00:00
22 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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 |
||
|
|
747e6a619e |
feat(desktop): complete plugin-era UI with details, install flow, settings, and team registry
Implement five missing D1-D3 components for full plugin era desktop support: 1. PluginDetails modal (sections/PluginDetails.tsx): Display full plugin manifest with all syncAttributes disclosures verbatim, spanKinds, commands, and on-disk sections loaded via pluginInfo. Defensive rendering for unknown fields. 2. InstallFlow stepper modal (sections/InstallFlow.tsx): Three-step flow for plugin installation - Step 1 source selection (org name input or folder via chooseDirectory), Step 2 installation with spinner and CLI error display verbatim, Step 3 success confirmation with "View details" button. Special handling for no-sync-config errors. 3. Plugin row actions (update sections/Plugins.tsx): Add Details, Verify, and Remove action buttons to plugin list. Remove action shows confirm modal naming plugin. Wired to CLI bridge calls. 4. Settings > Sharing pane (sections/SettingsSharing.tsx): Complete automatic sync configuration UI within Settings panes. Empty state with "Set up automatic sync" flow: cadence selection (daily/hourly) + work-matching toggle -> disclosure text via syncAutoEnable(accept:false) -> scrollable display -> Accept flow. Active state displays fingerprint (truncated), acceptedAt, cadence, work-matching, receipts list. Drift detection with "Review and re-accept" button. Always-visible "Stop automatic sync" danger button. 5. Team tab registry (components/TeamRegistry.tsx): Detect "teams.*" keys in payload plugins record; render Team section in nav when present. v1 renderers for teams.week (spend card) and teams.status (status link to teams.codeburn.app). Unknown keys fallback rendered. schemaVersion > 1 displays update prompt. All components reuse existing app patterns (card/list/button/modal styles, CSS tokens, no new dependencies). Tests added for component row states, disclosure flow, and Team tab detection. All gates pass: root 3839 tests, app 614 tests, typecheck clean, build succeeds. |
||
|
|
6d69803817 |
feat(desktop): plugin manager, install flow, sharing consent center, and dormant Team tab (plugin era D1-D3)
Part 1: Add --json output flags to three CLI commands for machine-readable output - codeburn plugin list --json: array of plugin objects with status and capabilities - codeburn plugin info <name> --json: manifest with dir and onDiskSections - codeburn sync auto status --json: status object with configured, accepted, killed, receipts Part 2: Implement Electron bridge with read and mutation handlers - Read handlers: pluginList, pluginInfo, syncAutoStatus (return parsed JSON) - Mutation handlers: pluginAdd, pluginRemove, pluginVerify, syncAutoEnable, syncAutoDisable - All handlers follow existing Envelope pattern with proper error handling - Special case: syncAutoEnable captures disclosure text when accept=false Part 3: Renderer UI components (minimal implementation D1-D3 shell) - Add Plugins section to nav rail at bottom (quiet entry, plugin icon) - Implement PluginsSection component with list rendering for loaded/rejected plugins - Update Section type and routing to include plugins navigation - Add test coverage for Plugins panel row states - Implemented as dormant Team tab registry placeholder for future plugin sections Tests: All CLI tests (3839 passed), app tests (613 passed), E2E gates all passing - CLI: tsc clean, vitest passes with 26 pre-existing jsdom errors - App: typecheck clean, npm test green, npm run build succeeds |
||
|
|
41245e7f62 |
fix(sync): schedule invokes runtime plus script explicitly; damaged acceptance reported plainly
Two fixes from a deep review of the consent scheduler. The LaunchAgent plist was being written with process.argv[1] as the sole ProgramArguments entry, which is a non-executable .ts/.js path under plain node and a stale copy under packaged Electron. buildLaunchAgentPlist now takes both runtimePath and scriptPath, emits them as separate <string> entries, and sets ELECTRON_RUN_AS_NODE so the packaged Electron binary behaves as a node runtime. Both paths are XML-escaped before being dropped into the plist so a stray & or < in a path cannot break it. The non-darwin crontab hint now prints the same two-argument form. Caller in src/sync/cli.ts passes process.execPath and process.argv[1]. When config.auto.accepted is present but missing fingerprint or acceptedAt, sync auto status used to interpolate the missing field and print the literal 'undefined'. It now detects the malformed record, prints a single line telling the user to re-run sync auto enable, and exits non zero. The run command already fails closed on this case and is unchanged. |
||
|
|
484daabf99 |
feat(plugins): sync exporter seam - per-call attributes and declared extra spans, wire-guarded (10B)
Loaded plugins with exporters/sync.mjs now enrich sync pushes with per-call attributes and declared extra spans (CB-3 phase 2). CLI spawns exporter child processes, passes batch calls via stdin, collects JSON output with perCall Map and extra spans array. All enrichment is guarded: perCall attrs attached to matching deduplicationKey, extra spans filtered by declared spanKinds, attributes filtered by declared syncAttributes, core keys never overwritten. Exporter timeout (30s), size cap (8MB stdout), and failures are handled gracefully - plugin contributes nothing on crash/timeout/bad JSON, stderr notice printed, push completes. Extra spans are capped at 2x calls.length and >64KB spans dropped. No ledger on CLI side for extra spans (plugin's responsibility). Dry-run shows exporter contributions. Wire is byte-identical when no exporters present. |
||
|
|
9616bbd0f5 | fix(sync): fresh-machine schedule install, work-matching disclosure line, named drift causes | ||
|
|
a9c5d8b6ec | fix(sync): plain-language meanings for every core field in the consent disclosure | ||
|
|
1e3a7228c8 | fix(sync): status recomputes the acceptance fingerprint with the same input as run | ||
|
|
05e4b7cbc1 | fix(sync): honest 7-day scope and stored work-matching choice in acceptance; shared push helper | ||
|
|
d92ddd71f4 |
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. |
||
|
|
52bde7c4dd |
feat(plugins): CB-3 plugin socket — wire guard, CLI inspector, payload seam
Teams issue #3 introduces the codeburn plugin socket: an opt-in escape hatch for third parties to add sync attributes, payload sections, and CLI commands without touching the codeburn CLI source tree. This commit ships the first half (CB-3) — the manifest layer, the wire guard, and the user- facing inspector. Release-key signing (the 9b seam) lands separately. Why split now: - The wire guard (filterPluginAttributes in sync/otlp.ts) is the load- bearing piece. With it, no plugin code can run until the user opts in by installing one — the default empty socket keeps every byte of the existing telemetry wire byte-identical. That is the contract the existing four sync test files were already pinning; this commit re-pins it explicitly with a new test (tests/plugin-socket.test.ts). - The inspector () makes rejections visible. Without it, a misconfigured plugin would just vanish silently — exactly the foot-gun the socket exists to prevent. What ships: - src/plugins/loader.ts: enumerates ~/.config/codeburn/plugins/<name>/, reads + parses each codeburn-plugin.json, applies name/dir match and cliCompat check, hands off to verifyPlugin (the 9b seam). Rejected plugins contribute nothing to the wire. - src/plugins/manifest.ts: parses + validates the manifest shape (name, version, cliCompat, capabilities.{commands, syncAttributes, payloadSections, spanKinds}). Returns {ok, reason} on any failure. - src/plugins/cli.ts: . Read-only; never mutates the plugins directory. - src/sync/otlp.ts: filterPluginAttributes strips any key not in the declared set, called from buildOtlpPayload when pluginAttributes are supplied. With no plugin installed, the call path is a no-op. - src/sync/push.ts, src/sync/cli.ts: thread pluginAttributeKeys through sendBatches -> buildOtlpPayload. The wire is unchanged when no plugin declares anything. - src/usage-aggregator.ts, src/menubar-json.ts: add the MenubarPayload.plugins field and populate it from pluginPayloadSections (empty when no plugin installed). - src/main.ts: register the plugin subcommand. - tests/plugin-socket.test.ts: 12 tests covering the wire guard, the byte-identical default, the loader rejection paths, and the CLI. - scripts/smoke-plugin-socket.mjs: end-to-end smoke test against the built CLI (13 assertions). Byte-identical guarantee: - With no plugin installed: loadPlugins() returns [], pluginPayloadSections returns {}, filterPluginAttributes(empty) returns []. The OTLP payload and the menubar payload are bit-for-bit the same as before this commit. - The dry-run output gains one new line listing the active plugin names (empty string when no plugin). User-facing only; not on the wire. What's intentionally NOT here: - Plugin command invocation: lands when at least one community plugin publishes a command (deferred). - : shipping this with no signed-plugin ecosystem in place would invite supply-chain risk. Deferred. - Release-key signing (the verifyPlugin return path). Deferred to 9b. Refs: teams issue #3, CB-3 sync boundary spec section 9a. |
||
|
|
8e61ac76af
|
feat(sync): additive CB-3 usage-span fields and coverage watermark (Teams boundary spec section 7) (#1135, #1140) (#1147) | ||
|
|
fcbc28540f |
fix(sync): never put a filesystem path on the wire as ai.project
Several providers key a project by its sanitized absolute path
("-Users-me-Projects-app"), and sync shipped that verbatim as ai.project
on usage and attribution spans — contradicting docs/sync/README.md's
promise that file paths stay local. Confirmed on real exports.
One choke point after parseAllSessions maps project to the leaf directory
name before either wire path reads it; codeburn yield's local output is
untouched. Never-lose: usage span ids and commit attribution keys carry
no project (unchanged, no re-send); session attribution keys hash the
record, so each already-synced session re-emits once and the receiver
upserts by (org, trace) — replaced, not duplicated. Two directories with
the same leaf name now collapse to one wire project identity; that is
the documented contract, and git.repo still disambiguates.
|
||
|
|
dbeae9b48c |
fix(sync,parser): review B — symmetric shape freeze, honest settle, stable residual keys
B-1 The freeze was one-directional and left the reverse hole wide open. Rows sync; at the 90-day durable age-out the cached rows are pruned, the rollup stops being dropped and serves again under a key that was never sent; the session is long past settle, so it pushes an aggregate on top of the per-request spans the receiver already holds. Reframed around the thing that actually matters: a copilot session's input/cache leaves this machine in one of two SHAPES — the raw rollup (`copilot:<sid>:shutdown:`), or reconciled output (rows plus `:shutdown-residual:`, which are disjoint by construction and together are exactly the rollup re-expressed). The receiver must never hold both. Whichever shape a session was first synced in, it stays in, and the other is frozen for that session permanently — in both directions. Growth WITHIN the sent shape is untouched, because same-shape output is additive, never substitutive: a resumed session's new rows and residuals still push if rows were sent, a new leg's rollup still pushes if rollups were. This also corrects the previous commit, which classed a residual as aggregate and so froze it for a session whose rows had gone out — the residual is reconciled output and belongs with the rows. B-2 A session with an unparseable timestamp was held forever while the CLI promised it would "push once it settles". Nothing could ever settle it. Settle now reads the newest moment a session can be SHOWN active; a session with nothing datable at all is sent rather than held. Mixed sessions still settle on their datable stamps. B-3 A stamp implausibly far in the future is broken data, not evidence the session is live, so it no longer counts toward that newest moment. One year-ahead row can no longer hold a month-old session hostage. Ordinary clock skew is absorbed by a one-hour grace in both directions and still reads as live. B-4 The residual dedup key carried the leg's POSITION. Legs sort across every cached file for a session, so an earlier leg arriving later renumbers every residual after it — and a renamed key is a span the receiver takes a second time, since there is no retraction for a usage span. Keyed by the leg's own instant instead: append-only files mean it never moves, and the equal-timestamp coalescing above makes it unique per leg. Residuals are new in this change and have never shipped, so no CACHE_VERSION concern. B-5 The dry-run "already synced" count now subtracts frozen too, matching the nothing-to-push line. Tests: symmetric freeze from the rows side (rollup frozen, residual and new rows still sent, per-turn untouched); all-unparseable sent, partly-unparseable still held; a year-ahead stamp ignored while a one-minute skew still holds; residual keys named after their leg instant with the positional names gone. The key-prefix pin picks up the residual's new tail. (c2) pins the property rather than one insertion scenario, because a second file's leg currently collides on the rollup's own dedup key before it can reach the residual sweep — the reachable repro would prove nothing about the next one, and that is stated at the test. Flakes: (f2) and (sc) re-bucket each run 10x isolated and 10x with four busy loops pinning cores — 40/40 clean. Neither has clock or ordering dependence at its margins: afterEach removes both tmpHome and the cache dir, and the two relative timestamps in the re-bucket test are 35 days apart so they cannot share a month. The likeliest cause of the transient failures is this branch's own commits rewriting src/parser.ts under a concurrent vitest. (f2) gains a self-check that its fingerprint sentinel really differs from the computed one, which is the one way it could have passed while exercising nothing. |
||
|
|
9ebd509c44 |
fix(sync,cache,ci): review A — forward-only sync, a guard that bites, call-level union
F1 — the upgrade-path guard was measuring the wrong layer. providerDetails come from the menubar payload, and on a version bump adoptOlderDailyCaches carries the superseded daily file forward as the baseline for exactly the days this scenario creates, so a session-cache loss was mostly masked: reverting the carry-forward showed a 10% dip where the real loss is 50%. It now sums export.json's per-call copilot records (straight out of the parse), deletes the baseline daily cache before the upgrade run so nothing else can answer, and asserts EQUALITY rather than "did not shrink" — the failure mode on the other side of the fix is a double. Proven: reverting the carry-forward now reports 80 calls -> 40, LOST history, and fails. (The double direction is asserted but not demonstrated; a faithful re-keying simulation is collapsed by serve-time dedup before it can be counted, which is noted at the step.) F2 — sync was forward-only in the wrong direction. A receiver that took `copilot:<sid>:shutdown:<model>:<n>` rollup spans from 0.9.20 keeps them forever (append-once, no retraction for a usage span) and would now also receive `copilot-store:` rows for the same sessions: permanent doubling on every synced receiver, on the first push after upgrade. Sessions whose rollup is already in the ledger are now FROZEN — their rows and residuals never go out, and the receiver keeps the older, lossier number. A bounded under-count in place of an unbounded over-count. Per-turn output spans are untouched either way (the rollup never held output, reconciliation never touches them), and sessions new to sync take the per-row path in full. `frozen` is reported by --dry-run and the nothing-to-push line; docs/sync/README.md gains an FAQ pointing at `codeburn sync reset --confirm` with the caveat that the receiver must be cleared too. F3 — docs/providers/copilot.md gains a Sharp edges section saying plainly that a day sealed on a short store snapshot is a permanent UNDER-REPORT the watermark advances past, not a stall, and that both realizable causes are now closed (read ordering, compaction anchor). F4 — the copilot dedup-key shapes are pinned by reading them back out of the source, minted keys and discriminator prefixes alike, with the reason: the durable union recognises history by key, so a changed prefix is a CACHE_VERSION bump, not a parse-version bump. F5 — the carry-forward comment now states its price: a bump no longer re-derives a call it carried forward, so cost-shaped fixes land (cost is recomputed from cached usage) but metadata and day-attribution fixes reach only newly parsed calls. F6 — the durable union filters at CALL level. A turn holding one cached call beside a new one used to be dropped whole; nothing enforced the one-call- per-turn assumption that made that safe. F7 — the retain-source fence no longer skips a store it cannot fingerprint. Present-but-unreadable defers, matching the classification path; only a genuinely absent one stays a skip. |
||
|
|
fb1bde94b7 |
fix(sync): hold a copilot session until its reconciliation can no longer change
The sent-ledger is append-once and the OTLP span id derives from the same deduplication key, so the pipeline assumes a served call is immutable: same key, same value, forever. Copilot's serve-time reconciliation is the first producer that breaks that (#988), three ways inside one session — a shutdown residual shrinks as the store rows covering it land, a rollup is dropped once rows cover its leg, and an unpaired row becomes supplementary when its journal call appears. Sent at an intermediate state, the receiver keeps that state forever AND receives what supersedes it. Local reports re-reconcile every pass and were never affected; this is only about what leaves the machine. Value-versioned keys were the other option, but usage spans have no upsert contract — receivers sum them, so a superseding span adds rather than replaces. (Attribution can do it because its spans are documented as upserts by `ai.session_id`.) Giving usage spans one is a receiver protocol change. So: hold, do not re-key. Every input to the reconciliation is written during the session, so a session quiet for 24 hours cannot reconcile further and its first send is also its last word. The whole session is held, not just its residual — holding the residual alone still ships a row whose pairing can flip. Nothing is dropped: `held` is reported by --dry-run and by the nothing-to-push line, and the next push after the window sends it. Scoped by provider because copilot is the only reconciling producer; every other provider's calls go out unchanged and undelayed. |
||
|
|
50c8251719 |
fix(sync): close credential-leak paths; session retraction; span/key/CLI hardening
Review rounds 2-3 + self-review on --attribution: Credential egress (round 2): - normalizeRemoteUrl: scp userinfo expressed as an optional regex group let backtracking re-parse a credential prefix as host:path (x-access-token:ghp_...@host/repo -> token in git.repo). Userinfo is now split off at the first @ BEFORE any host matching. - Positive validation (allow-list) as the final gate on EVERY branch: host must be hostname-shaped, every path segment repo-shaped, total identity <= 200 chars. Kills transport-helper remotes (ext:: leaks local SSH key paths, codecommit:: leaks AWS profile names), residual @, spaces/colons, and unbounded strings. - sanitizePrLinks: links are rebuilt from origin + pathname — userinfo, query strings, and fragments are dropped instead of passed through; collapsed duplicates dedupe. Attribution correctness (round 3 + self-review): - Double-count fix with precise retraction semantics: when a commit migrates to a later-parsed tighter-window session, the loser re-emits git.commit_count=0. Empty records are emitted ONLY on a true loss in THIS computation (lostCandidacy) — a commit that merely aged out of the --since range was lost to nobody, and retracting it would permanently zero a still-correct server-side count. The sync layer additionally requires a prior ledgered state for the session. - Session dedup key includes project + both window timestamps, so ongoing sessions re-emit with corrected span times. - Span end times clamped like the usage builder (never 0, never earlier than start + 1ms). - CLI mirrors the usage path on attribution push failures instead of claiming success. - Identity normalization: case-insensitive .git strip, doubled path slashes collapse. AI-Origin: human |
||
|
|
ccee28ae82 |
fix(sync): address attribution review — cwd-fallback egress, Windows paths, PR-link validation
Review findings on the --attribution PR: - Privacy: sessions whose project path no longer resolves inherited the cwd-fallback repo identity, egressing whatever (possibly confidential) repo the user pushes from and falsely attributing its commits. buildRepoGroups now tracks per-session identity provenance; the attribution path excludes fallback sessions from commit attribution entirely (no repo, no commits, PR links only) — they also can no longer steal a commit from a genuine session's window. - Privacy: Windows drive-letter paths (C:/..., C:\..., drive-relative) parsed as scp-like remotes, emitting local filesystem paths as repo identities. normalizeRemoteUrl rejects drive letters and single-character hosts (dotless intranet hosts still accepted). - Hardening: PR links are shape-checked before sending (https, /org/repo/pull/N path, <=256 chars, max 20 per session) — upstream parsers only truthiness-check them. - Safety valve: MAX_ATTRIBUTION_PER_PUSH (10k) caps a first --since all --attribution push; dry-run reports the cap. - Tests: adversarial normalize corpus, cwd-fallback egress repro, commit-stealing prevention, PR-link sanitization, and CLI-level tests (mock IdP + collector): dry-run sends nothing to the traces endpoint, flag-off emits no attribution span names on the wire. - Docs: reconciled the 'never sent' wording with reality (PR links ride even when repo is null; device_id/methodology/timestamps disclosed). CHANGELOG Unreleased entry added. AI-Origin: human |
||
|
|
1bf7206842 |
feat(sync): push git attribution spans with --attribution
Expose the yield session-to-commit correlation through codeburn sync so backends can join AI usage to git activity without local git hooks. - yield: export normalizeRemoteUrl (host/org/repo; credentials, ports, and .git stripped) and computeAttributionRecords, which reuses the exact repo-grouping + tightest-window attribution from computeYield (extracted into a shared buildRepoGroups) and joins in the normalized origin remote and session prLinks. - otlp: two new span types sharing the session traceId — codeburn.session.attribution (git.repo, git.pr_links, git.commit_count) and codeburn.commit (git.sha, git.in_main, git.was_reverted). Resource attribute codeburn.attribution_methodology=timestamp-window marks the attribution as inferred. - push: generic send core reused by usage and attribution batches. Dedup keys encode mutable state (inMain/wasReverted), so a state transition re-sends the updated fact while identical states dedupe via the existing sent-ledger. - cli: opt-in --attribution flag on sync push (dry-run aware); commits in repos with no network remote are never sent. AI-Origin: human |
||
|
|
f54c48f350 |
fix(sync): setup error handling, Windows browser open, themed callback pages
- Catch errors in 'sync setup' action: AuthError/DiscoveryError (login
timeout, port exhaustion, discovery failures) now print a clean one-line
message and exit 1 instead of crashing Node with an unhandled rejection
stack trace. Also guard the double rejection when all callback ports are
in use (both 'ready' and the callback promise reject).
- Windows: open the auth URL via 'rundll32 url.dll,FileProtocolHandler'
instead of 'cmd /c start'. cmd.exe splits its command line on '&', which
truncated the OAuth query string at the first parameter, so the IdP
received a bare /authorize request ('no parameters'). rundll32 receives
the URL as a plain process argument with no shell parsing.
- Theme the OAuth callback landing pages to match the dashboard (warm
paper background, ink text, forest-green success / terracotta failure),
fully inline with no network or asset dependencies.
AI-Origin: human
|
||
|
|
d8a7b2a95f |
fix(sync): address PR review — https enforcement, keychain test isolation, golden ID pins
Before-merge items: 1. HTTPS enforced on every remote endpoint (RFC 8252 §8.3): baseUrl, issuer, authorization/token/revocation endpoints, and the traces endpoint all reject non-https, with a loopback (127.0.0.1/::1/ localhost) exception for offline tests and local dev. Enforcement is central (assertHttps) — the browser-open guard is no longer the only check whose failure was swallowed. 2. Credential store test isolation: CODEBURN_SYNC_TOKEN_STORE=file forces the file store (honors HOME) so the offline suite never touches the real macOS login keychain. Set in the e2e suite. 3. Golden pins for deriveSpanId/deriveTraceId/deriveDeviceId with fixed inputs and expected hex — the idempotency contract depends on these encodings being stable across releases; a green-tests encoding change would silently double-count history on span-ID-keyed backends. getDeviceId refactored over a pure deriveDeviceId(host, user). Smaller review items: - Callback server: ready promise resolves the actually-bound port from the listening event (kills the 100ms-sleep race after port fallback); Connection: close on all responses + closeAllConnections() on shutdown (pooled keep-alive sockets from a closed server could swallow requests aimed at a later server on the same port); error handler guarded so a post-bind error can never rebind to a different port than advertised; optional ports param ([0] = ephemeral) removes fixed-port contention between parallel test workers. - fetchOidcConfig verifies the issuer claim matches the fetch origin (OIDC Discovery §4.3 mix-up defense). - partialSuccess.rejectedSpans wrapped in Number() — proto3 int64 JSON mapping sends strings from strict protojson servers; += would concatenate. - Ledger writes are atomic (temp + rename); corrupt-ledger recovery and no-tmp-left-behind tests added; XDG_CACHE_HOME honored (ledger is reconstructible state, not config). - Mock IdP now implements /oauth2/authorize (registers PKCE challenge, 302s to redirect_uri) and verifies S256 code_verifier + single-use codes at the token endpoint. The e2e drives the real redirect flow and asserts wrong-verifier and code-reuse are rejected — PKCE binding is now exercised end to end. - sync reset calls clearLedger() instead of reimplementing the path. - push sets exit code 1 on rate-limited/server-error outcomes so cron and script callers can detect incomplete pushes. Deferred (noted for fast-follow): macOS 'security -i' stdin mode (untestable on this Linux box), ai.cost_estimated as a real ParsedApiCall flag (touches core parser types). Sync suite: 81 passing (5x stable), 5 developer-only. AI-Origin: human |
||
|
|
ca39a69b6b |
feat(sync): push AI usage telemetry to a team OTLP backend (preview)
Adds an opt-in `codeburn sync` command group: setup, push, status,
logout, reset. Developers authenticate via standard OIDC browser login
(Authorization Code + PKCE, provider-agnostic — Cognito, Auth0, Okta,
Keycloak, etc.) and push per-call usage metadata to a team-operated
OTLP/HTTP endpoint.
Privacy is structural: the payload builder has no field that can carry
prompts, responses, file contents, or bash commands. Only metadata
leaves the machine (provider, model, tokens, cost, project, tool names,
timestamps). There is deliberately no flag to include more.
Setup derives everything from a single URL:
GET {base}/.well-known/codeburn-export.json
→ issuer, client_id, traces_path, max_batch_size
Modules:
- discovery.ts discovery doc fetch/validation (version-gated)
- auth.ts OIDC discovery, PKCE, localhost callback (:19876-78),
token exchange/refresh/revoke
- credentials.ts refresh token in OS keychain (macOS security / Linux
libsecret / Windows DPAPI / 0600 file fallback). All
subprocess calls use execFileSync arg arrays; tokens
flow via stdin or env var — never shell-interpolated
- config.ts ~/.config/codeburn/sync.json
- ledger.ts client-side sent-ledger for exact dedup (no watermark
races), 6-month prune
- otlp.ts ParsedApiCall[] → ExportTraceServiceRequest JSON with
deterministic IDs: span=SHA256(dedupKey)[:8],
trace=SHA256(sessionId)[:16] — every retry idempotent
- push.ts orchestration with typed outcomes; pushes run to
completion — 429 Retry-After honored (≤120s/wait,
3 retries/batch) before deferring; partial_success is
batch-atomic (nothing ledgered, whole batch retries);
50K safety valve, no routine cap
- cli.ts command layer; --dry-run reports exact counts/cost
without sending
Preview feature: protocol may change between releases.
AI-Origin: human
|