Skip to content

feat(local-ai): store downloaded models in the standard HF hub cache - #1288

Closed
larroy wants to merge 9 commits into
openclaw:mainfrom
larroy:dev/plarroy/better_download
Closed

larroy wants to merge 9 commits into
openclaw:mainfrom
larroy:dev/plarroy/better_download

Conversation

@larroy

@larroy larroy commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Moves LocalAI Inference model downloads from an app-private folder (%LOCALAPPDATA%\OpenClawTray\LocalAI\models\<org>\<repo>\<sha>\<file>) to the standard Hugging Face hub cache layout (models--<org>--<repo>\snapshots\<revision>\<file>, rooted at HF_HUB_CACHE/HF_HOME/the default ~/.cache/huggingface/hub).

This lets a model already downloaded by huggingface-cli, llama.cpp's --hf-repo, or another OpenClaw install be recognized and reused instead of re-downloaded, and vice versa.

Changes

  • Add HuggingFaceHubCache (OpenClaw.Shared) to resolve the cache root and compute/validate snapshot paths, with narrower reparse-point checks appropriate for a directory shared with other tools (only the target and its parent, not the whole tree — unlike the app-owned LocalAI root, which requires the whole tree to be reparse-point-free).
  • Extract the common Windows path-safety primitives (segment safety, device-name rejection, descendant/equality checks) into a new WindowsPathSafety utility in OpenClaw.Shared so LocalAiPathPolicy and HuggingFaceHubCache share one implementation instead of duplicating it.
  • Wire HuggingFaceModelInstaller, LocalAiInstallReconciler, and LocalAiManifest to the new cache; remove the now-unused LocalAiPathPolicy.TryGetModelPaths/ModelsDirectory.
  • Bump the install manifest schema to v4: ModelPath is now an absolute path into the hub cache rather than relative to the LocalAI root. Existing installs will reinstall on upgrade.
  • Side effect: uninstalling/reinstalling OpenClaw no longer deletes the downloaded model, since it never lived under the deleted LocalAI root.
  • Deliberately not implemented: content-addressed blobs/ storage + symlinks (real huggingface_hub cache semantics). Files are written directly at their snapshot path — matches the visible folder shape other tools recognize, but skips cross-revision dedup. This avoids requiring Windows Developer Mode/admin for symlinks and avoids conflicting with the existing reparse-point-rejection security model.

Testing

  • Added HuggingFaceHubCacheTests covering cache-root resolution precedence (HF_HUB_CACHE > HUGGINGFACE_HUB_CACHE > HF_HOME > default) and snapshot/managed-path validation.
  • Updated affected fixtures (LocalAiInstallRecoveryTests, LocalAiPortHandoffTests, LocalAiGatewayUninstallTests, LocalAiPortLifecycleTests) to use an isolated per-test HF_HUB_CACHE override (existing EnvironmentScope/EnvironmentVariableCollection pattern) so tests stay hermetic.
  • OpenClaw.Shared.Tests, OpenClaw.Connection.Tests, OpenClaw.Tray.Tests, and OpenClaw.SetupEngine.Tests all pass.

Proof

Verified that redoing the install workflow doesn't redownload the model (just verifies it recalculating the checksum)

Screenshot 2026-09-03 at 11 07 45 PM

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P1 Urgent regression or broken agent/channel workflow affecting real users now. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed September 10, 2026, 12:42 AM ET / 04:42 UTC (Revision 13).

ClawSweeper review

What this changes

Moves Local AI model downloads into the shared Hugging Face cache, adds verified reuse and legacy migration, and retains downloaded weights after later setup failures.

Merge readiness

⛔ Blocked before merge - 17 items remain

Keep open: the merged replacement layers deliberately leave normal cache downloads and active model selection unfinished. The original branch still has compatibility and filesystem-safety defects, while the maintainer explicitly retained this PR as the parent tracking item.

