Dashboard › cli › Distillation
24594d53-5a2a-419c-ab77-049562c58ac5["lore_tm_v1_lf7lMMkl4c0FzDcYksE79f2Hx3yowjMzKfyvTguS7_g"]
/home/byk/.local/share/opencode/worktree/0e8c2f3bbe145a3280d6fb6ed900a5121f382cf0/toolkit-bridge-upgrade/packages/cli/src/lib/delta-upgrade.ts is a 648-line delta-upgrade implementation backed by binpatch.src/lib/delta-upgrade.ts imports applyPatchChainInMemory, extractStableChain, filterAndSortChainTags, validateChainStep, getPatchFromVersion, getPatchTargetSha256, ghcrSource, githubReleaseSource, MAX_NIGHTLY_CHAIN_DEPTH, makeCache, OciClient, PATCH_TAG_PREFIX, resolveAndApply, and SIZE_THRESHOLD_RATIO from binpatch; it preserves the existing public API by re-exporting relevant types and extractSha256, getPatchFromVersion, getPatchTargetSha256, getStableTargetSha256, and PATCH_TAG_PREFIX.DeltaResult as { sha256: string; patchBytes: number; chainLength: number }.getPrimaryUpgradeSource(), which returns PRIMARY_UPGRADE_SOURCE or throws Error("No primary upgrade source is configured").InstrumentHook adapter as withTracing(name, "http.client", fn).join(getConfigDir(), "patch-cache"); cache keys use patch-chain:${fromVersion}-${toVersion}, load spans use operation "cache.get" with cache.key, cache.hit, and optional cache.item_size, and save spans use "cache.put" with total patch bytes as cache.item_size.binpatch strategies. stableSource(source) uses githubReleaseSource with getGitHubReleasesUrl(source), getPlatformBinaryName(), customFetch, tracing instrumentation, and user agent sentry-cli/${CLI_VERSION}. nightlySource(source) uses ghcrSource with registry https://ghcr.io, source.ghcrRepo, target tags nightly-${version}, compareVersions, customFetch, and the same user agent.canAttemptDelta(targetVersion): it rejects development builds where CLI_VERSION === "0.0.0-dev", rejects stable/nightly channel mismatches, and otherwise permits only non-downgrade targets via !isDowngrade(CLI_VERSION, targetVersion).fetchRecentReleases(signal?, source = getPrimaryUpgradeSource()), which requests ${getGitHubReleasesUrl(source)}?per_page=12 with GitHub API accept headers and an optional abort signal; HTTP failures, non-array JSON, and thrown errors return [], with malformed/error cases logged at debug level.downloadStablePatch(url, signal?), which returns downloaded bytes as Uint8Array only for an OK response and otherwise returns null; thrown failures are logged with "Failed to download stable patch".extractStableChain(opts) converts binpatchExtractStableChain failure results to null, while filterAndSortChainTags(allTags, currentVersion, targetVersion) delegates to binpatchFilterAndSortChainTags with local compareVersions.ChainStepResult failures as exactly version-mismatch, missing-layer, or size-exceeded. validateChainStep() first compares getPatchFromVersion(manifest) with opts.expectedFrom, then delegates to binpatchValidateChainStep; when binpatch rejects, it distinguishes an existing oversized layer from a missing layer by matching annotation org.opencontainers.image.title against opts.patchLayerName.resolveStableChain(currentVersion, targetVersion, signal?, source = getPrimaryUpgradeSource()), delegating to stableSource(source).resolveChain(...); the explicit source parameter preserves upgrade-source affinity.resolveNightlyChain(opts) with token, currentVersion, targetVersion, fullGzSize, optional preloadedTags, optional signal, and optional source; its OCI client uses source.ghcrRepo at https://ghcr.io.resolveNightlyChain() lists tags using PATCH_TAG_PREFIX unless preloadedTags is supplied, filters/sorts them between current and target versions, and returns null when the chain is empty or exceeds MAX_NIGHTLY_CHAIN_DEPTH.resolveNightlyChain() fetches all manifests concurrently and returns null on manifest-fetch failure. It validates each hop with the local validateChainStep() specifically to retain the three telemetry reasons version-mismatch | missing-layer | size-exceeded, rather than binpatchβs coarser malformed | over_budget.${getPlatformBinaryName()}.patch, each remaining size budget is opts.fullGzSize * SIZE_THRESHOLD_RATIO - totalSize, validation failures set active-span attribute telemetry_reason, and the final manifest must produce getPatchTargetSha256(manifest, binaryName).resolveNightlyChain() requires the final previousVersion to equal opts.targetVersion and a nonempty expectedSha256; otherwise it stamps telemetry_reason = "version-mismatch" and returns null. Successful resolution downloads all blobs with downloadBlobBuffer() and returns { patches, totalSize, expectedSha256, steps }.applyPatchChain(chain, oldBinaryPath, destPath, onBytes?), traced as "apply-patches" / "upgrade.delta.apply" with patches.count and patches.total_bytes. It calls applyPatchChainInMemory() and throws SHA-256 mismatch after patching: got ${sha256}, expected ${chain.expectedSha256} if output verification fails.makeProgressHandler(setMessage?). Each new progress phase gets a new bar; "apply" uses label "Applying patch(es)" and { format: "pct" }, while other phases use "Processing patch(es)" and { format: "bytes" }.newSize could show approximately 930 MB for a 310 MB install; download/read phases continue showing byte totals because those represent actual sizes.makeProgressHandler() converts cumulative event.written values into deltas via event.written - previousWritten, resets previousWritten to 0 on phase changes, and calls progress?.done() for "done" events.telemetry() as DeltaTelemetry & { _source: { current?: string } }. onResolved captures the selected source, sets active-span attribute delta.source, and logs the patch count and formatted total size; onOfflineMiss records "offline_miss"; onUnavailable sets telemetry_reason._source.current telemetry capture addresses apply failures occurring after successful chain resolution: it retains network/cache/offline source attribution so attemptDeltaUpgrade() can stamp delta.source on error spans.resolveDelta(source, targetVersion, oldBinaryPath, destPath, offline?, setMessage?); it calls resolveAndApply with currentVersion: CLI_VERSION, the instrumented cache, makeProgressHandler(setMessage), and telemetry, then returns both { result, source: tel._source.current }.resolveStableDelta(...) and resolveNightlyDelta(...) public call shapes while adding an optional final source: UpgradeSource = getPrimaryUpgradeSource() argument; each constructs the matching source strategy and strips the internal source metadata from the returned DeltaResult | null.attemptDeltaUpgrade(targetVersion, oldBinaryPath, destPath, offline?, setMessage?, source = getPrimaryUpgradeSource()). It returns null immediately when canAttemptDelta() is false and otherwise chooses channel "nightly" or "stable" based on isNightlyVersion(targetVersion).attemptDeltaUpgrade() creates tracing span "upgrade.delta" with delta.channel, delta.from_version, and delta.to_version; successful delta results record delta.patch_bytes and delta.chain_length, emit Sentry distributions upgrade.delta.patch_bytes and upgrade.delta.chain_length with { channel }, and set span status code 1.attemptDeltaUpgrade() sets delta.result = "unavailable" and still marks span status code 1.attemptDeltaUpgrade() reports it through Sentry.captureException at warning level with tags delta.from_version, delta.to_version, and delta.channel; when a chain source had already been captured, it sets delta.source on the active error span.attemptDeltaUpgrade() error path logs Delta upgrade failed (${message}), falling back to full download, sets span status code 2, records delta.result = "error" and delta.error = message, and returns null.prefetch(source, targetVersion, signal?) skips ineligible or already-aborted requests, resolves a chain from CLI_VERSION, skips chains without steps or requests aborted after resolution, and saves valid chains to the patch cache.prefetchNightlyPatches(targetVersion, signal?, source = getPrimaryUpgradeSource()) and prefetchStablePatches(targetVersion, signal?, source = getPrimaryUpgradeSource()) pass the provided UpgradeSource into nightlySource(source) or stableSource(source), preserving the source selected during version discovery through patch prefetch.