Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(build): invalidate remote bundles on source deletion

Chris87f0b718712a
diff --git a/apps/desktop/scripts/build-remote-bundles.mjs b/apps/desktop/scripts/build-remote-bundles.mjs
index 8be1d9a8fc..b674f25e05 100644
--- a/apps/desktop/scripts/build-remote-bundles.mjs
+++ b/apps/desktop/scripts/build-remote-bundles.mjs
@@ -10,17 +10,15 @@
// pre hooks, so without an explicit call there release builds
// would ship without the bundles.
//
-// mtime check: skips rebuild when bundle is newer than every src file +
-// build.mjs + package.json (the inputs that affect output). Cold clone runs
-// esbuild for both packages (~1-2s total); subsequent runs with no source
-// change are sub-100ms (just stat + copy if dest also needs refresh).
+// Cache by input paths/content and output content. Missing receipts rebuild once;
+// deleting an input or restoring old timestamps cannot leave a stale bundle cached.
import { spawnSync } from 'node:child_process';
-import { copyFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
+import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import process from 'node:process';
-import { newestBundleInputMtime } from './remote-bundle-inputs.mjs';
+import { bundleInputDigest, bundleInputsMatch, recordBundleInputs } from './remote-bundle-inputs.mjs';
const here = dirname(fileURLToPath(import.meta.url));
const DESKTOP_ROOT = resolve(here, '..');
@@ -62,16 +60,9 @@ const TARGETS = [
function bundleIfStale(target) {
const bundleAbs = join(target.pkgDir, target.bundleFile);
- const bundleMtime = existsSync(bundleAbs) ? statSync(bundleAbs).mtimeMs : 0;
- // Inputs that affect bundle output: all .ts under src/, build.mjs,
- // package.json (deps could change). pnpm-lock.yaml is at monorepo root —
- // skipping it intentionally; an esbuild bump would touch package.json
- // either way via devDependencies.
- const srcMtime = newestBundleInputMtime(target.pkgDir, target.dependencyDirs);
- if (bundleMtime >= srcMtime && bundleMtime > 0) {
- return false; // up-to-date
- }
- console.log(`[remote-bundles] ${target.pkgName}: bundling (src newer than dist)...`);
+ const inputDigest = bundleInputDigest(target.pkgDir, target.dependencyDirs);
+ if (bundleInputsMatch(bundleAbs, inputDigest)) return false;
+ console.log(`[remote-bundles] ${target.pkgName}: bundling (inputs or output changed)...`);
// 直接 spawn 当前 node + 包的 build.mjs, 不走 pnpm 包装层:
// 1. 跨平台干净 — pnpm 在 Windows 是 pnpm.cmd, fnm shim 又只暴露 pnpm 无后缀,
// spawn 时 EINVAL / not found 各种坑; 用 process.execPath 永远是当前 node
@@ -91,6 +82,7 @@ function bundleIfStale(target) {
);
process.exit(r.status ?? 1);
}
+ recordBundleInputs(bundleAbs, inputDigest);
return true;
}
@@ -101,14 +93,8 @@ function stageToResources(target) {
process.exit(1);
}
const destAbs = join(target.destDir, target.destFile);
- // mtime check on the staged copy too — skip copy when dest is fresh.
- // Avoids touching the file every build, which would invalidate forge
- // content-addressed caches if any.
- const srcMtime = statSync(bundleAbs).mtimeMs;
- const destMtime = existsSync(destAbs) ? statSync(destAbs).mtimeMs : 0;
- if (destMtime >= srcMtime && destMtime > 0) {
- return false;
- }
+ // Compare content too: a destination with a future mtime may still contain old code.
+ if (existsSync(destAbs) && readFileSync(destAbs).equals(readFileSync(bundleAbs))) return false;
mkdirSync(target.destDir, { recursive: true });
copyFileSync(bundleAbs, destAbs);
console.log(`[remote-bundles] ${target.pkgName}: staged → ${destAbs}`);
diff --git a/apps/desktop/scripts/remote-bundle-inputs.mjs b/apps/desktop/scripts/remote-bundle-inputs.mjs
index 0d44bc4bf0..e36415b4bf 100644
--- a/apps/desktop/scripts/remote-bundle-inputs.mjs
+++ b/apps/desktop/scripts/remote-bundle-inputs.mjs
@@ -1,28 +1,43 @@
-import { existsSync, readdirSync, statSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-function newestMtime(rootDir, relPaths) {
- let newest = 0;
- for (const rel of relPaths) {
- const abs = join(rootDir, rel);
- if (!existsSync(abs)) continue;
- const st = statSync(abs);
- if (st.isDirectory()) {
- for (const entry of readdirSync(abs, { recursive: true, withFileTypes: true })) {
- if (!entry.isFile()) continue;
- newest = Math.max(newest, statSync(join(entry.parentPath ?? abs, entry.name)).mtimeMs);
- }
- } else newest = Math.max(newest, st.mtimeMs);
- }
- return newest;
+function fileDigest(file) {
+ return createHash('sha256').update(readFileSync(file)).digest('hex');
}
-/** A workspace dependency can change without touching the consuming package's source. */
-export function newestBundleInputMtime(pkgDir, dependencyDirs = []) {
- let newest = newestMtime(pkgDir, ['src', 'build.mjs', 'package.json']);
- for (const dependency of dependencyDirs) {
+/** Include sorted paths as well as contents, so removals and preserved mtimes invalidate. */
+export function bundleInputDigest(pkgDir, dependencyDirs = []) {
+ const inputs = [];
+ function visit(root, rel, prefix) {
+ const abs = join(root, rel);
+ if (!existsSync(abs)) return;
+ if (statSync(abs).isDirectory()) {
+ for (const name of readdirSync(abs).sort()) visit(root, join(rel, name), prefix);
+ } else {
+ inputs.push([prefix, rel.replaceAll('\\', '/'), fileDigest(abs)]);
+ }
+ }
+ for (const rel of ['src', 'build.mjs', 'package.json']) visit(pkgDir, rel, 'package');
+ dependencyDirs.forEach((dependency, index) => {
if (!existsSync(dependency)) throw new Error(`Remote bundle source dependency is missing: ${dependency}`);
- newest = Math.max(newest, newestMtime(dependency, ['src', 'package.json', 'LICENSE.opencodex']));
+ for (const rel of ['src', 'package.json', 'LICENSE.opencodex']) visit(dependency, rel, `dependency:${index}`);
+ });
+ return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');
+}
+
+export function bundleInputsMatch(bundle, inputDigest) {
+ if (!existsSync(bundle)) return false;
+ try {
+ const receipt = JSON.parse(readFileSync(`${bundle}.inputs.json`, 'utf8'));
+ return receipt?.version === 1 && receipt.inputDigest === inputDigest && receipt.outputDigest === fileDigest(bundle);
+ } catch (error) {
+ if (error.code === 'ENOENT' || error instanceof SyntaxError) return false;
+ throw error;
}
- return newest;
+}
+
+/** Called only after a successful build; failed builds never bless stale output. */
+export function recordBundleInputs(bundle, inputDigest) {
+ writeFileSync(`${bundle}.inputs.json`, JSON.stringify({ version: 1, inputDigest, outputDigest: fileDigest(bundle) }) + '\n');
}
diff --git a/scripts/__tests__/remote-bundle-inputs.test.mjs b/scripts/__tests__/remote-bundle-inputs.test.mjs
index f9692ce779..398b8e7aeb 100644
--- a/scripts/__tests__/remote-bundle-inputs.test.mjs
+++ b/scripts/__tests__/remote-bundle-inputs.test.mjs
@@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
-import { newestBundleInputMtime } from '../../apps/desktop/scripts/remote-bundle-inputs.mjs';
+import { bundleInputDigest, bundleInputsMatch, recordBundleInputs } from '../../apps/desktop/scripts/remote-bundle-inputs.mjs';
function fixture(run) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-remote-bundle-inputs-'));
@@ -16,24 +16,68 @@ function fixture(run) {
try { run(root, write); } finally { fs.rmSync(root, { recursive: true, force: true }); }
}
-test('a compatibility dependency update invalidates a newer consumer bundle', () => fixture((root, write) => {
+function cache(root, write) {
write('proxy/src/index.ts', 1000);
- write('proxy/dist/proxy.mjs', 1500);
- write('compat/src/upstream/provider.ts', 2000);
- const newest = newestBundleInputMtime(path.join(root, 'proxy'), [path.join(root, 'compat')]);
- assert.equal(newest, 2000000);
- assert.ok(newest > fs.statSync(path.join(root, 'proxy/dist/proxy.mjs')).mtimeMs);
+ write('compat/src/keep.ts', 1000);
+ write('compat/src/remove.ts', 1000);
+ write('proxy/dist/proxy.mjs', 9000);
+ const bundle = path.join(root, 'proxy/dist/proxy.mjs');
+ const digest = () => bundleInputDigest(path.join(root, 'proxy'), [path.join(root, 'compat')]);
+ recordBundleInputs(bundle, digest());
+ assert.equal(bundleInputsMatch(bundle, digest()), true);
+ return { bundle, digest };
+}
+
+test('deleting dependency source invalidates a newer cached bundle', () => fixture((root, write) => {
+ const { bundle, digest } = cache(root, write);
+ fs.unlinkSync(path.join(root, 'compat/src/remove.ts'));
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
}));
-test('license changes invalidate the single-file remote artifact, generated output does not', () => fixture((root, write) => {
- write('proxy/src/index.ts', 1000);
- write('proxy/dist/proxy.mjs', 9000);
- write('compat/src/index.ts', 2000);
- write('compat/LICENSE.opencodex', 3000);
- assert.equal(newestBundleInputMtime(path.join(root, 'proxy'), [path.join(root, 'compat')]), 3000000);
+test('consumer source removal and renaming invalidate even with unchanged contents', () => fixture((root, write) => {
+ const { bundle, digest } = cache(root, write);
+ fs.renameSync(path.join(root, 'proxy/src/index.ts'), path.join(root, 'proxy/src/renamed.ts'));
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+ recordBundleInputs(bundle, digest());
+ fs.unlinkSync(path.join(root, 'proxy/src/renamed.ts'));
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+}));
+
+test('content changes with preserved old timestamps invalidate', () => fixture((root, write) => {
+ const { bundle, digest } = cache(root, write);
+ const file = path.join(root, 'compat/src/keep.ts');
+ fs.writeFileSync(file, 'changed');
+ fs.utimesSync(file, 1000, 1000);
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+}));
+
+test('license changes invalidate, generated output and timestamp-only changes do not', () => fixture((root, write) => {
+ const { bundle, digest } = cache(root, write);
+ write('compat/dist/generated.js', 10000);
+ fs.utimesSync(path.join(root, 'compat/src/keep.ts'), 11000, 11000);
+ assert.equal(bundleInputsMatch(bundle, digest()), true);
+ write('compat/LICENSE.opencodex', 1000);
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+}));
+
+test('missing/corrupt receipts and changed output rebuild; only recorded successful output is fresh', () => fixture((root, write) => {
+ const { bundle, digest } = cache(root, write);
+ fs.unlinkSync(`${bundle}.inputs.json`);
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+ for (const invalid of ['{broken', 'null', '{}']) {
+ fs.writeFileSync(`${bundle}.inputs.json`, invalid);
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+ }
+ recordBundleInputs(bundle, digest());
+ fs.writeFileSync(bundle, 'partial failed build');
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
+ recordBundleInputs(bundle, digest());
+ assert.equal(bundleInputsMatch(bundle, digest()), true);
+ fs.unlinkSync(bundle);
+ assert.equal(bundleInputsMatch(bundle, digest()), false);
}));
-test('missing declared dependency does not leave a stale bundle silently marked fresh', () => fixture((root, write) => {
+test('missing declared dependency fails instead of accepting stale output', () => fixture((root, write) => {
write('proxy/src/index.ts', 1000);
- assert.throws(() => newestBundleInputMtime(path.join(root, 'proxy'), [path.join(root, 'missing')]), /dependency is missing/);
+ assert.throws(() => bundleInputDigest(path.join(root, 'proxy'), [path.join(root, 'missing')]), /dependency is missing/);
}));