Priority: P2
Reviewed head: a3d08db6f624254f330d18614cb6c59bc6012d2f
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful implementation and visible progress evidence remain, but persisted-state and shared-cache safety defects prevent landing the original branch.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Authority-chain proof required: show that replaced cache candidates, redirected destination paths, and hard-linked partials cannot cause unverified reuse or unrelated writes. The inspected Windows screenshot positively shows verification progress, but not completed acquisition, schema upgrade, or inference from the resulting manifest; proof from the merged layers does not establish those remaining paths. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Authority-chain proof required: show that replaced cache candidates, redirected destination paths, and hard-linked partials cannot cause unverified reuse or unrelated writes. The inspected Windows screenshot positively shows verification progress, but not completed acquisition, schema upgrade, or inference from the resulting manifest; proof from the merged layers does not establish those remaining paths. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 10 items Repository policy: Read the complete root AGENTS.md and proof-validation skill. No applicable nested AGENTS.md or maintainer-notes directory was found. Applied upgrade, isolation, and current-head proof guidance; no builds, tests, helpers, or repository mutations were performed.
Introduced scope and review continuity: The pinned merge-base-to-head delta contains 20 files: production +1244/-211 and tests/support +1265/-108. The previous completed review examined this same head; comparison confirms the migration and installer files are unchanged. No pinned test merge is available, so findings describe introduced branch behavior, not alleged removal of current-main changes.
Merged layers explicitly preserve remaining work: GitHub confirms #1388 merged. Its contract retains schema 3 for normal writes, makes schema 4 a cache-copy receipt, preserves the active legacy path, forbids migration during ordinary reads, and leaves downloads and active selection to layer 3. The discussion explicitly says the parent remains open. #1385 supplies the shared verified-handle foundation.
Findings 6 actionable findings [P1] Preserve schema-3 runtime loading until explicit activation succeeds
[P1] Verify existing destination bytes before persisting migration
[P1] Accept verified standard snapshot symlinks during migration
Security Needs attention Verified candidate can change before reuse: A cache writer can replace the verified pathname before hard-link creation, bypassing the artifact digest decision. The verified handle must remain authoritative through materialization.
Partial-file writes can modify another linked file: Hard links pass the reparse-point check, allowing resume or restart writes through a shared-cache partial to modify the same file through an unrelated path.

How this fits together

Local AI setup acquires pinned model files and records their location in an installation manifest. The Windows runtime reads that manifest to launch llama-server, so cache migration affects both setup recovery and existing installations.

flowchart TD
  A[Pinned model catalog] --> C[Model acquisition]
  B[Existing cache files] --> C
  C --> D[Size and digest verification]
  D --> E[Shared model cache]
  F[Legacy installation] --> G[Manifest migration]
  E --> G
  G --> H[Local inference runtime]
Loading

Decision needed

Question Recommendation
Should layer 3 automatically activate cached models for existing installations, or initially retain explicit migration and legacy active paths? Stage activation: Keep existing installations on their active legacy paths until explicit verified activation and downgrade compatibility are proven.

