Skip to content

feat(computer): add Go daemon localmodels kit updater with hot-swap, rollback, and CLI (WHI-1151) - #1198

Open
oldwinter53 wants to merge 1 commit into
mainfrom
feat/whi-1151-go-daemon-kit-updater
Open

oldwinter53 wants to merge 1 commit into
mainfrom
feat/whi-1151-go-daemon-kit-updater

Conversation

@oldwinter53

Copy link
Copy Markdown

Refs WHI-1151

Summary

Implements Phase 1 / PR 3 of the Linger × localmodels decoupled upgrade architecture inside the Go Local Computer Daemon, building on merged PR #1183 (forward-compatibility hardening) and PR #1190 (signed active.json contract and lock-free ToolHandle):

  • Go Daemon KitUpdater (internal/localmodels/kit_updater.go):
    • Observable state machine (idle, checking, up_to_date, available, incompatible, downloading, verifying, waiting_for_jobs, activating, rolled_back, failed, disabled) with snake_case JSON KitUpdateStatus and ordered OnStatus observer hook for PR 4 Runner Gateway wiring.
    • Signed Schema v2 channel discovery (releases.heylinger.com/cli/localmodels/channels/{stable,next}/manifest.json + .sig) with adaptive baseline channel gating, monotonic sequence anti-rollback, rollout.percent == 0 kill-switch, rejected.json filtering (with manual force_retry), and region-ordered npm dist-tag fallback (registry.npmmirror.com / registry.npmjs.org → immutable CDN manifest or @simplexai/localmodels meta-package tarball, always validated through the same Ed25519 + Schema v2 compatibility pipeline).
    • Hardened netguard HTTPS transport honoring HTTP_PROXY/HTTPS_PROXY/NO_PROXY, strict body size caps (256 KiB manifest, 4 KiB signature, exact kit.bytes tarball cap), DNS-rebinding protection, and public-HTTPS redirect validation.
    • Silent background metadata-only polling (90 s initial delay + bounded jitter, 6 h interval; disabled under LINGER_LOCALMODELS_DEV_*); never auto-downloads or auto-applies without explicit trigger.
  • Safe Unpacking & #1155 Parity (internal/localmodels/kit_unpack{,_unix,_windows}.go):
    • Region-ordered mirror download (region.json / SIMPLEX_REGION) with streaming SHA-256 verification and automatic mirror failover; reuses already-unpacked verified <toolsRoot>/<sha256> directories.
    • Fail-closed tar extraction rejecting path traversal, absolute paths, symlinks, hardlinks, FIFOs/devices, duplicate files, Windows reserved names, and tar bombs; validates tool.json (manifestSha256, schemaVersion == 1, platform/arch, sourceCommit, every asset SHA-256) and optional bootstrap.sha256.
    • Mirrors #1155 permissions (POSIX 0700 dirs/executables, 0600 regular files; Windows owner-only ACLs via privatefs) and restores PEP 552 .pyc source mtimes.
  • Isolated Smoke Tests, Job-Quiesced Hot-Swap, kit migrate & Auto-Rollback (internal/localmodels/kit_smoke.go, library.go, speech.go, tts.go, internal/computerconfig/config.go):
    • Runs isolated pre-activation capabilities --json (localmodels.capabilities/v1, cliContract major 3) and library status --base-dir <tmp> --json against temporary state/base dirs before touching live state.
    • Adds ActiveJobCount() to Library, SpeechLibrary, and TtsLibrary (counting only CLI download/load/unload/adopted jobs — never active LLM inference leases), defers in waiting_for_jobs until CLI jobs drain, coordinates on Library.lifecycleMu, atomically persists active.json + computer.json (computerconfig.UpdateLocalModelsTool), swaps ToolHandle in-process, invalidates Speech/TTS support & voice caches, runs kit migrate --base-dir <dir> --json, and verifies live Library.Refresh.
    • Automatically rolls back ToolHandle, active.json, and computer.json, records <version>:<sha256> in rejected.json, and re-refreshes live state on post-swap TOOL_FAILED or timeout; prunes unreferenced older kits only when live verification succeeds and kit migrate reports zero skipped_running or errors.
  • Owner-Only Control Plane & Headless CLI (internal/linger/control/server.go, cmd/linger-computer-daemon/{main.go,localmodels_cli.go,localmodels_update_cli.go}):
    • Wires KitUpdater into linger-computer-daemon and adds GET /localmodels/kit-update and POST /localmodels/kit-update (check, apply, rollback, dismiss).
    • Adds linger-computer-daemon localmodels update [--status | --check | --apply | --rollback] [--channel stable|next] [--feed-url <https-url>] [--force-retry] [--json], delegating to a live Daemon when reachable and falling back to standalone mode when offline.
  • Scope: Cleanly scoped to apps/computer/local-daemon/ and apps/computer/AGENTS.md; Runner Gateway, OpenAPI, TeamHub, and Web UI wiring follow in PR 4.

