feat: support explicit source bundles through the common installer

This commit is contained in:
Codex
2026-10-06 18:31:23 +02:00
parent 785d96ea50
commit 5c05778614
11 changed files with 353 additions and 5 deletions
@@ -0,0 +1,89 @@
#!/usr/bin/env node
// Explicit advanced producer. The resulting bundle uses the ordinary document-first apply path.
import { mkdirSync, mkdtempSync, realpathSync, existsSync, readFileSync, rmSync, copyFileSync, chmodSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { parse } from 'yaml';
import { prepareBundle } from './release-bundle.mjs';
import { commandRunner } from './publish-installation.mjs';
import { dockerHub } from './release-registry.mjs';
const repositoryRoot = resolve(import.meta.dirname, '../..');
export function sourceOptions(args) {
const values = {};
for (let i = 0; i < args.length; i += 2) {
if (!['--revision', '--version', '--platform', '--output'].includes(args[i]) || !args[i + 1] || values[args[i]]) throw new Error('Use --revision COMMIT --version VERSION --platform linux/amd64|linux/arm64 --output NEW_DIRECTORY.');
values[args[i]] = args[i + 1];
}
if (!values['--revision'] || values['--revision'].startsWith('-') || !/^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$/.test(values['--version'] ?? '') || !['linux/amd64', 'linux/arm64'].includes(values['--platform']) || !values['--output']) throw new Error('Select an explicit source revision, version, Linux platform and new output directory.');
return { revision: values['--revision'], version: values['--version'], platform: values['--platform'], output: resolve(values['--output']) };
}
export async function buildSourceImages({ run, source, output, revision, version, platform }) {
const images = {};
for (const role of ['core', 'frontend']) {
const iid = join(output, `${role}.iid`);
await run('docker', ['buildx', 'build', '--load', '--platform', platform, '--file', `docker/${role}.Dockerfile`,
'--iidfile', iid, '--build-arg', `IMAGE_VERSION=${version}`, '--label', `org.opencontainers.image.revision=${revision}`,
'--label', `org.opencontainers.image.version=${version}`, '--provenance=false', '--sbom=false', '.'], { cwd: source, timeout: 45 * 60_000 });
const id = readFileSync(iid, 'utf8').trim();
if (!/^sha256:[a-f0-9]{64}$/.test(id)) throw new Error('Source build did not produce an immutable local image identity.');
const image = JSON.parse(await run('docker', ['image', 'inspect', '--format', '{{json .}}', id], { quiet: true }));
if (image.Id !== id || `${image.Os}/${image.Architecture}` !== platform || image.Config?.Labels?.['org.opencontainers.image.revision'] !== revision || image.Config?.Labels?.['org.opencontainers.image.version'] !== version) throw new Error('Built image identity differs from the selected source.');
images[role] = id;
}
return images;
}
export async function prepareSourceInstallation(options) {
// mkdir is exclusive: never replace a bundle or mix an incomplete previous build with new inputs.
mkdirSync(options.output, { mode: 0o700 });
if (realpathSync(options.output) !== options.output) throw new Error('Use a canonical output path.');
const logs = join(options.output, 'logs'); mkdirSync(logs, { mode: 0o700 });
const run = commandRunner(logs);
let temporary, source;
try {
const revision = (await run('git', ['rev-parse', '--verify', `${options.revision}^{commit}`], { quiet: true })).trim();
if (!/^[a-f0-9]{40}$/.test(revision)) throw new Error('Select a committed source revision.');
await run('docker', ['info', '--format', '{{.OSType}}']);
await run('docker', ['buildx', 'version']);
temporary = realpathSync(mkdtempSync(join(tmpdir(), 'thothii-source-')));
source = join(temporary, 'source');
await run('git', ['worktree', 'add', '--detach', source, revision]);
console.log(`Building explicit source installation ${revision} for ${options.platform}.`);
const images = await buildSourceImages({ run, source, output: options.output, revision, version: options.version, platform: options.platform });
const compose = parse(readFileSync(join(source, 'compose.yaml'), 'utf8'));
const registry = dockerHub();
for (const [role, service] of [['catalog', 'catalog-db'], ['qdrant', 'qdrant'], ['embedding', 'embedding']]) {
const [name, digest] = compose.services[service].image.split('@');
if (!/^sha256:[a-f0-9]{64}$/.test(digest ?? '')) throw new Error('Upstream source images must already be pinned.');
let repository = name.replace(/:[^/:]+$/, '').replace(/^docker.io\//, '');
if (!repository.includes('/')) repository = `library/${repository}`;
images[role] = (await registry.inspect(repository, digest, options.platform, { anonymous: true })).reference;
}
await run('npm', ['ci'], { cwd: join(source, 'backend'), timeout: 10 * 60_000 });
const target = options.platform.replace('/', '-');
const sourceTime = (await run('git', ['show', '-s', '--format=%cI', revision], { quiet: true })).trim();
await run(process.execPath, [join(repositoryRoot, 'backend/scripts/build-workspace-tools.mjs'), target], {
cwd: join(source, 'backend'), env: { ...process.env, THT_BUILD_SOURCE_ROOT: source, THT_BUILD_VERSION: options.version, THT_BUILD_TIME: sourceTime }, timeout: 10 * 60_000,
});
const bundle = join(options.output, 'bundle'); mkdirSync(bundle, { mode: 0o700 });
prepareBundle({ source, destination: bundle, platform: options.platform, version: options.version, revision, images, distribution: 'source' });
mkdirSync(join(bundle, 'bin'));
for (const executable of ['tht', 'tht-workspace-documents']) {
copyFileSync(join(source, 'dist/workspace-tools', target, executable), join(bundle, 'bin', executable));
chmodSync(join(bundle, 'bin', executable), 0o755);
}
await run('docker', ['compose', '-f', join(bundle, 'compose.yaml'), '-f', join(bundle, 'deploy/compose.local.yaml'), '--profile', 'catalog-maintenance', '--profile', 'workspace-maintenance', 'config', '--no-interpolate', '--no-env-resolution', '--format', 'json']);
console.log(`Source bundle prepared: ${bundle}. Use its operator for ordinary installation validate, plan and apply on this Docker daemon.`);
return bundle;
} finally {
if (source && existsSync(source)) await run('git', ['worktree', 'remove', '--force', source]).catch(() => {});
if (temporary && !existsSync(source ?? '')) rmSync(temporary, { recursive: true, force: true });
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
try { await prepareSourceInstallation(sourceOptions(process.argv.slice(2))); }
catch { console.error('Source preparation failed. Inspect the private build logs and use a new output directory to retry; no images were published.'); process.exitCode = 1; }
}
+8 -2
View File
@@ -7,11 +7,14 @@ export const serviceRoles = Object.freeze({ core: "core", frontend: "frontend",
export const sha256 = (data) => createHash("sha256").update(data).digest("hex");
/** Only distribution assets enter the bundle: never a checkout, environment file or workspace. */
export function prepareBundle({ source, destination, platform, version, revision, images }) {
export function prepareBundle({ source, destination, platform, version, revision, images, distribution = "prebuilt" }) {
if (!["prebuilt", "source"].includes(distribution)) throw new Error("Unknown installation distribution.");
const compose = parse(readFileSync(join(source, "compose.yaml"), "utf8"));
if (Object.keys(compose.services).sort().join() !== Object.keys(serviceRoles).sort().join()) throw new Error("Release service contract changed; review packaging before publishing.");
for (const [name, role] of Object.entries(serviceRoles)) {
if (!/^docker\.io\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/.test(images[role] ?? "")) throw new Error("Release requires immutable Docker Hub image references.");
const local = distribution === "source" && ["core", "frontend"].includes(role);
const pattern = local ? /^sha256:[a-f0-9]{64}$/ : /^docker\.io\/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/;
if (!pattern.test(images[role] ?? "")) throw new Error("Release requires immutable image references for its distribution.");
delete compose.services[name].build;
delete compose.services[name].pull_policy;
compose.services[name].image = images[role];
@@ -37,6 +40,7 @@ export function prepareBundle({ source, destination, platform, version, revision
}
}
const manifest = { schema_version: 1, version, revision, validator_protocol: 1,
...(distribution === "source" ? { distribution } : {}),
requirements: { cpus: 2, memory_bytes: 4 * 2 ** 30, disk_bytes: 10 * 2 ** 30 },
components: ["pi", "catalog-migrations", "workspace-maintenance"],
images: Object.fromEntries(Object.entries(images).map(([role, reference]) => [role, { [platform]: reference }])),
@@ -46,6 +50,8 @@ export function prepareBundle({ source, destination, platform, version, revision
Source / Sorgente: ${revision}
Distribution / Distribuzione: ${distribution}. ${distribution === 'source' ? 'Application images are local to the producer Docker daemon; this bundle is not a public image release. Le immagini applicative sono locali al daemon Docker del produttore.' : 'Application images are downloaded from Docker Hub. Le immagini applicative vengono scaricate da Docker Hub.'}
This prerelease provides images, document/preflight tools, non-interactive platform apply, prepared binding import and workspace/runtime readiness checks. A pending destructive schema review stops apply for a human decision. Windows/Omarchy/macOS and human-reviewed question acceptance remain separate; this is not a certified complete installation.
Questa prerelease fornisce immagini, preparazione/preflight, avvio non interattivo, import dei binding e controlli di readiness workspace/runtime. Una revisione distruttiva dello schema ferma apply per una decisione umana. Collaudi Windows/Omarchy/macOS e domanda con revisione umana restano separati: non è ancora un'installazione completa certificata.
@@ -0,0 +1,46 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { prepareBundle } from './release-bundle.mjs';
import { buildSourceImages, sourceOptions } from './prepare-source-installation.mjs';
test('source builds load local images from the isolated checkout without publication or secrets', async () => {
const output = mkdtempSync(join(tmpdir(), 'source-build-'));
const calls = [];
const revision = 'c'.repeat(40), version = '1.0.0-source', platform = 'linux/amd64';
const run = async (command, args, options) => {
calls.push({ command, args, options });
if (args[0] === 'buildx') {
assert.equal(options.cwd, '/isolated/committed-source');
assert.ok(args.includes('--load'));
assert.ok(!args.includes('--push'));
assert.ok(!args.includes('--secret'));
assert.deepEqual(args.filter((_, index) => args[index - 1] === '--build-arg'), [`IMAGE_VERSION=${version}`]);
writeFileSync(args[args.indexOf('--iidfile') + 1], `sha256:${'a'.repeat(64)}`);
return '';
}
return JSON.stringify({ Id: `sha256:${'a'.repeat(64)}`, Os: 'linux', Architecture: 'amd64', Config: { Labels: { 'org.opencontainers.image.revision': revision, 'org.opencontainers.image.version': version } } });
};
try {
assert.deepEqual(await buildSourceImages({ run, source: '/isolated/committed-source', output, revision, version, platform }), { core: `sha256:${'a'.repeat(64)}`, frontend: `sha256:${'a'.repeat(64)}` });
assert.equal(calls.length, 4);
assert.throws(() => sourceOptions(['--revision', 'HEAD']), /explicit/);
} finally { rmSync(output, { recursive: true, force: true }); }
});
test('source bundles identify their mode and use immutable local application images', () => {
const output = mkdtempSync(join(tmpdir(), 'source-bundle-'));
const images = Object.fromEntries(['core', 'frontend', 'catalog', 'qdrant', 'embedding'].map(role => [role,
['core', 'frontend'].includes(role) ? `sha256:${'a'.repeat(64)}` : `docker.io/example/${role}@sha256:${'b'.repeat(64)}`]));
try {
const manifest = prepareBundle({ source: resolve(import.meta.dirname, '../..'), destination: output,
platform: 'linux/arm64', version: '0.1.0-source', revision: 'c'.repeat(40), images, distribution: 'source' });
assert.equal(manifest.distribution, 'source');
assert.equal(manifest.images.core['linux/arm64'], images.core);
assert.doesNotMatch(readFileSync(join(output, 'compose.yaml'), 'utf8'), /build:/);
assert.throws(() => prepareBundle({ source: resolve(import.meta.dirname, '../..'), destination: output,
platform: 'linux/arm64', version: '0.1.0-source', revision: 'c'.repeat(40), images }), /immutable/);
} finally { rmSync(output, { recursive: true, force: true }); }
});