The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bundle): record tool digests after signing transforms
ethernet5eec230f4855
diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.mdindex d990bf7eabc..3d2b3b249fc 100644--- a/apps/desktop/BUILDING.md+++ b/apps/desktop/BUILDING.md@@ -60,6 +60,13 @@ Staging does not prove native startup or package replacement. Those checksuse the [bundled-update acceptance suite](../../tests/install/BUNDLED_UPDATES.md).Acceptance requires a native run with the actual signed release artifacts.+Packaged tool facts describe the final bytes, not only the staged archives.+Windows refreshes the tool digests after sanitization and batch signing.+The macOS custom signer retains the builder's entitlements and file selection.+It refreshes digests after child signatures and before the outer app signature.+Unsigned macOS builds refresh them at the end of `afterPack`.+Do not refresh facts in `afterSign`: that changes resources covered by the signature.+## Complete native buildFrom a checkout whose `HEAD` equals the release tag, run:diff --git a/apps/desktop/electron-builder.config.cjs b/apps/desktop/electron-builder.config.cjsindex d473568e707..67aaabf30ea 100644--- a/apps/desktop/electron-builder.config.cjs+++ b/apps/desktop/electron-builder.config.cjs@@ -11,7 +11,9 @@'use strict'const fs = require('node:fs')+const path = require('node:path')const feedContract = require('./update-feed.cjs')+const { createMacSigner } = require('./scripts/mac-sign.mjs')const {light,@@ -145,9 +147,9 @@ module.exports = {NSAppleMusicUsageDescription: `${displayName} accesses your music library when a plugin or feature you enable requests it.`},target: ['dmg', 'zip'],- sign: {- entitlements: 'electron/entitlements.mac.plist',- entitlementsInherit: 'electron/entitlements.mac.inherit.plist',+ sign: createMacSigner({+ entitlements: path.join(__dirname, 'electron/entitlements.mac.plist'),+ entitlementsInherit: path.join(__dirname, 'electron/entitlements.mac.inherit.plist'),hardenedRuntime: true,ignore: (/** @type {string} */ file) => {try {@@ -159,7 +161,7 @@ module.exports = {return true}}- }+ })},dmg: {title: `Install ${displayName}`,diff --git a/apps/desktop/scripts/after-pack-digests.test.mjs b/apps/desktop/scripts/after-pack-digests.test.mjsnew file mode 100644index 00000000000..7116164286e--- /dev/null+++ b/apps/desktop/scripts/after-pack-digests.test.mjs@@ -0,0 +1,89 @@+import assert from 'node:assert/strict'+import { execFileSync, spawnSync } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { pathToFileURL } from 'node:url'++import { test } from 'vitest'++const repo = path.resolve(import.meta.dirname, '../../..')+const hook = pathToFileURL(path.join(import.meta.dirname, 'after-pack.mjs')).href+const python = process.env.HERMES_PYTHON || process.env.UV_PYTHON || 'python'++function fixture() {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'after-pack-digests-'))+ const payload = path.join(directory, 'resources', 'agent-payload')+ const binary = path.join(payload, 'tools', 'uv', 'uv.exe')+ fs.mkdirSync(path.dirname(binary), { recursive: true })+ // A truncated PE certificate table is a sanitizer input, not an executable.+ const pe = Buffer.alloc(392)+ pe.write('MZ')+ pe.writeUInt32LE(128, 0x3c)+ pe.writeUInt32LE(0x4550, 128)+ pe.writeUInt16LE(240, 148)+ pe.writeUInt16LE(0x20b, 152)+ pe.writeUInt32LE(16, 260)+ pe.writeUInt32LE(pe.length, 296)+ pe.writeUInt32LE(24, 300)+ fs.writeFileSync(binary, pe)+ const env = { ...process.env, HERMES_HOME: path.join(directory, 'home'),+ HERMES_RUNTIME_DIR: path.join(directory, 'runtime'),+ UV_PYTHON: python, UV_PYTHON_DOWNLOADS: 'never', UV_OFFLINE: '1',+ UV_CACHE_DIR: path.join(directory, 'uv-cache') }+ for (const key of Object.keys(env)) {+ if (key.startsWith('AZURE_SIGN_')) delete env[key]+ }+ delete env.PYTHONHOME+ delete env.PYTHONPATH+ execFileSync(python, ['-c',+ 'from pathlib import Path; import sys; from scripts.bundles.payload import record_tools, write_manifest; from pm.store import current_target; root=Path(sys.argv[1]); write_manifest(root,target=current_target(),repo="repo"); record_tools(root,Path("pm/lock.json"),current_target(),{"uv":"uv"})',+ payload], { cwd: repo, env, encoding: 'utf8' })+ const facts = path.join(payload, 'tools', 'facts.json')+ const before = JSON.parse(fs.readFileSync(facts, 'utf8'))+ const context = { electronPlatformName: process.platform, appOutDir: directory,+ packager: { appInfo: { productFilename: 'Hermes' }, config: {}, buildResourcesDir: directory } }+ const run = () => spawnSync(process.execPath, ['--input-type=module', '-e',+ `import afterPack from ${JSON.stringify(hook)}; await afterPack(${JSON.stringify(context)})`,+ 'after-pack-test'], { cwd: directory, env, encoding: 'utf8', timeout: 60000 })+ return { directory, payload, binary, facts, before, run, env }+}++test.runIf(process.platform === 'win32')('afterPack records actual sanitized payload bytes', () => {+ const f = fixture()+ try {+ const result = f.run()+ assert.equal(result.status, 0, result.stdout + result.stderr)+ const finalBytes = fs.readFileSync(f.binary)+ assert.equal(finalBytes.readUInt32LE(296), 0)+ assert.equal(finalBytes.readUInt32LE(300), 0)+ const digest = execFileSync(python, ['-c',+ 'from pathlib import Path; import sys; from pm.store import tree_digest; print(tree_digest(Path(sys.argv[1])))',+ path.dirname(f.binary)], { cwd: repo, env: f.env, encoding: 'utf8' }).trim()+ const after = JSON.parse(fs.readFileSync(f.facts, 'utf8'))+ assert.notEqual(digest, f.before.packages.uv.digest)+ assert.deepEqual(after.packages.uv, { ...f.before.packages.uv, digest })+ } finally {+ fs.rmSync(f.directory, { recursive: true, force: true })+ }+})++test.runIf(process.platform === 'win32')('afterPack refuses missing or corrupt facts only for a present payload', () => {+ const f = fixture()+ try {+ for (const contents of ['not-json', null]) {+ if (contents === null) fs.unlinkSync(f.facts)+ else fs.writeFileSync(f.facts, contents)+ const result = f.run()+ assert.notEqual(result.status, 0, result.stdout + result.stderr)+ if (contents !== null) assert.equal(fs.readFileSync(f.facts, 'utf8'), contents)+ else assert.equal(fs.existsSync(f.facts), false)+ }+ fs.unlinkSync(path.join(f.payload, 'manifest.json'))+ const light = f.run()+ assert.equal(light.status, 0, light.stdout + light.stderr)+ assert.equal(fs.existsSync(f.facts), false)+ } finally {+ fs.rmSync(f.directory, { recursive: true, force: true })+ }+})diff --git a/apps/desktop/scripts/after-pack.mjs b/apps/desktop/scripts/after-pack.mjsindex 423e6eae8f2..86f3ab667ff 100644--- a/apps/desktop/scripts/after-pack.mjs+++ b/apps/desktop/scripts/after-pack.mjs@@ -24,6 +24,7 @@ import fs from 'node:fs'import { execFileSync } from 'node:child_process'import { batchSignAppTree } from './batch-sign-binaries.mjs'+import { rehashPayloadDigests } from './payload-digests.mjs'import { resolveSigningIdentity, signNestedChromium } from './sign-nested-chromium.mjs'import { sanitizeTree } from './sanitize-pe-signatures.mjs'import { stampExeIdentity } from './set-exe-identity.mjs'@@ -47,6 +48,9 @@ export default async function afterPack(context) {`[after-pack] repaired ${nested.repaired} framework links; signed ${nested.signed} nested chromium targets` +(identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)'))+ // The macOS signer refreshes this again before sealing the outer app.+ // Unsigned builds end here and still need final-byte facts.+ rehashPayloadDigests(payload)}return}@@ -90,4 +94,5 @@ export default async function afterPack(context) {config: context.packager.config,resourcesDir: context.packager.buildResourcesDir,})+ rehashPayloadDigests(payload)}diff --git a/apps/desktop/scripts/mac-sign.mjs b/apps/desktop/scripts/mac-sign.mjsnew file mode 100644index 00000000000..9ec198196df--- /dev/null+++ b/apps/desktop/scripts/mac-sign.mjs@@ -0,0 +1,28 @@+import path from 'node:path'++import { rehashPayloadDigests } from './payload-digests.mjs'++/**+ * @param {Pick<import('app-builder-lib').ElectronSignOptions, 'entitlements' | 'entitlementsInherit' | 'hardenedRuntime'> & { ignore: (file: string) => boolean }} policy+ * @returns {(opts: import('@electron/osx-sign').SignOptions, packager: import('app-builder-lib').MacPackager) => Promise<void>}+ */+export function createMacSigner(policy) {+ return async (opts, packager) => {+ const target = opts.platform === 'mas' ? (opts.type === 'development' ? 'mas-dev' : 'mas') : 'mac'+ const optionsForFile = await packager.helper.getOptionsForFile(opts.app, target, policy)+ const inheritedIgnore = opts.ignore+ const { sign } = await import('@electron/osx-sign')+ await sign({+ ...opts,+ ignore: file => (typeof inheritedIgnore === 'function' && inheritedIgnore(file)) || policy.ignore(file),+ // Batching defers child signatures until after all option callbacks.+ batchCodesignCalls: false,+ optionsForFile: file => {+ if (file === opts.app) {+ rehashPayloadDigests(path.join(opts.app, 'Contents', 'Resources', 'agent-payload'))+ }+ return optionsForFile(file)+ }+ })+ }+}diff --git a/apps/desktop/scripts/mac-sign.test.mjs b/apps/desktop/scripts/mac-sign.test.mjsnew file mode 100644index 00000000000..49c19191daa--- /dev/null+++ b/apps/desktop/scripts/mac-sign.test.mjs@@ -0,0 +1,158 @@+import assert from 'node:assert/strict'+import childProcess from 'node:child_process'+import fs from 'node:fs'+import { createRequire } from 'node:module'+import os from 'node:os'+import path from 'node:path'++import { Arch, MacPackager } from 'app-builder-lib'+import { MacTargetHelper } from 'app-builder-lib/internal'+import { test, vi } from 'vitest'++const require = createRequire(import.meta.url)+const config = require('../electron-builder.config.cjs')+const repo = path.resolve(import.meta.dirname, '../../..')+const desktop = path.resolve(import.meta.dirname, '..')+const python = process.env.HERMES_PYTHON || process.env.UV_PYTHON || 'python'++function fixture() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mac-digest-order-'))+ const app = path.join(root, 'Hermes.app')+ const payload = path.join(app, 'Contents', 'Resources', 'agent-payload')+ const tools = path.join(payload, 'tools')+ const nested = path.join(tools, 'chromium', 'Browser.app')+ const binaries = [path.join(app, 'Contents', 'MacOS', 'Hermes'),+ path.join(tools, 'python', 'bin', 'python3'),+ path.join(nested, 'Contents', 'MacOS', 'Browser')]+ for (const binary of binaries) {+ fs.mkdirSync(path.dirname(binary), { recursive: true })+ const bytes = Buffer.alloc(64)+ bytes.writeUInt32LE(0xfeedfacf)+ bytes.writeUInt32LE(0x100000c, 4)+ fs.writeFileSync(binary, bytes)+ }+ const ignored = path.join(tools, 'python', 'non-macho.bin')+ fs.writeFileSync(ignored, Buffer.alloc(64))+ const env = { ...process.env, HERMES_HOME: path.join(root, 'home'),+ HERMES_RUNTIME_DIR: path.join(root, 'state'), UV_PYTHON: python,+ UV_OFFLINE: '1', UV_PYTHON_DOWNLOADS: 'never', UV_CACHE_DIR: path.join(root, 'cache') }+ delete env.PYTHONHOME+ delete env.PYTHONPATH+ const py = code => childProcess.execFileSync(python, ['-c', code, payload], {+ cwd: repo, env, encoding: 'utf8', timeout: 60000+ }).trim()+ py('from pathlib import Path; import sys; from scripts.bundles.payload import record_tools,write_manifest; from pm.store import current_target; root=Path(sys.argv[1]); write_manifest(root,target=current_target(),repo="repo"); record_tools(root,Path("pm/lock.json"),current_target(),{"python":"python","chromium":"chromium"})')+ const facts = path.join(tools, 'facts.json')+ const initial = JSON.parse(fs.readFileSync(facts, 'utf8'))+ return { root, app, payload, tools, nested, binaries, ignored, env, py, facts, initial }+}++async function signThroughBuilder(f) {+ const packager = {+ config,+ appInfo: { type: 'module' },+ info: { getWorkspaceRoot: async () => repo },+ buildResourcesDir: path.join(desktop, 'build'),+ resourceList: Promise.resolve([]),+ getResource: async value => path.resolve(desktop, value),+ expandArch: value => [value]+ }+ packager.helper = new MacTargetHelper(packager)+ const identity = { name: 'Developer ID Application: Test Fixture (ABC123)' }+ const declared = typeof config.mac.sign === 'object' ? config.mac.sign : undefined+ const opts = await packager.helper.buildSignOptions(+ f.app, identity, declared, path.join(f.root, 'fixture.keychain-db'), Arch.arm64, 'mac')+ // This is the builder's real dispatch, not a test-only invocation of a factory.+ await MacPackager.prototype.doSign.call(packager, opts, config.mac.sign, identity)+}++function armEnvironment(f) {+ for (const name of ['HERMES_HOME', 'HERMES_RUNTIME_DIR', 'UV_PYTHON', 'UV_OFFLINE', 'UV_PYTHON_DOWNLOADS', 'UV_CACHE_DIR']) {+ vi.stubEnv(name, f.env[name])+ }+ vi.stubEnv('PYTHONHOME', undefined)+ vi.stubEnv('PYTHONPATH', undefined)+}++test('builder dispatch refreshes real facts after every payload signature and before the outer seal', async () => {+ const f = fixture()+ const signed = []+ const commands = []+ let outerFacts+ let digestsAtSeal+ armEnvironment(f)+ // Execute the installed walk and argument builders; intercept only native codesign.+ const native = vi.spyOn(childProcess, 'execFile').mockImplementation((file, args, options, callback) => {+ try {+ assert.equal(file, 'codesign', 'no other native signing or keychain command is permitted')+ if (args.includes('--sign')) {+ const target = args.at(-1)+ commands.push(args)+ if (target === f.app) {+ digestsAtSeal = JSON.parse(f.py('from pathlib import Path; import sys,json; from pm.store import tree_digest; root=Path(sys.argv[1]); print(json.dumps({name:tree_digest(root/"tools"/name) for name in ("python","chromium")}))'))+ outerFacts = JSON.parse(fs.readFileSync(f.facts, 'utf8'))+ } else if (fs.statSync(target).isDirectory()) {+ const signature = path.join(target, 'Contents', '_CodeSignature', 'CodeResources')+ fs.mkdirSync(path.dirname(signature), { recursive: true })+ fs.writeFileSync(signature, 'fixture byte mutation, not a native signature')+ } else {+ fs.appendFileSync(target, 'fixture byte mutation, not a native signature')+ }+ signed.push(target)+ }+ callback(null, '', '')+ } catch (error) {+ callback(error, '', '')+ }+ return undefined+ })+ try {+ await signThroughBuilder(f)+ assert.equal(signed.at(-1), f.app)+ assert.deepEqual(new Set(signed.slice(0, -1)), new Set([...f.binaries, f.nested]))+ assert.ok(!signed.includes(f.ignored))+ for (const args of commands) {+ assert.equal(args[args.indexOf('--sign') + 1], 'Developer ID Application: Test Fixture (ABC123)')+ assert.equal(args[args.indexOf('--keychain') + 1], path.join(f.root, 'fixture.keychain-db'))+ assert.equal(path.resolve(args[args.indexOf('--entitlements') + 1]),+ path.join(desktop, 'electron', args.at(-1) === f.app ? 'entitlements.mac.plist' : 'entitlements.mac.inherit.plist'))+ if (process.platform === 'darwin') assert.ok(args.includes('--options') && args[args.indexOf('--options') + 1].includes('runtime'))+ }+ for (const name of Object.keys(digestsAtSeal)) {+ assert.notEqual(digestsAtSeal[name], f.initial.packages[name].digest)+ assert.deepEqual(outerFacts.packages[name], { ...f.initial.packages[name], digest: digestsAtSeal[name] })+ }+ } finally {+ native.mockRestore()+ vi.unstubAllEnvs()+ fs.rmSync(f.root, { recursive: true, force: true })+ }+}, 30000)++test('builder dispatch refuses corrupt payload facts before the outer seal but signs a payload-free app', async () => {+ const f = fixture()+ const signed = []+ armEnvironment(f)+ fs.writeFileSync(f.facts, 'invalid-json')+ const native = vi.spyOn(childProcess, 'execFile').mockImplementation((file, args, options, callback) => {+ assert.equal(file, 'codesign')+ if (args.includes('--sign')) signed.push(args.at(-1))+ callback(null, '', '')+ return undefined+ })+ try {+ await assert.rejects(signThroughBuilder(f))+ assert.ok(signed.includes(f.binaries[1]))+ assert.ok(!signed.includes(f.app))+ assert.equal(fs.readFileSync(f.facts, 'utf8'), 'invalid-json')+ fs.rmSync(f.payload, { recursive: true })+ signed.length = 0+ await signThroughBuilder(f)+ assert.deepEqual(signed, [f.binaries[0], f.app])+ assert.ok(!fs.existsSync(f.payload))+ } finally {+ native.mockRestore()+ vi.unstubAllEnvs()+ fs.rmSync(f.root, { recursive: true, force: true })+ }+}, 30000)diff --git a/apps/desktop/scripts/payload-digests.mjs b/apps/desktop/scripts/payload-digests.mjsnew file mode 100644index 00000000000..6f90cb1e847--- /dev/null+++ b/apps/desktop/scripts/payload-digests.mjs@@ -0,0 +1,12 @@+import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'++/** @param {string} payload */+export function rehashPayloadDigests(payload) {+ // Light builds have no payload. Present payloads require valid tool facts.+ if (!fs.existsSync(path.join(payload, 'manifest.json'))) return+ execFileSync('uv', ['run', '--no-project', 'python',+ path.resolve(import.meta.dirname, '../../../scripts/bundles/payload.py'), 'rehash', payload],+ { stdio: 'inherit' })+}diff --git a/pm/lock.py b/pm/lock.pyindex cf8f8ba145e..f1c47c8f257 100644--- a/pm/lock.py+++ b/pm/lock.py@@ -21,6 +21,7 @@ any machine by substitution.from __future__ import annotationsimport json+import refrom pathlib import PathSCHEMA = 1@@ -121,6 +122,39 @@ class Facts:def get(self, name: str) -> dict | None:return self._packages.get(name)+ def refresh_digests(self, store_root: Path) -> int:+ """Publish all tool digests after packaging finishes changing their bytes."""+ from pm.store import tree_digest++ packages = _read(self.path, strict=True)["packages"]+ root = store_root.resolve()+ count = 0+ for name, fact in packages.items():+ if not isinstance(fact, dict):+ raise ValueError(f"invalid payload fact: {name}")+ if "entry" not in fact and "stamp" in fact:+ continue+ entry_name = fact.get("entry")+ artifacts = fact.get("artifacts")+ if (not isinstance(entry_name, str) or entry_name in ("", ".", "..")+ or any(c in entry_name for c in "/\\:")+ or not isinstance(fact.get("version"), str) or not fact["version"]+ or not isinstance(fact.get("target"), str) or not fact["target"]+ or not isinstance(artifacts, list) or not artifacts+ or any(not isinstance(sha, str) or not re.fullmatch(r"[a-f0-9]{64}", sha)+ for sha in artifacts)):+ raise ValueError(f"incomplete payload tool: {name}")+ entry = root / entry_name+ if not entry.is_dir() or not entry.resolve().is_relative_to(root):+ raise ValueError(f"incomplete payload tool: {name}")+ fact["digest"] = tree_digest(entry)+ count += 1+ if not count:+ raise ValueError(f"payload facts carry no tool entries: {self.path}")+ _write(self.path, {"schema": SCHEMA, "packages": packages})+ self._packages = packages+ return count+def installed(self,name: str,diff --git a/scripts/bundles/payload.py b/scripts/bundles/payload.pyindex 5f5d45fd171..fc35129f8ca 100644--- a/scripts/bundles/payload.py+++ b/scripts/bundles/payload.py@@ -61,6 +61,14 @@ def record_tools(root: Path, lock_path: Path, target: str, entries: dict[str, sttarget=target, artifacts=[a["sha256"] for a in artifacts], digest=tree_digest(entry))+def rehash_tools(root: Path) -> int:+ """Record final tool bytes before the enclosing package is signed."""+ from pm.lock import Facts++ store = root / "tools"+ return Facts(store / "facts.json", strict=True).refresh_digests(store)++def plant_surfaces(repo: Path, source: Path, *, dashboard: bool = True) -> None:tui = source / "ui-tui/dist/entry.js"if not tui.is_file():@@ -222,12 +230,15 @@ def stage_launchers(root: Path, manifest: dict, *, run=subprocess.run) -> list[sdef main() -> None:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("action", choices=["launchers", "relocate", "surfaces"])+ parser.add_argument("action", choices=["launchers", "relocate", "surfaces", "rehash"])parser.add_argument("payload", type=Path)parser.add_argument("--source", type=Path, default=ROOT)parser.add_argument("--tui-only", action="store_true")parser.add_argument("--repo-dir", help="staged repository directory when no manifest exists yet")args = parser.parse_args()+ if args.action == "rehash":+ print(f"rehashed {rehash_tools(args.payload)} payload tools")+ returnif args.action == "relocate":relativize_links(args.payload)returndiff --git a/tests/scripts/test_payload_digests.py b/tests/scripts/test_payload_digests.pynew file mode 100644index 00000000000..6e4b1fe1038--- /dev/null+++ b/tests/scripts/test_payload_digests.py@@ -0,0 +1,80 @@+"""Packaged facts describe final tool bytes without changing their identity."""+import copy+import json+from pathlib import Path+import subprocess+import sys++from pm.lock import Facts, Lockfile+from pm.store import current_target, tree_digest+from scripts.bundles import payload+++def _payload(tmp_path):+ root = tmp_path / "payload"+ store = root / "tools"+ entries = {"python": "python", "uv": "uv"}+ lock = Lockfile(tmp_path / "lock.json")+ for name, entry in entries.items():+ directory = store / entry+ directory.mkdir(parents=True)+ (directory / "tool").write_bytes(b"staging bytes")+ lock.set_pin(name, "1.0", {current_target(): {+ "url": "https://example.invalid/tool.zip", "sha256": "a" * 64,+ }})+ lock.save()+ payload.record_tools(root, lock.path, current_target(), entries)+ Facts(store / "facts.json").record_state("venv", "selection", ["web"])+ return root+++def _rehash(root, cwd):+ return subprocess.run(+ [sys.executable, str(Path(payload.__file__)), "rehash", str(root)],+ cwd=cwd, capture_output=True, text=True, encoding="utf-8", timeout=60,+ )+++def test_rehash_records_all_changed_tools_and_preserves_identity(tmp_path):+ root = _payload(tmp_path)+ path = root / "tools" / "facts.json"+ before = json.loads(path.read_text(encoding="utf-8"))+ (root / "tools/python/tool").write_bytes(b"final python bytes")+ (root / "tools/uv/tool").write_bytes(b"final uv bytes")+ result = _rehash(root, tmp_path)+ assert result.returncode == 0, result.stderr+ after = json.loads(path.read_text(encoding="utf-8"))+ for name in ("python", "uv"):+ expected = dict(before["packages"][name])+ expected["digest"] = tree_digest(root / "tools" / expected["entry"])+ assert after["packages"][name] == expected+ assert expected["digest"] != before["packages"][name]["digest"]+ assert after["packages"]["venv"] == before["packages"]["venv"]+ saved = path.read_bytes()+ assert _rehash(root, tmp_path).returncode == 0+ assert path.read_bytes() == saved+++def test_invalid_tool_evidence_never_partially_rewrites_facts(tmp_path):+ root = _payload(tmp_path)+ path = root / "tools" / "facts.json"+ before = json.loads(path.read_text(encoding="utf-8"))+ (root / "tools/python/tool").write_bytes(b"final python bytes")+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "kept").write_bytes(b"foreign")+ for entry in ("missing", "../outside", str(outside)):+ invalid = copy.deepcopy(before)+ invalid["packages"]["uv"]["entry"] = entry+ path.write_text(json.dumps(invalid), encoding="utf-8")+ saved = path.read_bytes()+ assert _rehash(root, tmp_path).returncode != 0+ assert path.read_bytes() == saved+ assert (outside / "kept").read_bytes() == b"foreign"+ for raw in (b"not JSON", b'{"schema":1,"packages":{}}'):+ path.write_bytes(raw)+ assert _rehash(root, tmp_path).returncode != 0+ assert path.read_bytes() == raw+ path.unlink()+ assert _rehash(root, tmp_path).returncode != 0+ assert not path.exists()