Skip to content

Extract @codeburn/core: one engine, CLI as first customer (tracking) #809

Open

Description

@iamtoruk

Tracking issue for the @codeburn/core extraction (accepted direction of RFC #796, amended). Work happens on the long-lived integration branch feat/core-extraction; phase PRs target that branch, never main. Main merges once, when Phases 0-7 plus the dual-registry bridge are complete and green.

End state

One implementation: @codeburn/core owns deterministic decoding -> content-minimized observations -> pure detection. The CLI is Core's first customer: it keeps all side effects (discovery, SQLite, caches, pricing, aggregation, UI, apply) and delegates every parse/detect call. No parser or detector exists in both places once migrated.

Decisions (final)

  • D1 Fingerprint privacy key: required, caller-supplied; the CLI auto-generates and stores a per-install key.
  • D2 Classification stays host-side (D2-A), scope explicitly includes the user-corrections scanner (workflow-insights) — no free text crosses the Core boundary.
  • D3 Pricing stays fully host-side for the preview.
  • D4 Detector redesign may re-baseline savings numbers, with documented diff + changelog entry.
  • D5 Core findings are advisory (D5-A); the host re-derives concrete fix payloads; act/apply stays CLI-side.
  • D6 Preview scope: Claude + Codex decoders only.
  • D7 Previous-major retention promise deferred until a real external consumer exists.
  • D8 Publish as 0.x at preview; 1.0 only after the provider long tail is migrated.

Gates (every phase PR)

  1. Parity: byte-identical CLI report output on the golden fixture corpus vs the pre-migration path.
  2. Perf (Phases 3/4/8): cold and warm parse within 5% of pre-migration on the corpus — the scanner and incremental-append machinery must survive extraction.
  3. Full suite green; no working path deleted until its replacement passes both gates; every phase reversible (opt-in module or move-with-shim).

Phases

  1. Pricing lift-out (no package split): decoders emit token counts + basis (measured/derived/estimated); a single host-side pricing pass produces costUSD/savings exactly as today. Removes calculateCost from all provider files + parser.ts. Determinism test with network stubbed.
  2. Workspaces + mechanical move: packages/{core,cli} via git mv, no logic change.
  3. Schema + invariants + harness: ObservationEnvelope, diagnostics, HMAC resource fingerprints, content-smuggling fixture, import-smoke harness. Rich-capture fields (loc deltas, interruptions, branch) are first-class in the observation schema from day one.
  4. Claude decoder carve-out from parser.ts (parity + perf gated).
  5. Codex decoder + explicit serializable incremental state (round-trip resume test).
  6. Detector redesign over fingerprints (evidence, confidence, algorithmVersion).
  7. Classifier + corrections relocation per D2-A.
  8. act/apply reconciliation per D5-A.
  9. Dual-registry bridge + long tail (~35 providers, one PR each) — bridge lands on the branch; tail migrates after the main merge as ordinary PRs.
  10. Publish 0.x preview (npm pack installable without CLI/native deps; import-smoke + content-smuggling green in a scratch install; export-coverage test keeps the CLI a real caller of every export).

Workflow

  • Weekly main -> branch syncs (Phase 0 touches ~30 provider files; keeping the conflict window short matters).
  • Every phase PR gets maintainer review before landing on the branch.
  • Full plan with test strategy, risk register, and effort estimates is maintained internally; this issue tracks phase status.

Phase status: [x] 0 [x] 1 [x] 2 [x] 3 [x] 4 [x] 5 [x] 6 [x] 7 [x] 8-bridge [ ] main merge [ ] 9

Activity

  1. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 0 complete on feat/core-extraction (PRs #810-#819, 10 landed). Every provider decoder now emits token counts + costBasis; the single host-side pricing pass (src/pricing-pass.ts) computes cost before any cache write. Two add-only seam fields emerged from real shapes: pricingModel (display model != priced model: antigravity, cursor) and fallbackCostUSD (table-preferred with provider-figure fallback: codebuff, session-message, sqlite-session-parser). Byte-identical throughout: zero parse-version or cache-version bumps; full suite green at every step.

    Documented residuals (all in-code): codex.ts x2 (results-cache persists decoder output verbatim — owned by Phase 4), copilot shutdown site (prices output=0 by design), mistral-vibe allocation branch. parser.ts Claude sites are Phase 3 scope by design.

    Next: Phase 1 (npm workspaces + mechanical packages/cli move).

  2. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 1 complete (#820): npm workspaces, CLI moved wholesale to packages/cli via 334 history-preserving renames, @codeburn/core typed skeleton in place and depended on. Byte-identical CLI behavior verified (--help diff, payload keys, stage-cli closure superset); 2252 tests green from the workspace root; the appx workflow passed its first windows-latest run on the new layout. One commit, single-revert reversible. Next: Phase 2 — Core schema, invariants, conformance harness, fingerprints.

  3. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 2 complete (#821): @codeburn/core foundation — strict 0.1.0 ObservationEnvelope (structurally content-free, rich-capture numerics first-class), versioned decode/detect contracts, domain-separated HMAC fingerprints (required privacy key), diagnostics, drift-tested JSON Schemas, and both guardrail harnesses (import-smoke with non-vacuity check; content-smuggling). zod-only runtime. 91 core tests; root suite untouched at 2252. Next: Phase 3 — Claude decoder carve-out behind byte-parity + perf (±5%) gates.

  4. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 3 complete (#822): Claude decode carved into @codeburn/core (two-layer: rich pure decode + minimizing toObservations); parser.ts is now an adapter (−1335 lines) keeping I/O, caches, incremental append, classification, pricing. Gates: byte-parity on suite + synthetic corpus + a frozen 5.1GB real corpus (baseline self-consistency proven first; float-tolerant compare — live-corpus comparisons are invalid, methodology documented); perf dead-even cold and warm. Core 99 tests incl. a real-decode content-smuggling case; import-smoke covers the claude subpath; zero parse-version bumps; zero consumer churn via re-exports. Next: Phase 4 — Codex decoder + explicit serializable incremental state (also retires the two Phase-0 codex residuals).

  5. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 4 complete (#823): Codex decoder in @codeburn/core with explicit plain-JSON serializable state — round-trip resume proven at every split index incl. forked-session boundaries; end-to-end CLI resume via byteOffset+state (codex gains incremental append parsing). Both Phase-0 codex pricing residuals retired. CODEX_CACHE_VERSION 7→8 (sanctioned lossless bump; re-derive = one cold run). Frozen-corpus parity independently verified (codex-only + full payload, 51k calls); perf +1.4% cold / +0.4% warm. Core: 108 tests. Flag for Phase 9: cli dist bare-imports @codeburn/core — publish requires core published or bundled. Next: Phase 5 detector redesign.

  6. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 5 complete (#824): duplicate-reads, junk-reads, and context-bloat detectors redesigned into @codeburn/core over resource fingerprints (schema 0.2.0; raw paths never enter core; CLI derives fix payloads via a host-side reverse map per D5-A). D1 privacy keystore live. Numbers parity held byte-for-byte — no D4 re-baseline needed (145 optimize tests unchanged; frozen-corpus optimize output identical, independently verified). Junk-reads predicate proven a strict superset of the legacy regex after a review-driven classifier extension. Core 135 tests; detector purity enforced by import-smoke. Next: Phase 6 classifier relocation.

  7. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 6 complete (#825): D2-A executed and locked. Audit confirmed the classification/corrections boundary was already fully host-side post-Phase 3 (zero leakage, every consumer mapped). Deliverable: a 9-test architecture gate — core source scan (no category names, correction phrases, classifier identifiers, userMessage outside the 4 rich-decode carriers) + schema scan freezing all 44 string-typed fields as bounded (a future unconstrained string property fails CI). Root 2254 unchanged; core 144. Phase 7 (act/apply gate) in flight.

  8. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 7 complete (#826): D5-A executed and locked. Audit found no gap — fix/apply payloads were already fully host-derived (core Findings contribute only decisions + counts; the envelope is transient and never persisted; fingerprints never inverted). Gates added: parse-time rejection of fix-payload keys in the Finding schema (core) + byte-identical fix-payload goldens with host-derivation proof (CLI). Core 151, root 2260. Phase 8.1 (dual-registry bridge + qwen exemplar + tail recipe) in flight.

  9. iamtoruk commented on Jul 26, 2026

    @iamtoruk
    MemberAuthor

    Phase 8.1 complete (bridge PR merged): dual-registry bridge live — bridged and legacy providers resolve identically through the public registry; qwen migrated as the exemplar (decode in exactly one package, golden byte-identical); docs/core/phase8-recipe.md carries the tail fan-out with the full census (15 simple / 11 sqlite / 5 shared-module / 3 stateful / 1 network-special). The long tail migrates one gated PR at a time from here; frozen-corpus compare required for corpus-present providers. Remaining: tail migrations (background), Phase 9 publish 0.x, final main merge.

  10. iamtoruk commented on Jul 27, 2026

    @iamtoruk
    MemberAuthor

    Phase 8 complete @ d8ea608. All 36 provider identities (35 tail + the qwen exemplar) now decode in @codeburn/core; the CLI retains all I/O, caches, pricing, and stitching.

    Final tally for the phase: simple 15/15, sqlite-rowed 11/11, shared-module 5/5 (+4 modules unified), stateful 3/3 (bespoke adapters), network special 1/1 — PRs #810–#842. Nine consecutive frozen-corpus cumulative 1:1 passes against the pre-extraction baseline (8578199): five overview surfaces byte-identical, menubar month/lifetime and full JSON export equal at rel_tol 1e-9, warm perf within ±5%. ~30 draft defects were caught by the two-tier validation protocol before commit; zero red CI runs.

    Remaining before the final main merge: Phase 9 (publish @codeburn/core 0.x or bundle via noExternal — the cli dist bare-imports core), and the flagged follow-up sweep (bare-Record prototype exposure in several pre-existing tool maps, schema-wide envelope dedup-key hashing decision, import-smoke's spawned-build heap env, cursor-cache.ts honoring CODEBURN_CACHE_DIR).

  11. iamtoruk commented on Jul 27, 2026

    @iamtoruk
    MemberAuthor

    Phase 9 publish: done. @codeburn/[email protected] is live on npm (public, under the new codeburn org), verified by a clean external install + subpath import + decode smoke test. The cli's bare imports of @codeburn/core now resolve for external installs. One release-time note: packages/cli's dependency on core is the workspace "*" — pin to ^0.9.19 when the cli itself is next published.

  12. laulpogan commented on Jul 27, 2026

    @laulpogan

    Follow-on work after #847 — five decisions I can't make alone

    #847 is the first of three changes I've prepared against feat/core-extraction. It's build/release/CI only, no src/ changes, and it stands on its own.

    The other two are written, rebased on #847, and green locally (634 tests, 38 files). I'm not opening them as PRs yet, for two reasons: CONTRIBUTING.md asks for one PR at a time, and both change published wire formats. @codeburn/[email protected] is already on npm, so these are breaking changes for anyone consuming it — that's a maintainer's call, not mine.

    Below are the five decisions. Each is a yes/no. If you say no to any of them, I'll drop that piece.


    1. Observation schema 0.2.0 → 0.3.0: fingerprint width and dedupKey

    Three changes, all breaking:

    • Fingerprints widen from 16 to 32 hex chars (64 → 128 bits). At 64 bits, a host holding ~5 billion refs expects a collision by the birthday bound, and two colliding session refs silently merge their calls.
    • dedupKey becomes callRef, a fingerprint. This is the one I'd most want to land. Provider dedup keys are built from provider-native ids: droid:${sessionId}:${call.id}, gemini:${data.sessionId}:${messageKey}, and so on. They shipped verbatim on the wire, which reopened the hole the rest of the layer closes. Two content-smuggling tests currently document this as accepted, one of them saying "hashing dedup keys uniformly is a schema-wide change, not a cursor-local one" — this is that change.
    • Envelopes gain fingerprints: { algorithm, keyId }. Refs are comparable only across envelopes sharing a key id. Without this, a consumer merging two envelopes cannot tell whether their refs are related, and joining across key ids fabricates sessions. The key id is derived one-way from the key and is not the key.

    Decision: ship 0.3.0 with all three, or a subset?

    2. Cap provider, model, pricingModel, providerId

    These were z.string().min(1) — unbounded, so free-text channels. The architecture gate allowlisted them as "machine identifiers," and a hostile fixture in content-smuggling.test.ts plants a prompt in model and asserts it survives.

    Capping them to a charset means a non-canonical label has to go somewhere. I made the adapters degrade it to 'unknown' rather than fail validation, so one bad label doesn't cost you the whole session.

    Honest limitation: a charset can't separate sk-live-0123456789abcdef from claude-opus-4-8, or feature/acme-acquisition from anthropic/claude-sonnet-5. They're the same shape. What the cap does guarantee is that no prose, prompt, file content, command line, whitespace, or newline reaches the field. I've pinned that residual in a test rather than papered over it.

    Decision: accept the cap plus the 'unknown' fallback?

    3. Finding schema: drop impactUSD, add a subject

    Currently a finding carries impactUSD and can aggregate many sessions with no single subject.

    • impactUSD removed. Core has no pricing and never measured cash. A dollar figure here invites a host to render "you wasted $X" from a fixed assumption.
    • Every finding names one subject ({ kind, ref }), and detectors emit at most one finding per session instead of one aggregate. Project rollups stay a host concern — you already know each session's projectRef.
    • Confidence rationale becomes controlled codes instead of an algorithm-authored sentence; evidence kind becomes a closed enum.
    • Token effects move to an optional estimate carrying methodId/methodVersion and a required nonCash: true that cannot be set false.

    Decision: replace the finding contract, or keep impactUSD for existing consumers?

    4. Rename context-bloat → low-context-before-edit, and drop its token estimate

    The name describes the opposite of what it measures — it fires when there's too little context, not too much.

    More importantly, its estimate had the wrong sign. It computed the reads a healthy ratio would have required and reported them as tokens-saved. Those reads never happened, and performing them would add tokens. Ten edits and zero reads currently produce 24,000 "tokens saved." I've dropped the estimate entirely and left counts plus the ratio; whether to spend more context is the host's call.

    The other two detectors keep a token estimate, but as avoidable-tokens with methodId: fixed-read-token-assumption, and AVG_TOKENS_PER_READ is renamed ASSUMED_TOKENS_PER_READ — 600 is a flat heuristic applied regardless of file size, not a measurement.

    Decision: rename and drop the estimate?

    5. The exported Decoder type

    contracts.ts exports a generic Decoder that no shipped provider implements and none ever has. It describes one step from records to observations; every real provider runs two — a provider-specific rich decode, then toObservations. Anyone typing against it gets a compile error and no explanation.

    I've marked it @deprecated (kept as an alias so existing imports resolve) and added RichDecoder / ObservationAdapter describing the two real stages, plus a supportedProviders() registry so consumers stop hard-coding the provider list or scraping package.json.

    Decision: deprecate now, or delete outright?


    One thing I could not do

    The plan I was working from specified an inputKinds field on the provider registry ('jsonl' | 'json' | 'rows' | 'bytes' | 'report'). I left it out. I couldn't establish the value for all 34 providers without per-provider investigation of the discovery layer, and a registry that guesses is worse than one that stays quiet — a consumer would route real data on it. supportsIncrementalState is derived from actual decoder signatures and is in there. Happy to add inputKinds per provider, backed by evidence, if it's wanted.

    Also worth flagging

    packages/core has no prepublishOnly, and the build is tsup && tsc with clean: true. If tsup succeeds and tsc fails, dist holds .js with no declarations — and npm pack still succeeds, with all 41 exports subpaths pointing at files absent from the tarball. #847 now adds a publish guard for this. Pre-existing, not introduced by these changes, but worth knowing if anything published from a dirty tree.

    Say the word on each and I'll open whichever are approved, one at a time.

  13. laulpogan commented on Aug 2, 2026

    @laulpogan

    Two short follow-ups on the above — my last comment was long, so this one isn't.

    1. 0.9.20 is on npm now. It went out ~5 min after #847 merged, and I confirmed the tarball is the PR's output: 238 files, 151 .d.ts, no dangling .d.ts.map, all 41 export targets resolving, and prepublishOnly ran for that publish. Good — but it means the schema changes in the two held branches now break a published package rather than a hypothetical one. That raises the cost of deciding late, not the cost of deciding no.

    If five questions is too much surface, the one I'd actually push for is dedupKey → fingerprinted callRef. Provider dedup keys ship session/message/record ids verbatim (droid:${sessionId}:${call.id}), which undoes the fingerprinting everywhere else. Two content-smuggling tests already document this as a known hole, one of them saying the fix is "a schema-wide change, not a cursor-local one." Happy to drop the other four and send just that.

    2. What's the merge plan for feat/core-extraction? It's 81 ahead of main and 26 behind, with no PR open. Of the 15 src/ files main touched in those 26 commits, 14 exist on the branch as packages/cli/src/. I checked whether any of it had already broken core — 5a12dcc is host-side turn classification, which the architecture gate keeps out of core, so nothing is corrupted today. But the gap grows daily, and both held branches sit on top of it.

    If porting main → feat/core-extraction would help, I'm happy to take it. Otherwise just knowing whether the branch is on a path to main tells me whether to keep the two rebased or park them.

    No rush on either — mainly flagging that (1) got more expensive and (2) has no owner that I can see.

  14. ozymandiashh commented on Aug 4, 2026

    @ozymandiashh
    Collaborator

    Carrying over three acceptance criteria from RFC #796 (closing that one in favor of this epic — raised by @laulpogan there). None of them block the phase work; (3) is the only one that is time-sensitive relative to the tail.

    1. Document the three versioning axes. The RFC committed to three independently-advancing axes — package semver, observation/finding schemaVersion, detector algorithmVersion — each with documented bump rules. RELEASING.md § Versioning covers the package axis only ("CodeBurn uses semantic versioning… the CLI and macOS menubar share the same version number"). The practice already exists on the branch — schemas frozen per version, schema-drift.test.ts enforcing it — it is just undocumented. @codeburn/[email protected] is live on npm, so consumers have no stated compat contract right now.

    2. Machine-readable provider coverage. "Provider coverage is machine-readable and tested" — there is no supportedProviders() export on the branch; packages/core/src/index.ts re-exports schema/observations/diagnostics/fingerprint/contracts only. Phase 8's dual-registry bridge is internal wiring, not a published manifest. Related and worth reconciling either way: packages/core/package.json on the branch already ships 34 provider subpath exports, against D6's "Claude + Codex decoders only" preview scope.

    3. Gate against parsers or detectors landing outside Core. architecture-gate.test.ts enforces D2 (no category literals, classification identifiers, correction phrases, or userMessage outside the rich-decode allowlist) plus string-field bounding on every schema version — both scan packages/core. Nothing scans packages/cli for parser or detector decision logic, which is the RFC's "no new parser or detector decision logic outside Core" rule. The ~35-provider tail migrating post-merge as ordinary PRs is exactly the window where a CLI-side parser can slip back in.

    @laulpogan offered a PR for (1) and (2). @iamtoruk — (3) needs your call on scope: does the CLI-side gate block the main merge, or is landing it before the first tail PR enough?

  15. added a commit that references this issue on Aug 5, 2026
  16. added
    enhancement
    area: cli
    on Sep 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: clienhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions