From 785d96ea50c39d52f3bf4b5cad4ab57cc91a4204 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 6 Oct 2026 18:23:24 +0200 Subject: [PATCH] feat: prepare installation workspaces through existing readiness services --- PROJECT_STATE.md | 7 +- backend/scripts/publish-installation.mjs | 2 +- backend/scripts/release-bundle.mjs | 4 +- backend/test/catalog-schema-routes.test.ts | 24 ++++++ .../installation-readiness-client.test.ts | 65 +++++++++++++++ docs/install/installation-preflight.md | 19 ++++- docs/install/standalone-manual-en.md | 24 +++++- docs/install/standalone-manual-it.md | 27 +++++-- .../2026-10-06-installation-readiness.md | 36 +++++++++ tools/tht/cmd/tht/installation_apply.go | 3 + ...installation_preflight_integration_test.go | 3 +- tools/tht/internal/installapply/bindings.go | 27 +++++-- .../internal/installapply/import-bindings.mjs | 79 +++++++++++++++++-- tools/tht/internal/installapply/run.go | 71 ++++++++++++++--- tools/tht/internal/installapply/run_test.go | 29 ++++++- 15 files changed, 378 insertions(+), 42 deletions(-) create mode 100644 backend/test/installation-readiness-client.test.ts create mode 100644 docs/reports/2026-10-06-installation-readiness.md diff --git a/PROJECT_STATE.md b/PROJECT_STATE.md index aaf2fa15..2e655d0f 100644 --- a/PROJECT_STATE.md +++ b/PROJECT_STATE.md @@ -36,7 +36,12 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git. Catalog import receipts survive administrative deletion; reruns stop on divergence. Source/native command, authenticated client, concurrent/recovery and real PostgreSQL tests cover this increment. These changes are not included in published preview.5. - Workspace readiness, integrated source/recovery paths, real-host + Ticket #49 adds existing durable Catalog Sync Runs and preprocessing to apply, + preserving human review (exit 3), curated content and Memory. Named one-shot checks + 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 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/publish-installation.mjs b/backend/scripts/publish-installation.mjs index dd04c738..7bf89da0 100644 --- a/backend/scripts/publish-installation.mjs +++ b/backend/scripts/publish-installation.mjs @@ -95,7 +95,7 @@ export async function publishInstallation(options) { await run('docker', ['info', '--format', '{{.OSType}}']); await run('docker', ['buildx', 'version']); const registry = dockerHub(await dockerCredentials(run)); - const hosting = await giteaHosting({ run, repository: options.repository, identity, body: `Installer prerelease for ${identity.platforms.join(', ')}.\n\nImages: docker.io/${identity.namespace}/thothii-core:${identity.version} and docker.io/${identity.namespace}/thothii-frontend:${identity.version}.\n\nDownload the native operator bundle and SHA256SUMS.txt below. This release supplies images, document validation, preflight and non-interactive platform apply. Database binding import, workspace readiness and Windows/Omarchy/macOS acceptance remain subsequent steps. No example databases, credentials or user workspace data are included.` }); + const hosting = await giteaHosting({ run, repository: options.repository, identity, body: `Installer prerelease for ${identity.platforms.join(', ')}.\n\nImages: docker.io/${identity.namespace}/thothii-core:${identity.version} and docker.io/${identity.namespace}/thothii-frontend:${identity.version}.\n\nDownload the native operator bundle and SHA256SUMS.txt below. This release supplies images, document validation, preflight, non-interactive platform apply, prepared binding import and workspace/runtime readiness checks. Destructive schema review remains a human decision. Windows/Omarchy/macOS and human-reviewed question acceptance remain subsequent steps. No example databases, credentials or user workspace data are included.` }); async function prepare() { if (state.assets) { const names = [...identity.platforms.map((platform) => `thothii-${identity.version}-${platform.replace('/', '-')}.tar.gz`), 'SHA256SUMS.txt']; diff --git a/backend/scripts/release-bundle.mjs b/backend/scripts/release-bundle.mjs index b0670227..1c8e59a5 100644 --- a/backend/scripts/release-bundle.mjs +++ b/backend/scripts/release-bundle.mjs @@ -46,8 +46,8 @@ export function prepareBundle({ source, destination, platform, version, revision Source / Sorgente: ${revision} -This prerelease provides images, document/preflight tools and non-interactive platform apply. Database binding import, workspace readiness and Windows/Omarchy/macOS acceptance remain separate steps; this is not a certified complete installation. -Questa prerelease fornisce immagini, preparazione/preflight e avvio non interattivo della piattaforma. Import dei binding, readiness workspace e collaudi Windows/Omarchy/macOS restano passi separati: non è ancora un'installazione completa certificata. +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. Use bin/tht and its sibling bin/tht-workspace-documents together; no Node, Python, Bun or application checkout is required on the consumer host. Windows: use the Linux amd64 bundle inside Ubuntu WSL2, not a native Windows shell. diff --git a/backend/test/catalog-schema-routes.test.ts b/backend/test/catalog-schema-routes.test.ts index 5283c8b4..699aad23 100644 --- a/backend/test/catalog-schema-routes.test.ts +++ b/backend/test/catalog-schema-routes.test.ts @@ -15,10 +15,34 @@ import { import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js"; import type { WorkspaceRegistry, WorkspaceRevision } from "../src/workspaces/registry.js"; import type { WorkspaceDescriptor } from "../src/workspaces/schema.js"; +// @ts-expect-error The native operator embeds this plain ESM client. +import { prepareWorkspace } from "../../tools/tht/internal/installapply/import-bindings.mjs"; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +test("installation retry preserves the durable destructive review and source comments", async () => { + const { app, repository, database, setObserved } = await setup(); + try { + await seedCatalog(repository, database); + const tablesBefore = await repository.listTables(database.id); + setObserved({ schemaVersion: 1, capabilities: { tables: "available", columns: "available", relationships: "available" }, tables: [], columns: [], relationships: [] }); + const started = await app.inject({ method: "POST", url: `/catalog/databases/${database.id}/sync-runs`, payload: { version: database.version, scope: "all", tableIds: [] } }); + const run = await waitFor(repository, started.json().id, "awaiting_confirmation"); + const request = async (path: string, body?: unknown) => { + expect(body).toBeUndefined(); + const response = await app.inject({ method: "GET", url: path }); + return new Response(response.body, { status: response.statusCode, headers: { "content-type": "application/json" } }); + }; + for (let attempt = 0; attempt < 2; attempt++) { + await expect(prepareWorkspace(request, "psd-clinical", revision.commit)).rejects.toMatchObject({ code: "schema_review_required", runId: run.id }); + } + expect(await repository.listTables(database.id)).toEqual(tablesBefore); + expect(await repository.listSyncRuns(database.id)).toHaveLength(1); + expect((await repository.getSyncRun(run.id))?.state).toBe("awaiting_confirmation"); + } finally { await app.close(); } +}); + const workspace: WorkspaceDescriptor = { workspace: { schema_version: 4, id: "psd-clinical", name: "Policlinico San Donato", language: "it" }, dwh: { engine: "postgres", database: "warehouse", schema: "datawarehouse", port: 5432, supported_transports: ["postgres_direct"] }, diff --git a/backend/test/installation-readiness-client.test.ts b/backend/test/installation-readiness-client.test.ts new file mode 100644 index 00000000..6fa3fbf8 --- /dev/null +++ b/backend/test/installation-readiness-client.test.ts @@ -0,0 +1,65 @@ +import { expect, test } from "vitest"; +// The shipped operator client is plain ESM, shared by the embedded command and these API-boundary tests. +// @ts-expect-error JavaScript operator module has no separate declaration file. +import { prepareWorkspace } from "../../tools/tht/internal/installapply/import-bindings.mjs"; + +const revision = "a".repeat(40); + +test.each(["blocked", "failed"])("configured Evidence/index failure (%s) remains a real stop", async state => { + const request = async (path: string, body?: unknown): Promise => { + if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, schemaSyncedVersion: 2, + binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]); + if (path.endsWith("/sync-runs")) return Response.json([]); + if (path.endsWith("/preprocessing")) return Response.json({ state }, { status: body === undefined ? 200 : 422 }); + throw Error("unexpected destructive operation"); + }; + await expect(prepareWorkspace(request, "chinook", revision, async () => {})).rejects.toMatchObject({ code: `preprocessing_${state}` }); +}); + +test("SSH metadata connectivity cannot be mistaken for session transport support", async () => { + const calls: string[] = []; + const request = async (path: string) => { + calls.push(path); + return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, + binding: { transport: "ssh_tunnel" }, workspaceRevision: { commit: revision } }]); + }; + await expect(prepareWorkspace(request, "chinook", revision)).rejects.toMatchObject({ code: "session_transport_unsupported" }); + expect(calls).toEqual(["/catalog/databases"]); +}); +test("a destructive synchronization stops at the existing domain gate without confirmation", async () => { + const calls: string[] = []; + const request = async (path: string) => { + calls.push(path); + if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, + binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]); + if (path.endsWith("/sync-runs")) return Response.json([{ id: "run-id", state: "awaiting_confirmation", scope: "all" }]); + throw Error("unexpected operation"); + }; + await expect(prepareWorkspace(request, "chinook", revision)).rejects.toMatchObject({ code: "schema_review_required", runId: "run-id" }); + expect(calls).toEqual(["/catalog/databases", "/catalog/databases/database-id/sync-runs"]); +}); + +test("fresh additive sync and preprocessing use existing APIs once, then repeat as a no-op", async () => { + const writes: string[] = []; + let synchronized = false, preprocessed = false; + const request = async (path: string, body?: unknown) => { + if (body !== undefined) writes.push(path); + if (path === "/catalog/databases") return Response.json([{ id: "database-id", workspaceId: "chinook", version: 2, + schemaSyncedVersion: synchronized ? 2 : undefined, + binding: { transport: "postgres_direct" }, workspaceRevision: { commit: revision } }]); + if (path === "/catalog/databases/database-id") return Response.json({ version: 2, schemaSyncedVersion: 2 }); + if (path.endsWith("/sync-runs")) { + if (body) { expect(body).toEqual({ version: 2, scope: "all", tableIds: [] }); return Response.json({ id: "run-id", state: "queued", scope: "all" }); } + return Response.json(synchronized ? [{ id: "run-id", state: "succeeded", scope: "all" }] : []); + } + if (path === "/catalog/sync-runs/run-id") { synchronized = true; return Response.json({ id: "run-id", state: "succeeded", scope: "all" }); } + if (path === "/workspaces/chinook/preprocessing") { + if (body) preprocessed = true; + return Response.json({ state: preprocessed ? "ready" : "required" }); + } + throw Error("unexpected operation"); + }; + expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" }); + expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" }); + expect(writes).toEqual(["/catalog/databases/database-id/sync-runs", "/workspaces/chinook/preprocessing"]); +}); diff --git a/docs/install/installation-preflight.md b/docs/install/installation-preflight.md index 4880f95c..301e0843 100644 --- a/docs/install/installation-preflight.md +++ b/docs/install/installation-preflight.md @@ -127,8 +127,19 @@ Reruns compare live configuration and encrypted-store contents, retain equivalen and stop on divergence. No bootstrap document becomes runtime authority. The application tests the imported connection; a successful host probe alone is insufficient. -Success reports `platform_ready: true`, `bindings_ready: true`, `workspace_ready: false`. +Success reports `platform_ready: true`, `bindings_ready: true`, `workspace_ready: true`. The bounded `binding_import` report distinguishes authentication, workspace reconciliation, -binding reconciliation and container connectivity failures. Workspace preprocessing, -model use and final readiness remain separate obligations. Published preview.5 predates -binding import; use a subsequent matching image/operator release for this extension. +binding reconciliation and container connectivity failures. `workspace_preparation` +reports existing Catalog synchronization and preprocessing outcomes. Pending destructive +review returns exit 3 with `schema_review_required`; resolve it in Administration and +repeat apply. Other failures return exit 1. No confirmation, curation overwrite, AI +description generation or Memory clearing is implicit. Current completed stages are reused. + +`runtime_checks` retains workspace diagnostics (DWH, Evidence, Qdrant and embedding), +workflow diagnostics and Pi/default-provider smoke as pending/passed/failed. These +checks use bounded named one-shot containers, preserving cancellation cleanup. The +Pi smoke sends a short provider request with no DWH context and may incur usage. +Runtime failure preserves platform/binding success but leaves workspace readiness false. +`functional_acceptance` stays false: only a real human-reviewed question provides that +acceptance. Published preview.5 predates binding import and readiness; use a subsequent +matching image/operator release for this extension. diff --git a/docs/install/standalone-manual-en.md b/docs/install/standalone-manual-en.md index c3d4457f..aa1cec0e 100644 --- a/docs/install/standalone-manual-en.md +++ b/docs/install/standalone-manual-en.md @@ -223,10 +223,26 @@ secret store. It verifies the remote, branch, revision and exact contents agains prepared plan, without silently retargeting an existing checkout. Database connectivity is tested again by the application in the containers. -`platform_ready: true, bindings_ready: true, workspace_ready: false` confirms the platform, -authentication and database connections. Workspace preprocessing and model checks remain -necessary before a question. The three curated examples remain deferred. This extension -requires a bundle newer than preview.5; preview.5 only certifies platform startup. +Execution continues through existing Catalog Sync Runs and preprocessing, reusing +source comments, curated descriptions and Evidence without AI description generation +or Memory clearing. Evidence may be absent; an invalid configured source blocks +preparation. Completed, current work is not duplicated. SSH supports metadata +diagnostics but not sessions; select direct or REST transport for a usable workspace. + +A destructive synchronization awaiting review returns exit code 3 and +`schema_review_required`, with workspace and run identifiers. Open Administration, +review the diff through its existing domain gate, then repeat `apply`. The installer +never confirms the diff or asks for configuration interactively. + +Before reporting `workspace_ready: true`, it checks DWH connectivity, Evidence, +Qdrant/embedding dimensions, workflow configuration and Pi with the default model. +**The Pi check sends a short provider request and can incur usage charges**; it +contains no DWH data and creates no user session. `runtime_checks` retains each +check as `pending`, `passed` or `failed`. `platform_ready` and `bindings_ready` +remain distinct from full workspace readiness. `functional_acceptance: false` +means a real human-reviewed question still needs testing in the UI. The three +curated examples remain deferred. This extension requires a bundle newer than +preview.5; preview.5 only certifies platform startup. An equivalent rerun does not duplicate bindings or credentials. Administrative changes or deletion stop import with `binding_reconciliation_required`: compare the bootstrap diff --git a/docs/install/standalone-manual-it.md b/docs/install/standalone-manual-it.md index 300df56a..958ddc0e 100644 --- a/docs/install/standalone-manual-it.md +++ b/docs/install/standalone-manual-it.md @@ -231,11 +231,28 @@ secret store esistente. Verifica che remoto, branch, revisione e contenuti coinc con i documenti del piano; non cambia implicitamente un checkout già presente. La connessione al DWH viene riprovata dall'applicazione nei container. -Il risultato `platform_ready: true, bindings_ready: true, workspace_ready: false` -conferma piattaforma, autenticazione e collegamenti database. Preprocessing del -workspace e prova modello rimangono necessari prima di una domanda. I tre database -di esempio restano differiti. Questa estensione richiede un bundle successivo a -preview.5; preview.5 certifica soltanto l'avvio della piattaforma. +L'esecuzione prosegue con i Catalog Sync Runs esistenti e con il preprocessing: +riusa commenti, descrizioni curate ed Evidence senza generare descrizioni con AI +e senza cancellare Memory. Evidence assenti sono ammesse; una fonte configurata +ma non valida blocca la preparazione. Un run già completato e ancora valido non +viene duplicato. SSH supporta i controlli di metadati, ma non le sessioni: per un +workspace utilizzabile scegliere un trasporto diretto o REST. + +Se una sincronizzazione distruttiva richiede revisione, `apply` termina con codice +3 e `schema_review_required`, riportando workspace e run. Aprire Amministrazione, +valutare il diff e decidere nel controllo di dominio esistente, poi ripetere +`apply`. L'installatore non conferma il diff e non chiede parametri interattivi. + +Prima di dichiarare `workspace_ready: true`, esegue anche i controlli DWH, +Evidence, Qdrant/dimensioni embedding, configurazione del workflow e una prova Pi +sul provider/modello predefinito. **La prova invia una breve richiesta al provider +e può consumare credito**; non contiene dati DWH e non crea una sessione utente. +`runtime_checks` mostra ogni controllo come `pending`, `passed` o `failed`. +`platform_ready` e `bindings_ready` rimangono distinti dalla readiness completa. +`functional_acceptance: false` ricorda che la domanda reale con revisione umana +va ancora collaudata nell'interfaccia. I tre database di esempio restano differiti. +Questa estensione richiede un bundle successivo a preview.5; preview.5 certifica +soltanto l'avvio della piattaforma. Un secondo avvio non duplica binding o credenziali. Se un amministratore ha modificato o eliminato un binding, il codice `binding_reconciliation_required` ferma l'import: diff --git a/docs/reports/2026-10-06-installation-readiness.md b/docs/reports/2026-10-06-installation-readiness.md new file mode 100644 index 00000000..88985568 --- /dev/null +++ b/docs/reports/2026-10-06-installation-readiness.md @@ -0,0 +1,36 @@ +# Installation workspace readiness — T07/#49 + +Implemented on `codex/guided-standalone-install`, following binding import T06. + +`installation apply` now calls existing authenticated Catalog Sync Runs and +workspace preprocessing services. It polls existing work, skips current completed +preparation and never confirms destructive schema changes. Pending human review +returns exit 3, the workspace/run identifier and an Administration instruction. +It does not generate AI descriptions, clear Memory or overwrite curated content. +Optional Evidence remains optional; invalid configured Evidence blocks readiness. + +Named, bounded one-shot containers run the existing workspace, workflow and +Pi/default-provider diagnostics. Reports preserve pending/failed runtime checks +and distinguish platform, bindings, workspace readiness and functional acceptance. +A real human-reviewed question remains manual acceptance. The Pi smoke sends a +short provider request without DWH context and can incur usage charges. + +## Verification + +- Focused backend tests: 55 passed, including actual Catalog APIs preserving the + same destructive review and source comments across two installation retries. +- Full backend suite on Node 24.16.0: 1,436 passed, 41 skipped, one failure in the + existing concurrent OIDC state-creation test. Its isolated 48-test group passed + on immediate rerun. Repeating the full suite with two workers passed all 1,437 + tests (41 skipped, 114 files passed). +- TypeScript typecheck and full Go suite passed. +- Rebuilt native macOS arm64 bundle: public prepare/validate/plan/apply/retry test + passed with closed stdin and no language runtimes in PATH. Docker is an external + process fixture in that test, so this is not a real OS/platform acceptance. +- Strict documentation build passed; release-bundle packaging regression passed. +- Standards and Spec reviews found no actionable violations. + +The current public preview.5 predates this code. These checks do not constitute a +published-image consumer proof, a real provider acceptance, or Windows/WSL2, +Omarchy or macOS manual acceptance. Integrated source mode and comprehensive +interruption recovery are subsequent T08/T09 increments. diff --git a/tools/tht/cmd/tht/installation_apply.go b/tools/tht/cmd/tht/installation_apply.go index 442085f1..ea0b73f7 100644 --- a/tools/tht/cmd/tht/installation_apply.go +++ b/tools/tht/cmd/tht/installation_apply.go @@ -92,6 +92,9 @@ func installationApplyCommand(ctx context.Context, installationPath string, args result, err := installapply.Run(ctx, installapply.Request{PlanPath: planPath, InstallationPath: installationPath}, runner, check) write(result) if err != nil { + if result.WorkspacePreparation != nil && result.WorkspacePreparation.Code == "schema_review_required" { + return 3 + } return 1 } return 0 diff --git a/tools/tht/cmd/tht/installation_preflight_integration_test.go b/tools/tht/cmd/tht/installation_preflight_integration_test.go index 36f187c4..5b0f1276 100644 --- a/tools/tht/cmd/tht/installation_preflight_integration_test.go +++ b/tools/tht/cmd/tht/installation_preflight_integration_test.go @@ -112,6 +112,7 @@ container) :;; *) exit 1;;`, 1) script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *' ps '*) true;; *) false;; esac; then printf '%s\n' '[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]'; else printf '%s\n'`, 1) script = strings.Replace(script, "else printf '%s\\n'", `elif case "$*" in *'protected input arrives only through stdin'*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"bindings_ready","completed":1}'; else printf '%s\n'`, 1) + script = strings.Replace(script, "elif case", `elif case "$*" in *"await importPreparedBindings(undefined, 'workspaces');"*) true;; *) false;; esac; then while IFS= read -r line; do :; done; printf '%s\n' '{"ok":true,"code":"workspaces_prepared","completed":1}'; elif case "$*" in *'/app/backend/dist/operator-command.js'*) true;; *) false;; esac; then printf '%s\n' '{"ready":true}'; elif case`, 1) write(filepath.Join(root, "docker"), []byte(script)) _ = os.Chmod(filepath.Join(root, "docker"), 0o700) planPath := filepath.Join(installation, "plan.json") @@ -143,7 +144,7 @@ container) :;; PlatformReady bool `json:"platform_ready"` WorkspaceReady bool `json:"workspace_ready"` } - if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || result.WorkspaceReady || strings.Contains(text, "PRIVATE_") { + if code != 0 || json.Unmarshal([]byte(text), &result) != nil || !result.PlatformReady || !result.WorkspaceReady || strings.Contains(text, "PRIVATE_") { t.Fatalf("noninteractive apply attempt %d: %s", attempt, text) } } diff --git a/tools/tht/internal/installapply/bindings.go b/tools/tht/internal/installapply/bindings.go index 8dd6e9b2..2280ffc7 100644 --- a/tools/tht/internal/installapply/bindings.go +++ b/tools/tht/internal/installapply/bindings.go @@ -24,11 +24,14 @@ import ( var bindingClientModule string var bindingClient = bindingClientModule + "\nawait importPreparedBindings();\n" +var readinessClient = bindingClientModule + "\nawait importPreparedBindings(undefined, 'workspaces');\n" type BindingReport struct { - OK bool `json:"ok"` - Code string `json:"code"` - Completed int `json:"completed"` + OK bool `json:"ok"` + Code string `json:"code"` + Completed int `json:"completed"` + WorkspaceID string `json:"workspaceId,omitempty"` + RunID string `json:"runId,omitempty"` } // Secrets travel only over the child pipe; they never enter argv, generated assets or journals. @@ -122,19 +125,29 @@ func bindingPayload(plan preflight.Plan) ([]byte, error) { } func importBindings(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte) (BindingReport, error) { - bound, cancel := context.WithTimeout(ctx, 15*time.Minute) + return runPreparedClient(ctx, plan, runner, payload, false) +} + +func runPreparedClient(ctx context.Context, plan preflight.Plan, runner compose.Runner, payload []byte, prepare bool) (BindingReport, error) { + client, success, timeout := bindingClient, "bindings_ready", 15*time.Minute + codes := []string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"} + if prepare { + client, success, timeout = readinessClient, "workspaces_prepared", 60*time.Minute + codes = append(codes, "workspaces_prepared", "workspace_preparation_failed", "session_transport_unsupported", "schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending") + } + bound, cancel := context.WithTimeout(ctx, timeout) defer cancel() name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-bindings") if err != nil { return BindingReport{Code: "binding_import_failed"}, err } result, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name, - "--entrypoint", "node", "core", "--input-type=module", "-e", bindingClient), bytes.NewReader(payload)) + "--entrypoint", "node", "core", "--input-type=module", "-e", client), bytes.NewReader(payload)) var report BindingReport - if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains([]string{"bindings_ready", "authentication_required", "workspace_reconciliation_required", "binding_reconciliation_required", "container_connection_failed", "binding_import_failed"}, report.Code) { + if json.Unmarshal([]byte(result.Stdout), &report) != nil || !slices.Contains(codes, report.Code) { return BindingReport{Code: "binding_import_failed"}, errors.New("Binding import did not return a valid report") } - if err != nil || result.ExitCode != 0 || !report.OK || report.Code != "bindings_ready" || report.Completed < 1 { + if err != nil || result.ExitCode != 0 || !report.OK || report.Code != success || report.Completed < 1 { return report, errors.New("Binding import stopped; reconcile the prepared documents with application administration and repeat planning") } return report, nil diff --git a/tools/tht/internal/installapply/import-bindings.mjs b/tools/tht/internal/installapply/import-bindings.mjs index 96c086f5..c75823aa 100644 --- a/tools/tht/internal/installapply/import-bindings.mjs +++ b/tools/tht/internal/installapply/import-bindings.mjs @@ -1,8 +1,63 @@ // Fixed client executed inside the released core; protected input arrives only through stdin. -export async function importPreparedBindings(base = "http://core:8787") { +const stopped = (code, runId) => Object.assign(new Error(code), { code, ...(runId ? { runId } : {}) }); +const jsonResponse = async (response, code) => { + if (!response.ok) throw stopped(code); + return response.json(); +}; + +export async function prepareWorkspace(request, workspaceId, revision, pause = () => new Promise(resolve => setTimeout(resolve, 2000))) { + const databases = await jsonResponse(await request("/catalog/databases"), "workspace_preparation_failed"); + const database = databases.find(item => item.workspaceId === workspaceId); + if (!database || database.workspaceRevision?.commit !== revision) throw stopped("workspace_reconciliation_required"); + if (database.binding.transport === "ssh_tunnel") throw stopped("session_transport_unsupported"); + const runs = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`), "schema_sync_failed"); + let active = runs.find(run => ["queued", "running", "awaiting_confirmation", "applying"].includes(run.state)); + const waitForSync = async run => { + for (let attempt = 0; attempt < 900; attempt++) { + if (run.state === "awaiting_confirmation") throw stopped("schema_review_required", run.id); + if (run.state === "succeeded") return; + if (!["queued", "running", "applying"].includes(run.state)) throw stopped("schema_sync_failed", run.id); + await pause(); + run = await jsonResponse(await request(`/catalog/sync-runs/${run.id}`), "schema_sync_failed"); + } + throw stopped("schema_sync_pending", run.id); + }; + if (active) await waitForSync(active); + let current = active + ? await jsonResponse(await request(`/catalog/databases/${database.id}`), "schema_sync_failed") : database; + if (current.version !== database.version) throw stopped("workspace_reconciliation_required"); + if (current.schemaSyncedVersion !== current.version) { + active = await jsonResponse(await request(`/catalog/databases/${database.id}/sync-runs`, { + version: database.version, scope: "all", tableIds: [], + }), "schema_sync_failed"); + await waitForSync(active); + current = await jsonResponse(await request(`/catalog/databases/${database.id}`), "schema_sync_failed"); + if (current.version !== database.version || current.schemaSyncedVersion !== current.version) throw stopped("workspace_reconciliation_required"); + } + const path = `/workspaces/${encodeURIComponent(workspaceId)}/preprocessing`; + let state = await jsonResponse(await request(path), "preprocessing_failed"); + let started = false; + for (let attempt = 0; attempt < 900; attempt++) { + if (state.state === "ready") return { workspaceId, state: "ready" }; + if (state.state === "blocked") throw stopped("preprocessing_blocked"); + if (["required", "failed"].includes(state.state) && !started) { + started = true; + await jsonResponse(await request(path, {}), "preprocessing_failed"); + } else if (state.state !== "running") throw stopped("preprocessing_failed"); + await pause(); + state = await jsonResponse(await request(path), "preprocessing_failed"); + } + throw stopped("preprocessing_pending"); +} + +const readinessCodes = new Set(["workspace_preparation_failed", "workspace_reconciliation_required", "session_transport_unsupported", + "schema_review_required", "schema_sync_failed", "schema_sync_pending", "preprocessing_failed", "preprocessing_blocked", "preprocessing_pending"]); + +export async function importPreparedBindings(base = "http://core:8787", mode = "bindings") { let cookie = "", csrf = "", origin = "", completed = 0, code = "authentication_required"; +let workspaceId, runId; const request = async (path, body) => fetch(base + path, { - method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(180000), + method: body === undefined ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(mode === "workspaces" ? 1800000 : 180000), headers: { "content-type": "application/json", origin, ...(cookie ? { cookie } : {}), ...(csrf ? { "x-thothii-csrf": csrf } : {}) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); @@ -22,6 +77,13 @@ try { if (!source.ok) throw Error(); const { revision } = await source.json(); for (const entry of prepared.databases) { + if (mode === "workspaces") { + workspaceId = entry.configuration.workspaceId; + code = "workspace_preparation_failed"; + await prepareWorkspace(request, workspaceId, revision); + completed++; + continue; + } code = "binding_import_failed"; const response = await request("/installation/bindings", { ...entry, revision }); if (response.status === 409) code = "binding_reconciliation_required"; @@ -31,10 +93,17 @@ try { if (value.connectionStatus !== "reachable" || !["applied", "unchanged"].includes(value.status)) throw Error(); completed++; } - code = "bindings_ready"; -} catch { process.exitCode = 1; } + workspaceId = undefined; + code = mode === "workspaces" ? "workspaces_prepared" : "bindings_ready"; +} catch (error) { + if (readinessCodes.has(error?.code)) { + code = error.code; + if (/^[a-f0-9-]{36}$/.test(error.runId ?? "")) runId = error.runId; + } + process.exitCode = 1; +} finally { if (cookie && csrf) { try { await request("/auth/logout", {}); } catch {} } - process.stdout.write(JSON.stringify({ ok: code === "bindings_ready", code, completed })); + process.stdout.write(JSON.stringify({ ok: ["bindings_ready", "workspaces_prepared"].includes(code), code, completed, workspaceId, runId })); } } diff --git a/tools/tht/internal/installapply/run.go b/tools/tht/internal/installapply/run.go index 52058387..ab02414a 100644 --- a/tools/tht/internal/installapply/run.go +++ b/tools/tht/internal/installapply/run.go @@ -24,15 +24,22 @@ import ( ) type Request struct{ PlanPath, InstallationPath string } +type RuntimeCheck struct { + ID string `json:"id"` + Status string `json:"status"` +} type Result struct { - SchemaVersion int `json:"schema_version"` - PlatformReady bool `json:"platform_ready"` - WorkspaceReady bool `json:"workspace_ready"` - BindingsReady bool `json:"bindings_ready"` - BindingImport *BindingReport `json:"binding_import,omitempty"` - Stage string `json:"stage"` - Action string `json:"action"` - Journal string `json:"journal,omitempty"` + SchemaVersion int `json:"schema_version"` + PlatformReady bool `json:"platform_ready"` + WorkspaceReady bool `json:"workspace_ready"` + BindingsReady bool `json:"bindings_ready"` + BindingImport *BindingReport `json:"binding_import,omitempty"` + WorkspacePreparation *BindingReport `json:"workspace_preparation,omitempty"` + RuntimeChecks []RuntimeCheck `json:"runtime_checks"` + FunctionalAcceptance bool `json:"functional_acceptance"` + Stage string `json:"stage"` + Action string `json:"action"` + Journal string `json:"journal,omitempty"` } type journal struct { SchemaVersion int `json:"schema_version"` @@ -49,6 +56,9 @@ type Check func(context.Context, preflight.Plan) error func Run(ctx context.Context, request Request, runner compose.Runner, check Check) (result Result, err error) { result = Result{SchemaVersion: 1, Stage: "plan", Action: "Produce a current plan from complete prepared documents."} + for _, id := range []string{"workspace-test", "workflow-doctor", "pi-test"} { + result.RuntimeChecks = append(result.RuntimeChecks, RuntimeCheck{ID: id, Status: "pending"}) + } fail := func(stage, action string) (Result, error) { result.Stage = stage result.Action = action @@ -208,20 +218,61 @@ func Run(ctx context.Context, request Request, runner compose.Runner, check Chec result.BindingsReady = err == nil return err }}, + {"workspace-preparation", func() error { + report, err := runPreparedClient(ctx, plan, runner, payload, true) + result.WorkspacePreparation = &report + return err + }}, + } + for index, check := range result.RuntimeChecks { + action := check.ID + stages = append(stages, struct { + name string + run func() error + }{action, func() error { + err := runtimeDiagnostic(ctx, plan, runner, action) + result.RuntimeChecks[index].Status = "passed" + if err != nil { + result.RuntimeChecks[index].Status = "failed" + } + return err + }}) } // Reconcile each idempotent stage against Docker/migration authority on every retry. // A journal entry alone is never proof that a container or migration still exists. for _, stage := range stages { if err := operation(stage.name, stage.run); err != nil { + if result.WorkspacePreparation != nil && result.WorkspacePreparation.Code == "schema_review_required" { + return fail(stage.name, "Review the pending schema synchronization in application Administration, then repeat apply. No destructive change was confirmed by the installer.") + } return fail(stage.name, err.Error()) } } result.PlatformReady = true - result.Stage = "bindings-ready" - result.Action = "Platform and prepared database bindings are ready. Complete workspace readiness before a human-reviewed question." + result.WorkspaceReady = true + result.Stage = "workspace-ready" + result.Action = "Platform, workspace preparation and runtime checks passed. Open the application for the manual human-reviewed question." return result, nil } +func runtimeDiagnostic(ctx context.Context, plan preflight.Plan, runner compose.Runner, action string) error { + bound, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + name, err := compose.NewOneShotContainerName(plan.Installation.ProjectName() + "-readiness") + if err != nil { + return err + } + value, err := runner.Run(bound, plan.Installation.ComposeArgs("run", "--rm", "-T", "--no-deps", "--pull", "never", "--name", name, + "--entrypoint", "node", "core", "/app/backend/dist/operator-command.js", action), nil) + var report struct { + Ready bool `json:"ready"` + } + if err != nil || value.ExitCode != 0 || json.Unmarshal([]byte(value.Stdout), &report) != nil || !report.Ready { + return errors.New("Runtime diagnostic failed; inspect application diagnostics and correct the prepared configuration") + } + return nil +} + func installAssets(installation config.Installation, plan preflight.Plan) error { names := make([]string, 0, len(plan.Release.Files)) for name := range plan.Release.Files { diff --git a/tools/tht/internal/installapply/run_test.go b/tools/tht/internal/installapply/run_test.go index 3b7894ec..3e4c7497 100644 --- a/tools/tht/internal/installapply/run_test.go +++ b/tools/tht/internal/installapply/run_test.go @@ -86,7 +86,7 @@ type dockerFixture struct { func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) (compose.Result, error) { if input != nil { - if args[len(args)-1] != bindingClient { + if args[len(args)-1] != bindingClient && args[len(args)-1] != readinessClient { return compose.Result{}, fmt.Errorf("unexpected interactive input") } command := strings.Join(args, " ") @@ -101,6 +101,12 @@ func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) ( return compose.Result{}, fmt.Errorf("file newline leaked into scalar credential") } r.calls = append(r.calls, append([]string{}, args...)) + if args[len(args)-1] == readinessClient { + if r.fail == "schema-review" { + return compose.Result{ExitCode: 1, Stdout: `{"ok":false,"code":"schema_review_required","completed":0,"workspaceId":"chinook","runId":"e9ca48f6-0a09-49bd-a003-04f9d518d702"}`}, nil + } + return compose.Result{Stdout: `{"ok":true,"code":"workspaces_prepared","completed":1}`}, nil + } return compose.Result{Stdout: `{"ok":true,"code":"bindings_ready","completed":1}`}, nil } r.calls = append(r.calls, append([]string{}, args...)) @@ -137,6 +143,9 @@ func (r *dockerFixture) Run(_ context.Context, args []string, input io.Reader) ( if strings.Contains(line, " ps ") { return compose.Result{Stdout: `[{"Service":"core","State":"running","Health":"healthy"},{"Service":"frontend","State":"running","Health":"healthy"},{"Service":"catalog-db","State":"running","Health":"healthy"},{"Service":"qdrant","State":"running","Health":"healthy"},{"Service":"embedding","State":"running","Health":"healthy"},{"Service":"embedding-model-init","State":"exited","ExitCode":0}]`}, nil } + if strings.Contains(line, "/app/backend/dist/operator-command.js") { + return compose.Result{Stdout: `{"ready":true}`}, nil + } return compose.Result{Stdout: `{"ok":true}`}, nil } @@ -162,7 +171,7 @@ func TestApplyReleasedPlanWithoutInputAndRepeatPreservesData(t *testing.T) { if err != nil { t.Fatal(err) } - if !result.PlatformReady || result.WorkspaceReady { + if !result.PlatformReady || !result.WorkspaceReady || result.Stage != "workspace-ready" { t.Fatalf("wrong readiness: %+v", result) } } @@ -185,6 +194,22 @@ func TestApplyReleasedPlanWithoutInputAndRepeatPreservesData(t *testing.T) { } } } + +func TestWorkspaceReviewAndRuntimeFailureNeverClaimWorkspaceReady(t *testing.T) { + for _, stage := range []string{"schema-review", "operator-command.js pi-test"} { + t.Run(stage, func(t *testing.T) { + path, p := fixture(t) + r := &dockerFixture{fail: stage} + 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.PlatformReady || !result.BindingsReady || result.WorkspaceReady { + t.Fatalf("readiness failure hidden: %+v %v", result, err) + } + if stage == "schema-review" && (result.WorkspacePreparation == nil || result.WorkspacePreparation.Code != "schema_review_required") { + t.Fatalf("human gate lost: %+v", result) + } + }) + } +} func flatten(calls [][]string) []string { out := []string{} for _, c := range calls {