Critical Path Impact

No network round trips or extra file walks are added to the user message -> provider_ready path. KitUpdater.Start runs a deferred background metadata-only poller (90 s initial delay + jitter) completely off startup and inference paths.

Verification

  • go test -race -count=1 ./internal/computerconfig/... ./internal/localmodels/... ./internal/linger/control/... ./internal/daemon/... ./cmd/linger-computer-daemon/...
  • GOOS=windows GOARCH=amd64 go build ./... and Windows go test -c on internal/computerconfig, internal/localmodels, internal/linger/control, cmd/linger-computer-daemon
  • golangci-lint run --new-from-rev=origin/main ./... and .golangci.doc-comments.yml (0 issues)
  • make check-repository-gate BASE=origin/main

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request changes (3 P1, 4 P2, 2 P3) · merge base 9ef0028 · 1 commit, 21 files

Findings

P1

  • apps/computer/local-daemon/cmd/linger-computer-daemon/main.go:616 (and :970) — buildDaemonKitUpdater receives baseProviderEnvironment (built at main.go:182 via computerconfig.RuntimeEnvironment at internal/computerconfig/environment.go:34), which strips all LINGER_* variables, and then reads environment["LINGER_APP_VERSION"] from it. Because LINGER_APP_VERSION is always empty in the resident Daemon, ValidateKitManifestCompatibility (internal/localmodels/kit_manifest.go:647) completely skips minLingerVersion and maxLingerVersion checks: a Daemon on an older Linger release will treat an incompatible kit as available and activate it into active.json, only for startup resolveStartupLocalModelsTool (main.go:215, which gets raw environment) to retire it on next launch. Pass lingerVersion resolved from the raw process environment into buildDaemonKitUpdater separately from the scrubbed baseProviderEnvironment used for child tool invocations.

  • apps/computer/local-daemon/internal/localmodels/kit_updater.go:1190 (and main.go:210-214, localmodels_update_cli.go:230-234) — Overwriting computer.json's local_models.python and local_models.module_directory via UpdateLocalModelsTool destroys the bundled baseline pointer because startup (main.go:210-214) and standalone CLI (localmodels_update_cli.go:151-164, 230-234) both load BundledTool from computer.json. On the first upgrade from bundled v1 to active v2, active.json records Previous: nil (kit_updater.go:1164-1185) while computer.json is overwritten to v2. After any Daemon restart—or in a follow-up standalone localmodels update --rollback --config computer.json call—Rollback sees active.Record.Previous == nil and samePathOrResolvedParent(bundledDir, active.KitDir) == true (kit_updater.go:1513) and fails with no_rollback_target (which is why localmodels_update_cli_test.go:347-353 had to pass --python/--module-dir explicitly). It also breaks fail-closed startup fallback on headless Computers: if active.json is later retired as incompatible (kit_active.go:478-496) or corrupted, ResolveEffectiveKit falls back to computer.json and keeps running the retired v2, and a later upgrade drops v1 from PruneUnusedKitDirs keepDirs (kit_updater.go:1306). Keep computer.json pinned to the bundled baseline and let <toolsRoot>/active.json remain the single source of truth for signed overrides (every Daemon and stateless CLI path already resolves active.json ahead of computer.json), removing UpdateLocalModelsTool and UpdateComputerConfig—or persist the bundled baseline separately so restart, rollback, and retirement never lose it.

  • apps/computer/local-daemon/internal/localmodels/kit_updater.go:1244 (and :1263-1270, :1345-1370) — verifyLiveSwap races with Library.StopAll and caller cancellation. While commitActivationLocked holds u.library.lifecycleMu (e.g., during the up-to-30s runKitMigrate), StopAll (internal/localmodels/lifecycle_stop.go:279-281) increments l.stoppingCount before blocking on lifecycleMu. When verifyLiveSwap then calls u.library.Refresh(verifyCtx), Library.Refresh (internal/localmodels/library.go:1036-1041) short-circuits and returns l.currentSnapshotLocked() without executing the new kit: on a warm cache (l.current != nil), verifyLiveSwap sees the stale pre-swap Available: true snapshot and commits an unverified kit; on a cold cache (l.current == nil, returning stoppingRefusal with CodeToolFailed at library.go:443, 3001) or when caller ctx is canceled during verifyLiveSwap, commitActivationLocked treats the error as a broken kit and permanently blacklists a healthy version in rejected.json (kit_updater.go:1263-1270). Check u.library.isStoppingOrClosed() before/after verifyLiveSwap and check errors.Is(ctx.Err(), context.Canceled): roll back cleanly without calling RecordRejectedKit, and never treat a stoppingCount > 0 short-circuit as a passing verification.