Why: The merged migration contract deliberately defers activation and downgrade gating; choosing when persisted installations switch requires rollout intent.

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Authority-chain proof required: show that replaced cache candidates, redirected destination paths, and hard-linked partials cannot cause unverified reuse or unrelated writes. The inspected Windows screenshot positively shows verification progress, but not completed acquisition, schema upgrade, or inference from the resulting manifest; proof from the merged layers does not establish those remaining paths. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Preserve schema-3 runtime loading until explicit activation succeeds (P1) - The schema bump and required ModelCacheRoot make existing schema-3 manifests fail ordinary LoadAsync; LlamaServerRuntimeService.TryLoadInstallAsync never enters setup reconciliation. The prior blocker remains. Preserve legacy loading and selection until explicit activation succeeds, following the contract in feat(local-ai): add verified legacy model cache migration #1388; do not implement the earlier suggestion to migrate during runtime reads.
  • Verify existing destination bytes before persisting migration (P1) - An existing snapshot immediately returns success, after which migration rewrites the active model path. A corrupt destination therefore replaces the reference to valid legacy weights before reconciliation detects the mismatch; ordinary runtime validation checks size rather than hashing. Retain the legacy manifest unless the destination passes its pinned size and digest checks, using main's verified migration owner.
  • Accept verified standard snapshot symlinks during migration (P1) - Mutation validation rejects a standard snapshot-to-blob symlink before the existing-destination branch can reuse it. An installation with valid weights already cached by Hugging Face tooling therefore remains schema 3 and fails the subsequent load. Verify existing destinations through the safe read path, reserving mutation validation for entries this transaction creates.
  • Retain legacy weights until the manifest transaction commits (P2) - The migration moves the active legacy file before the cancellable manifest write. Cancellation, write failure, or process termination in between leaves the persisted installation pointing at a missing file. Copy from a verified handle and retain the legacy source through commit, as main's migration transaction does. This was visible at the previously reviewed head and is a late finding.
  • Materialize reused content from the same verified handle (P2) - VerifyFileAsync disposes its stream before this code resolves and hard-links the candidate pathname. Another cache writer can replace the candidate after hashing, causing different bytes to be accepted as ReusedVerified; the destination parent can also change during verification. Keep verified source and destination identity bound through materialization, using main's verified-handle foundation. This unchanged-head gap was missed in the earlier review.
  • Reject shared-cache partials with additional hard links (P1) - The new shared-cache mutation check rejects reparse points but accepts ordinary hard links. If a short .partial links to another file, a server that ignores Range leads to FileMode.Create truncating that other file; a valid range response appends to it instead. Inspect the opened file identity/link count and replace only the cache entry before writing. Main's migration tests cover this invariant. This is a late finding on the unchanged reviewed head.
  • Resolve security concern: Verified candidate can change before reuse - A cache writer can replace the verified pathname before hard-link creation, bypassing the artifact digest decision. The verified handle must remain authoritative through materialization.
  • Resolve security concern: Partial-file writes can modify another linked file - Hard links pass the reparse-point check, allowing resume or restart writes through a shared-cache partial to modify the same file through an unrelated path.
  • Resolve merge risk (P1) - The branch and main assign different meanings to schema 4; the activation and downgrade contract remains unresolved.
  • Resolve merge risk (P1) - GitHub reports conflicts and no pinned test merge is available, so the eventual combined implementation requires a fresh review.
  • Resolve merge risk (P1) - Shared-cache pathname replacement and hard-link behavior remain unproven at the final filesystem operation.
  • Complete next step (P2) - Agree the layer-3 rollout contract, integrate the remaining work with main, and resolve the findings before merge. Add completed, redacted Windows proof; screenshots or recordings are preferred for visible behavior, while terminal output and logs count. Update the PR body to trigger re-review, or ask a maintainer to comment @clawsweeper re-review.
  • Improve patch quality - Complete the remaining integration against main's migration contract, preserving legacy loading and addressing the listed transaction defects.
  • Improve patch quality - Prove safe final filesystem effects when another cache writer replaces a candidate or supplies a linked partial.
  • Improve patch quality - Provide completed current-head fresh-install, cache-reuse, upgrade, and inference evidence with required proof-pool declarations and validation results.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] Preserve schema-3 runtime loading until explicit activation succeeds — src/OpenClaw.Connection/LocalAi/LocalAiManifest.cs:120
  • [P1] Verify existing destination bytes before persisting migration — src/OpenClaw.SetupEngine/LocalAiManifestMigration.cs:134-135
  • [P1] Accept verified standard snapshot symlinks during migration — src/OpenClaw.SetupEngine/LocalAiManifestMigration.cs:131-132
  • [medium] Verified candidate can change before reuse — src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:483
  • [medium] Partial-file writes can modify another linked file — src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:592
Agent review details

Security

Needs attention: Shared-cache verification and mutation are not bound to stable file identities; no unrelated supply-chain change was found.

Review metrics

Metric Value Why it matters
Production and test delta Production +1244/-211; tests/support +1265/-108 The growth supports cache reuse and migration, but the landed replacement layers now provide part of that foundation.

Root-cause cluster

Relationship: canonical
Canonical: #1288
Summary: This remains the explicitly retained parent for the cache transition; two merged layers implement only portions of it.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Build the remaining layer on main (recommended)
    Retain the merged migration and verified-handle implementations while narrowing the remaining work to safe acquisition and approved activation.
  2. Pause activation
    Keep this parent open while the rollout contract and final-I/O proof are resolved.

Technical review

Best possible solution:

Complete layer 3 using main's verified-handle and migration owners, preserving legacy runtime loading until an explicitly approved, upgrade-tested cache activation succeeds.

Do we have a high-confidence way to reproduce the issue?

Yes, the branch defects have concrete source paths: load a schema-3 manifest directly, migrate with a corrupt or symlink destination, or resume a hard-linked partial. These were not executed in this read-only review.

Is this the best way to solve the issue?

No, the original migration and cache-mutation implementation should not be carried forward unchanged; main now provides safer reusable owners and an explicit staged migration contract.

Full review comments:

  • [P1] Preserve schema-3 runtime loading until explicit activation succeeds — src/OpenClaw.Connection/LocalAi/LocalAiManifest.cs:120
    The schema bump and required ModelCacheRoot make existing schema-3 manifests fail ordinary LoadAsync; LlamaServerRuntimeService.TryLoadInstallAsync never enters setup reconciliation. The prior blocker remains. Preserve legacy loading and selection until explicit activation succeeds, following the contract in feat(local-ai): add verified legacy model cache migration #1388; do not implement the earlier suggestion to migrate during runtime reads.
    Confidence: 0.99
  • [P1] Verify existing destination bytes before persisting migration — src/OpenClaw.SetupEngine/LocalAiManifestMigration.cs:134-135
    An existing snapshot immediately returns success, after which migration rewrites the active model path. A corrupt destination therefore replaces the reference to valid legacy weights before reconciliation detects the mismatch; ordinary runtime validation checks size rather than hashing. Retain the legacy manifest unless the destination passes its pinned size and digest checks, using main's verified migration owner.
    Confidence: 0.99
  • [P1] Accept verified standard snapshot symlinks during migration — src/OpenClaw.SetupEngine/LocalAiManifestMigration.cs:131-132
    Mutation validation rejects a standard snapshot-to-blob symlink before the existing-destination branch can reuse it. An installation with valid weights already cached by Hugging Face tooling therefore remains schema 3 and fails the subsequent load. Verify existing destinations through the safe read path, reserving mutation validation for entries this transaction creates.
    Confidence: 0.99
  • [P2] Retain legacy weights until the manifest transaction commits — src/OpenClaw.SetupEngine/LocalAiManifestMigration.cs:139-140
    The migration moves the active legacy file before the cancellable manifest write. Cancellation, write failure, or process termination in between leaves the persisted installation pointing at a missing file. Copy from a verified handle and retain the legacy source through commit, as main's migration transaction does. This was visible at the previously reviewed head and is a late finding.
    Confidence: 0.98
    Late finding: first raised on code an earlier review cycle already covered.
  • [P2] Materialize reused content from the same verified handle — src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:483-488
    VerifyFileAsync disposes its stream before this code resolves and hard-links the candidate pathname. Another cache writer can replace the candidate after hashing, causing different bytes to be accepted as ReusedVerified; the destination parent can also change during verification. Keep verified source and destination identity bound through materialization, using main's verified-handle foundation. This unchanged-head gap was missed in the earlier review.
    Confidence: 0.97
    Late finding: first raised on code an earlier review cycle already covered.
  • [P1] Reject shared-cache partials with additional hard links — src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:592-598
    The new shared-cache mutation check rejects reparse points but accepts ordinary hard links. If a short .partial links to another file, a server that ignores Range leads to FileMode.Create truncating that other file; a valid range response appends to it instead. Inspect the opened file identity/link count and replace only the cache entry before writing. Main's migration tests cover this invariant. This is a late finding on the unchanged reviewed head.
    Confidence: 0.97
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3ce56b8902d5.

Labels

Label justifications:

  • P2: Shared model-cache reuse is a bounded Local AI improvement with substantive remaining integration work.
  • merge-risk: 🚨 compatibility: The branch changes persisted manifest semantics and rejects existing schema-3 runtime installations.
  • merge-risk: 🚨 security-boundary: Shared-cache verification and pathname-based mutations are separated, allowing changed targets or hard-linked partials to escape the intended integrity boundary.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Authority-chain proof required: show that replaced cache candidates, redirected destination paths, and hard-linked partials cannot cause unverified reuse or unrelated writes. The inspected Windows screenshot positively shows verification progress, but not completed acquisition, schema upgrade, or inference from the resulting manifest; proof from the merged layers does not establish those remaining paths. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. Authority-chain proof required: show that replaced cache candidates, redirected destination paths, and hard-linked partials cannot cause unverified reuse or unrelated writes. The inspected Windows screenshot positively shows verification progress, but not completed acquisition, schema upgrade, or inference from the resulting manifest; proof from the merged layers does not establish those remaining paths.

Evidence

Security concerns:

  • [medium] Verified candidate can change before reuse — src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:483
    A cache writer can replace the verified pathname before hard-link creation, bypassing the artifact digest decision. The verified handle must remain authoritative through materialization.
    Confidence: 0.97
  • [medium] Partial-file writes can modify another linked file — src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:592
    Hard links pass the reparse-point check, allowing resume or restart writes through a shared-cache partial to modify the same file through an unrelated path.
    Confidence: 0.97

What I checked:

  • Repository policy: Read the complete root AGENTS.md and proof-validation skill. No applicable nested AGENTS.md or maintainer-notes directory was found. Applied upgrade, isolation, and current-head proof guidance; no builds, tests, helpers, or repository mutations were performed. (AGENTS.md:1, a3d08db6f624)
  • Introduced scope and review continuity: The pinned merge-base-to-head delta contains 20 files: production +1244/-211 and tests/support +1265/-108. The previous completed review examined this same head; comparison confirms the migration and installer files are unchanged. No pinned test merge is available, so findings describe introduced branch behavior, not alleged removal of current-main changes. (a3d08db6f624)
  • Merged layers explicitly preserve remaining work: GitHub confirms feat(local-ai): add verified legacy model cache migration #1388 merged. Its contract retains schema 3 for normal writes, makes schema 4 a cache-copy receipt, preserves the active legacy path, forbids migration during ordinary reads, and leaves downloads and active selection to layer 3. The discussion explicitly says the parent remains open. feat(shared): add safe Hugging Face cache primitives #1385 supplies the shared verified-handle foundation. (src/OpenClaw.Connection/LocalAi/LocalAiManifest.cs, 3ce56b8902d5)
  • Main and latest release still use private downloads: Inspected HuggingFaceModelInstaller on fetched main and latest-release commit c7c6fb0: both still obtain model paths through LocalAiPathPolicy.TryGetModelPaths. The central download switch is therefore neither completed on reviewed main nor established in v2026.7.1-4. (src/OpenClaw.SetupEngine/HuggingFaceModelInstaller.cs:111, c7c6fb06be03)
  • Prior compatibility findings remain in the branch: The branch requires schema 4 and ModelCacheRoot, but ordinary runtime loading calls LoadAsync without setup reconciliation. Its separate migration accepts any existing destination without digest verification and rejects standard snapshot symlinks through mutation validation. (src/OpenClaw.SetupEngine/LocalAiManifestMigration.cs:129, a3d08db6f624)
  • Migration coverage does not establish integrity: The legacy upgrade test supplies arbitrary text as weights and an AcceptingModelVerifier. It proves relocation but cannot detect a corrupt destination or prove the production digest check precedes manifest persistence. Main's replacement migration tests separately cover corrupt destinations, standard symlinks, interruption, concurrent manifest changes, and hard-linked partials. (tests/OpenClaw.SetupEngine.Tests/LocalAiInstallRecoveryTests.cs:843, a3d08db6f624)

Likely related people:

  • shanselman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Joel: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-03T23:22:32.362Z sha 46a93c8 :: needs real behavior proof before merge. :: [P1] Migrate schema-v3 manifests instead of stopping setup | [P1] Validate cache ancestors before creating the snapshot directory
  • reviewed 2026-09-04T01:16:24.752Z sha f46ae8d :: needs real behavior proof before merge. :: [P1] Handle schema-v3 manifests as reinstallable upgrade input | [P1] Validate cache ancestors before creating the snapshot directory
  • reviewed 2026-09-04T05:13:29.436Z sha 9322000 :: needs real behavior proof before merge. :: [P1] Preserve schema-3 models when the cache is on another volume
  • reviewed 2026-09-04T05:59:00.478Z sha 1efd304 :: needs real behavior proof before merge. :: [P1] Preserve legacy models across cache volumes | [P1] Verify an existing shared snapshot before migrating
  • reviewed 2026-09-04T06:14:32.763Z sha 1efd304 :: needs real behavior proof before merge. :: [P1] Handle schema-3 migrations across cache volumes
  • reviewed 2026-09-04T17:22:58.925Z sha 1efd304 :: needs real behavior proof before merge. :: [P1] Handle schema-3 migrations across cache volumes | [P1] Verify an existing shared snapshot before committing migration
  • reviewed 2026-09-08T22:50:33.228Z sha a3d08db :: needs real behavior proof before merge. :: [P1] Migrate legacy manifests before normal runtime loading | [P1] Verify an existing snapshot before committing migration | [P1] Allow verified standard snapshot links during migration
  • reviewed 2026-09-10T00:41:39.686Z sha a3d08db :: needs real behavior proof before merge. :: [P1] Migrate legacy manifests before normal runtime loading | [P1] Verify an existing snapshot before committing migration | [P1] Allow verified standard snapshot links during migration

@larroy
larroy force-pushed the dev/plarroy/better_download branch from 5672c46 to 3426209 Compare September 3, 2026 21:30
plarroy-nv and others added 2 commits September 3, 2026 14:46
Move LocalAI Inference model downloads from an app-private folder
(%LOCALAPPDATA%\OpenClawTray\LocalAI\models\<org>\<repo>\<sha>\<file>)
to the standard Hugging Face hub cache layout
(models--<org>--<repo>\snapshots\<revision>\<file>, rooted at
HF_HUB_CACHE/HF_HOME/the default ~/.cache/huggingface/hub). This lets
a model already downloaded by huggingface-cli, llama.cpp's --hf-repo,
or another OpenClaw install be recognized and reused instead of
re-downloaded, and vice versa.

- Add HuggingFaceHubCache (OpenClaw.Shared) to resolve the cache root
  and compute/validate snapshot paths, with narrower reparse-point
  checks appropriate for a directory shared with other tools (only the
  target and its parent, not the whole tree).
- Extract the common Windows path-safety primitives (segment safety,
  device-name rejection, descendant/equality checks) into a new
  WindowsPathSafety utility in OpenClaw.Shared so LocalAiPathPolicy and
  HuggingFaceHubCache share one implementation instead of duplicating it.
- Wire HuggingFaceModelInstaller, LocalAiInstallReconciler, and
  LocalAiManifest to the new cache; remove the now-unused
  LocalAiPathPolicy.TryGetModelPaths/ModelsDirectory.
- Bump the install manifest schema to v4: ModelPath is now an absolute
  path into the hub cache rather than relative to the LocalAI root.
  Existing installs will reinstall on upgrade.
- Side effect: uninstalling/reinstalling OpenClaw no longer deletes the
  downloaded model, since it never lived under the deleted LocalAI root.
- Update affected test fixtures to use an isolated per-test HF_HUB_CACHE
  (via the existing EnvironmentScope/EnvironmentVariableCollection
  pattern) and add HuggingFaceHubCacheTests covering cache-root
  precedence and path validation.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@larroy
larroy force-pushed the dev/plarroy/better_download branch from 3426209 to 0a1edfd Compare September 3, 2026 21:55
Reconciler_MigratesLegacyCudaPrefixedUuidSelector still called the old
3-arg CreateManifest after the schema-v4 switch to absolute hub-cache
ModelPaths. Pass the per-test HF_HUB_CACHE cacheRoot and scope the
environment so the manifest resolves and the CS7036 build error goes
away.
Model acquisition only looked for the pinned revision's snapshot path.
Standard hub-cache tools (huggingface_hub, hf CLI, llama.cpp) store
content in the content-addressed blobs store or under another
revision's snapshot, so identical verified bytes were invisible and
OpenClaw re-downloaded multi-GB models.

Discovery now enumerates the blob named by the pinned SHA-256 plus
same-named snapshot entries across all revisions of the repository.
Each candidate must pass the existing snapshot-read validation and the
pinned size and SHA-256 check; verified content is hardlinked into the
pinned snapshot path so manifests keep their canonical form and
rollback removes only the link, never the pre-existing blob.

Validation: build.ps1; Shared.Tests 3925 passed; Tray.Tests 2833
passed; SetupEngine.Tests 1037 passed. Real-cache proof: the pinned
35B blob (22,663,387,424 bytes) and sibling-revision snapshot are
now discovered.
@larroy larroy changed the title feat(local-ai): store downloaded models in the standard HF hub cache [WIP][Don't review] feat(local-ai): store downloaded models in the standard HF hub cache Sep 4, 2026
plarroy-nv and others added 2 commits September 3, 2026 21:36
…able

Follow-up fixes from reviewing the hub-cache migration.

Source:
- Record the hub cache root in the manifest (schema 4) and validate the
  model path against it. Validity no longer depends on the ambient
  HF_HUB_CACHE/HF_HOME of whichever process loads the manifest.
- Migrate schema-3 manifests in place, relocating the already-downloaded
  weights into the hub cache. Existing installs previously hit a terminal
  "run uninstall" and re-downloaded tens of gigabytes of identical bytes.
- Mark a reused hard link as created this run so rollback removes the
  link, and resolve a symlink candidate to its blob before linking so the
  pinned snapshot never becomes a reparse point.
- Create the snapshot directory lazily and remove it when empty, so a
  failed install leaves no bogus revision in this shared cache.
- Unlink a huggingface_hub pointer whose blob fails verification instead
  of refusing forever and stranding setup on a bad blob.
- Hash a resumable partial before sending the request, and report
  verification progress under its own phase: hashing multi-gigabyte
  weights was silent and read as a hang.

Tests:
- Replace five symlink tests that silently returned (and reported as
  passed) on machines without Developer Mode with a [SymbolicLinkFact]
  gate that skips, or fails loudly under OPENCLAW_REQUIRE_SYMLINK_TESTS.
- Isolate LocalAiPortLifecycleTests from the developer's real Hugging
  Face cache and serialize its environment mutation with a collection.
- Cover reuse end to end: a second install of the same revision performs
  no HTTP, and a new revision of already-downloaded content is linked
  rather than downloaded again. Also cover rollback of a reused link,
  empty-directory cleanup, verification progress, and both schema-3
  migration outcomes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Legacy Windows-node context cleanup now checks the registered WSL distributions before querying the prior distro. This makes a rerun idempotent after OpenClawGateway-Dev has already been removed instead of failing the uninstall. Missing-distro diagnostics are also recognized across stdout and stderr.
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. labels Sep 4, 2026
AcquireLocalAiModelStep.RollbackAsync only ever runs after the model
was already downloaded and digest-verified (the step never sets
LocalAiModelInstall on its own failure), so it only fires when a
later, unrelated step fails (e.g. GPU/inference verification). It was
unconditionally deleting the multi-gigabyte verified .gguf in that
case, forcing a full re-download on the next setup attempt even though
the file was fine.

Stop deleting the model on rollback; still clear the context handoff
and clean up stray .partial files. The verified file stays in the
shared HF hub cache so the next run's reuse-by-digest check in
HuggingFaceModelInstaller.InstallAsync picks it back up instead of
re-downloading.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 4, 2026
@larroy larroy changed the title [WIP][Don't review] feat(local-ai): store downloaded models in the standard HF hub cache feat(local-ai): store downloaded models in the standard HF hub cache Sep 4, 2026
@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper provided proof, review again.

@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 4, 2026
@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper edited the description and provided proof

@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review again. I provided proof

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@larroy

larroy commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper what is missing?

…wnload

# Conflicts:
#	src/OpenClaw.SetupEngine/WindowsNodeBootstrapContextStep.cs
#	tests/OpenClaw.SetupEngine.Tests/SetupStepsTests.cs
@larroy

larroy commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review again

@clawsweeper

clawsweeper Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. P1 Urgent regression or broken agent/channel workflow affecting real users now. labels Sep 8, 2026
@shanselman shanselman added the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
shanselman added a commit that referenced this pull request Sep 10, 2026
Adds validated standard Hugging Face cache paths and handle-bound verified reads as layer 1 of the #1288 replacement train.
shanselman added a commit that referenced this pull request Sep 10, 2026
Layer 2 of #1288 after #1385: add explicit, handle-bound migration of verified legacy Local AI model weights into the standard Hugging Face cache while preserving the active legacy model path. Layer 3 owns downloads and active selection.`n`nCo-authored-by: Copilot App <[email protected]>`nCopilot-Session: e7ffdfcb-cd94-420d-9f35-b268846a60fc
@shanselman shanselman reopened this Sep 10, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 10, 2026
@shanselman

shanselman commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Automation disclosure: This comment was generated and posted by GitHub Copilot using Scott Hanselman's authenticated GitHub account, acting on his behalf.

@larroy, thank you for driving #1288 (feat(local-ai): store downloaded models in the standard HF hub cache). Your PR established the product direction and much of the implementation surface we are now finishing.

We split the landing into #1385 (feat(shared): add safe Hugging Face cache primitives), #1388 (feat(local-ai): add verified legacy model cache migration), and a final installer/runtime wiring layer because we wanted to preserve schema-3 installs, keep LoadAsync side-effect free, and tighten shared-cache path and rollback safety. We should have explained that plan and coordinated with you before landing maintainer-owned replacement layers. I am sorry that we did not.

We do not want the replacement train to erase your contribution. The final layer is still in progress. We would like to coordinate it with you rather than simply closing this PR underneath you. If you would prefer, we can help reshape this branch to the remaining layer-3 delta, or land the final maintainer PR with explicit attribution to this PR and your work. We will not close #1288 until the complete replacement exists and we have made the relationship and credit clear.
Update: Scott has since spoken directly with Pedro. Pedro is comfortable with the maintainer replacement train moving forward and is not attached to preserving #1288 as the final landing vehicle. We will proceed with a credited final wiring PR, and will close this PR only after that replacement exists.

@shanselman shanselman removed the status: 🚢 actively landing A maintainer or agent is actively driving this item through implementation, validation, or merge. label Sep 10, 2026
@shanselman

Copy link
Copy Markdown
Collaborator

Superseded by #1397 (feat(local-ai): safely use the standard Hugging Face hub cache), which preserves and credits Pedro Larroy's original work while completing the compatibility, verified migration, rollback, uninstall, recovery, cross-volume, and cache-ownership safety contracts. Thank you @larroy for the original #1288 (feat(local-ai): store downloaded models in the standard HF hub cache) direction and implementation foundation.

@shanselman shanselman closed this Sep 10, 2026
shanselman added a commit that referenced this pull request Sep 10, 2026
Completes layer 3 of #1288 with verified standard-cache acquisition, explicit schema rollout, safe runtime identity binding, recovery, rollback, and uninstall behavior. Preserves and credits Pedro Larroy (@larroy) for the original direction and implementation.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 3d314994-f5c9-4f11-8ce3-06e750fb27b3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants