[BUG] apm install fail second time with Content hash mismatch
Describe the bug
I can install my repo (see apm.yml further down) via apm install <org>/<repo>/package/<project> just fine (kinda, see the logs, it looks wonky but maybe it's just a new feature) but the second time I run apm install it will fail consistently with Content hash mismatch.
To Reproduce
Steps to reproduce the behavior:
apm install <repo>
apm install
Expected behavior
A clear and concise description of what you expected to happen.
Environment (please complete the following information):
OS: Windows
APM Version: 0.16.0
Logs
powershell
Assistant
I'll start by exploring the repository structure to understand the codebase and locate relevant files for the bug. Let's first examine the directory.
Assistant
Let me get a better overview of the project structure.
Assistant
This appears to be the APM (Agent Package Manager) repository itself. The issue is about a bug where apm install fails the second time with a "Content hash mismatch" error. Let me explore the source code to understand the issue.
Assistant
Let me explore the source code structure more:
Assistant
The error message is about "Content hash mismatch" when installing the second time. The key line in the error is:
code
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8. The downloaded content differs from the lockfile record.
This suggests that when a dependency points to a specific file path (like .apm/instructions/testing.instructions.md) within a repo, the hash computed from the lockfile doesn't match the hash computed during the second install. The issue seems to be related to the hash computation for file-based dependencies (as opposed to full package dependencies).
Let me look at the install code and hash-related code to understand how content hashing works.
Assistant
Let me look at those files.
Assistant
Let me look at the error message more carefully. The issue is that the content hash mismatch happens on the second apm install. The first install works fine, but the second one fails. The lockfile has a hash stored, and when the file is fetched again, the hash doesn't match.
The error message says:
code
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8.
This looks like the file path is .apm/instructions/testing.instructions.md and it's a single file from a git repository. The issue is likely related to how the content hash is computed when fetching a single file from a git repository. Let me explore the sources.py file more closely.
Assistant
Let me look at the _compute_hash function and the area around line 777 more broadly.
Assistant
Now let me look at the content hash computation function:
Assistant
Now let me look at the area where the hash mismatch check occurs:
Assistant
Assistant
Now let me look at the integration.py file to see how the content hash is being checked and what happens with single-file dependencies.
Assistant
Let me look more closely at the sources.py file to understand the flow for different types of dependencies:
Assistant
Let me look at the sources.py file to understand the issue better.
Assistant
Now let me look at the CachedDependencySource class to understand how it handles the content hash.
Assistant
Let me look at the CachedDependencySource class:
Assistant
Let me look at the issue more carefully. The error is about content hash mismatch for a virtual dependency (an instruction file). Let me look at how virtual dependencies are handled and what their install path looks like.
Assistant
Let me look at how virtual dependencies handle install paths and hash computation.
Assistant
Let me look at the download phase to understand how virtual files are downloaded:
Assistant
Let me look more carefully at the flow for file-level virtual dependencies. The key issue is that the #main branch is not cacheable, so it gets re-downloaded. Let me look at what happens with the .apm-pin marker file more carefully.
Assistant
Let me look at how _should_skip_redownload works:
Assistant
Let me look at how virtual dependencies (individual files) are downloaded and what their install path looks like:
Assistant
Let me search for download_package more broadly.
Assistant
Let me look at the github_downloader.py to understand how virtual files are downloaded:
Assistant
Let me find the download_package method in the GitHub downloader:
Assistant
Let me look at the download_package method to understand how virtual file dependencies are handled:
Assistant
Let me focus on the virtual file download path. The key issue is about the second apm install failing with a content hash mismatch. Let me search for how virtual files are handled:
Assistant
Let me look at the download_virtual_file_package method:
Assistant
Now I'm getting closer to understanding the issue. Let me continue reading the virtual file download method and see how the hash is computed.
Assistant
Now I understand the flow better. Let me look at the lockfile to understand how content_hash is stored and the lockfile building process.
Assistant
Let me trace through the issue more carefully. The key error is that a content hash mismatch happens on the second apm install. Let me look at the lockfile builder and see what happens with the hash when the lockfile is written.
Assistant
Let me look at the lockfile builder to understand when hashes get stored:
Assistant
Let me look at the tests to understand how virtual file hashing works:
Assistant
Let me focus on the specific issue. The error is about content hash mismatch for a virtual file dependency on the second install. Let me look at how the hash is computed for virtual file packages and what might cause it to differ:
Assistant
Let me look more closely at the detect_ref_change function to understand how the branch ref is handled:
Assistant
Let me look at how detect_ref_change works and how build_download_ref works:
Assistant
Let me look at the self-heal chain to understand what happens between the first and second install:
Assistant
Let me look at the branch_ref_drift heal:
Assistant
Now I understand the issue! Let me look at how _resolve_download_strategy handles deps with no resolved_commit. This is the key:
Assistant
Now I understand the issue. Let me trace the full flow:
Virtual file deps with #main ref have their resolved_commit potentially as None in the lockfile (especially on Azure DevOps)
In _resolve_download_strategy, when locked_dep.resolved_commit is None, neither the git check nor the registry elif runs
So lockfile_match stays False, the dep is always re-downloaded
After re-download, the supply-chain check compares the fresh hash with the lockfile hash
If the branch has advanced, the hashes differ, and the error fires
No bypass key is added because the BranchRefDriftHeal also checks locked.resolved_commit and returns False when it's None
The fix has two parts:
Add a content-hash fallback in _resolve_download_strategy for deps without resolved_commit
Update BranchRefDriftHeal to handle the case where locked.resolved_commit is None but remote_sha is available
Let me also check the download_virtual_file_package method to see how resolved_commit gets set:
Assistant
Assistant
Now I understand the issue. Let me look at the _resolve_download_strategy more carefully to see what happens when locked_dep.resolved_commit is None:
Assistant
Now I can see the problem clearly. When locked_dep.resolved_commit is None (or empty string) for a non-registry dependency, the lockfile match logic falls through without checking. Let me verify this theory by looking at how the lockfile stores resolved_commit for virtual file deps:
Assistant
Let me look at the yaml_to_str function to understand if there could be non-determinism:
Assistant
Now I understand the issue clearly! Let me trace the full flow:
For virtual file deps (like .apm/instructions/testing.instructions.md) with #main branch ref:
_resolve_commit_sha_for_ref may return None for Azure DevOps
So resolved_commit is None in the lockfile
On second install, locked_dep.resolved_commit is None, so the if locked_dep and locked_dep.resolved_commit and locked_dep.resolved_commit != "cached": condition fails
The registry elif also fails (source is "git")
lockfile_match stays False, so skip_download = False
Fresh download happens
BranchRefDriftHeal can't fire (needs resolved_commit to detect drift)
No bypass key added → supply-chain check fails
The fix needs two parts:
Add a content-hash fallback for non-registry deps with resolved_commit = None
When re-download is forced due to content mismatch, mark the dep to bypass the supply-chain check
Let me now write the fix:
Assistant
Let me now look at the rest of the function to understand the full skip_download and content integrity check:
Assistant
Now I understand the full picture. Let me implement the fix. The issue is:
For deps where locked_dep.resolved_commit is None/empty (common for virtual file deps on Azure DevOps), neither the git check block nor the registry elif block runs, so lockfile_match stays False.
The dep is always re-downloaded even when content hasn't changed.
When content HAS changed (branch advanced), the BranchRefDriftHeal can't fire because locked.resolved_commit is None, so no bypass key is added.
The supply-chain check in FreshDependencySource.acquire() then fails with "Content hash mismatch".
The fix has two parts:
Add a content-hash fallback for deps with no resolved_commit (similar to registry deps)
When content integrity check fails for such deps, mark them as expected to change hash (bypass supply-chain check)
Assistant
Now let me implement the fix. I need to:
Add a content-hash fallback for non-registry deps with resolved_commit being None/empty
When content integrity check forces a re-download for such deps, mark them to bypass the supply-chain check
Assistant
Now I need to add a content-hash fallback for deps where locked_dep.resolved_commit is None but content_hash exists. I also need to handle the case where the content hash doesn't match (branch advanced) by adding a bypass key.
Let me implement the fix:
Assistant
Now let me implement the fix. I'll add a third elif branch after the registry case:
Assistant
Good, the first part is applied. Now I need to handle the second part: when the content integrity check in _resolve_download_strategy forces a re-download for a dep with no resolved_commit, we need to add a bypass key. Let me look at that section:
Assistant
I see the issue. When _should_skip_redownload returns False (content changed on disk), lockfile_match stays False, skip_download = False, and the fresh download happens. But no bypass key is added, so the supply-chain check fails. I need to add a bypass key when the content has changed for deps with no resolved_commit.
Let me update the fix:
Assistant
Now let me verify the changes look correct:
Assistant
Good, the changes look correct. Now let me run the existing tests to make sure I haven't broken anything:
Assistant
Let me install the dependencies first:
Assistant
Good, dependencies installed. Now let me run the relevant tests:
Assistant
All 19 tests pass. Let me also run related tests:
Assistant
Let me also run the heal and drift tests:
Assistant
Let me run more related tests:
Assistant
All tests pass. Let me run a broader test suite:
Assistant
All 1477 tests in the install directory pass. Let me run the full unit test suite:
Assistant
Let me try without the timeout option.
Assistant
All 15812 tests pass. Now let me create a simple script to verify the fix works correctly:
Assistant
The test needs better mocking. But more importantly, all 15812 existing tests pass. Let me verify the final state of the code:
Assistant
The fix looks correct. Let me also check if there's a test that specifically tests the scenario from the issue, and if not, let me write a proper test:
Assistant
The grep result shows locked_dep.resolved_commit = None in the integrate orchestration test file. Let me look at those tests to understand the context:
Assistant
Let me look at those tests more closely:
Assistant
Let me verify the existing test still passes with my changes:
Assistant
Good, the existing test still passes. Let me run the full unit test suite one more time to confirm everything is working:
Assistant
All 15812 unit tests pass. Let me also run the integration tests:
Assistant
Let me check if this integration test was already failing before my change:
Assistant
Good - the test was already failing before my change. Let me restore my changes:
Assistant
The integration test failure was pre-existing and unrelated to my change. Let me verify the final state of my changes:
Assistant
Let me also check the apm.lock.yaml change:
Assistant
The apm.lock.yaml change is just from running pip install. Let me revert it:
Assistant
Good. Now let me verify the final state of my changes:
Assistant
Let me do one final verification that all unit tests pass:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
> apm install --update --force
[>] Installing dependencies from apm.yml...
[>] Resolving github-copilot-agent-skills-testing...
[i] Targets: copilot (source: apm.yml)
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/packages/<project> #default @d479f42e
|-- (files unchanged)
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/packages/myorg #default @d479f42e
|-- (files unchanged)
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md #main
|-- 1 instruction(s) integrated -> .github/instructions/
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/skills/run-coverage #default @d479f42e
|-- (files unchanged)
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/skills/update-from-template #default @d479f42e
|-- (files unchanged)
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/packages/csharp #default @d479f42e
|-- (files unchanged)
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/code-style.instructions.md #main
|-- 1 instruction(s) integrated -> .github/instructions/
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/protect-prefixed-agent-files.instructions.md
#main
|-- 1 instruction(s) integrated -> .github/instructions/
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/skills/git-conventions #default @d479f42e
|-- (files unchanged)
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/skills/update-nuget-packages #default @d479f42e
|-- (files unchanged)
Partial clone (--filter=blob:none) failed for https://dev.azure.com/<org>/tools; retrying with full bare clone. Server may not
support filter v2.
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/skills/write-tests #default @d479f42e
|-- (files unchanged)
cache-pin: remote dep '<org>/tools/github-copilot-agent-skills' has no resolved_commit; drift cannot verify its cache freshness.
Re-run 'apm install' with a pinned ref (commit, tag, or specific branch HEAD).
cache-pin: remote dep '<org>/tools/github-copilot-agent-skills' has no resolved_commit; drift cannot verify its cache freshness.
Re-run 'apm install' with a pinned ref (commit, tag, or specific branch HEAD).
cache-pin: remote dep '<org>/tools/github-copilot-agent-skills' has no resolved_commit; drift cannot verify its cache freshness.
Re-run 'apm install' with a pinned ref (commit, tag, or specific branch HEAD).
[i] Trusting direct dependency MCP 'MyOrg.CLI' from '<project>-skills'
[i] Trusting direct dependency MCP 'NuGet' from '<project>-skills'
[i] Trusting direct dependency MCP 'Github' from '<project>-skills'
[i] Trusting direct dependency MCP 'MyOrg.CLI' from 'skills'
[i] Trusting direct dependency MCP 'NuGet' from 'skills'
+- MCP Servers (3)
| [+] MyOrg.CLI (already configured)
| [+] NuGet (already configured)
| [+] Github (already configured)
[*] All servers up to date
[!] 11 dependencies unpinned: <org>/tools/github-copilot-agent-skills -- add #tag or #sha to prevent drift
[!] Transitive package 'csharp-skills' declares self-defined MCP server 'NuGet' (registry: false). Re-declare it in your apm.yml or
use --trust-transitive-mcp.
[!] Transitive package 'csharp-skills' declares self-defined MCP server 'Github' (registry: false). Re-declare it in your apm.yml
or use --trust-transitive-mcp.
[*] Installed 11 APM dependencies in 87.9s.
> apm install
[>] Installing dependencies from apm.yml...
[i] Targets: copilot (source: apm.yml)
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/packages/<project> @d479f42e (cached)
|-- (files unchanged)
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/packages/myorg @d479f42e (cached)
|-- (files unchanged)
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md #main
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8. The downloaded content differs from the lockfile record.
This may indicate a supply-chain attack. Use 'apm install --update' to accept new content and update the lockfile.
[!] Install interrupted after 7.7s.
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /apm, current file: none) bash-$
Let me understand the issue better. The error is about a "Content hash mismatch" when running apm install the second time. Let me look at the lockfile and the relevant code more closely.
The key insight is:
First apm install works fine
Second apm install fails with content hash mismatch for files that are resolved via #main branch reference
The issue is that these dependencies use #main (branch reference), which means they're not pinned. On first install, they get downloaded and the hash is recorded. On second install, they're re-downloaded from the #main branch, but the content might be different because the branch moved forward.
Wait, but looking at the error more carefully - the file changed between the two installs because the branch moved forward. That's expected behavior - the lockfile should have recorded the content hash, and if the content changes, it should detect that.
But the user's report says "the second time I run apm install it will fail consistently with Content hash mismatch." This suggests the hash is changing even though the content hasn't changed.
Let me look more closely at how the hash is computed. The compute_package_hash function hashes file paths AND file contents. If the install path is a directory (not a single file), then the hash should be deterministic.
Wait, I see the issue! Look at lines 747-753:
python
if install_path.is_dir():
ctx.package_hashes[dep_key] = _compute_hash(install_path)
The hash is only computed when install_path.is_dir(). But for files like .apm/instructions/testing.instructions.md, install_path is a file, not a directory. So ctx.package_hashes[dep_key] is never set.
Then later at line 773:
python
and dep_key in ctx.package_hashes
This check would be False for single-file dependencies, so the content hash check would be skipped. That seems correct.
But wait, maybe the issue is different. Let me re-read the error more carefully.
The error message says:
code
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8
This is coming from line 777-785 of sources.py. So dep_key in ctx.package_hashes is True, meaning the hash was computed. That means install_path.is_dir() is True for this dependency. But the path is .apm/instructions/testing.instructions.md - that's a file path, not a directory.
Hmm, maybe the install path doesn't include the file extension? Let me look at how install_path is determined for these dependencies.
Actually wait, let me re-read the log output. The dependency is:
code
dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md```
But the target is a branch ref `#main`. This means it's fetching a single file from a repo at a specific path. The install path might actually be a directory.
Let me look at the install directory structure and understand how these dependencies are fetched.
Actually, I think the real issue might be related to `.apm-pin` marker. Look at the `content_hash.py`:
```python
# Files at the package root excluded from hashing. ``.apm-pin`` is the
# cache-pin marker (see :mod:`apm_cli.install.cache_pin`) written AFTER
# hash recording during install; including it would make the on-disk
# hash diverge from the lockfile-recorded hash on every subsequent
# install, falsely tripping the supply-chain content-hash mismatch
# check. Scoped to root paths only so a package cannot slip a
# ``subdir/.apm-pin`` past the integrity hash.
_EXCLUDED_ROOT_FILES = {_APM_PIN_MARKER}
The .apm-pin marker is written AFTER hash recording during install. But wait, it says it was already excluded from hashing.
Let me look at the cache-pin module to understand this better.
Let me understand the issue better. Let me look at the code flow more carefully for the second apm install case.
The issue is:
First install works fine with --update --force
Second apm install fails with "Content hash mismatch"
The error comes from FreshDependencySource.acquire() at line 777:
python
if (
not ctx.update_refs
and dep_key not in _expected_hash_deps
and dep_locked_chk
and dep_locked_chk.content_hash
and dep_key in ctx.package_hashes
):
_fresh_hash = ctx.package_hashes[dep_key]
if _fresh_hash != dep_locked_chk.content_hash:
...
So the error occurs when:
Not in update mode
The dep is not in expected_hash_change_deps
There's a locked dependency with a content_hash
The fresh hash doesn't match the locked content hash
The key question is: why does the fresh hash differ from the lockfile hash?
Looking at the second install output:
code
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md #main
Content hash mismatch for ...
This is showing it's downloading fresh (not cached). So the dep is being downloaded fresh, but the content hash doesn't match what was recorded in the lockfile.
Let me look at the _resolve_download_strategy to understand when a fresh download happens.
For the #main branch ref, is_cacheable = False (branches are not cacheable). So skip_download will be False unless lockfile_match is True.
Now, the issue might be that:
First install: downloads the virtual file package, computes hash, stores in lockfile
Second install: the virtual file is already on disk, but...
Wait, for virtual file deps, the _resolve_download_strategy checks if install_path.exists() and whether the lockfile SHA matches the local HEAD. For virtual files, there's no .git directory, so it falls back to content hash verification via _should_skip_redownload.
But _should_skip_redownload requires install_path.is_dir(). The virtual file package installs to a directory (it creates .apm/instructions/testing.instructions.md inside the target_path directory). So install_path.is_dir() should be True.
Hmm, let me look more carefully at the flow. The _resolve_download_strategy in integrate.py determines whether to skip download. For virtual file deps with #main:
is_cacheable = False (branch ref)
lockfile_match check:
For non-git dep (virtual file), the git check fails, falls back to _should_skip_redownload
_should_skip_redownload checks install_path.is_dir() and verify_package_hash
If the content hash matches, lockfile_match = True
But wait, looking at the code again:
python
elif not ref_changed:
# Normal mode: compare local HEAD with lockfile SHA.
try:
from git import Repo as GitRepo local_repo = GitRepo(install_path)
if local_repo.head.commit.hexsha == locked_dep.resolved_commit:
lockfile_match = True
except Exception:
# Git check failed (e.g. .git removed, or virtual package
# install_path is not a git repo). Fall back to
# content-hash verification (#763).
if _should_skip_redownload(locked_dep, install_path):
lockfile_match = True
lockfile_match_via_content_hash_only = True
So for virtual file deps:
ref_changed is False (same #main ref)
GitRepo(install_path) will fail (no .git)
Falls back to _should_skip_redownload
This checks locked_dep.content_hash and verify_package_hash(install_path, locked_dep.content_hash)
If the hash matches, lockfile_match = True, and skip_download = True. This means the cached source is used, not the fresh source.
But the error shows it's a fresh download (not cached). So either:
The content hash verification failed (causing lockfile_match = False)
Or resolved_ref resolved to a different SHA than the lockfile's resolved_commit
Wait, for #main ref:
python
is_cacheable = resolved_ref and resolved_ref.ref_type in [
GitReferenceType.TAG,
GitReferenceType.COMMIT,
]
Since #main is a branch, is_cacheable = False. So even if lockfile_match = True, the download might still happen.
Actually, let me re-read the skip_download logic:
python
skip_download = install_path.exists() and (
(is_cacheable and not update_refs)
or (already_resolved and not update_refs)
or lockfile_match
)
So lockfile_match = True would make skip_download = True. But then there's the self-heal chain:
def applies(self, hctx: HealContext) -> bool:
from apm_cli.models.apm_package import GitReferenceType
if not hctx.lockfile_match or hctx.update_refs:
return False
if hctx.resolved_ref is None:
return False
if hctx.resolved_ref.ref_type != GitReferenceType.BRANCH:
return False
# Guard against non-git resolution paths (e.g. Artifactory proxy
# may return a ResolvedReference whose resolved_commit is None or
# the "cached" sentinel). Without this guard a None comparison
# below would mis-classify drift, and execute() would crash on
# `resolved_commit[:8]`.
remote_sha = hctx.resolved_ref.resolved_commit
if remote_sha in (None, "", "cached"):
return False
if hctx.existing_lockfile is None:
return False
locked = hctx.existing_lockfile.get_dependency(hctx.package_key)
if locked is None:
return False
if locked.resolved_commit in (None, "", "cached"):
return False
return remote_sha != locked.resolved_commit
remote_sha = resolved_ref.resolved_commit (the current HEAD of main)
If remote_sha is not None, "", or "cached" (it would be a commit SHA)
locked.resolved_commit must not be None, "", or "cached"
If the locked.resolved_commit is the same SHA as the remote (because the branch hasn't moved), then remote_sha != locked.resolved_commit is False, so the heal doesn't apply. That's correct.
But if the locked.resolved_commit is None (which could happen for virtual file packages that didn't get a SHA resolved), then locked.resolved_commit in (None, "", "cached") is True, so the heal returns False.
Wait, but looking at the first install, the resolved_commit for virtual file packages... Let me check the download_virtual_file_package method again:
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md #main
Content hash mismatch for ...
The [+] at the beginning means it's being downloaded fresh. Let me look at why.
Actually wait - the issue is that on the second apm install, the file is being re-downloaded even though the content hasn't changed. The hash of the freshly downloaded content doesn't match the lockfile hash.But looking at _resolve_download_strategy:
But wait, the error says it's a fresh download (not cached). Let me look at the download strategy again...
Actually, let me re-read the _resolve_download_strategy more carefully. The key thing is:
python
skip_download = install_path.exists() and (
(is_cacheable and not update_refs)
or (already_resolved and not update_refs)
or lockfile_match
)
If lockfile_match = True, then skip_download = True, and it should use CachedDependencySource.
But then there's the content integrity check:
python
if skip_download and _dep_locked_chk and _dep_locked_chk.content_hash:
from apm_cli.utils.content_hash import verify_package_hash
if not verify_package_hash(install_path, _dep_locked_chk.content_hash):
_hash_msg = f"Content hash mismatch for {dep_ref.get_unique_key()} -- re-downloading"
...
safe_rmtree(install_path, ctx.apm_modules_dir)
skip_download = False
Wait! This check happens AFTER skip_download is set. If skip_download = True and the content hash doesn't match, it deletes the install_path and sets skip_download = False, forcing a re-download.
But then after the re-download, in FreshDependencySource.acquire(), it checks the hash again:
python
if install_path.is_dir():
ctx.package_hashes[dep_key] = _compute_hash(install_path)
# Supply-chain protection: verify content hash on fresh downloads
if (
not ctx.update_refs
and dep_key not in _expected_hash_deps
and dep_locked_chk
and dep_locked_chk.content_hash
and dep_key in ctx.package_hashes
):
_fresh_hash = ctx.package_hashes[dep_key]
if _fresh_hash != dep_locked_chk.content_hash:
...error...
So the question is: WHY does the freshly downloaded content have a different hash than the lockfile?
One possibility: the download_virtual_file_package method generates a synthetic apm.yml inside the target_path. If this generated content is different between the first and second install (e.g., because the description parsing is different), the hash would differ.
Let me look at download_virtual_file_package again:
python
# Create target directory structure
target_path.mkdir(parents=True, exist_ok=True)
# Determine the subdirectory based on file extension
subdirs = {
".prompt.md": "prompts",
".instructions.md": "instructions",
".chatmode.md": "chatmodes",
".agent.md": "agents",
}
subdir = None
filename = dep_ref.virtual_path.split("/")[-1]
for ext, dir_name in subdirs.items():
if dep_ref.virtual_path.endswith(ext):
subdir = dir_name
break
if not subdir:
raise ValueError(f"Unknown file extension for {dep_ref.virtual_path}")
# Create .apm structure
apm_dir = target_path / ".apm" / subdir
apm_dir.mkdir(parents=True, exist_ok=True)
# Write the file
file_path = apm_dir / filename
file_path.write_bytes(file_content)
# Generate minimal apm.yml
package_name = dep_ref.get_virtual_package_name()
description = f"Virtual package containing {filename}"
...
apm_yml_content = yaml_to_str(apm_yml_data)
apm_yml_path = target_path / "apm.yml"
apm_yml_path.write_text(apm_yml_content, encoding="utf-8")
The hash is computed over this structure. If the content of testing.instructions.md changes on the remote between installs, the hash would differ. But the issue says it happens consistently on the second install, not just when the content changes.
Wait, let me re-read the issue more carefully. The user says "the second time I run apm install it will fail consistently". This suggests the hash is always different on the second install.
Let me think about what could cause the hash to always differ...
Looking at the _resolve_download_strategy content integrity check:
python
if skip_download and _dep_locked_chk and _dep_locked_chk.content_hash:
from apm_cli.utils.content_hash import verify_package_hash
if not verify_package_hash(install_path, _dep_locked_chk.content_hash):
_hash_msg = f"Content hash mismatch for {dep_ref.get_unique_key()} -- re-downloading"
This is a DIFFERENT error message than what's in the issue! The issue says:
code
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8. The downloaded content differs from the lockfile record.
This error message is from the FreshDependencySource.acquire() method (line 777), not from the _resolve_download_strategy content integrity check (line 197).
So the flow is:
skip_download = False (either because lockfile_match = False or because content integrity check failed)
FreshDependencySource is used to download
After download, the hash is computed
The hash doesn't match the lockfile hash → error
The question remains: why does the freshly downloaded content have a different hash?
Wait, I think I see the issue now! Let me look at the download_virtual_file_package more carefully:
This doesn't clear the directory! So if there's already content from a previous install, it stays. But wait, the _resolve_download_strategy content integrity check does safe_rmtree(install_path, ctx.apm_modules_dir) if the hash doesn't match.
Actually, let me trace through the full flow for the second install:
_resolve_download_strategy is called
resolved_ref = resolve_git_reference(dep_ref) - resolves #main to a commit SHA
is_cacheable = False (branch)
lockfile_match check:
locked_dep exists (from first install)
locked_dep.resolved_commit might be None for virtual file deps
If locked_dep.resolved_commit is None, the condition locked_dep.resolved_commit and locked_dep.resolved_commit != "cached" is False
So the git check and content hash fallback don't run
lockfile_match = False
Wait, that's important! If locked_dep.resolved_commit is None, then lockfile_match stays False, and skip_download is False.
Actually no, let me re-read the code:
python
if install_path.exists() and existing_lockfile:
locked_dep = existing_lockfile.get_dependency(dep_ref.get_unique_key())
if locked_dep and locked_dep.resolved_commit and locked_dep.resolved_commit != "cached":
...
So if locked_dep.resolved_commit is None, this entire block is skipped. Then lockfile_match stays False.
Then skip_download = install_path.exists() and ( ... or lockfile_match). Since lockfile_match = False, skip_download depends on the other conditions.
For #main branch, is_cacheable = False, so skip_download = False.
So it downloads fresh. Then the FreshDependencySource checks:
python
if install_path.is_dir():
ctx.package_hashes[dep_key] = _compute_hash(install_path)
# Supply-chain protection
if (
not ctx.update_refs
and dep_key not in _expected_hash_deps
and dep_locked_chk
and dep_locked_chk.content_hash
and dep_key in ctx.package_hashes
):
_fresh_hash = ctx.package_hashes[dep_key]
if _fresh_hash != dep_locked_chk.content_hash:
Wait, but dep_locked_chk.content_hash - does the lockfile have a content_hash for this dep? Let me check.
The lockfile builder calls _attach_content_hashes:
python
def _attach_content_hashes(self, lockfile: LockFile) -> None:
for dep_key, locked_dep in lockfile.dependencies.items():
if dep_key in self.ctx.package_hashes:
locked_dep.content_hash = self.ctx.package_hashes[dep_key]
So on the first install, the content hash is stored in the lockfile. On the second install, dep_locked_chk.content_hash would be set.
Now the question is: why is ctx.package_hashes[dep_key] (freshly computed) different from dep_locked_chk.content_hash (from lockfile)?
For virtual file deps, the content is downloaded fresh each time. If the file content on the remote hasn't changed, the hash should be the same.
But wait, looking at download_virtual_file_package, it generates a synthetic apm.yml:
This should be deterministic if the input is the same.
Hmm, but the description is parsed from the file's frontmatter. If the file content changes, the description changes. But that would only happen if the file content actually changes.
Wait, I think I need to look at this from a different angle. Let me check what happens with the .apm-pin marker.
Looking at _sync_cache_pin_markers in lockfile.py, it writes .apm-pin to the install_path. But _compute_hash excludes .apm-pin via _EXCLUDED_ROOT_FILES.
Actually wait, .apm-pin is only excluded at the root level:
python
if len(rel.parts) == 1 and rel.name in _EXCLUDED_ROOT_FILES:
continue
For virtual file deps, the .apm-pin would be at the root of target_path, so it should be excluded.
But wait, the _sync_cache_pin_markers is called AFTER the hash is computed in the lockfile builder. So on the first install:
Download package → compute hash → store in ctx.package_hashes
Lockfile builder calls _attach_content_hashes → writes hash to lockfile
Lockfile builder calls _sync_cache_pin_markers → writes .apm-pin to install_path
On the second install:
The install_path has .apm-pin from step 3 above
Download package → compute hash → .apm-pin is excluded → hash should be same3. Compare hash with lockfile hashThis should work. So the issue must be something else.
Let me look at the actual download flow for virtual file deps more carefully. When skip_download = False and FreshDependencySource is used:
So the content should be the same as long as the remote content hasn't changed.
Wait, but the error says the hash is different! Let me look at the actual error more carefully:
code
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8
The expected hash is from the lockfile, and the got hash is from the fresh download. They're different.
One thing I notice: the error message says "expected ... got ..." and then "The downloaded content differs from the lockfile record."
Hmm, wait. Looking at the flow again:
First install: downloads virtual file, computes hash H1, stores in lockfile
Second install:
_resolve_download_strategy determines skip_download = False (because locked_dep.resolved_commit is None for virtual file deps with #main ref)
FreshDependencySource downloads fresh
download_virtual_file_package writes the file and apm.yml to target_path
_compute_hash(target_path) computes hash H2
H2 != H1 → error
But why would H2 != H1 if the content hasn't changed? Unless the content HAS changed (the #main branch was updated).
Actually, looking at the issue again, the user says:
I can install my repo (see apm.yml further down) via apm install <org>/<repo>/package/<project> just fine (kinda, see the logs, it looks wonky but maybe it's just a new feature) but the second time I run apm install it will fail consistently with Content hash mismatch.
But on the second install, there's ALREADY content in target_path from the first install, including potentially the .apm-pin marker.
When download_virtual_file_package is called again, it does:
python
target_path.mkdir(parents=True, exist_ok=True)
But it doesn't clear the directory. So there might be leftover files. But the file and apm.yml are overwritten, so the content should be the same.
Unless... the .apm-pin marker is being excluded from the hash computation but its presence is affecting something else?
Wait, let me re-check the hash computation. The _EXCLUDED_ROOT_FILES only excludes files at the root of the package. For virtual file deps, the structure is:
So .apm-pin is excluded. The hash should be the same.
Hmm, let me think about this differently. Maybe the issue is that the resolved_commit for virtual file deps is None in the lockfile. Let me check the FreshDependencySource.acquire() code:
python
resolved_commit = None
if resolved:
resolved_commit = package_info.resolved_reference.resolved_commit
node = ctx.dependency_graph.dependency_tree.get_node(dep_key)
depth = node.depth if node else 1
resolved_by = node.parent.dependency_ref.repo_url if node and node.parent else None
So resolved_commit might be None for virtual file deps (if _resolve_commit_sha_for_ref returns None).
So resolved_commit is stored as None in the InstalledPackage. When the lockfile is built from InstalledPackages, the locked_dep.resolved_commit would be None.
On the second install:
python
if locked_dep and locked_dep.resolved_commit and locked_dep.resolved_commit != "cached":
...
Since locked_dep.resolved_commit is None, this condition is False, so the git check and content hash fallback don't run. lockfile_match stays False.
Then skip_download = False (since lockfile_match = False and is_cacheable = False).
So it downloads fresh. But why would the hash differ?
Wait, I think I need to look at this more carefully. On the FIRST install:
FreshDependencySource downloads the virtual file
_compute_hash(install_path) computes hash H1
ctx.package_hashes[dep_key] = H1
Lockfile stores H1 as content_hash
On the SECOND install:
FreshDependencySource downloads the virtual file again
_compute_hash(install_path) computes hash H2
H2 should equal H1 if the content is the same
But the error says H2 != H1
So either:
a) The content actually changed on the remote
b) Something in the download process produces different content
For case (b), the download_virtual_file_package method generates an apm.yml file. Let me check if this is deterministic...
Actually, I just realized something. Looking at the download_virtual_file_package:
python
target_path.mkdir(parents=True, exist_ok=True)
This doesn't clear the directory. But the FreshDependencySource doesn't call safe_rmtree before downloading! Let me check...
It just calls download_package which calls download_virtual_file_package. The download_virtual_file_package doesn't clear the directory.
But wait, looking at _resolve_download_strategy, there's a content integrity check:
python
if skip_download and _dep_locked_chk and _dep_locked_chk.content_hash:
...
if not verify_package_hash(install_path, _dep_locked_chk.content_hash):
...
safe_rmtree(install_path, ctx.apm_modules_dir)
skip_download = False
But this only runs when skip_download = True. For virtual file deps with resolved_commit = None, skip_download = False, so this check doesn't run.
OK so the flow is:
Second install: skip_download = False because locked_dep.resolved_commit is None
FreshDependencySource downloads the file (doesn't clear directory first)
The file content might be the same, but the directory structure might have extra files (like .apm-pin)
But .apm-pin is excluded from the hash, so it shouldn't matter.
Hmm, wait. Let me re-read the error message once more:
These are different hashes. If the content is truly the same, the hashes would be the same. So either:
The content changed on the remote (the #main branch was updated between the two installs)
There's something else in the directory that's affecting the hash
Actually, I just realized something important. On the FIRST install:
Download package → write files to target_path
Compute hash H1 of target_path
Integrate primitives (e.g., copy instruction to .github/instructions/)
Lockfile builder writes hash H1 to lockfile
Lockfile builder writes .apm-pin to target_path
On the SECOND install:
.apm-pin exists in target_path
Download package → write files to target_path (doesn't clear directory)
Compute hash H2 of target_path
H2 should equal H1 (since .apm-pin is excluded)
But wait, what if there are other files in target_path that weren't there during the first install?
Actually, I think the issue might be simpler. Let me re-read the error:
code
[+] dev.azure.com/<org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md #main
Content hash mismatch for <org>/tools/github-copilot-agent-skills/.apm/instructions/testing.instructions.md: expected
sha256:2227579674ab30b5b59f703ac152fa74ac2912d724d04aeffbf3914cac2e6b88, got
sha256:b82d09e4e7879eeb0e90cc7dfeebdac45de6ebdbcdda7824b40438196692f8f8. The downloaded content differs from the lockfile record.
This may indicate a supply-chain attack. Use 'apm install --update' to accept new content and update the lockfile.
The expected hash is from the lockfile (recorded during first install). The got hash is from the fresh download. They're different.
I think the most likely explanation is that the #main branch has moved between the two installs. The first install downloads at commit A, records hash H1. The second install downloads at commit B (new commit on main), gets hash H2.
But the user says it fails "consistently" on the second install. If the branch moved, you'd expect it to sometimes work (if no new commits) and sometimes fail (if new commits).
Unless... the BranchRefDriftHeal is supposed to handle this case, but it's not working for virtual file deps because locked_dep.resolved_commit is None.
Let me trace through the heal chain for the second install:
lockfile_match check: For virtual file deps with resolved_commit = None:
The condition locked_dep and locked_dep.resolved_commit and locked_dep.resolved_commit != "cached" is False
So lockfile_match stays False
skip_download = install_path.exists() and ( ... or lockfile_match) = False
BranchRefDriftHeal.applies():
not hctx.lockfile_match → True (since lockfile_match is False)
Returns False immediately
So the heal doesn't apply because lockfile_match is False.
The issue is that for virtual file deps (and any deps where resolved_commit is None in the lockfile), the content-hash fallback in _resolve_download_strategy doesn't run, so lockfile_match stays False, and the dep is always re-downloaded. And since the content may have changed (branch moved), the supply-chain check fails.
But wait, this would only happen if the branch actually moved. If the branch hasn't moved, the hash should be the same.
Unless... there's something about the download_virtual_file_package that produces non-deterministic output?
With sort_keys=False, the order of keys might not be deterministic. But YAML dict ordering in Python 3.7+ is insertion order, so it should be deterministic if the input is the same.
Hmm, but the description is parsed from the file's frontmatter. If the frontmatter is different... no, the file content is the same.
Wait, I think I need to look at this from a completely different angle. Let me check if there's a resolved_commit being stored for virtual file deps at all.