P2

  • apps/computer/local-daemon/internal/localmodels/kit_updater.go:2121 (and :2085-2119) — The production HTTPS transport (newKitHTTPClient), DNS-rebinding DialContext, CheckRedirect policy, proxy env handling (buildKitProxyFunc/collectConfiguredProxyHosts), and validatePublicHTTPSHost have zero unit tests because every test in kit_updater_test.go and localmodels_update_cli_test.go injects a custom HTTPClient (u.customHTTPClient = true), bypassing both newKitHTTPClient and validatePublicHTTPSHost (kit_updater.go:2085-2092). Add focused tests covering validatePublicHTTPSHost (loopback/private/IMDS/non-canonical IPv4 literals), CheckRedirect (non-HTTPS, credentials, non-public target, hop cap), proxy selection, and connect-time IP rejection in newKitHTTPClient.

  • apps/computer/local-daemon/internal/localmodels/kit_updater.go:2068 (and :2096-2119) — validateFetchURL and validatePublicHTTPSHost duplicate validatePublicHTTPSURL from internal/localmodels/kit_manifest.go:503-545, allowQuery is passed false at all 4 call sites (kit_updater.go:1736, 1878, 2022, 2065), and validateFeedURL (:2064) is a single-use one-line wrapper. Extract validatePublicHTTPSHost in kit_manifest.go, share it from validatePublicHTTPSURL, validateFetchURL, and CheckRedirect, and drop the unused allowQuery parameter and validateFeedURL.

  • apps/computer/local-daemon/internal/localmodels/kit_updater.go:629 (and :2423-2455) — Dismiss checks u.opBusy, mutates u.status to idle, releases u.mu at :629, and calls u.notify(snap) at :630. Between u.mu.Unlock() and u.notifyMu.Lock() (:2450), a concurrent Check/Apply/Rollback (e.g., background poll tick) can acquire opBusy, transition to checking/available, and acquire notifyMu first, causing observers to receive [checking, idle] and violate OnStatus's strict publication-order guarantee (:481-483). Serialize Dismiss through tryAcquireOp/releaseOp so transitions and notifications stay strictly ordered without deadlocking re-entrant observers.

  • apps/computer/local-daemon/internal/localmodels/kit_updater.go:533 (and :641, :960, :1403) — KitUpdater.Close() cancels u.ctx and waits on u.wg, but Check, Apply, and Rollback do not bind their contexts to u.ctx (only waitForActiveJobs at :1638 watches u.ctx.Done()) and do not participate in u.wg. On Daemon shutdown (main.go:655-659, 621, 251), if POST /localmodels/kit-update apply outlives controlServer.Close's 2s grace window, kitUpdater.Close() returns immediately while download, unpack, or active.json writes continue racing against localModels.Close() and process exit. Derive each operation's context from ctx and u.ctx (via context.AfterFunc) and track active operations in u.wg inside tryAcquireOp/releaseOp.

P3

  • apps/computer/local-daemon/internal/localmodels/kit_updater_test.go:1409 — TestKitUpdaterDevOverrideDisabledAndDismiss uses time.Sleep(40 * time.Millisecond) to verify a disabled updater did not poll. Because Start returns synchronously without spawning a goroutine when u.disabled (kit_updater.go:514), remove the sleep and assert !devUpdater.started and hits.Load() == 0 after devUpdater.Close().

  • apps/computer/local-daemon/internal/localmodels/kit_unpack.go:88 (and kit_unpack_unix.go:59, kit_updater.go:243, kit_unpack_test.go:172) — Code comments reference PR number #1155, violating the repository convention against issue/PR numbers in comments (AGENTS.md). State the permission invariant directly (owner-writable 0700/0600 POSIX permissions) without #1155.

Checked: archive layout and size cap (packages/local-installation/src/localmodels-tool.ts:329) · privatefs check on 0500/0700 dirs (apps/computer/local-daemon/internal/platform/privatefs/privatefs_unix.go:27) · control server write timeouts (apps/computer/local-daemon/internal/linger/control/listener_unix.go:64)

Unverified: go test -race on apps/computer/local-daemon (Go toolchain unavailable in review environment)

Process: needs rebase onto main (1 commit behind)

CI: all 9 checks passed (computer-go runs without -race; local @linger/computer checks not run)


Automated review of c0c5bc9 by Antigravity.

@oldwinter53
oldwinter53 force-pushed the feat/whi-1151-go-daemon-kit-updater branch from c0c5bc9 to 2f354ab Compare December 5, 2026 16:22
@oldwinter53

Copy link
Copy Markdown
Author

Rebased onto latest main (13ebbbec2) and addressed all review findings in 2f354ab47:

P1

  • LINGER_APP_VERSION in resident Daemon (main.go): Passed resolveLingerAppVersion(environment) from the raw process environment into buildDaemonKitUpdater separately from scrubbed baseProviderEnvironment. Added TestBuildDaemonKitUpdaterEnforcesRawLingerAppVersion.
  • Bundled baseline preservation (kit_active.go, kit_updater.go, main.go, localmodels_update_cli.go): Persisted the verified bundled baseline in owner-only <toolsRoot>/bundled.json (linger.localmodels-bundled/v1, validated against <toolsRoot>/<sha256>/tool.json with symlink rejection) before the first bundled-to-active upgrade overwrites computer.json. Wired ResolveEffectiveKit, NewKitUpdater, Rollback, PruneUnusedKitDirs, and startup config reconciliation to retain and fall back to the verified bundled baseline across restarts, standalone --rollback --config computer.json without --python/--module-dir, incompatible/corrupt active.json retirement, and GC. Added TestBundledBaselinePersistsAcrossRetirementCorruptionAndPrune, TestKitUpdaterRollbackAcrossRestartPreservesBundledBaseline, TestReconcileStartupLocalModelsConfigRevertsComputerJSONOnRetirement, and updated TestRunLocalModelsUpdateCLIStandaloneEndToEnd.
  • verifyLiveSwap vs Library.StopAll and cancellation (kit_updater.go, library.go): Checked stopState() (stoppingCount / stopGen / closed) before and after Library.Refresh and distinguished parent ctx/u.ctx cancellation from genuine kit failures / liveVerifyTimeout. Interruption by StopAll or cancellation now rolls back ToolHandle, active.json, and computer.json cleanly without calling RecordRejectedKit and never commits an unverified warm-cache snapshot. Added TestKitUpdaterVerifyLiveSwapAbortsOnStopAllWithoutRejecting (warm and cold cache) and TestKitUpdaterVerifyLiveSwapCanceledDoesNotRejectKit.

P2

  • Production HTTPS client & SSRF/redirect/proxy tests (kit_updater_test.go): Added direct unit tests for validatePublicHTTPSHost, newKitHTTPClient CheckRedirect policy, buildKitProxyFunc / collectConfiguredProxyHosts, and connect-time DialContext rejection of loopback/private/IMDS targets (including IMDS proxy rejection and local proxy allowance).
  • URL/host validation deduplication (kit_manifest.go, kit_updater.go): Extracted shared validatePublicHTTPSHost in kit_manifest.go used by validatePublicHTTPSURL, validateFetchURL, and CheckRedirect; dropped unused allowQuery parameter and validateFeedURL wrapper.
  • Dismiss observer ordering (kit_updater.go): Serialized Dismiss through acquireOp/releaseOp so concurrent operations cannot race ahead of Dismiss notifications. Added TestKitUpdaterDismissSerializesWithObserverOrder.
  • Close cancellation & draining (kit_updater.go): Tracked active operations in u.wg via acquireOp/releaseOp and bound every operation context to u.ctx via context.AfterFunc so Close() cancels and waits for in-flight checks, downloads, applies, and rollbacks. Added TestKitUpdaterCloseCancelsAndWaitsForInFlightApply.

