From 5c0577861483cc9695a7abe4f3e2ff30c1d95fca Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 6 Oct 2026 18:31:23 +0200 Subject: [PATCH] feat: support explicit source bundles through the common installer --- PROJECT_STATE.md | 5 +- .../scripts/prepare-source-installation.mjs | 89 +++++++++++++++++++ backend/scripts/release-bundle.mjs | 10 ++- backend/scripts/source-installation.test.mjs | 46 ++++++++++ docs/install/standalone-manual-en.md | 29 ++++++ docs/install/standalone-manual-it.md | 31 +++++++ .../reports/2026-10-06-source-installation.md | 16 ++++ tools/tht/internal/installapply/run.go | 15 +++- tools/tht/internal/installapply/run_test.go | 34 +++++++ tools/tht/internal/preflight/release.go | 36 +++++++- tools/tht/internal/preflight/source_test.go | 47 ++++++++++ 11 files changed, 353 insertions(+), 5 deletions(-) create mode 100644 backend/scripts/prepare-source-installation.mjs create mode 100644 backend/scripts/source-installation.test.mjs create mode 100644 docs/reports/2026-10-06-source-installation.md create mode 100644 tools/tht/internal/preflight/source_test.go diff --git a/PROJECT_STATE.md b/PROJECT_STATE.md index 2e655d0f..322cc3b2 100644 --- a/PROJECT_STATE.md +++ b/PROJECT_STATE.md @@ -41,7 +41,10 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git. cover workspace diagnostics, workflow configuration and Pi/default-model smoke. Reports distinguish platform, binding, workspace readiness and manual functional acceptance. This increment also requires a later release than preview.5. - Integrated source/recovery paths, real-host + Ticket #50 adds an explicit `prepare-source-installation.mjs` producer from an + isolated committed worktree. Source bundles pin local application image IDs and + upstream Docker Hub digests; the same native plan/apply path verifies provenance, + shares journal/locks and never falls back to a build. Extended recovery, real-host acceptance and curated examples remain pending. Earlier previews are superseded for platform apply; no complete installer/OS acceptance is claimed. diff --git a/backend/scripts/prepare-source-installation.mjs b/backend/scripts/prepare-source-installation.mjs new file mode 100644 index 00000000..bf28e0e2 --- /dev/null +++ b/backend/scripts/prepare-source-installation.mjs @@ -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; } +} diff --git a/backend/scripts/release-bundle.mjs b/backend/scripts/release-bundle.mjs index 1c8e59a5..12419fde 100644 --- a/backend/scripts/release-bundle.mjs +++ b/backend/scripts/release-bundle.mjs @@ -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. diff --git a/backend/scripts/source-installation.test.mjs b/backend/scripts/source-installation.test.mjs new file mode 100644 index 00000000..f8ef2c80 --- /dev/null +++ b/backend/scripts/source-installation.test.mjs @@ -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 }); } +}); diff --git a/docs/install/standalone-manual-en.md b/docs/install/standalone-manual-en.md index aa1cec0e..0d3769e7 100644 --- a/docs/install/standalone-manual-en.md +++ b/docs/install/standalone-manual-en.md @@ -266,6 +266,35 @@ the lock; after a forcibly killed process, confirm that its owner is no longer r before explicitly removing a stale lock. A different release requires the upgrade path rather than this command. +## Advanced source build with the same prepared documents + +Source compilation is an explicit choice before planning. It requires a ThothII +checkout containing the selected commit, Git, Node 24/npm, Go, Docker Buildx and +network access for dependencies. From `backend`, after `npm ci`: + +```bash +node scripts/prepare-source-installation.mjs \ + --revision COMMIT --version 0.1.0-source.1 \ + --platform linux/amd64 --output /private/path/new-build +``` + +The command builds an isolated temporary worktree, excluding local edits and +untracked secrets. It does not publish images. The output directory must be new; +after failure preserve its private logs and retry in a new directory. Select +`--platform linux/arm64` explicitly when appropriate. + +Use the resulting `bundle/bin/tht` and `bundle/release-manifest.json` in the same +`installation validate`, `plan` and `apply` steps above. The sealed plan records +`release.distribution: source`, revision, version and immutable local image IDs. +Use the Docker daemon containing those images and a Linux operator host matching +the bundle architecture; Windows runs the operator in WSL2. + +`apply` pulls only PostgreSQL, Qdrant and Ollama and shares locks, journal, +migrations, binding import and readiness with prebuilt installation. A missing +local image or different source revision blocks planning, without automatic build +fallback. Changing revision or distribution requires a separate installation or +explicit upgrade. Source testing does not certify a public Docker Hub release. + ## Manual source path: the two repositories The remaining sections describe the existing manual path. Do not run its build/setup diff --git a/docs/install/standalone-manual-it.md b/docs/install/standalone-manual-it.md index 958ddc0e..ddb5b3ea 100644 --- a/docs/install/standalone-manual-it.md +++ b/docs/install/standalone-manual-it.md @@ -275,6 +275,37 @@ nuovo piano. Ctrl+C rilascia il lock; dopo un arresto forzato del processo verif che non sia più attivo prima di rimuovere esplicitamente il suo lock residuo. Un rilascio differente richiede il percorso di aggiornamento, non questo comando. +## Percorso avanzato da sorgenti con gli stessi documenti + +La build è una scelta esplicita precedente alla predisposizione del piano. +Richiede un checkout ThothII con il commit desiderato, Git, Node 24/npm, Go, +Docker Buildx e rete per le dipendenze. Da `backend`, dopo `npm ci`: + +```bash +node scripts/prepare-source-installation.mjs \ + --revision COMMIT --version 0.1.0-source.1 \ + --platform linux/amd64 --output /percorso/privato/build-nuova +``` + +Il comando usa un worktree temporaneo del commit, escludendo modifiche locali e +segreti non tracciati. Non pubblica immagini. L'output deve essere nuovo; se la +build fallisce, conservarne i log privati e riprovare in una nuova directory. +Per Linux arm64 scegliere esplicitamente `--platform linux/arm64`. + +Usare `bundle/bin/tht` e `bundle/release-manifest.json` prodotti dal comando +negli stessi passi `installation validate`, `plan` e `apply` descritti sopra. +Il piano sigilla `release.distribution: source`, revisione, versione e identità +immutabili delle immagini locali. L'operatore deve usare lo stesso daemon Docker +che contiene quelle immagini; la piattaforma del bundle deve corrispondere al +sistema Linux che esegue l'operatore. Su Windows usare WSL2. + +`apply` scarica solo PostgreSQL, Qdrant e Ollama. Usa gli stessi lock, journal, +migrazioni, binding e controlli di readiness del percorso precompilato. Un'immagine +locale mancante o di un'altra revisione blocca il piano: nessuna build automatica. +Cambiare revisione o modalità richiede una nuova installazione o il percorso +esplicito di aggiornamento. La prova da sorgenti non vale come accettazione del +rilascio pubblico Docker Hub. + ## Percorso manuale da sorgenti: i due repository Le sezioni successive documentano il percorso manuale esistente. Non eseguire i diff --git a/docs/reports/2026-10-06-source-installation.md b/docs/reports/2026-10-06-source-installation.md new file mode 100644 index 00000000..bbe5df6d --- /dev/null +++ b/docs/reports/2026-10-06-source-installation.md @@ -0,0 +1,16 @@ +# Explicit source installation — T08/#50 + +The advanced `backend/scripts/prepare-source-installation.mjs` command builds core +and frontend from an isolated committed worktree, loads local image IDs and creates +a source bundle. It never publishes images or uses uncommitted operator files. +Native planning checks local image identity, OCI revision/version and architecture; +the sealed manifest records source mode. Apply shares document validation, lock, +journal, migrations, binding import and readiness with the prebuilt path. Only +upstream service images are pulled. Switching distribution is not an implicit upgrade. + +Verification before the real source build: source producer command-boundary and +bundle tests passed (3 Node tests including prebuilt packaging); Go preflight and +apply suites passed, including local identity rejection, no registry fallback and +source apply through the common readiness stages. Standards and Spec review found +no code findings. A real build/start proof remains pending and is required before +calling T08 acceptance complete; it does not certify a published-image installation. diff --git a/tools/tht/internal/installapply/run.go b/tools/tht/internal/installapply/run.go index ab02414a..51e18df8 100644 --- a/tools/tht/internal/installapply/run.go +++ b/tools/tht/internal/installapply/run.go @@ -29,6 +29,7 @@ type RuntimeCheck struct { Status string `json:"status"` } type Result struct { + Distribution string `json:"distribution"` SchemaVersion int `json:"schema_version"` PlatformReady bool `json:"platform_ready"` WorkspaceReady bool `json:"workspace_ready"` @@ -42,6 +43,7 @@ type Result struct { Journal string `json:"journal,omitempty"` } type journal struct { + Distribution string `json:"distribution,omitempty"` SchemaVersion int `json:"schema_version"` Installation string `json:"installation"` ReleaseRevision string `json:"release_revision"` @@ -76,6 +78,7 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec if err != nil || !reflect.DeepEqual(manifest, plan.Release) { return fail("release", "Restore the exact verified release bundle and generate a new plan if its identity changed.") } + result.Distribution = manifest.Mode() if err := safeio.EnsurePrivateDirectory(filepath.Join(installation.ProjectDirectory, ".tht")); err != nil { return fail("lock", "The installation control directory must be private and canonical.") } @@ -106,13 +109,20 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec } defer clear(payload) result.Journal = filepath.Join(installation.ControlDirectory(), "installation-apply.json") - state := journal{SchemaVersion: 1, Installation: installation.Path, ReleaseRevision: plan.Release.Revision, PlanSeal: plan.InputSeal} + state := journal{SchemaVersion: 1, Installation: installation.Path, ReleaseRevision: plan.Release.Revision, PlanSeal: plan.InputSeal, Distribution: manifest.Mode()} if _, err := os.Lstat(result.Journal); err == nil { data, readErr := safeio.ReadCanonicalPrivateRegular(result.Journal, 16<<10) var previous journal if readErr != nil || json.Unmarshal(data, &previous) != nil || previous.SchemaVersion != 1 || previous.Installation != installation.Path || previous.ReleaseRevision != plan.Release.Revision { return fail("journal", "The existing installation journal is invalid or belongs to another release; this command is not a product upgrade.") } + previousMode := previous.Distribution + if previousMode == "" { + previousMode = "prebuilt" + } + if previousMode != manifest.Mode() { + return fail("journal", "Changing between source and prebuilt requires an explicit upgrade or a separate installation.") + } } else if !os.IsNotExist(err) { return fail("journal", "Cannot safely read the installation journal.") } @@ -181,6 +191,9 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec return nil }}, {"pull", func() error { + if manifest.Mode() == "source" { + return docker(30*time.Minute, "pull", "--policy", "always", "catalog-db", "qdrant", "embedding", "embedding-model-init") + } return docker(30*time.Minute, "--profile", "catalog-maintenance", "--profile", "workspace-maintenance", "pull", "--policy", "always") }}, {"runtime-identity", func() error { diff --git a/tools/tht/internal/installapply/run_test.go b/tools/tht/internal/installapply/run_test.go index 3e4c7497..88fcfd70 100644 --- a/tools/tht/internal/installapply/run_test.go +++ b/tools/tht/internal/installapply/run_test.go @@ -82,6 +82,7 @@ type dockerFixture struct { calls [][]string fail string wrongImage bool + source bool } func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (compose.Result, error) { @@ -133,6 +134,9 @@ func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) ( continue } services[service] = map[string]string{"image": "docker.io/example/" + role + "@sha256:" + strings.Repeat("a", 64)} + if r.source && (role == "core" || role == "frontend") { + services[service] = map[string]string{"image": "sha256:" + strings.Repeat("a", 64)} + } } if r.wrongImage { services["core"] = map[string]string{"image": "unverified:latest"} @@ -149,6 +153,36 @@ func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) ( return compose.Result{Stdout: `{"ok":true}`}, nil } +func TestExplicitSourceApplySharesReadinessAndPullsOnlyUpstream(t *testing.T) { + path, p := fixture(t) + p.Release.Distribution = "source" + for _, role := range []string{"core", "frontend"} { + p.Release.Images[role][p.Platform] = "sha256:" + strings.Repeat("a", 64) + } + data, _ := json.Marshal(p.Release) + if err := os.WriteFile(p.ManifestPath, data, 0o600); err != nil { + t.Fatal(err) + } + _ = os.Remove(path) + _ = os.Remove(path + ".key") + if err := preflight.WritePlan(path, &p); err != nil { + t.Fatal(err) + } + r := &dockerFixture{source: true} + result, err := Run(context.Background(), Request{PlanPath: path, InstallationPath: p.Installation.Path}, r, func(context.Context, preflight.Plan) error { return nil }) + if err != nil || !result.WorkspaceReady || result.Distribution != "source" { + t.Fatalf("source apply: %+v %v", result, err) + } + for _, call := range flatten(r.calls) { + if strings.Contains(call, " pull ") && !strings.Contains(call, "pull --policy always catalog-db qdrant embedding embedding-model-init") { + t.Fatal("source application images pulled") + } + if strings.Contains(call, " build ") { + t.Fatal("apply implicitly built source") + } + } +} + func TestApplyRefusesUnreleasedEffectiveImageBeforePull(t *testing.T) { path, p := fixture(t) r := &dockerFixture{wrongImage: true} diff --git a/tools/tht/internal/preflight/release.go b/tools/tht/internal/preflight/release.go index 4ea4b905..c497b8bb 100644 --- a/tools/tht/internal/preflight/release.go +++ b/tools/tht/internal/preflight/release.go @@ -19,6 +19,7 @@ import ( // Manifest is the publication/consumer contract. Each platform maps to a single-image digest, // not a mutable tag or multi-platform index. Maintenance roles use Images["core"]. type Manifest struct { + Distribution string `json:"distribution,omitempty"` SchemaVersion int `json:"schema_version"` Version string `json:"version"` Revision string `json:"revision"` @@ -30,6 +31,13 @@ type Manifest struct { Compose []string `json:"compose"` } +func (m Manifest) Mode() string { + if m.Distribution == "source" { + return "source" + } + return "prebuilt" +} + var hex256 = regexp.MustCompile(`^[a-f0-9]{64}$`) var imageReference = regexp.MustCompile(`^docker\.io/[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$`) @@ -37,6 +45,9 @@ func invalidRelease() error { return errors.New("release manifest or packaged files are incomplete, incompatible or invalid") } func (m Manifest) Validate() error { + if m.Distribution != "" && m.Distribution != "prebuilt" && m.Distribution != "source" { + return invalidRelease() + } if m.SchemaVersion != 1 || m.ValidatorProtocol != Protocol || !regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$`).MatchString(m.Version) || !regexp.MustCompile(`^[a-f0-9]{40}$`).MatchString(m.Revision) { return invalidRelease() } @@ -56,7 +67,11 @@ func (m Manifest) Validate() error { return invalidRelease() } for platform, ref := range m.Images[service] { - if (platform != "linux/amd64" && platform != "linux/arm64") || !imageReference.MatchString(ref) { + valid := imageReference.MatchString(ref) + if m.Mode() == "source" && (service == "core" || service == "frontend") { + valid = strings.HasPrefix(ref, "sha256:") && hex256.MatchString(strings.TrimPrefix(ref, "sha256:")) + } + if (platform != "linux/amd64" && platform != "linux/arm64") || !valid { return invalidRelease() } } @@ -110,6 +125,25 @@ func CheckImages(ctx context.Context, runner Runner, m Manifest, platform string r.Add("image-"+service, "error", "release.images."+service, "Publish the selected Linux architecture before producing an executable plan.") continue } + if m.Mode() == "source" && (service == "core" || service == "frontend") { + result, err := docker(ctx, runner, "image", "inspect", "--format", "{{json .}}", ref) + var image struct { + ID string `json:"Id"` + OS string `json:"Os"` + Architecture string `json:"Architecture"` + Config struct { + Labels map[string]string `json:"Labels"` + } `json:"Config"` + } + good := err == nil && result.ExitCode == 0 && json.Unmarshal([]byte(result.Stdout), &image) == nil && image.ID == ref && + image.OS+"/"+image.Architecture == platform && image.Config.Labels["org.opencontainers.image.revision"] == m.Revision && image.Config.Labels["org.opencontainers.image.version"] == m.Version + outcome := "passed" + if !good { + outcome = "error" + } + r.Add("image-"+service, outcome, "release.images."+service, "Require the explicitly built local image, matching source revision, version and architecture; rebuild the selected source bundle if it is missing.") + continue + } result, err := docker(ctx, runner, "manifest", "inspect", "--verbose", ref) var manifest struct { Descriptor struct { diff --git a/tools/tht/internal/preflight/source_test.go b/tools/tht/internal/preflight/source_test.go new file mode 100644 index 00000000..52483dec --- /dev/null +++ b/tools/tht/internal/preflight/source_test.go @@ -0,0 +1,47 @@ +package preflight + +import ( + "context" + "encoding/json" + "github.com/aritmolab/thothii/tools/tht/internal/compose" + "io" + "strings" + "testing" +) + +type localDocker struct { + fakeDocker + wrong bool +} + +func (d *localDocker) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) { + if args[0] != "image" { + return d.fakeDocker.Run(ctx, args, input) + } + revision := strings.Repeat("b", 40) + if d.wrong { + revision = strings.Repeat("c", 40) + } + value, _ := json.Marshal(map[string]any{"Id": args[len(args)-1], "Os": "linux", "Architecture": "amd64", "Config": map[string]any{"Labels": map[string]string{"org.opencontainers.image.revision": revision, "org.opencontainers.image.version": "1.0.0"}}}) + return compose.Result{Stdout: string(value)}, nil +} +func TestSourceImagesNeedExplicitDistributionAndMatchingLocalIdentity(t *testing.T) { + m := Manifest{Distribution: "source", Revision: strings.Repeat("b", 40), Version: "1.0.0", Images: map[string]map[string]string{}} + for _, role := range []string{"core", "frontend", "catalog", "qdrant", "embedding"} { + ref := "docker.io/example/" + role + "@sha256:" + strings.Repeat("a", 64) + if role == "core" || role == "frontend" { + ref = "sha256:" + strings.Repeat("a", 64) + } + m.Images[role] = map[string]string{"linux/amd64": ref} + } + if !CheckImages(context.Background(), &localDocker{}, m, "linux/amd64").OK { + t.Fatal("explicit local images rejected") + } + if CheckImages(context.Background(), &localDocker{wrong: true}, m, "linux/amd64").OK { + t.Fatal("different source accepted") + } + m.Distribution = "" + if CheckImages(context.Background(), &localDocker{}, m, "linux/amd64").OK { + t.Fatal("implicit source fallback accepted") + } +}