P3

  • Removed time.Sleep(40ms) from TestKitUpdaterDevOverrideDisabledAndDismiss; asserted !devUpdater.started and hits.Load() == 0 after Close().
  • Removed PR number references from comments in kit_unpack.go, kit_unpack_unix.go, kit_updater.go, and kit_unpack_test.go.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve with nits (1 P2) · follow-up on c0c5bc9 · merge base 13ebbbe · 2 commits, 24 files

Resolved: raw LINGER_APP_VERSION forwarding (main.go:617) · persisted bundled baseline (kit_active.go:494) · StopAll/cancel live-verify fencing (kit_updater.go:1396) · production HTTPS/redirect/proxy tests (kit_updater_test.go:1909) · shared validatePublicHTTPSHost (kit_manifest.go:524) · Dismiss observer serialization (kit_updater.go:606) · Close op cancellation and wait (kit_updater.go:2463) · sleep-free disabled test (kit_updater_test.go:1412) · PR number comments removed (kit_unpack.go:88)

Findings

P2

  • apps/computer/local-daemon/internal/localmodels/kit_active.go:571 (and :383-443) — verifyBundledKitDirectory duplicates the ~55-line directory containment, symlink-escape, privatefs, tool.json schema/target, and relative-entry verification body of verifyActiveKitDirectory right above it in the same file, differing only in skipping the manifest-bound SHA256/ManifestSHA256/SourceCommit checks and defaulting target to CurrentKitTarget(). Future security or layout hardening applied to one path can silently drift from the other. Collapse both into a single verifyKitDirectory(cleanRoot, rawKitDir, target string, expected *KitManifestTarget) helper that enforces the manifest-bound fields when expected != nil and validates kitHex64Pattern otherwise.

Checked: RuntimeEnvironment LINGER_* scrubbing (apps/computer/local-daemon/internal/computerconfig/environment.go:34) · installer kit permission parity (packages/local-installation/src/localmodels-tool.ts:363) · StopAll stopGen fencing (apps/computer/local-daemon/internal/localmodels/library.go:514)

Unverified: go test -race on apps/computer/local-daemon (Go toolchain unavailable in review environment) · local @linger/computer TS and process tests

Process: squash review-fixup commit 2f354ab into a8ef1d1 before rebase merge; rerun check (computer-go)

CI: 8/9 passed; computer-go failed on unrelated native test (touched packages passed; no -race)


Automated review of 2f354ab by Antigravity.

@oldwinter53
oldwinter53 force-pushed the feat/whi-1151-go-daemon-kit-updater branch from 2f354ab to 4ee90be Compare December 5, 2026 16:41
@oldwinter53

Copy link
Copy Markdown
Author

Collapsed verifyActiveKitDirectory and verifyBundledKitDirectory into shared verifyKitDirectory(cleanRoot, rawKitDir, target string, expected *KitManifestTarget) in apps/computer/local-daemon/internal/localmodels/kit_active.go, squashed the review fixes into a single clean commit (4ee90be24) on origin/main (13ebbbec2), and re-verified go test -race, golangci-lint, Windows cross-compilation, and make check-repository-gate.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approve · follow-up on 2f354ab · merge base 13ebbbe · 1 commit, 24 files

Resolved: shared kit directory verification (kit_active.go:383)

Checked: active.json TS schema parity (packages/local-installation/src/localmodels-active.ts:1540) · proxy IMDS netguard policy (apps/computer/local-daemon/internal/platform/netguard/netguard.go:79) · probe exclusion in ActiveJobCount (apps/computer/local-daemon/internal/localmodels/concurrency_probe.go:833)

Unverified: local go test -race (no Go toolchain in review env) · local @linger/computer TS/process tests

CI: all 9 checks passed (computer-go runs without -race; local @linger/computer checks skipped)


Automated review of 4ee90be by Antigravity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants