Author SHA1 Message Date
CodexandClaude Opus 5.5 0adda6e8af docs: add complete Archify architecture diagram set
Thirteen source-backed interactive diagrams in docs/architecture with an
index page (thothii-diagrams.html): runtime and deployment architecture,
module tree, F1-F8 workflow, session and catalog-sync lifecycles,
new-question, gate round-trip, resume and OIDC sequences, session runtime
classes, metadata dataflow and Metadata Catalog ERD. Replaces the old
thothii-core sequence diagram.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:24:07 +02:00
CodexandClaude Opus 5.5 31e6d3a162 docs: regenerate runtime architecture diagram with Archify 3.1
Source-backed Italian map of the NL→SQL runtime (frontend, backend,
Pi, tht-gate, tht CLI and their stores), with file/line evidence
pinned to c77957af.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 11:01:04 +02:00
CodexandClaude Opus 5.5 c77957af93 merge: bring main (domain-docs retrofit) into guided standalone install
Drop the local duplicate ETL commit (already on main as 3222713e), keep
CONTEXT.md deleted and move its installation terms into GLOSSARY.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:36:16 +02:00
CodexandClaude Haiku 5.5 9e8ffe2dc5 fix: restart long-running local ThothII services after Docker or host restart
Set restart: unless-stopped on catalog-db, embedding, core, frontend and qdrant
in the local overlay, so the stack comes back after a Docker Desktop or Mac
restart unless it was stopped explicitly. One-shot services and
workspace-maintenance keep restart: "no".

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-17 19:10:26 +02:00
CodexandClaude Haiku 5.5 6578578acb fix: delegate run-stack.sh to the supported tht start path
The direct Compose path did not render model projections or PSD secrets, so
embedding-model-init failed on every run. run-stack.sh now execs
scripts/thothii-local.sh start, which uses tht start.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-17 18:31:48 +02:00
CodexandClaude Haiku 5.5 b17d41802d feat: add local start/stop/status script for ThothII via tht
Wraps tht start/stop/status for the PSD installation. Before starting it
stops other thothii-* Compose projects (stop only, volumes kept) and fails
early if the published ports 8080, 8787 or 6333 are held by a non-Docker
process. It warns, without stopping them, when PeopleKitchens containers run.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-17 18:22:19 +02:00
Codex 40b524e393 docs: record published installer and recovery acceptance results 2026-10-06 19:24:55 +02:00
Codex 977cf0e978 fix: persist local session identity on the writable session volume 2026-10-06 19:11:15 +02:00
Codex af6cf88b5a feat: recover interrupted installation preparation safely 2026-10-06 19:02:01 +02:00
Codex 5c05778614 feat: support explicit source bundles through the common installer 2026-10-06 18:31:23 +02:00
Codex 785d96ea50 feat: prepare installation workspaces through existing readiness services 2026-10-06 18:23:24 +02:00
Codex af4c7b5df9 feat: import prepared Catalog bindings through authenticated services 2026-10-06 18:04:07 +02:00
Codex d720da721b docs: record verified published platform installation trial 2026-10-06 16:22:53 +02:00
Codex 24b03d4caf fix: reject invalid authentication origin authorities 2026-10-06 16:12:32 +02:00
Codex 2aac228cdc fix: validate maintenance profiles and canonical local auth origins 2026-10-06 16:09:39 +02:00
Codex d79e261e09 fix: run catalog migrations without Pi home initialization 2026-10-06 15:49:42 +02:00
Codex 8b9a086fd6 feat: apply sealed installation plans without interactive setup 2026-10-06 15:45:18 +02:00
Codex c3c9f509bf test: prepare Chinook database for installation acceptance without Evidence 2026-09-28 18:25:33 +02:00
Codex 931ac2fad4 docs: record verified Docker Hub installation prerelease 2026-09-28 17:54:05 +02:00
Codex ec0421e9fd feat: publish verified installation images and native release bundles 2026-09-28 17:46:09 +02:00
Codex 55f3569e55 feat(cli): validate prerequisites and seal installation plans 2026-09-28 17:03:25 +02:00
Codex b9c3369e7b feat(cli): prepare and validate application documents offline 2026-09-28 16:33:07 +02:00
Codex 64e6b9664a feat(cli): prepare and validate workspace documents offline
Reuse the runtime catalog and workspace parsers in a standalone helper paired with tht. Add document templates, safe diagnostics, local Evidence checks, native bundle builds, shared CLI fixtures and IT/EN preparation guides. Record the approved document-first specification and ticket breakdown. Refs #43.
2026-09-28 15:35:25 +02:00
Codex 67ee52624c wip: guided standalone installation and workspace checks 2026-09-26 16:41:15 +02:00
168 changed files with 188678 additions and 8803 deletions
+13
View File
@@ -558,6 +558,19 @@ servizi applicativi locali. DWH e provider LLM restano esterni.
Le attività iniziali che rendono disponibile un'installazione: verifica dell'host, configurazione,
credenziali protette e avvio. Non è un installer dell'applicazione.
**Installation preparation**:
La compilazione dei documenti che descrivono workspace e parametri dell'installazione, prima di
applicarli.
**Installation validation**:
La verifica ripetibile di completezza e coerenza dei documenti di installazione, che distingue ciò
che è verificabile prima dell'avvio da ciò che richiede l'applicazione in esecuzione.
**Installation execution**:
L'applicazione dei documenti verificati per predisporre e avviare ThothII, senza chiedere nuovi
parametri all'operatore.
_Avoid_: installazione interattiva
**Platform acceptance**:
La verifica che un'installazione si predisponga e si avvii su una combinazione di sistema
operativo, architettura e runtime. È distinta dalla verifica funzionale con DWH e LLM.
+66 -7
View File
@@ -1,10 +1,60 @@
# Project state
Updated: 2026-09-27. This is a current snapshot, not a release diary. Stable commands
Updated: 2026-10-06. This is a current snapshot, not a release diary. Stable commands
and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git.
## Current contracts
- Document-first installation ticket #43 provides offline `tht workspace prepare`
and `tht workspace validate` through a native two-executable bundle. Build and
test instructions are in [the host CLI guide](tools/tht/README.md). Local validation
reuses runtime workspace/catalog parsers and explicitly defers runtime Evidence,
database binding and readiness checks. Ticket #44 adds `tht installation prepare`,
explicit `installation credentials`, and `installation validate --workspaces PATH`
for protected application documents, canonical model settings and schema-v1
database bootstrap inputs. These commands do not start services or import Catalog
bindings. Ticket #45 adds host `installation preflight` and `installation plan`
with release/image checks, canonical external diagnostics and private input seals;
see [the preflight reference](docs/install/installation-preflight.md).
Ticket #46 adds the maintainer release producer and the first public
[Linux amd64 prerelease](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1),
with Docker Hub core/frontend images and a downloadable native operator bundle.
See [publication instructions](docs/install/publishing-images.md) and
[verification evidence](docs/reports/2026-09-28-installation-prerelease.md).
Ticket #47 delivers `installation apply --plan PATH`: fresh checks, immutable
pulls, local operator UID, resumable volume initialization, Catalog/Memory migrations
and service/authentication health. Tests cover the public native command with closed
stdin and Linux volume/private-secret behavior using published images. Platform success
explicitly leaves workspace readiness false. The earlier
[preview.5 release](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5)
publishes amd64/arm64 images and native bundles. Its unmodified arm64 archive passed
apply/retry, UI/admin login and live user revocation in a Linux consumer without host
language runtimes; see [verification evidence](docs/reports/2026-10-06-installation-apply.md).
Ticket #48 now adds authenticated binding import after platform health: exact prepared
repository verification, ordinary local admin login/CSRF, existing encrypted secret
storage, optimistic versions and container-side Catalog connection tests. Durable
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 included from preview.6 onward.
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 is included from preview.6 onward.
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. Ticket #51 adds guarded
interrupted preprocessing recovery, fencing of delayed/orphan workers and preserved
pending schema review even during binding retry. The current
[preview.7 release](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.7)
includes these increments and fixes local session identity persistence for the
mapped operator UID. It publishes amd64/arm64 images and native bundles, with
anonymous pull and image smoke checks. See the
[completion and acceptance report](docs/reports/2026-10-06-installation-completion.md)
for consumer results and the next user steps. Real-host acceptance and curated
examples remain pending; no Windows/Omarchy/macOS acceptance is claimed.
- React supports full/embedded rendering independently of local/OIDC/upstream auth,
with EN/IT UI and immutable session interaction language. See
[application shell](docs/architecture/application-shell.md) and
@@ -29,11 +79,13 @@ and invariants are in [AGENTS.md](AGENTS.md); prior snapshots remain in Git.
## Installation and workspace boundaries
Fresh standalone installations follow the manual terminal procedures in
Fresh standalone installations follow the document-first procedures in
[Italian](docs/install/standalone-manual-it.md) or
[English](docs/install/standalone-manual-en.md), without an installer or launcher.
[English](docs/install/standalone-manual-en.md). The guides retain a separate manual
source path; do not mix its setup commands with a released-bundle installation.
The [Compose reference](docs/operations/compose-reference.md) is for maintainers,
not another quick start. Catalog and Memory migrations are explicit.
not another quick start. Document-first apply runs Catalog and Memory migrations
before bringing up application services.
Descriptors, authentication, provider credentials, certificates and runtime bindings
stay in protected installation-local paths. Do not copy secrets into examples or
@@ -72,8 +124,15 @@ A later deployment does not prove every earlier acceptance item passed.
## Remaining acceptance and design gates
- Fresh-machine Mac, Windows/WSL2 and Linux installation acceptance, including real
DWH/model endpoints, remains a separate operator exercise.
- The first installation acceptance uses an ad hoc
[Chinook workspace without Evidence](docs/testing/chinook-installation-smoke.md),
backed by a separate local PostgreSQL test container. Its fixture import,
read-only credentials, offline validation, platform apply, binding import and full
workspace readiness were verified using source and published preview.7 bundles.
A human-reviewed question and Windows/WSL2 host acceptance remain pending. Evidence
acceptance and the three curated examples are separate later work.
- Fresh-machine installation acceptance, including real DWH/model endpoints, remains
a separate operator exercise, ordered Windows/WSL2, then Omarchy, then macOS.
- Real IdP/portal login, logout, embedded interaction and PSD semantic acceptance
follow the [manual matrix](docs/testing/authentication-manual-acceptance.md) and
delivery reports; synthetic tests do not close them.
@@ -90,7 +149,7 @@ A later deployment does not prove every earlier acceptance item passed.
## Documentation maintenance
MkDocs publishes only 20 product/operator pages and five approved assets.
MkDocs publishes only 22 product/operator pages and five approved assets.
Architecture, contracts, ADRs, plans, research, tests and release evidence are
excluded from HTML and search. The repository itself is public: editorial exclusion
is not confidentiality.
+5 -4
View File
@@ -34,11 +34,12 @@ for the executed consolidation and the inventory of historical sources retained
## Docker Compose and installation
For a fresh installation, follow the complete manual procedure in
For a fresh installation, follow the guided terminal procedure in
[Italian](docs/install/standalone-manual-it.md) or
[English](docs/install/standalone-manual-en.md). Configure protected files first;
then run the documented build, explicit migrations and startup commands with the
same installation descriptor and Compose project. There is no installer or launcher.
[English](docs/install/standalone-manual-en.md). The single
`tht setup --complete` command validates protected files, builds the images, runs
Catalog migration, starts the stack and imports the configured workspace repository.
There is no graphical installer or native launcher.
The mandatory stack includes frontend, core, PostgreSQL catalog, Qdrant, Ollama
and the embedding initializer. DWH and LLM endpoints remain external dependencies.
+609
View File
@@ -6,11 +6,13 @@
"": {
"name": "thothii-backend",
"dependencies": {
"@aws-sdk/client-s3": "3.1141.0",
"@fastify/cookie": "11.1.2",
"@fastify/cors": "^11.2.0",
"@fastify/rate-limit": "11.2.0",
"@types/pg": "^8.20.3",
"fastify": "^5.0.0",
"ipaddr.js": "2.4.0",
"kysely": "^0.29.5",
"libphonenumber-js": "1.13.12",
"openid-client": "6.8.5",
@@ -23,11 +25,320 @@
"@testcontainers/postgresql": "^12.1.0",
"@types/node": "24.13.3",
"@types/validator": "13.15.10",
"bun": "1.4.2",
"tsx": "^4.19.0",
"typescript": "^5.6.0",
"vitest": "^2.1.0"
}
},
"node_modules/@aws-sdk/checksums": {
"version": "3.1001.1",
"resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1001.1.tgz",
"integrity": "sha512-x12Q17KYlJAd3nKf8LV5LV0vt8sh8/6YfQLGPtrGnQf/tW4jqxPGq5GPpuVitpQYM3eUR4XB7CbxZf751NMbLw==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/client-s3": {
"version": "3.1141.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1141.0.tgz",
"integrity": "sha512-uOVH37xGLenAdJkCPCin/JJG2PgWrFcSsDnQ9+C9Zq8N9Oalo5ol4xmn5fG28iWAlA/b/9boQZgHbMh+UsIhcg==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/checksums": "^3.1001.1",
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/credential-provider-node": "^3.972.84",
"@aws-sdk/middleware-sdk-s3": "^3.972.77",
"@aws-sdk/signature-v4-multi-region": "^3.996.47",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/fetch-http-handler": "^5.8.0",
"@smithy/node-http-handler": "^4.12.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/core": {
"version": "3.978.1",
"resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.978.1.tgz",
"integrity": "sha512-LbY9aGsEiznDWmUc30Nwv3aIX/+dbwTx8KfS0yOC3NPYMO+O91e6jkT1azf34FwjOndq8/Q+RcVVZz5xnerwdg==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/types": "^3.974.6",
"@aws-sdk/xml-builder": "^3.972.41",
"@aws/lambda-invoke-store": "^0.3.0",
"@smithy/core": "^3.35.0",
"@smithy/signature-v4": "^5.7.3",
"@smithy/types": "^4.19.0",
"bowser": "^2.11.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-env": {
"version": "3.972.72",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.72.tgz",
"integrity": "sha512-xTKO/FWJPozTIXbozVnVGoNBhaGba8TBcx+KyUjRVeOlXE+dUc7GTR1cLvu0uTdIdmemzaFbqqCshXeZA1fZew==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-http": {
"version": "3.972.74",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.74.tgz",
"integrity": "sha512-u91E/hT8f4d1xy0Jl7VG4nVKJ3lxbrZkoBTeSVoJdWBiSEUMwMS/9+e0H/aJVQV//Lt5wuzP+E69v4aRSsNTmw==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/fetch-http-handler": "^5.8.0",
"@smithy/node-http-handler": "^4.12.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-ini": {
"version": "3.973.17",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.17.tgz",
"integrity": "sha512-ged4KXdBkvIC81bLvNHHuQKdKak/VXhQTR1NWYTTqW0474nlmsxy9O/vlgTIohDDWH3xpBdtVMZRyjb+DnocDA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/credential-provider-env": "^3.972.72",
"@aws-sdk/credential-provider-http": "^3.972.74",
"@aws-sdk/credential-provider-login": "^3.972.79",
"@aws-sdk/credential-provider-process": "^3.972.72",
"@aws-sdk/credential-provider-sso": "^3.973.16",
"@aws-sdk/credential-provider-web-identity": "^3.972.78",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/credential-provider-imds": "^4.5.2",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-login": {
"version": "3.972.79",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.79.tgz",
"integrity": "sha512-L+Z85anONJd8MaiuraO4wRxATCdEejBZ3K3eymzWI5JPXa9sOS9CkIm72PBKqXKX+Z9p9NGMX5AIMXm0LEflgw==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-node": {
"version": "3.972.84",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.84.tgz",
"integrity": "sha512-oHt854odINVwzwsh+c5x69j0ajm4DbqqqVJ+O1ECsCIZeMDAbzFpXItaqP7UZstJj/ATdTk/KFSH0LaNAgV+kA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/credential-provider-env": "^3.972.72",
"@aws-sdk/credential-provider-http": "^3.972.74",
"@aws-sdk/credential-provider-ini": "^3.973.17",
"@aws-sdk/credential-provider-process": "^3.972.72",
"@aws-sdk/credential-provider-sso": "^3.973.16",
"@aws-sdk/credential-provider-web-identity": "^3.972.78",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/credential-provider-imds": "^4.5.2",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-process": {
"version": "3.972.72",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.72.tgz",
"integrity": "sha512-rLIp2xbMjX/k9/od7APpqq1ZgXXnV0pOL1Th3ZsL8Wu0TRtBsDTVS8iPqcfRFcHakFxPvR04OSTv2ka2qOb/2A==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-sso": {
"version": "3.973.16",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.16.tgz",
"integrity": "sha512-IGihaJfFZYacJJr/odqILCoK7W/mvrZ7cuK7ECn3sAu4vLC6u0V8bS7mCGbdugJ8Aum2tnvqmx0F2MRFp2rn9g==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/token-providers": "3.1138.0",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/credential-provider-web-identity": {
"version": "3.972.78",
"resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.78.tgz",
"integrity": "sha512-/y9WvNtlcPBGLR0qc1a+9J/xtYZfVczvLUOuXaVWylzttH7ewsxwHtjmiJSolNrVSDorIxHGHMU61CbonRkmwA==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/middleware-sdk-s3": {
"version": "3.972.77",
"resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.77.tgz",
"integrity": "sha512-E7W2UOeUoc+lg3uIfR/dM7ZwusHwhBQrKMnlkRv4EXRR+C0YtV1pg25xC7GdZIhXH+NAMgZPCbE7o5to2cjFiw==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/signature-v4-multi-region": "^3.996.47",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/nested-clients": {
"version": "3.997.46",
"resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.46.tgz",
"integrity": "sha512-oRxtBcka/JGHGs9l9p9IVajGoTP8vTPmoAzdHGy4Qcy9P5vPnDf6nhIeM/COQNY9k/OahImTRaLkHftoXvfcmQ==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/signature-v4-multi-region": "^3.996.47",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/fetch-http-handler": "^5.8.0",
"@smithy/node-http-handler": "^4.12.1",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/signature-v4-multi-region": {
"version": "3.996.47",
"resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.47.tgz",
"integrity": "sha512-Zk08macMvQTHzQJCLJVkOlviVoqwYMrpXv4lmLN7b7sAbiMoOK7Go0NYdR5UeF+MW8LIbRmwrNy9u/5VvX1U5g==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/types": "^3.974.6",
"@smithy/signature-v4": "^5.7.3",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/token-providers": {
"version": "3.1138.0",
"resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1138.0.tgz",
"integrity": "sha512-GpyAr0DD63YOEmYFM6Df+gJuIgC92MMTiBK4FTKfxii5MJ9ge20epR7LyroulscYlG89J+ZB2ivFDPjvfQhzdw==",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/core": "^3.978.1",
"@aws-sdk/nested-clients": "^3.997.46",
"@aws-sdk/types": "^3.974.6",
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/types": {
"version": "3.974.6",
"resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.6.tgz",
"integrity": "sha512-v/clNZzZnDxGyvpHMOGpJKVXFAExJzUNAAjaWGdcx8QAcXLGwTaOkw33p5SHAi0YAioK32xB3hWwOekRVfmfKg==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws-sdk/xml-builder": {
"version": "3.972.41",
"resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.41.tgz",
"integrity": "sha512-ctjVSyCMegrWfXlx6VqzSBFI6UqmQ5ZlnfMhdLIiWmhoH8UAQxSCP5N3OpG7X3k4LnS7ou74C4mt20+bfTW2aQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/@aws/lambda-invoke-store": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",
"integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@balena/dockerignore": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@balena/dockerignore/-/dockerignore-1.0.2.tgz",
@@ -802,6 +1113,174 @@
"node": ">=8"
}
},
"node_modules/@oven/bun-darwin-aarch64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-darwin-aarch64/-/bun-darwin-aarch64-1.4.2.tgz",
"integrity": "sha512-MXdZkP1featqxZ+/VTXWG1BVjM4OGBehVY2Q88EeUj/7L0UMeCGItmyPYTN+wxvlGJ6F66JEtzsw+GvQWewnag==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@oven/bun-darwin-x64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64/-/bun-darwin-x64-1.4.2.tgz",
"integrity": "sha512-gZTxZuLjkUhAWjTETu3tw0WhsEdNkJ64daj60ybhPf835a2yollV3yTkK9JozvzKPx4TRFzLSl8C+U525pxVbw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@oven/bun-freebsd-aarch64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-freebsd-aarch64/-/bun-freebsd-aarch64-1.4.2.tgz",
"integrity": "sha512-SMNItMw1Z8QeeQVKnw8jA7xQNkeXdP+OPgin4Wi/QTx/B8RHHLnuZfqmFy7NtVeT2NF0kKYppW4WWd2CCYZjhQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
]
},
"node_modules/@oven/bun-freebsd-x64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-freebsd-x64/-/bun-freebsd-x64-1.4.2.tgz",
"integrity": "sha512-THbPKXhO54N0DpFRKZNDZpQ7dpbX0bWASuARckAUS9wRtFIHsiY+uULXJvxJGo2YD1YewvXQ4G8Fj7XT5oBCiw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
]
},
"node_modules/@oven/bun-linux-aarch64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64/-/bun-linux-aarch64-1.4.2.tgz",
"integrity": "sha512-3BBP9ovJ2RGHFH6Ae1CAtxNtG1+YY6GD6rmYbsUosoAk9+OEl6zeDQ/k4fBkc6dYOJCtWnx8hUxzNzQATSmvYQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@oven/bun-linux-aarch64-android": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64-android/-/bun-linux-aarch64-android-1.4.2.tgz",
"integrity": "sha512-3mZKO2rhsNgbAUtAHC1UKUlF2zTxFraDZT/Elv8wzyH0fJL9h+Iv3TgB9lO63w89PRn3eFe+NRA1bhVgikKNPQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
]
},
"node_modules/@oven/bun-linux-aarch64-musl": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64-musl/-/bun-linux-aarch64-musl-1.4.2.tgz",
"integrity": "sha512-+Sm6y+lSiSFBOtXmnekp5Q6n1tUKlyv71FCPWBc61Cgb14T5eBs8SN/nh4MUCOKzONkI3O+as3MGUgikS4aCBQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@oven/bun-linux-x64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-linux-x64/-/bun-linux-x64-1.4.2.tgz",
"integrity": "sha512-9/E/UXOTpSo3YsV5g+FhtTd/qTpiWoKuxS12cqtuYA1ssu9fRAoPQnipFgGyck3tWO63iUdxBiygq+kELFawng==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@oven/bun-linux-x64-android": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-android/-/bun-linux-x64-android-1.4.2.tgz",
"integrity": "sha512-6HC5tzcC79113n2IHCTJMWv+HsQImv4ZFEK2XpYLxY6HbT8tM4cUM2Zv1bHZBQsS3jv/zYBamDJ1UX7If0d5tw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
]
},
"node_modules/@oven/bun-linux-x64-musl": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl/-/bun-linux-x64-musl-1.4.2.tgz",
"integrity": "sha512-vVTKUg1bnPhRP/Hp73jIVoFh2vPFNYEqYX0ERKfZBOQEEHitNAeukZzzuUDZS0SoDCIpuWUGSpd/CDMbjdR+Uw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@oven/bun-windows-aarch64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-windows-aarch64/-/bun-windows-aarch64-1.4.2.tgz",
"integrity": "sha512-8EJ1ST7339WJE3poPW5nBgVW/lWf9HBz4W27ZUNhburKmcBLOByPyE6DP9fHD8FQGm5c+ilUN2hX1mrW0jxq9Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@oven/bun-windows-x64": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/@oven/bun-windows-x64/-/bun-windows-x64-1.4.2.tgz",
"integrity": "sha512-+bN6OuVld/9diT/RLSXSW7JE6CvNE3gL9XsAEjULi1nUsXd6DNO6GuA9jNdNb3r8PdJFnYHr5aypNV1Oj3Rd9g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@pinojs/redact": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1235,6 +1714,87 @@
"win32"
]
},
"node_modules/@smithy/core": {
"version": "3.35.0",
"resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.35.0.tgz",
"integrity": "sha512-zRMhfkByhT2snNdr1si24vJitU6Cr9ix2MikUfWmkAgp4jrNP0GcKSP5YvwQ+TlI8AZXER5QOGJn3JsVtSD9/A==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/credential-provider-imds": {
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.5.2.tgz",
"integrity": "sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/core": "^3.33.2",
"@smithy/types": "^4.17.2",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/fetch-http-handler": {
"version": "5.8.0",
"resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz",
"integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/core": "^3.33.3",
"@smithy/types": "^4.18.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/node-http-handler": {
"version": "4.12.1",
"resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.12.1.tgz",
"integrity": "sha512-ThMkboGeONWXAelq9FvGsuJC4rOi+qyC4/zhUF58xYpxUg5sQKx2VXZYJmtNjr4dSuBJ1HeJXETQILCz3wOHvw==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/core": "^3.33.3",
"@smithy/types": "^4.18.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/signature-v4": {
"version": "5.7.4",
"resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.7.4.tgz",
"integrity": "sha512-tHy0K0VtqNd5Y7Y41h0a0Lhh0L1GzC08dTWg0F7vRJWFtTENg7IZikf3wQkanYIRdb7ngoIPMTmqgUi401fEeQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/core": "^3.35.0",
"@smithy/types": "^4.19.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/types": {
"version": "4.19.0",
"resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz",
"integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@testcontainers/postgresql": {
"version": "12.1.0",
"resolved": "https://registry.npmjs.org/@testcontainers/postgresql/-/postgresql-12.1.0.tgz",
@@ -1821,6 +2381,12 @@
"node": ">= 6"
}
},
"node_modules/bowser": {
"version": "2.14.1",
"resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",
"integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
@@ -1876,6 +2442,43 @@
"node": ">=10.0.0"
}
},
"node_modules/bun": {
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/bun/-/bun-1.4.2.tgz",
"integrity": "sha512-TrSXo6HJfIEaczpb3kjX82I2pL47vK1QUNmHRCUdz9IzaOwa9lzOXSWwu2l18YHE3sNfGRapVLd4nNm+22vVVA==",
"cpu": [
"arm64",
"x64"
],
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"os": [
"darwin",
"linux",
"android",
"freebsd",
"win32"
],
"bin": {
"bun": "bin/bun.exe",
"bunx": "bin/bunx.exe"
},
"optionalDependencies": {
"@oven/bun-darwin-aarch64": "1.4.2",
"@oven/bun-darwin-x64": "1.4.2",
"@oven/bun-freebsd-aarch64": "1.4.2",
"@oven/bun-freebsd-x64": "1.4.2",
"@oven/bun-linux-aarch64": "1.4.2",
"@oven/bun-linux-aarch64-android": "1.4.2",
"@oven/bun-linux-aarch64-musl": "1.4.2",
"@oven/bun-linux-x64": "1.4.2",
"@oven/bun-linux-x64-android": "1.4.2",
"@oven/bun-linux-x64-musl": "1.4.2",
"@oven/bun-windows-aarch64": "1.4.2",
"@oven/bun-windows-x64": "1.4.2"
}
},
"node_modules/byline": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/byline/-/byline-5.0.0.tgz",
@@ -4114,6 +4717,12 @@
"node": ">=20"
}
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/tsx": {
"version": "4.22.4",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz",
+4
View File
@@ -3,6 +3,7 @@
"private": true,
"type": "module",
"scripts": {
"build:workspace-tools": "node scripts/build-workspace-tools.mjs",
"dev": "tsx watch src/server.ts",
"prebuild": "node scripts/clean-dist.mjs",
"build": "tsc -p tsconfig.json",
@@ -14,11 +15,13 @@
"test:schema-v3-verifier": "npm run test:schema-v4-verifier"
},
"dependencies": {
"@aws-sdk/client-s3": "3.1141.0",
"@fastify/cookie": "11.1.2",
"@fastify/cors": "^11.2.0",
"@fastify/rate-limit": "11.2.0",
"@types/pg": "^8.20.3",
"fastify": "^5.0.0",
"ipaddr.js": "2.4.0",
"kysely": "^0.29.5",
"libphonenumber-js": "1.13.12",
"openid-client": "6.8.5",
@@ -31,6 +34,7 @@
"@testcontainers/postgresql": "^12.1.0",
"@types/node": "24.13.3",
"@types/validator": "13.15.10",
"bun": "1.4.2",
"tsx": "^4.19.0",
"typescript": "^5.6.0",
"vitest": "^2.1.0"
+49
View File
@@ -0,0 +1,49 @@
// Maintainer-only build. The resulting two-binary bundle needs no extra host runtime.
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repository = process.env.THT_BUILD_SOURCE_ROOT ? resolve(process.env.THT_BUILD_SOURCE_ROOT) : resolve(dirname(fileURLToPath(import.meta.url)), "../..");
const backend = join(repository, "backend");
const native = `${process.platform === "win32" ? "windows" : process.platform}-${process.arch === "x64" ? "amd64" : process.arch}`;
const targets = {
"windows-amd64": ["windows", "amd64", "bun-windows-x64"],
"darwin-amd64": ["darwin", "amd64", "bun-darwin-x64"],
"darwin-arm64": ["darwin", "arm64", "bun-darwin-arm64"],
"linux-amd64": ["linux", "amd64", "bun-linux-x64"],
"linux-arm64": ["linux", "arm64", "bun-linux-arm64"],
};
const requested = process.argv.slice(2);
const selected = requested.length === 1 && requested[0] === "--all" ? Object.keys(targets) : requested.length ? requested : [native];
if (selected.some((target) => !targets[target])) {
console.error(`Usage: npm run build:workspace-tools -- [${Object.keys(targets).join("|")}|--all]`);
process.exit(2);
}
function run(command, args, cwd = backend, env = process.env) {
const result = spawnSync(command, args, { cwd, env, stdio: "inherit" });
if (result.error || result.status !== 0) throw new Error(`Build failed: ${command}`);
}
const revision = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repository, encoding: "utf8" });
if (revision.status !== 0) throw new Error("Cannot read build revision");
const commit = revision.stdout.trim();
const buildTime = process.env.THT_BUILD_TIME ?? new Date().toISOString();
const releaseVersion = process.env.THT_BUILD_VERSION ?? "0.0.0-dev";
if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?$/.test(releaseVersion) || !Number.isFinite(Date.parse(buildTime))) throw new Error("Invalid build identity");
const module = "github.com/aritmolab/thothii/tools/tht/internal/version";
const bunPackage = JSON.parse(readFileSync(join(backend, "node_modules", "bun", "package.json"), "utf8"));
const bun = join(backend, "node_modules", "bun", bunPackage.bin.bun);
for (const target of selected) {
const [os, arch, bunTarget] = targets[target];
const output = join(repository, "dist", "workspace-tools", target);
mkdirSync(output, { recursive: true });
const extension = os === "windows" ? ".exe" : "";
const names = [`tht${extension}`, `tht-workspace-documents${extension}`];
run(bun, ["build", "src/workspace-documents-cli.ts", "--compile", `--target=${bunTarget}`, "--outfile", join(output, names[1])]);
run("go", ["build", "-trimpath", "-ldflags", `-s -w -X ${module}.semanticVersion=${releaseVersion} -X ${module}.commit=${commit} -X ${module}.buildTime=${buildTime}`, "-o", join(output, names[0]), "./cmd/tht"], join(repository, "tools", "tht"), { ...process.env, CGO_ENABLED: "0", GOOS: os, GOARCH: arch });
const hashes = names.map((name) => `${createHash("sha256").update(readFileSync(join(output, name))).digest("hex")} ${name}\n`).join("");
writeFileSync(join(output, "SHA256SUMS"), hashes);
writeFileSync(join(output, "build.json"), JSON.stringify({ version: releaseVersion, commit, buildTime, target, bun: JSON.parse(readFileSync(join(backend, "package.json"), "utf8")).devDependencies.bun }, null, 2) + "\n");
console.log(output);
}
@@ -0,0 +1,93 @@
#!/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 { randomBytes } from 'node:crypto';
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`);
const localTag = `thothii-source-${role}:${randomBytes(16).toString('hex')}`;
await run('docker', ['buildx', 'build', '--load', '--tag', localTag, '--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.');
// Containerd and classic Docker stores expose different IDs; resolve the local
// daemon identity through our unique build tag, then pin that immutable ID.
const image = JSON.parse(await run('docker', ['image', 'inspect', '--format', '{{json .}}', localTag], { quiet: true }));
if (!/^sha256:[a-f0-9]{64}$/.test(image.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] = image.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; }
}
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env node
// Maintainer-only producer. Consumers download the resulting native bundle.
import { spawn } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync, realpathSync, renameSync, rmSync, statSync, copyFileSync, chmodSync, openSync, closeSync, readdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { parse } from "yaml";
import { prepareBundle, sha256 } from "./release-bundle.mjs";
import { dockerCredentials, dockerHub } from "./release-registry.mjs";
import { giteaHosting } from "./release-hosting.mjs";
import { publishVerifiedRelease } from "./release-publication.mjs";
const repositoryRoot = resolve(import.meta.dirname, "../..");
export function optionsFromArgs(args) {
const values = {};
for (let i = 0; i < args.length; i += 2) {
if (!['--revision', '--version', '--namespace', '--platforms', '--output', '--repository'].includes(args[i]) || !args[i + 1] || values[args[i]]) throw new Error("Usage: --revision REF --version VERSION --namespace DOCKER_HUB_NAMESPACE --platforms linux/amd64 --output NEW_OR_MATCHING_DIRECTORY [--repository HTTPS_GITEA_REPO]");
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'] ?? '') || !/^[a-z0-9][a-z0-9_-]{1,38}$/.test(values['--namespace'] ?? '') || !values['--output']) throw new Error("Supply an explicit source revision, semantic release version, Docker Hub namespace and output directory.");
const platforms = (values['--platforms'] ?? '').split(',');
if (!platforms.length || new Set(platforms).size !== platforms.length || platforms.some((p) => !['linux/amd64', 'linux/arm64'].includes(p))) throw new Error("Select explicit Linux image platforms; begin with linux/amd64 for Windows/WSL2 and Omarchy.");
const repository = values['--repository'] ?? 'https://git.tylconsulting.it/mptyl/ThothII';
const url = new URL(repository);
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !/^\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(url.pathname)) throw new Error("Use a credential-free HTTPS Gitea owner/repository URL.");
return { revision: values['--revision'], version: values['--version'], namespace: values['--namespace'], platforms: platforms.sort(), output: resolve(values['--output']), repository };
}
export function commandRunner(logs) {
let sequence = 0;
return async (command, args, { cwd = repositoryRoot, input = '', env = process.env, quiet = false, timeout = 120_000 } = {}) => {
const log = join(logs, `${++sequence}-${basename(command)}.log`);
return new Promise((accept, reject) => {
if (process.platform === 'win32') { reject(new Error('Run the release producer on Linux, WSL2 or macOS.')); return; }
const child = spawn(command, args, { cwd, env, detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
const stdout = [], stderr = []; let size = 0, overflow = false, settled = false, reapTimer;
const terminate = () => {
if (overflow) return;
overflow = true;
try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
// An escaped descendant must never retain our pipes indefinitely.
reapTimer = setTimeout(() => { child.stdout.destroy(); child.stderr.destroy(); finish(-1); }, 500);
};
const timer = setTimeout(terminate, timeout);
const collect = (chunks) => (data) => { size += data.length; if (size > 64 * 2 ** 20) terminate(); else chunks.push(data); };
child.stdout.on('data', collect(stdout)); child.stderr.on('data', collect(stderr));
child.stdin.on('error', () => {}); child.stdin.end(input);
child.on('error', () => { settled = true; clearTimeout(timer); clearTimeout(reapTimer); reject(new Error(`Required maintainer command ${basename(command)} is unavailable.`)); });
function finish(code) {
if (settled) return;
settled = true;
clearTimeout(timer); clearTimeout(reapTimer);
if (!quiet) writeFileSync(log, Buffer.concat([...stdout, ...stderr]), { mode: 0o600 });
if (code !== 0 || overflow) reject(new Error(`${basename(command)} failed${quiet ? '.' : `; inspect private log ${log}`}`));
else accept(Buffer.concat(stdout).toString());
}
child.on('close', finish);
});
};
}
function acquireOutput(output) {
if (!existsSync(output)) mkdirSync(output, { mode: 0o700 });
if (realpathSync(output) !== output || !statSync(output).isDirectory() || (statSync(output).mode & 0o077)) throw new Error("Use a canonical owner-only output directory.");
if (!existsSync(join(output, 'publication-state.json')) && readdirSync(output).length) throw new Error("Choose an empty output directory or the matching previous publication directory.");
const lock = join(output, '.publisher.lock');
if (existsSync(lock)) {
const pid = Number(readFileSync(lock, 'utf8'));
if (!Number.isInteger(pid) || pid <= 0) throw new Error("Inspect the incomplete publisher lock before retrying.");
let alive = true;
try { process.kill(pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
if (alive) throw new Error("Another publisher owns this output directory.");
rmSync(lock);
}
const fd = openSync(lock, 'wx', 0o600); writeFileSync(fd, String(process.pid)); closeSync(fd);
return () => rmSync(lock, { force: true });
}
export async function publishInstallation(options) {
const unlock = acquireOutput(options.output);
const logs = join(options.output, 'logs'); mkdirSync(logs, { recursive: true, mode: 0o700 });
const run = commandRunner(logs);
let worktree, temporary;
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("Source revision is not a commit.");
const identity = { revision, version: options.version, namespace: options.namespace, platforms: options.platforms, repository: options.repository };
const statePath = join(options.output, 'publication-state.json');
let state = { identity };
if (existsSync(statePath)) {
state = JSON.parse(readFileSync(statePath, 'utf8'));
if (JSON.stringify(state.identity) !== JSON.stringify(identity)) throw new Error("Output directory belongs to a different release; choose a new directory.");
}
const save = () => { const temp = statePath + '.tmp'; writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600 }); renameSync(temp, statePath); };
save();
console.log(`Release ${identity.version}: ${identity.namespace}, ${identity.platforms.join(',')}, source ${revision}`);
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, 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'];
if (state.assets.length !== names.length) throw new Error("Cached artifact set is incomplete.");
for (const asset of state.assets) if (!names.includes(asset.name) || asset.path !== join(options.output, asset.name) || !existsSync(asset.path) || sha256(readFileSync(asset.path)) !== asset.sha256) throw new Error("Previously built release artifact changed; do not overwrite an immutable version.");
for (const [platform, images] of Object.entries(state.images)) for (const reference of Object.values(images)) {
const [repository, digest] = reference.replace(/^docker.io\//, '').split('@');
await registry.inspect(repository, digest, platform, { anonymous: true });
}
return state.assets;
}
temporary = realpathSync(mkdtempSync(join(tmpdir(), 'thothii-release-')));
worktree = join(temporary, 'source');
await run('git', ['worktree', 'add', '--detach', worktree, revision]);
const sourceCompose = parse(readFileSync(join(worktree, 'compose.yaml'), 'utf8'));
for (const role of ['core', 'frontend']) {
console.log(`Preparing public repository ${identity.namespace}/thothii-${role}`);
await registry.ensurePublic(identity.namespace, `thothii-${role}`);
let existing = null;
for (const platform of identity.platforms) {
const image = await registry.inspect(`${identity.namespace}/thothii-${role}`, identity.version, platform, { allowMissing: true });
if (image && (image.labels['org.opencontainers.image.revision'] !== revision || image.labels['org.opencontainers.image.version'] !== identity.version)) throw new Error("Image tag already belongs to another immutable build; select a new release version.");
existing = existing || image;
}
if (!existing) {
console.log(`Building and publishing ${role} (${identity.platforms.join(', ')})`);
await run('docker', ['buildx', 'build', '--platform', identity.platforms.join(','), '--file', `docker/${role}.Dockerfile`, '--tag', `docker.io/${identity.namespace}/thothii-${role}:${identity.version}`, '--build-arg', `IMAGE_VERSION=${identity.version}`, '--label', `org.opencontainers.image.revision=${revision}`, '--label', `org.opencontainers.image.source=${identity.repository}`, '--provenance=false', '--sbom=false', '--push', '.'], { cwd: worktree, timeout: 45 * 60_000 });
}
}
state.images = {};
for (const platform of identity.platforms) {
const images = {};
for (const role of ['core', 'frontend']) images[role] = (await registry.inspect(`${identity.namespace}/thothii-${role}`, identity.version, platform, { anonymous: true })).reference;
for (const [role, service] of [['catalog', 'catalog-db'], ['qdrant', 'qdrant'], ['embedding', 'embedding']]) {
const [named, digest] = sourceCompose.services[service].image.split('@');
let repository = named.replace(/:[^/:]+$/, '').replace(/^docker.io\//, '');
if (!repository.includes('/')) repository = 'library/' + repository;
images[role] = (await registry.inspect(repository, digest, platform, { anonymous: true })).reference;
}
state.images[platform] = images;
}
save();
console.log('Building native operator bundles from the selected source');
await run('npm', ['ci'], { cwd: join(worktree, 'backend'), timeout: 10 * 60_000 });
const sourceTime = (await run('git', ['show', '-s', '--format=%cI', revision], { quiet: true })).trim();
const targets = identity.platforms.map((platform) => platform.replace('/', '-'));
await run('node', [join(repositoryRoot, 'backend/scripts/build-workspace-tools.mjs'), ...targets], { cwd: join(worktree, 'backend'), env: { ...process.env, THT_BUILD_SOURCE_ROOT: worktree, THT_BUILD_VERSION: identity.version, THT_BUILD_TIME: sourceTime }, timeout: 10 * 60_000 });
const assets = [];
for (const platform of identity.platforms) {
const target = platform.replace('/', '-');
const name = `thothii-${identity.version}-${target}`;
const bundle = join(options.output, name);
if (existsSync(bundle)) rmSync(bundle, { recursive: true }); // owned staging, never an installed runtime
mkdirSync(bundle);
prepareBundle({ source: worktree, destination: bundle, platform, version: identity.version, revision, images: state.images[platform] });
mkdirSync(join(bundle, 'bin'));
for (const executable of ['tht', 'tht-workspace-documents']) {
copyFileSync(join(worktree, 'dist/workspace-tools', target, executable), join(bundle, 'bin', executable));
chmodSync(join(bundle, 'bin', executable), 0o755);
}
// Resolve source-independent resource/config shape without any operator credentials.
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']);
const archive = join(options.output, name + '.tar.gz');
await run('tar', ['-czf', archive, '-C', options.output, name]);
assets.push({ name: basename(archive), path: archive, bytes: statSync(archive).size, sha256: sha256(readFileSync(archive)) });
}
const sums = join(options.output, 'SHA256SUMS.txt');
writeFileSync(sums, assets.map((asset) => `${asset.sha256} ${asset.name}\n`).join(''));
assets.push({ name: 'SHA256SUMS.txt', path: sums, bytes: statSync(sums).size, sha256: sha256(readFileSync(sums)) });
// An empty Docker configuration proves the consumer can pull without publisher credentials.
const publicConfig = join(temporary, 'public-docker'); mkdirSync(publicConfig);
for (const [platform, images] of Object.entries(state.images)) {
for (const reference of Object.values(images)) {
console.log(`Verifying anonymous pull ${reference.split('@')[0]} (${platform})`);
await run('docker', ['--config', publicConfig, 'pull', '--platform', platform, reference], { timeout: 20 * 60_000 });
}
console.log(`Smoke checking published images (${platform})`);
await run('docker', ['run', '--rm', '--platform', platform, '--network', 'none', '--entrypoint', '/bin/sh', images.core, '-ec', 'test "$(pi --version)" = "$PI_VERSION"; tht --help >/dev/null; test -f /app/backend/dist/catalog/migrate.js; test -x /app/docker/workspace-maintenance-entrypoint.sh; test -f /app/docker/catalog-migrate.sh; test ! -e /run/secrets/thothii.secrets'], { timeout: 5 * 60_000 });
await run('docker', ['run', '--rm', '--platform', platform, '--network', 'none', '--entrypoint', '/usr/local/bin/frontend-config-smoke', images.frontend], { timeout: 60_000 });
}
state.assets = assets; save();
return assets;
}
const published = await publishVerifiedRelease({ hosting, prepare });
state.releaseURL = published.html_url; state.complete = true; save();
console.log(`Published and verified: ${published.html_url}`);
return published;
} finally {
if (worktree && existsSync(worktree)) await run('git', ['worktree', 'remove', '--force', worktree]).catch(() => {});
if (temporary && !existsSync(worktree ?? '')) rmSync(temporary, { recursive: true, force: true });
unlock();
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
try { await publishInstallation(optionsFromArgs(process.argv.slice(2))); }
catch (error) { console.error(error instanceof SyntaxError ? 'Invalid release metadata; no secret values are printed.' : error.message); process.exitCode = 1; }
}
+74
View File
@@ -0,0 +1,74 @@
import { createHash } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync, lstatSync } from "node:fs";
import { dirname, join } from "node:path";
import { parse, stringify } from "yaml";
export const serviceRoles = Object.freeze({ core: "core", frontend: "frontend", "catalog-db": "catalog", "catalog-migrate": "core", "workspace-maintenance": "core", qdrant: "qdrant", embedding: "embedding", "embedding-model-init": "embedding" });
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, 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)) {
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];
compose.services[name].platform = platform;
}
const files = {};
const write = (name, data) => {
mkdirSync(dirname(join(destination, name)), { recursive: true });
writeFileSync(join(destination, name), data);
files[name] = sha256(data);
};
write("compose.yaml", stringify(compose));
for (const name of ["deploy/compose.local.yaml", "deploy/compose.git-https.yaml", "deploy/compose.git-ssh.yaml", "docker/catalog-db-init.sql", "docker/embedding-model-init.sh"]) {
const path = join(source, name);
if (!lstatSync(path).isFile()) throw new Error("Release asset must be a regular tracked file.");
write(name, readFileSync(path));
}
// Any future source bind mount must be deliberately added to the asset allowlist.
for (const service of Object.values(compose.services)) {
for (const volume of service.volumes ?? []) {
const sourcePath = typeof volume === "string" ? volume.split(":")[0] : volume.type === "bind" ? volume.source : undefined;
if (sourcePath?.startsWith(".") && !files[sourcePath.replace(/^\.\//, "")]) throw new Error("Source bind mount is missing from the release bundle.");
}
}
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 }])),
files, compose: ["compose.yaml", "deploy/compose.local.yaml"] };
writeFileSync(join(destination, "release-manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
writeFileSync(join(destination, "README.md"), `# ThothII ${version} — ${platform}
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.
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.
Run as the same non-root operator that prepared the documents, with access to local Docker.
1. bin/tht workspace prepare --directory NEW_WORKSPACE --id practice --name Practice
2. bin/tht workspace validate --directory WORKSPACE
3. bin/tht installation prepare --directory NEW_PRIVATE_INSTALLATION
4. bin/tht installation preflight --directory INSTALLATION --release ABSOLUTE_RELEASE_DIR/release-manifest.json
5. Complete the commented documents, generate technical credentials explicitly, then run installation validate and installation plan with --installation ABSOLUTE_INSTALLATION_FILE.
6. bin/tht --installation ABSOLUTE_INSTALLATION_FILE installation apply --plan ABSOLUTE_PLAN --json
Images are pinned by digest; runtime credentials and user workspaces are never bundled.
Consult the accompanying IT/EN guides for prepared documents, retry behavior and mandatory runtime checks.
`);
for (const [name, target] of [["standalone-manual-it.md", "GUIDE-IT.md"], ["standalone-manual-en.md", "GUIDE-EN.md"], ["installation-preflight.md", "PREFLIGHT.md"]]) writeFileSync(join(destination, target), readFileSync(join(source, "docs/install", name)));
return manifest;
}
+40
View File
@@ -0,0 +1,40 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { resolve, join } from "node:path";
import { parse } from "yaml";
import { prepareBundle } from "./release-bundle.mjs";
test("consumer bundle pins every service and carries all source bind resources", () => {
const output = mkdtempSync(join(tmpdir(), "thoth-release-test-"));
const images = Object.fromEntries(["core", "frontend", "catalog", "qdrant", "embedding"].map((role) => [role, `docker.io/tylconsulting/${role}@sha256:${"a".repeat(64)}`]));
try {
prepareBundle({ source: resolve(import.meta.dirname, "../.."), destination: output, platform: "linux/amd64", version: "0.1.0-install-preview.1", revision: "b".repeat(40), images });
const manifest = JSON.parse(readFileSync(join(output, "release-manifest.json")));
const compose = parse(readFileSync(join(output, "compose.yaml"), "utf8"));
assert.equal(compose.services.core.image, images.core);
assert.equal(compose.services["catalog-migrate"].image, images.core);
assert.equal(compose.services["workspace-maintenance"].image, images.core);
assert.equal(compose.services["embedding-model-init"].image, images.embedding);
// Both session commands and maintenance must retain local identity under a
// writable shared volume when the installer maps the operator's Unix UID.
assert.equal(compose.services.core.environment.THT_HOME, "/data/sessions/.thothii");
assert.equal(compose.services["workspace-maintenance"].environment.THT_HOME,
compose.services.core.environment.THT_HOME);
for (const service of Object.values(compose.services)) {
assert.equal(service.build, undefined);
assert.equal(service.pull_policy, undefined);
assert.equal(service.platform, "linux/amd64");
for (const volume of service.volumes ?? []) {
if (typeof volume === "string" && volume.startsWith("./")) assert.ok(existsSync(join(output, volume.split(":")[0])));
}
}
assert.equal(manifest.validator_protocol, 1);
assert.deepEqual(manifest.compose, ["compose.yaml", "deploy/compose.local.yaml"]);
assert.ok(manifest.files["docker/catalog-db-init.sql"]);
assert.ok(manifest.files["docker/embedding-model-init.sh"]);
assert.ok(!existsSync(join(output, "backend")));
assert.ok(!existsSync(join(output, "harness")));
} finally { rmSync(output, { recursive: true, force: true }); }
});
+69
View File
@@ -0,0 +1,69 @@
import { readFileSync } from "node:fs";
import { boundedFetch, readLimited } from "./release-registry.mjs";
import { sha256 } from "./release-bundle.mjs";
export async function giteaHosting({ run, repository, identity, body }) {
const remote = new URL(repository);
const credential = await run("git", ["credential", "fill"], { input: `protocol=https\nhost=${remote.host}\n\n`, quiet: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
const fields = Object.fromEntries(credential.trim().split("\n").map((line) => { const at = line.indexOf("="); return [line.slice(0, at), line.slice(at + 1)]; }));
if (!fields.username || !fields.password) throw new Error("Gitea publishing credentials are unavailable in the Git credential store.");
const authorization = `Basic ${Buffer.from(`${fields.username}:${fields.password}`).toString("base64")}`;
const api = `${remote.origin}/api/v1/repos${remote.pathname.replace(/\.git$/, "")}`;
const marker = `<!-- thothii-release:${JSON.stringify(identity)} -->`;
const tag = `installation-v${identity.version}`;
async function request(path, options = {}, allowMissing = false) {
const response = await boundedFetch(api + path, { ...options, headers: { Authorization: authorization, ...options.headers } }, 120_000);
if (allowMissing && response.status === 404) return null;
if (!response.ok) throw new Error(`Gitea release operation failed (HTTP ${response.status}).`);
const bytes = await readLimited(response, 4 * 2 ** 20);
try { return JSON.parse(bytes.toString()); } catch { throw new Error("Gitea returned invalid release metadata."); }
}
const json = (method, value) => ({ method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(value) });
async function verifyTag(required = false) {
const existing = await request(`/tags/${encodeURIComponent(tag)}`, {}, true);
if ((!existing && required) || (existing && existing.commit?.sha !== identity.revision)) throw new Error("Release Git tag does not match the requested source revision.");
}
async function assets(release) { return request(`/releases/${release.id}/assets`); }
async function verifyAsset(asset, expected, publicRead) {
const url = new URL(asset.browser_download_url);
if (url.origin !== remote.origin) throw new Error("Unexpected release asset origin.");
const response = await boundedFetch(url, { headers: publicRead ? {} : { Authorization: authorization } }, 120_000);
if (!response.ok || sha256(await readLimited(response, expected.bytes + 1)) !== expected.sha256) throw new Error("Published release asset does not match its verified checksum.");
}
return {
async open() {
const info = await request("");
if (info.private || !info.permissions?.push) throw new Error("Release hosting must be a public Gitea repository with publication rights.");
await verifyTag();
const existing = await request(`/releases/tags/${encodeURIComponent(tag)}`, {}, true);
if (existing) {
if (!existing.body?.includes(marker)) throw new Error("Release version already belongs to another source or publication identity; it will not be overwritten.");
return existing;
}
return request("/releases", json("POST", { tag_name: tag, target_commitish: identity.revision, name: `ThothII ${identity.version}`, body: `${body}\n\n${marker}`, draft: true, prerelease: true }));
},
async upload(release, asset) {
const matching = (await assets(release)).filter((item) => item.name === asset.name);
if (matching.length > 1) throw new Error("Ambiguous release assets; no published files were replaced.");
if (matching.length === 1) { await verifyAsset(matching[0], asset, false); return; }
const data = readFileSync(asset.path);
if (sha256(data) !== asset.sha256) throw new Error("Local release asset changed before upload.");
const form = new FormData(); form.append("attachment", new Blob([data]), asset.name);
await request(`/releases/${release.id}/assets?name=${encodeURIComponent(asset.name)}`, { method: "POST", body: form });
},
async verify(release, expected, publicRead) {
await verifyTag(publicRead);
const uploaded = await assets(release);
if (uploaded.length !== expected.length) throw new Error("Release asset set is incomplete or contains unexpected files.");
for (const asset of expected) {
const matching = uploaded.filter((item) => item.name === asset.name);
if (matching.length !== 1) throw new Error("Release asset missing or ambiguous.");
await verifyAsset(matching[0], asset, publicRead);
}
},
async publish(release) {
await verifyTag();
return request(`/releases/${release.id}`, json("PATCH", { draft: false }));
},
};
}
+43
View File
@@ -0,0 +1,43 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { giteaHosting } from './release-hosting.mjs';
test('release hosting refuses a pre-existing Git tag on another commit', async () => {
const fetch = globalThis.fetch;
const revision = 'a'.repeat(40);
let writes = 0;
globalThis.fetch = async (url, options) => {
if (options.method) { writes++; return Response.json({ id: 1, draft: true }); }
if (String(url).includes('/releases/tags/')) return new Response('', { status: 404 });
if (String(url).includes('/tags/installation-v')) return Response.json({ commit: { sha: 'b'.repeat(40) } });
return Response.json({ private: false, permissions: { push: true } });
};
try {
const hosting = await giteaHosting({ run: async () => 'username=test\npassword=test\n', repository: 'https://example.test/owner/repo', identity: { revision, version: '1.0.0' }, body: '' });
await assert.rejects(hosting.open(), /tag.*revision/i);
assert.equal(writes, 0);
} finally { globalThis.fetch = fetch; }
});
test('matching Git tag is accepted and verified again before publishing', async () => {
const fetch = globalThis.fetch;
const identity = { revision: 'a'.repeat(40), version: '1.0.0' };
let sha = identity.revision;
let writes = 0;
globalThis.fetch = async (url, options) => {
if (options.method) { writes++; return Response.json({ id: 1, draft: false }); }
if (String(url).includes('/releases/tags/')) return Response.json({ id: 1, draft: true, body: `<!-- thothii-release:${JSON.stringify(identity)} -->` });
if (String(url).includes('/tags/')) return Response.json({ commit: { sha } });
if (String(url).endsWith('/assets')) return Response.json([]);
return Response.json({ private: false, permissions: { push: true } });
};
try {
const hosting = await giteaHosting({ run: async () => 'username=test\npassword=test\n', repository: 'https://example.test/owner/repo', identity, body: '' });
const release = await hosting.open();
await hosting.verify(release, [], false);
sha = 'b'.repeat(40);
await assert.rejects(hosting.verify(release, [], false), /tag.*revision/i);
await assert.rejects(hosting.publish(release), /tag.*revision/i);
assert.equal(writes, 0);
} finally { globalThis.fetch = fetch; }
});
+18
View File
@@ -0,0 +1,18 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { commandRunner } from './publish-installation.mjs';
test('publisher timeout terminates descendants that retain output pipes', async () => {
const logs = mkdtempSync(join(tmpdir(), 'release-process-test-'));
try {
const started = Date.now();
await assert.rejects(commandRunner(logs)(process.execPath, ['-e', `
require('child_process').spawn(process.execPath, ['-e', 'setTimeout(() => {}, 2500)'], {stdio: 'inherit'});
setTimeout(() => {}, 2500);
`], { timeout: 250, quiet: true }));
assert.ok(Date.now() - started < 1800, 'timeout must not wait for the descendant to exit naturally');
} finally { rmSync(logs, { recursive: true, force: true }); }
});
+14
View File
@@ -0,0 +1,14 @@
/** Drafts are the publication boundary. A partial build/upload is never a consumer release. */
export async function publishVerifiedRelease({ hosting, prepare }) {
const release = await hosting.open();
const assets = await prepare();
if (!release.draft) {
await hosting.verify(release, assets, true);
return release;
}
for (const asset of assets) await hosting.upload(release, asset);
await hosting.verify(release, assets, false);
const published = await hosting.publish(release);
await hosting.verify(published, assets, true);
return published;
}
@@ -0,0 +1,34 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { publishVerifiedRelease } from "./release-publication.mjs";
test("an interrupted preparation stays draft and retry publishes only after every artifact verifies", async () => {
const events = [];
let failing = true;
const hosting = {
open: async () => ({ id: 7, draft: true }),
upload: async (_draft, asset) => events.push(`upload:${asset.name}`),
verify: async (_draft, assets, publicRead) => events.push(`verify:${publicRead}:${assets.length}`),
publish: async () => { events.push("publish"); return { html_url: "https://example.test/release" }; },
};
const prepare = async () => {
if (failing) throw new Error("frontend build unavailable");
return [{ name: "bundle.tar.gz" }, { name: "SHA256SUMS" }];
};
await assert.rejects(publishVerifiedRelease({ hosting, prepare }), /frontend/);
assert.deepEqual(events, []);
failing = false;
await publishVerifiedRelease({ hosting, prepare });
assert.deepEqual(events, ["upload:bundle.tar.gz", "upload:SHA256SUMS", "verify:false:2", "publish", "verify:true:2"]);
});
test("a published version is verified without replacing any asset", async () => {
const events = [];
await publishVerifiedRelease({ prepare: async () => [{ name: "bundle.tar.gz" }], hosting: {
open: async () => ({ id: 7, draft: false }),
upload: async () => { throw new Error("overwrote a published version"); },
publish: async () => { throw new Error("republished a version"); },
verify: async (_release, _assets, publicRead) => events.push(publicRead),
} });
assert.deepEqual(events, [true]);
});
+86
View File
@@ -0,0 +1,86 @@
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { sha256 } from "./release-bundle.mjs";
const accept = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json";
export async function boundedFetch(url, options = {}, timeout = 30_000) {
try { return await fetch(url, { ...options, redirect: options.redirect ?? "error", signal: AbortSignal.timeout(timeout) }); }
catch { throw new Error("Release network request failed; retry with the same output directory."); }
}
export async function readLimited(response, maximum) {
const chunks = []; let size = 0;
for await (const chunk of response.body) { size += chunk.length; if (size > maximum) throw new Error("Release response exceeded its bound."); chunks.push(chunk); }
return Buffer.concat(chunks);
}
async function jsonResponse(response, description) {
if (!response.ok) throw new Error(`${description} refused (HTTP ${response.status}).`);
const bytes = await readLimited(response, 4 * 2 ** 20);
try { return { bytes, value: JSON.parse(bytes.toString()) }; }
catch { throw new Error("Release service returned invalid metadata."); }
}
export async function dockerCredentials(run) {
const config = JSON.parse(readFileSync(join(process.env.DOCKER_CONFIG || join(homedir(), ".docker"), "config.json"), "utf8"));
const server = "https://index.docker.io/v1/";
const helper = config.credHelpers?.[server] || config.credsStore;
if (!helper || !/^[A-Za-z0-9._-]+$/.test(helper)) throw new Error("Use docker login with an OS credential store before publishing.");
const auth = JSON.parse(await run(`docker-credential-${helper}`, ["get"], { input: server + "\n", quiet: true }));
if (!auth.Username || !auth.Secret) throw new Error("Docker Hub login is unavailable.");
return auth;
}
export function dockerHub(auth) {
async function token(repository, anonymous) {
const url = new URL("https://auth.docker.io/token");
url.searchParams.set("service", "registry.docker.io");
url.searchParams.set("scope", `repository:${repository}:pull`);
const response = await boundedFetch(url, { headers: anonymous ? {} : { Authorization: `Basic ${Buffer.from(`${auth.Username}:${auth.Secret}`).toString("base64")}` } });
return (await jsonResponse(response, "Registry authentication")).value.token;
}
async function registryJSON(repository, route, anonymous, allowMissing = false) {
const bearer = await token(repository, anonymous);
let response = await boundedFetch(`https://registry-1.docker.io/v2/${repository}/${route}`, { redirect: "manual", headers: { Accept: accept, Authorization: `Bearer ${bearer}` } });
if ([302, 307].includes(response.status) && route.startsWith("blobs/")) {
const target = new URL(response.headers.get("location"));
if (target.protocol !== "https:" || target.username || target.password) throw new Error("Invalid registry blob redirect.");
// Signed blob URLs are fetched without forwarding registry credentials.
response = await boundedFetch(target);
}
if (allowMissing && response.status === 404) return null;
const { bytes, value } = await jsonResponse(response, "Registry read");
const digest = `sha256:${sha256(bytes)}`;
const advertised = response.headers.get("docker-content-digest");
if (advertised && advertised !== digest) throw new Error("Registry content digest mismatch.");
return { value, digest };
}
return {
async ensurePublic(namespace, name) {
const response = await boundedFetch("https://hub.docker.com/v2/auth/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ identifier: auth.Username, secret: auth.Secret }) });
const bearer = (await jsonResponse(response, "Docker Hub authentication")).value.access_token;
const headers = { Authorization: `Bearer ${bearer}`, "Content-Type": "application/json" };
const path = `https://hub.docker.com/v2/namespaces/${namespace}/repositories`;
let existing = await boundedFetch(`${path}/${name}`, { headers });
if (existing.status === 404) {
existing = await boundedFetch(path, { method: "POST", headers, body: JSON.stringify({ namespace, name, registry: "docker.io", is_private: false, description: `ThothII ${name.endsWith("core") ? "core with embedded Pi" : "standalone frontend"}` }) });
}
const data = (await jsonResponse(existing, "Public repository preparation")).value;
if (data.is_private !== false) throw new Error("Selected Docker Hub repository is private; make this release repository public before retrying.");
},
async inspect(repository, reference, platform, { anonymous = false, allowMissing = false } = {}) {
let image = await registryJSON(repository, `manifests/${reference}`, anonymous, allowMissing);
if (!image) return null;
if (reference.startsWith("sha256:") && image.digest !== reference) throw new Error("Requested image digest does not match registry content.");
if (image.value.manifests) {
const match = image.value.manifests.find((entry) => `${entry.platform?.os}/${entry.platform?.architecture}` === platform);
if (!match || !/^sha256:[a-f0-9]{64}$/.test(match.digest)) throw new Error("Image does not contain the requested platform.");
image = await registryJSON(repository, `manifests/${match.digest}`, anonymous);
if (image.digest !== match.digest) throw new Error("Image index digest mismatch.");
}
if (reference.startsWith("sha256:") && !image.value.config) throw new Error("Image metadata is incomplete.");
const configDigest = image.value.config?.digest;
if (!/^sha256:[a-f0-9]{64}$/.test(configDigest ?? "")) throw new Error("Image configuration digest is invalid.");
const config = await registryJSON(repository, `blobs/${configDigest}`, anonymous);
if (config.digest !== configDigest || `${config.value.os}/${config.value.architecture}` !== platform) throw new Error("Image configuration or platform mismatch.");
return { reference: `docker.io/${repository}@${image.digest}`, labels: config.value.config?.Labels ?? {} };
},
};
}
+28
View File
@@ -0,0 +1,28 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { dockerHub } from "./release-registry.mjs";
import { sha256 } from "./release-bundle.mjs";
test("registry verifies pinned config/platform and does not forward auth to blob storage", async () => {
const original = globalThis.fetch;
const config = JSON.stringify({ os: "linux", architecture: "amd64", config: { Labels: { "org.opencontainers.image.revision": "b".repeat(40) } } });
const configDigest = "sha256:" + sha256(config);
const manifest = JSON.stringify({ schemaVersion: 2, config: { digest: configDigest } });
const imageDigest = "sha256:" + sha256(manifest);
const auth = [];
globalThis.fetch = async (target, options) => {
const url = new URL(target);
if (url.hostname === "auth.docker.io") return new Response(JSON.stringify({ token: "registry-token" }));
if (url.hostname === "blob.example.test") { auth.push(options.headers?.Authorization); return new Response(config); }
if (url.pathname.includes("/blobs/")) return new Response(null, { status: 307, headers: { location: "https://blob.example.test/config" } });
return new Response(manifest, { headers: { "docker-content-digest": imageDigest } });
};
try {
const registry = dockerHub({ Username: "publisher", Secret: "PRIVATE_TOKEN" });
const image = await registry.inspect("example/core", imageDigest, "linux/amd64", { anonymous: true });
assert.equal(image.reference, `docker.io/example/core@${imageDigest}`);
assert.deepEqual(auth, [undefined]);
await assert.rejects(registry.inspect("example/core", imageDigest, "linux/arm64"), /platform mismatch/);
await assert.rejects(registry.inspect("example/core", "sha256:" + "0".repeat(64), "linux/amd64"), /Requested image digest/);
} finally { globalThis.fetch = original; }
});
@@ -0,0 +1,47 @@
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}`]);
// Containerd may expose the manifest as local Id while Buildx writes its config digest.
writeFileSync(args[args.indexOf('--iidfile') + 1], `sha256:${'b'.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 }); }
});
+4
View File
@@ -48,6 +48,8 @@ import { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js";
import { CatalogService } from "./catalog/service.js";
import { catalogDatabaseRoutes } from "./routes/catalog-databases.js";
import { installationRoutes } from "./routes/installation.js";
import { InstallationBindings } from "./catalog/installation-bindings.js";
import { CatalogOperationCoordinator } from "./catalog/operation-coordinator.js";
import { ConcreteCatalogPostgresAccess, type CatalogPostgresAccess } from "./catalog/postgres-access.js";
import { CatalogTableService } from "./catalog/table-service.js";
@@ -530,6 +532,8 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
}).readLatestJob(),
});
catalogDatabaseRoutes(app, { repository: catalogRepository, service: catalogService, operations: catalogOperationCoordinator });
installationRoutes(app, new InstallationBindings(catalogRepository, catalogService, workspaceRegistry,
workspaceSecretStore, catalogOperationCoordinator, config.workspaceRegistry.installationId), workspaceRegistry);
catalogTableRoutes(app, {
repository: catalogRepository,
service: catalogTableService,
+21
View File
@@ -0,0 +1,21 @@
import { readFileSync, lstatSync } from "node:fs";
import { parseAllDocuments } from "yaml";
import { decode, DocumentError, runWorkspaceDocuments } from "../workspaces/documents.js";
import { validateDatabaseBootstrap } from "./bootstrap-documents.js";
/** Internal sibling protocol: only references cross back to Go, never secret contents. */
export function runBootstrapValidation(args: string[]): { status: number; output: string } {
try {
if (args.length !== 5 || args[0] !== "--directory" || args[2] !== "--bootstrap" || args[4] !== "--json") throw new Error("usage");
const checked = runWorkspaceDocuments(["validate", "--directory", args[1], "--json"]);
if (checked.status !== 0) return checked;
const info = lstatSync(args[3]);
if (!info.isFile() || info.isSymbolicLink() || info.size > 1024 * 1024) throw new Error("file");
const validated = decode(readFileSync(args[3], "utf8"), "database-bootstrap.yaml", (source) =>
validateDatabaseBootstrap(parseAllDocuments(source)[0].toJSON(), args[1]), "database bootstrap schema v1 and the Catalog binding contract");
return { status: 0, output: JSON.stringify({ schema_version: 1, ok: true, secret_files: validated.secretFiles, warnings: validated.warnings, issues: [] }) };
} catch (error) {
const issue = error instanceof DocumentError ? error.issue : { document: "database-bootstrap.yaml", field: "$", code: "bootstrap_invalid", correction: "Supply one complete Catalog database configuration per workspace in a readable local bootstrap document." };
return { status: 1, output: JSON.stringify({ schema_version: 1, ok: false, issues: [issue] }) };
}
}
@@ -0,0 +1,52 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { z } from "zod";
import { databaseConfigurationSchema } from "./configuration-schema.js";
import { parseWorkspaceCatalogYaml } from "../workspaces/catalog.js";
import { parseWorkspaceYaml } from "../workspaces/schema.js";
import { discoverWorkspaceSecretRequirements } from "../workspaces/secret-requirements.js";
const reference = z.string().min(1).max(4096);
const database = databaseConfigurationSchema.extend({
secretFiles: z.object({ password: reference.optional(), apiKey: reference.optional(), sshPrivateKey: reference.optional(), sshPrivateKeyPassphrase: reference.optional(), sshKnownHosts: reference.optional(), tlsCa: reference.optional() }).strict(),
evidenceSecretFiles: z.object({ "evidence.signed_urls": reference.optional(), "evidence.access_key": reference.optional(), "evidence.secret_key": reference.optional(), "evidence.session_token": reference.optional() }).strict().optional(),
});
const bootstrap = z.object({ schemaVersion: z.literal(1),
authentication: z.object({ username: z.string().min(1).max(128), passwordFile: reference }).strict().optional(),
databases: z.array(database).min(1).max(1000) }).strict();
export const parseDatabaseBootstrap = (value: unknown) => bootstrap.parse(value);
export interface BootstrapReference { field: string; path: string }
/** Offline bootstrap boundary: runtime Catalog owns the resulting bindings after import. */
export function validateDatabaseBootstrap(value: unknown, workspaceRoot: string): { secretFiles: BootstrapReference[]; warnings: string[] } {
const document = bootstrap.parse(value);
const catalog = parseWorkspaceCatalogYaml(readFileSync(join(workspaceRoot, "thoth-workspaces.yaml"), "utf8"));
const expected = new Set(catalog.workspaces.map((entry) => entry.id));
const seen = new Set<string>();
const secretFiles: BootstrapReference[] = [];
if (document.authentication) secretFiles.push({ field: "authentication.passwordFile", path: document.authentication.passwordFile });
const warnings: string[] = [];
const issue = (path: (string | number)[], message: string): never => { throw new z.ZodError([{ code: "custom", path, message }]); };
document.databases.forEach((entry, index) => {
if (!expected.has(entry.workspaceId) || seen.has(entry.workspaceId)) issue(["databases", index, "workspaceId"], "Declare each catalog workspace exactly once.");
seen.add(entry.workspaceId);
const required = entry.binding.transport === "rest_api"
? entry.binding.restAuth === "none" ? [] : ["apiKey"] as const
: entry.binding.transport === "ssh_tunnel" ? ["password", "sshPrivateKey", "sshKnownHosts"] as const : ["password"] as const;
for (const name of required) {
if (!entry.secretFiles[name]) issue(["databases", index, "secretFiles", name], "Supply a protected file reference for this transport.");
}
if (entry.binding.transport === "ssh_tunnel") warnings.push(`databases.${index}:ssh_tunnel supports Catalog diagnostics, not NL-to-SQL sessions; choose direct or REST for practice.`);
for (const [name, path] of Object.entries(entry.secretFiles)) secretFiles.push({ field: `databases.${index}.secretFiles.${name}`, path });
const workspace = parseWorkspaceYaml(readFileSync(join(workspaceRoot, entry.workspaceId, "workspace.yaml"), "utf8"));
const requirements = discoverWorkspaceSecretRequirements(workspace, {});
for (const requirement of requirements.filter((item) => item.connector === "evidence" && item.required)) {
if (!(entry.evidenceSecretFiles as Record<string, string> | undefined)?.[requirement.id]) issue(["databases", index, "evidenceSecretFiles"], "Supply the configured Evidence authentication file references.");
}
for (const [name, path] of Object.entries(entry.evidenceSecretFiles ?? {})) secretFiles.push({ field: `databases.${index}.evidenceSecretFiles.${name}`, path });
});
if (seen.size !== expected.size) issue(["databases"], "Add a database binding for every catalog workspace.");
return { secretFiles, warnings };
}
@@ -0,0 +1,47 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { S3Client, ListObjectsV2Command } from "@aws-sdk/client-s3";
import { parseWorkspaceYaml } from "../workspaces/schema.js";
import { evidencePolicy } from "../workspaces/evidence/preprocessing.js";
import type { parseDatabaseBootstrap } from "./bootstrap-documents.js";
import { probePublicEvidenceUrl, publicEvidenceAgent } from "./evidence-probe-http.js";
type Entry = ReturnType<typeof parseDatabaseBootstrap>["databases"][number];
/** Read-only availability probes; domain correctness and materialization remain runtime gates. */
export async function probeEvidence(entry: Entry, root: string): Promise<void> {
const evidence = parseWorkspaceYaml(readFileSync(join(root, entry.workspaceId, "workspace.yaml"), "utf8")).evidence;
if (!evidence || evidence.source.type === "filesystem") return;
if (evidencePolicy(evidence)) throw new Error("Evidence egress policy refused");
const secret = (name: keyof NonNullable<Entry["evidenceSecretFiles"]>) => {
const path = entry.evidenceSecretFiles?.[name];
if (!path) throw new Error("Evidence credential missing");
return readFileSync(path, "utf8").trim();
};
const source = evidence.source;
if (source.type === "http") {
const urls: unknown = source.authentication === "signed_urls_file"
? JSON.parse(secret("evidence.signed_urls")) : source.uris;
if (!Array.isArray(urls) || urls.length !== source.uris.length || urls.length > 1000) throw new Error("Invalid signed URLs");
for (const [index, value] of urls.entries()) {
if (typeof value !== "string") throw new Error("Invalid signed URL");
const url = new URL(value);
const provenance = new URL(source.uris[index]);
// Signed queries may authorize the same identity, never a different host/path.
if (url.origin !== provenance.origin || url.pathname !== provenance.pathname || url.username || url.password || url.hash) throw new Error("Invalid signed URL identity");
await probePublicEvidenceUrl(url);
}
return;
}
// The shared runtime policy currently permits trusted AWS endpoints with explicit file credentials.
const location = new URL(source.uri);
const client = new S3Client({
region: source.region ?? "us-east-1", maxAttempts: 1,
requestHandler: { httpsAgent: publicEvidenceAgent(), connectionTimeout: 5_000, requestTimeout: 5_000 },
credentials: { accessKeyId: secret("evidence.access_key"), secretAccessKey: secret("evidence.secret_key"),
...(entry.evidenceSecretFiles?.["evidence.session_token"] ? { sessionToken: secret("evidence.session_token") } : {}) },
});
try {
await client.send(new ListObjectsV2Command({ Bucket: location.hostname, Prefix: decodeURIComponent(location.pathname.slice(1)), MaxKeys: 1 }), { abortSignal: AbortSignal.timeout(5_000) });
} finally { client.destroy(); }
}
+53
View File
@@ -0,0 +1,53 @@
import { readFileSync } from "node:fs";
import { parse } from "yaml";
import { parseDatabaseBootstrap } from "./bootstrap-documents.js";
import { runBootstrapValidation } from "./bootstrap-cli.js";
import { createConcreteDiagnosticAdapters, type DiagnosticAdapters } from "../workspaces/diagnostics.js";
import { probeEvidence } from "./bootstrap-evidence-probes.js";
interface ProbeCheck { id: string; outcome: "passed" | "error"; field: string; action: string }
/** Uses the same read-only, authenticated connector diagnostics as the Catalog. */
export async function probeBootstrapDependencies(value: unknown, adapters: DiagnosticAdapters = createConcreteDiagnosticAdapters(), workspaceRoot?: string) {
const document = parseDatabaseBootstrap(value);
const checks: ProbeCheck[] = [];
for (const [index, entry] of document.databases.entries()) {
let outcome: ProbeCheck["outcome"] = "passed";
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5_000);
try {
if (entry.binding.transport === "ssh_tunnel") throw new Error("session transport unavailable");
await adapters.probeConnector({
role: "dwh", transport: entry.binding.transport,
host: entry.binding.host, port: entry.binding.port, user: entry.binding.username,
baseUrl: entry.binding.baseUrl,
credentialFile: entry.binding.transport === "rest_api" ? entry.secretFiles.apiKey : entry.secretFiles.password,
tlsCaFile: entry.secretFiles.tlsCa, tlsServername: entry.binding.tlsServername,
resource: { database: entry.databaseName, schema: entry.schema },
timeoutMs: 5_000, signal: controller.signal,
diagnostic: { method: "GET", path: entry.binding.restPath ?? "/health", auth: entry.binding.restAuth ?? "bearer" },
});
} catch { outcome = "error"; } finally { clearTimeout(timer); }
checks.push({ id: `database-${index}`, outcome, field: `database-bootstrap.databases.${index}`,
action: entry.binding.transport === "ssh_tunnel"
? "Choose postgres_direct or rest_api for NL-to-SQL practice; SSH diagnostics alone cannot establish session readiness."
: "Require an authenticated read-only connection and access to the configured database/schema; correct endpoint, permissions or protected credentials." });
if (workspaceRoot) {
let evidenceOutcome: ProbeCheck["outcome"] = "passed";
try { await probeEvidence(entry, workspaceRoot); } catch { evidenceOutcome = "error"; }
checks.push({ id: `evidence-${index}`, outcome: evidenceOutcome, field: `workspaces.${index}.evidence`, action: "Require readable local Evidence or authenticated bounded HTTP/S3 access under the canonical egress policy; domain meaning is verified during practice." });
}
}
return { schema_version: 1, ok: checks.every((check) => check.outcome === "passed"), checks };
}
export async function runBootstrapProbes(args: string[]) {
const validation = runBootstrapValidation(args);
if (validation.status !== 0) return validation;
try {
const report = await probeBootstrapDependencies(parse(readFileSync(args[3], "utf8")), undefined, args[1]);
return { status: report.ok ? 0 : 1, output: JSON.stringify(report) };
} catch {
return { status: 1, output: JSON.stringify({ schema_version: 1, ok: false, checks: [{ id: "database-probes", outcome: "error", field: "database-bootstrap", action: "Revalidate prepared documents and protected credential references." }] }) };
}
}
@@ -0,0 +1,44 @@
import { z } from "zod";
import { parseCredentialFreeHttpUrl } from "../auth/url-policy.js";
import { DATABASE_TRANSPORTS } from "./types.js";
const workspaceIdSchema = z.string().regex(/^[a-z][a-z0-9-]{2,62}$/);
const identifier = z.string().trim().min(1).max(128).regex(/^[A-Za-z_][A-Za-z0-9_$-]*$/);
const nonEmpty = z.string().trim().min(1).max(512);
const port = z.number().int().min(1).max(65_535);
const optionalText = nonEmpty.optional();
const sshHost = z.string().trim().min(1).max(255).regex(/^[A-Za-z0-9_.:\[\]-]+$/).optional();
const sshUsername = z.string().trim().min(1).max(128).regex(/^[A-Za-z0-9._-]+$/).optional();
const bindingSchema = z.object({
transport: z.enum(DATABASE_TRANSPORTS),
host: optionalText,
port: port.optional(),
username: optionalText,
baseUrl: z.string().max(2048)
.refine((value) => parseCredentialFreeHttpUrl(value) !== undefined)
.optional(),
restPath: z.string().regex(/^\/(?!\/)[^?#\\\u0000-\u001f]*$/).max(512).optional(),
restAuth: z.enum(["none", "bearer", "x-api-key"]).optional(),
tlsServername: optionalText,
sshHost,
sshPort: port.optional(),
sshUsername,
sshTargetHost: sshHost,
sshTargetPort: port.optional(),
}).strict().superRefine((binding, context) => {
const required = binding.transport === "postgres_direct"
? ["host", "port", "username"] as const
: binding.transport === "rest_api"
? ["baseUrl", "restPath", "restAuth"] as const
: ["username", "sshHost", "sshPort", "sshUsername", "sshTargetHost", "sshTargetPort"] as const;
for (const field of required) {
if (binding[field] === undefined) context.addIssue({ code: "custom", path: [field], message: "Required" });
}
});
export const databaseConfigurationSchema = z.object({
workspaceId: workspaceIdSchema,
engine: z.literal("postgres"),
databaseName: identifier,
schema: identifier,
binding: bindingSchema,
}).strict();
@@ -0,0 +1,57 @@
import { lookup } from "node:dns/promises";
import { request as httpRequest } from "node:http";
import { request as httpsRequest, Agent } from "node:https";
import type { LookupFunction } from "node:net";
import ipaddr from "ipaddr.js";
const refused = () => new Error("Evidence network policy refused");
function normalizedPublicAddress(value: string): string {
const address = ipaddr.process(value);
if (address.range() !== "unicast") throw refused();
return address.toString();
}
/** Reject the entire DNS answer set, then pin the connection to that verified set. */
export async function resolvePublicEvidenceHost(hostname: string) {
const values = await lookup(hostname.replace(/^\[|\]$/g, ""), { all: true });
if (!values.length) throw refused();
values.forEach((value) => normalizedPublicAddress(value.address));
return values;
}
const publicLookup: LookupFunction = (hostname, options, callback) => {
void resolvePublicEvidenceHost(hostname).then((values) => {
if (options.all) callback(null, values);
else callback(null, values[0].address, values[0].family);
}, () => callback(refused(), "", 0));
};
// Node's direct agent does not inherit HTTP proxy environment or ambient credentials.
export const publicEvidenceAgent = () => new Agent({ lookup: publicLookup });
export async function probePublicEvidenceUrl(url: URL): Promise<void> {
if (!['http:', 'https:'].includes(url.protocol)) throw refused();
const signal = AbortSignal.timeout(5_000);
const values = await Promise.race([
resolvePublicEvidenceHost(url.hostname),
new Promise<never>((_, reject) => signal.addEventListener("abort", () => reject(refused()), { once: true })),
]);
signal.throwIfAborted();
const allowed = new Set(values.map((value) => normalizedPublicAddress(value.address)));
const pinned: LookupFunction = (_hostname, options, callback) => {
if (options.all) callback(null, values);
else callback(null, values[0].address, values[0].family);
};
await new Promise<void>((resolve, reject) => {
const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, {
method: "GET", lookup: pinned, signal, agent: false,
}, (response) => {
try {
const peer = response.socket.remoteAddress;
if (!peer || !allowed.has(normalizedPublicAddress(peer)) || !response.statusCode || response.statusCode < 200 || response.statusCode >= 300) throw refused();
resolve();
} catch { reject(refused()); } finally { response.destroy(); }
});
request.on("error", () => reject(refused()));
request.end();
});
}
@@ -0,0 +1,77 @@
import { createHash } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
import { z } from "zod";
import { databaseConfigurationSchema } from "./configuration-schema.js";
import { CATALOG_SECRET_IDS } from "./secrets.js";
import type { CatalogRepository } from "./types.js";
import type { CatalogService } from "./service.js";
import type { CatalogOperationCoordinator } from "./operation-coordinator.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
import type { WorkspaceSecretStore } from "../workspaces/secret-store.js";
import { discoverWorkspaceSecretRequirements } from "../workspaces/secret-requirements.js";
const secret = z.string().min(1).refine(value => Buffer.byteLength(value, "utf8") <= 65536);
export const installationBindingSchema = z.object({
schemaVersion: z.literal(1), revision: z.string().regex(/^[a-f0-9]{40}$/),
configuration: databaseConfigurationSchema,
secrets: z.object({ password: secret.optional(), apiKey: secret.optional(), sshPrivateKey: secret.optional(),
sshPrivateKeyPassphrase: secret.optional(), sshKnownHosts: secret.optional(), tlsCa: secret.optional() }).strict(),
evidenceSecrets: z.object({ "evidence.signed_urls": secret.optional(), "evidence.access_key": secret.optional(),
"evidence.secret_key": secret.optional(), "evidence.session_token": secret.optional() }).strict(),
}).strict();
export class InstallationReconciliationRequired extends Error {}
const conflict = () => { throw new InstallationReconciliationRequired("Reconcile the prepared documents with current administrative state."); };
/** Only called behind the ordinary authenticated administration permission boundary. */
export class InstallationBindings {
constructor(private readonly repository: CatalogRepository, private readonly catalog: CatalogService,
private readonly registry: WorkspaceRegistry, private readonly secrets: WorkspaceSecretStore,
private readonly operations: CatalogOperationCoordinator, private readonly installationId: string) {}
async apply(raw: unknown) {
const request = installationBindingSchema.parse(raw);
const workspaceId = request.configuration.workspaceId;
const { workspace, revision } = await this.registry.read(workspaceId);
if (revision.commit !== request.revision) return conflict();
const input = await this.catalog.normalizeInput(request.configuration);
const required = input.binding.transport === "rest_api" ? (input.binding.restAuth === "none" ? [] : ["apiKey"])
: input.binding.transport === "ssh_tunnel" ? ["password", "sshPrivateKey", "sshKnownHosts"] : ["password"];
if (required.some(name => !request.secrets[name as keyof typeof request.secrets])) return conflict();
const evidenceRequirements = discoverWorkspaceSecretRequirements(workspace, {}).filter(item => item.connector === "evidence" && item.required);
if (evidenceRequirements.some(item => !(request.evidenceSecrets as Record<string, string>)[item.id])) return conflict();
const values: Record<string, string> = { ...request.evidenceSecrets };
for (const [name, value] of Object.entries(request.secrets)) values[CATALOG_SECRET_IDS[name as keyof typeof CATALOG_SECRET_IDS]] = value;
// Stable installation-local identity is persisted atomically with the initial binding.
// A crash before any host journal update is recoverable without adopting a manually created row.
const hex = createHash("sha256").update(`thothii-installation-binding-v1\0${this.installationId}\0${workspaceId}`).digest("hex");
const id = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
const applied = await this.operations.run(id, async () => {
let current = await this.repository.getByWorkspace(workspaceId);
let changed = false;
if (!current) { current = await this.repository.create(input, id); changed = true; }
if (current.id !== id || !isDeepStrictEqual(input, {
workspaceId: current.workspaceId, engine: current.engine, databaseName: current.databaseName,
schema: current.schema, binding: Object.fromEntries(Object.entries(current.binding).filter(([, value]) => value !== undefined)),
})) return conflict();
const configured = this.secrets.configured(workspaceId).filter(name => name.startsWith("catalog.") || name.startsWith("evidence."));
if (configured.some(name => values[name] === undefined || !this.secrets.matches(workspaceId, name, values[name]))) return conflict();
const missing = Object.fromEntries(Object.entries(values).filter(([name]) => !configured.includes(name)));
if (Object.keys(missing).length) {
if (current.version !== 1) return conflict();
// Synchronous atomic vault update cannot interleave with another mutation in this core.
this.secrets.putMany(workspaceId, missing); changed = true;
}
if (current.version === 1) {
const touched = await this.repository.touch(id, current.version);
if (!touched) return conflict();
current = touched; changed = true;
}
return { current, changed };
});
const tested = await this.catalog.test(applied.current);
if (!tested || tested.version !== applied.current.version || (await this.registry.read(workspaceId)).revision.commit !== request.revision) return conflict();
return { schemaVersion: 1, workspaceId, databaseId: tested.id, version: tested.version,
status: applied.changed ? "applied" : "unchanged", connectionStatus: tested.connectionStatus };
}
}
+10 -4
View File
@@ -52,6 +52,7 @@ function clone(value: WorkspaceDatabase): WorkspaceDatabase {
/** Deterministic repository used by route tests and local contract consumers. */
export class MemoryCatalogRepository implements CatalogRepository {
private readonly records = new Map<string, WorkspaceDatabase>();
private readonly installationImports = new Set<string>();
private readonly tables = new Map<string, CatalogTable>();
private readonly columns = new Map<string, CatalogColumn>();
private readonly relationships = new Map<string, CatalogPhysicalRelationship>();
@@ -77,6 +78,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
async beginPreprocessing(
workspaceId: string,
inputFingerprint: string,
runId?: string,
): Promise<CatalogPreprocessingStartResult> {
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
if (!database) return { kind: "not_found" };
@@ -95,6 +97,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
...database,
preprocessingStatus: "running",
preprocessingInputFingerprint: inputFingerprint,
preprocessingRunId: runId,
preprocessedMetadataRevision: undefined,
preprocessingStartedAt: now,
preprocessingFinishedAt: undefined,
@@ -109,12 +112,14 @@ export class MemoryCatalogRepository implements CatalogRepository {
metadataContentRevision: number,
inputFingerprint: string,
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
runId?: string,
): Promise<WorkspaceDatabase | undefined> {
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
if (!database
|| database.preprocessingStatus !== "running"
|| database.metadataContentRevision !== metadataContentRevision
|| database.preprocessingInputFingerprint !== inputFingerprint) return undefined;
|| database.preprocessingInputFingerprint !== inputFingerprint
|| database.preprocessingRunId !== runId) return undefined;
const updated: WorkspaceDatabase = {
...database,
preprocessingStatus: outcome.status,
@@ -175,13 +180,13 @@ export class MemoryCatalogRepository implements CatalogRepository {
...relationships.map((relationship) => relationship.updatedAt),
]));
}
async create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase> {
if ([...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) {
async create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase> {
if ((creationId && this.installationImports.has(input.workspaceId)) || [...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) {
throw new CatalogConflictError("Workspace database already exists");
}
const now = new Date().toISOString();
const record: WorkspaceDatabase = {
id: randomUUID(),
id: creationId ?? randomUUID(),
...structuredClone(input),
version: 1,
createdAt: now,
@@ -191,6 +196,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
preprocessingStatus: "failed",
};
this.records.set(record.id, record);
if (creationId) this.installationImports.add(input.workspaceId);
return clone(record);
}
async update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined> {
+4
View File
@@ -16,6 +16,8 @@ import * as canonicalModelIdsMigration from "./migrations/010_canonical_model_id
import * as localSensitivityAnalysisMigration from "./migrations/011_local_sensitivity_analysis.js";
import * as sensitivityReasonMigration from "./migrations/012_sensitivity_reason.js";
import * as catalogPreprocessingStateMigration from "./migrations/013_catalog_preprocessing_state.js";
import * as installationBindingImportsMigration from "./migrations/014_installation_binding_imports.js";
import * as preprocessingRunIdentityMigration from "./migrations/015_preprocessing_run_identity.js";
const connectionString = process.env.THT_CATALOG_MIGRATOR_DATABASE_URL;
const host = process.env.THT_CATALOG_DB_HOST;
@@ -54,6 +56,8 @@ const provider: MigrationProvider = {
"011_local_sensitivity_analysis": localSensitivityAnalysisMigration,
"012_sensitivity_reason": sensitivityReasonMigration,
"013_catalog_preprocessing_state": catalogPreprocessingStateMigration,
"014_installation_binding_imports": installationBindingImportsMigration,
"015_preprocessing_run_identity": preprocessingRunIdentityMigration,
};
},
};
@@ -0,0 +1,16 @@
import { type Kysely, sql } from "kysely";
import type { CatalogDatabase } from "../repository.js";
/** Import receipts survive administrative deletion; they contain no credentials or configuration. */
export async function up(db: Kysely<CatalogDatabase>): Promise<void> {
await db.schema.createTable("installation_binding_imports")
.addColumn("workspace_id", "text", column => column.primaryKey())
// Deliberately no cascading FK: absence of a previously imported database requires reconciliation.
.addColumn("database_id", "uuid", column => column.notNull().unique())
.addColumn("created_at", "timestamptz", column => column.notNull().defaultTo(sql`now()`))
.execute();
}
export async function down(db: Kysely<CatalogDatabase>): Promise<void> {
await db.schema.dropTable("installation_binding_imports").execute();
}
@@ -0,0 +1,13 @@
import type { Kysely } from "kysely";
import type { CatalogDatabase } from "../repository.js";
/** Fences late completions when recovery repeats exactly the same input revision. */
export async function up(db: Kysely<CatalogDatabase>): Promise<void> {
await db.schema.alterTable("workspace_databases")
.addColumn("preprocessing_run_id", "text").execute();
}
export async function down(db: Kysely<CatalogDatabase>): Promise<void> {
await db.schema.alterTable("workspace_databases")
.dropColumn("preprocessing_run_id").execute();
}
+10 -2
View File
@@ -76,6 +76,7 @@ interface WorkspaceDatabaseTable {
metadataContentRevision: Generated<number>;
preprocessingStatus: Generated<WorkspaceDatabase["preprocessingStatus"]>;
preprocessingInputFingerprint: Generated<string | null>;
preprocessingRunId: Generated<string | null>;
preprocessedMetadataRevision: Generated<number | null>;
preprocessingStartedAt: NullableTimestamp;
preprocessingFinishedAt: NullableTimestamp;
@@ -273,6 +274,7 @@ interface CatalogSyncEventTable {
}
export interface CatalogDatabase {
installationBindingImports: { workspaceId: string; databaseId: string; createdAt: Generated<Date> };
workspaceDatabases: WorkspaceDatabaseTable;
databaseBindings: DatabaseBindingTable;
catalogTables: CatalogTableTable;
@@ -342,6 +344,7 @@ function serialize(row: JoinedRow): WorkspaceDatabase {
metadataContentRevision: Number(row.metadataContentRevision),
preprocessingStatus: row.preprocessingStatus,
preprocessingInputFingerprint: present(row.preprocessingInputFingerprint),
preprocessingRunId: present(row.preprocessingRunId),
preprocessedMetadataRevision: row.preprocessedMetadataRevision == null
? undefined
: Number(row.preprocessedMetadataRevision),
@@ -507,6 +510,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
async beginPreprocessing(
workspaceId: string,
inputFingerprint: string,
runId?: string,
): Promise<CatalogPreprocessingStartResult> {
return await this.db.transaction().execute(async (trx) => {
const database = await trx.selectFrom("workspaceDatabases")
@@ -539,6 +543,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
.set({
preprocessingStatus: "running",
preprocessingInputFingerprint: inputFingerprint,
preprocessingRunId: runId ?? null,
preprocessedMetadataRevision: null,
preprocessingStartedAt: sql`now()`,
preprocessingFinishedAt: null,
@@ -556,6 +561,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
metadataContentRevision: number,
inputFingerprint: string,
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
runId?: string,
): Promise<WorkspaceDatabase | undefined> {
const result = await this.db.updateTable("workspaceDatabases")
.set({
@@ -569,6 +575,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
.where("preprocessingStatus", "=", "running")
.where("metadataContentRevision", "=", metadataContentRevision)
.where("preprocessingInputFingerprint", "=", inputFingerprint)
.where("preprocessingRunId", runId === undefined ? "is" : "=", runId ?? null)
.returning("id")
.executeTakeFirst();
return result ? await this.get(result.id) : undefined;
@@ -681,10 +688,11 @@ export class KyselyCatalogRepository implements CatalogRepository {
}, row.updatedAt === null ? null : new Date(row.updatedAt).toISOString());
}
async create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase> {
async create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase> {
try {
return await this.db.transaction().execute(async (trx) => {
const id = randomUUID();
const id = creationId ?? randomUUID();
if (creationId) await trx.insertInto("installationBindingImports").values({ workspaceId: input.workspaceId, databaseId: id }).execute();
await trx.insertInto("workspaceDatabases").values({
id,
workspaceId: input.workspaceId,
+4 -1
View File
@@ -40,6 +40,7 @@ export interface WorkspaceDatabase {
metadataContentRevision: number;
preprocessingStatus: CatalogPreprocessingStatus;
preprocessingInputFingerprint?: string;
preprocessingRunId?: string;
preprocessedMetadataRevision?: number;
preprocessingStartedAt?: string;
preprocessingFinishedAt?: string;
@@ -453,16 +454,18 @@ export interface CatalogRepository {
beginPreprocessing(
workspaceId: string,
inputFingerprint: string,
runId?: string,
): Promise<CatalogPreprocessingStartResult>;
finishPreprocessing(
workspaceId: string,
metadataContentRevision: number,
inputFingerprint: string,
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
runId?: string,
): Promise<WorkspaceDatabase | undefined>;
clearPreprocessing(workspaceId: string): Promise<CatalogPreprocessingClearResult>;
getCatalogMetrics(databaseId?: string): Promise<CatalogMetrics | undefined>;
create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase>;
create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase>;
update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined>;
recordTest(id: string, expectedVersion: number, result: DatabaseTestResult): Promise<WorkspaceDatabase | undefined>;
touch(id: string, expectedVersion: number): Promise<WorkspaceDatabase | undefined>;
+121 -1
View File
@@ -16,12 +16,16 @@ import { loadSettings } from "./settings/settings-store.js";
import { ThtRunner, type SessionRow } from "./tht/tht-runner.js";
import { WorkspaceRegistry } from "./workspaces/registry.js";
import { WorkspaceSecretStore } from "./workspaces/secret-store.js";
import { createProductionWorkspaceDiagnoser } from "./workspaces/diagnostics.js";
import { resolveCatalogRuntimeBinding } from "./catalog/runtime-binding.js";
import { CatalogService } from "./catalog/service.js";
import { validateOperationalWorkspace } from "./workspaces/schema.js";
import { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js";
type OperatorAction = "maintenance-activate" | "maintenance-deactivate" | "maintenance-status"
| "session-inventory" | "workflow-doctor" | "workspace-integrity"
| "pi-test" | "effective-settings";
| "workspace-pull" | "workspace-test" | "pi-test" | "effective-settings";
const lifecyclePrincipal: PrincipalContext = {
issuer: "tht-operator-command",
@@ -119,6 +123,119 @@ async function workspaceIntegrity(config: AppConfig): Promise<{
return { ready: true, ...integrity };
}
async function workspacePull(config: AppConfig): Promise<{
ready: boolean;
status: "succeeded" | "degraded";
branch: string;
head?: string;
degraded: boolean;
}> {
const status = await new WorkspaceRegistry(config.workspaceRegistry).pull();
return {
ready: !status.degraded,
status: status.degraded ? "degraded" : "succeeded",
branch: status.branch,
...(status.head ? { head: status.head } : {}),
degraded: status.degraded,
};
}
interface WorkspaceTestReport {
id: string;
status: "ready" | "failed";
database: "reachable" | "not_configured" | "failed";
diagnostics: string[];
}
async function workspaceTest(config: AppConfig): Promise<{
ready: boolean;
workspaces: WorkspaceTestReport[];
}> {
if (!config.catalogDatabase) throw new Error("Catalog database is not configured");
const registry = new WorkspaceRegistry(config.workspaceRegistry);
const revisions = await registry.list();
const repository = createCatalogRepository(config.catalogDatabase);
try {
const secretStore = new WorkspaceSecretStore({
root: config.workspaceSecretStoreRoot,
runtimeRoot: config.workspaceSecretRuntimeRoot,
installationId: config.workspaceRegistry.installationId,
});
const catalogService = new CatalogService(
repository,
registry,
secretStore,
config.workspaceRegistry.secretRoots,
config.workspaceDiagnosticTimeoutMs,
);
const diagnose = createProductionWorkspaceDiagnoser(config.workspaceDiagnosticTimeoutMs, undefined, {
internalQdrantUrl: config.internalQdrantUrl,
internalEmbeddingUrl: config.internalEmbeddingUrl,
internalEmbeddingId: config.internalEmbeddingId,
internalEmbeddingModel: config.internalEmbeddingModel,
internalEmbeddingDimensions: config.internalEmbeddingDimensions,
});
const databases = await repository.list();
const reports: WorkspaceTestReport[] = [];
for (const revision of revisions) {
const diagnostics: string[] = [];
let workspace: ReturnType<typeof validateOperationalWorkspace>;
try {
workspace = validateOperationalWorkspace((await registry.read(revision.id)).workspace);
} catch {
reports.push({ id: revision.id, status: "failed", database: "not_configured", diagnostics: ["workspace_invalid"] });
continue;
}
const database = databases.find((candidate) => candidate.workspaceId === revision.id);
if (!database) {
reports.push({ id: revision.id, status: "failed", database: "not_configured", diagnostics: ["database_binding_missing"] });
continue;
}
let tested;
try {
tested = await catalogService.test(database);
} catch {
reports.push({ id: revision.id, status: "failed", database: "failed", diagnostics: ["database_unreachable"] });
continue;
}
if (!tested || tested.connectionStatus !== "reachable") {
reports.push({ id: revision.id, status: "failed", database: "failed", diagnostics: ["database_unreachable"] });
continue;
}
let lease: ReturnType<typeof resolveCatalogRuntimeBinding>;
try {
lease = resolveCatalogRuntimeBinding({
workspace,
database: tested,
environment: process.env,
secretRoots: config.workspaceRegistry.secretRoots,
secretStore,
});
} catch {
reports.push({ id: revision.id, status: "failed", database: "reachable", diagnostics: ["binding_missing"] });
continue;
}
try {
// CatalogService.test() above is the authoritative database probe and records its
// outcome. The remaining diagnoser pass checks Evidence and internal semantic services;
// skipping its legacy DWH probe avoids requiring a second response-shape contract for a
// REST health endpoint.
const result = await diagnose(lease.workspace, lease.bindings, { writeProbe: false, skipDwh: true });
diagnostics.push(...result.diagnostics.map((diagnostic) => diagnostic.code));
const ready = result.activatable;
reports.push({ id: revision.id, status: ready ? "ready" : "failed", database: "reachable", diagnostics });
} catch {
reports.push({ id: revision.id, status: "failed", database: "reachable", diagnostics: ["connector_unavailable"] });
} finally {
lease.release();
}
}
return { ready: reports.length > 0 && reports.every((report) => report.status === "ready"), workspaces: reports };
} finally {
await repository.close?.();
}
}
export async function runOperatorAction(
action: OperatorAction,
config: AppConfig,
@@ -132,6 +249,8 @@ export async function runOperatorAction(
if (action === "session-inventory") return await sessionInventory(config);
if (action === "workflow-doctor") return await workflowDiagnostics(config);
if (action === "workspace-integrity") return await workspaceIntegrity(config);
if (action === "workspace-pull") return await workspacePull(config);
if (action === "workspace-test") return await workspaceTest(config);
const modelCatalog = loadRuntimeModelCatalog(config.modelCatalogFile);
if (action === "effective-settings") {
return effectiveSettings(config, loadSettings(config), modelCatalog);
@@ -146,6 +265,7 @@ async function main(): Promise<void> {
if (!action || ![
"maintenance-activate", "maintenance-deactivate", "maintenance-status", "session-inventory",
"workflow-doctor", "workspace-integrity", "pi-test", "effective-settings",
"workspace-pull", "workspace-test",
].includes(action)) throw new Error("invalid operator action");
const result = await runOperatorAction(action, loadConfig(process.env));
process.stdout.write(`${JSON.stringify(result)}\n`);
+1 -1
View File
@@ -155,7 +155,7 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
const installationConfig = (): PiInstallationConfig => {
const settings = readSettings();
const reasoning = config.defaults.thinking ?? settings.thinking;
const reasoning = config.defaults.thinking ?? settings.thinking ?? "low";
const selected = deps.modelCatalog.defaultInteraction
? splitCanonicalModelId(deps.modelCatalog.defaultInteraction)
: undefined;
+1 -42
View File
@@ -1,60 +1,19 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { isPrincipalContext, requirePermission } from "../auth/authorization.js";
import { parseCredentialFreeHttpUrl } from "../auth/url-policy.js";
import { databaseConfigurationSchema as configSchema } from "../catalog/configuration-schema.js";
import { CatalogService, type CatalogSecretName } from "../catalog/service.js";
import { WorkspaceRegistryError } from "../workspaces/git-repository.js";
import {
CatalogConflictError,
CatalogOperationInProgressError,
CatalogUnavailableError,
DATABASE_TRANSPORTS,
type CatalogRepository,
type DatabaseConfigurationInput,
} from "../catalog/types.js";
import type { CatalogOperationCoordinator } from "../catalog/operation-coordinator.js";
const idSchema = z.uuid();
const workspaceIdSchema = z.string().regex(/^[a-z][a-z0-9-]{2,62}$/);
const identifier = z.string().trim().min(1).max(128).regex(/^[A-Za-z_][A-Za-z0-9_$-]*$/);
const nonEmpty = z.string().trim().min(1).max(512);
const port = z.number().int().min(1).max(65_535);
const optionalText = nonEmpty.optional();
const sshHost = z.string().trim().min(1).max(255).regex(/^[A-Za-z0-9_.:\[\]-]+$/).optional();
const sshUsername = z.string().trim().min(1).max(128).regex(/^[A-Za-z0-9._-]+$/).optional();
const bindingSchema = z.object({
transport: z.enum(DATABASE_TRANSPORTS),
host: optionalText,
port: port.optional(),
username: optionalText,
baseUrl: z.string().max(2048)
.refine((value) => parseCredentialFreeHttpUrl(value) !== undefined)
.optional(),
restPath: z.string().regex(/^\/(?!\/)[^?#\\\u0000-\u001f]*$/).max(512).optional(),
restAuth: z.enum(["none", "bearer", "x-api-key"]).optional(),
tlsServername: optionalText,
sshHost,
sshPort: port.optional(),
sshUsername,
sshTargetHost: sshHost,
sshTargetPort: port.optional(),
}).strict().superRefine((binding, context) => {
const required = binding.transport === "postgres_direct"
? ["host", "port", "username"] as const
: binding.transport === "rest_api"
? ["baseUrl", "restPath", "restAuth"] as const
: ["username", "sshHost", "sshPort", "sshUsername", "sshTargetHost", "sshTargetPort"] as const;
for (const field of required) {
if (binding[field] === undefined) context.addIssue({ code: "custom", path: [field], message: "Required" });
}
});
const configSchema = z.object({
workspaceId: workspaceIdSchema,
engine: z.literal("postgres"),
databaseName: identifier,
schema: identifier,
binding: bindingSchema,
}).strict();
const updateSchema = configSchema.extend({ version: z.number().int().positive() });
const secretNames = [
"password",
+38
View File
@@ -0,0 +1,38 @@
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { isPrincipalContext, requirePermission } from "../auth/authorization.js";
import { InstallationBindings, InstallationReconciliationRequired } from "../catalog/installation-bindings.js";
import { CatalogConflictError, CatalogOperationInProgressError } from "../catalog/types.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
const sourceSchema = z.object({ remote: z.string().min(1).max(4096), branch: z.string().min(1).max(256),
revision: z.string().regex(/^(?:[a-f0-9]{40}|content-snapshot)$/),
files: z.record(z.string().min(1).max(4096), z.string().regex(/^[a-f0-9]{64}$/))
.refine(files => Object.keys(files).length > 0 && Object.keys(files).length <= 10000),
}).strict();
export function installationRoutes(app: FastifyInstance, bindings: InstallationBindings, registry: WorkspaceRegistry): void {
app.post("/installation/workspace-source", { bodyLimit: 2 * 1024 * 1024 }, async (request, reply) => {
if (!isPrincipalContext(requirePermission(request, reply, "workspace.manage"))) return reply;
try { return await registry.prepareInstallation(sourceSchema.parse(request.body)); }
catch (error) {
return reply.code(error instanceof z.ZodError ? 400 : 409).send({ code: "installation_workspace_reconciliation_required" });
}
});
app.post("/installation/bindings", { bodyLimit: 1024 * 1024 }, async (request, reply) => {
for (const permission of ["workspace.manage", "database.manage", "workspace.secrets.manage"] as const) {
if (!isPrincipalContext(requirePermission(request, reply, permission))) return reply;
}
try {
const result = await bindings.apply(request.body);
return reply.code(result.connectionStatus === "reachable" ? 200 : 422).send(result);
} catch (error) {
if (error instanceof z.ZodError) return reply.code(400).send({ code: "installation_input_invalid" });
if (error instanceof CatalogOperationInProgressError) return reply.code(409).send({ code: "installation_operation_pending" });
if (error instanceof InstallationReconciliationRequired || error instanceof CatalogConflictError) {
return reply.code(409).send({ code: "installation_reconciliation_required" });
}
return reply.code(503).send({ code: "installation_binding_unavailable" });
}
});
}
@@ -10,6 +10,7 @@ import type { ThtRunner } from "../tht/tht-runner.js";
import type { WorkspacePreprocessingService } from "../workspaces/preprocessing-service.js";
import type { PreprocessingJobState } from "../workspaces/preprocessing-state.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
import { PreprocessingStateError } from "../workspaces/preprocessing-state.js";
const workspaceIdSchema = z.string().regex(/^[a-z][a-z0-9-]{2,62}$/);
const ACTIVE_SYNC_STATES = new Set(["queued", "running", "awaiting_confirmation", "applying"]);
@@ -317,6 +318,9 @@ export async function readWorkspacePreprocessingStatus(
}
function safeError(reply: FastifyReply, error: unknown) {
if (error instanceof PreprocessingStateError) {
return reply.code(409).send({ code: "preprocessing_conflict", state: "running", message: "Preprocessing is still owned by another process." });
}
if (error instanceof CatalogUnavailableError) {
return reply.code(503).send({
code: "catalog_unavailable",
@@ -357,7 +361,8 @@ export function workspacePreprocessingRoutes(
try {
const workspaceId = workspaceIdFrom(request);
const before = await readWorkspacePreprocessingStatus(workspaceId, deps);
if (!before.actionable) {
const options = z.object({ recoverInterrupted: z.boolean().optional() }).strict().parse(request.body ?? {});
if (!before.actionable && !(before.state === "running" && options.recoverInterrupted)) {
return reply.code(409).send({ ...before, code: "preprocessing_blocked" });
}
+10
View File
@@ -0,0 +1,10 @@
/** Compiled with its runtime for the host CLI: no installation, Docker or host Node required. */
import { runWorkspaceDocuments } from "./workspaces/documents.js";
import { runBootstrapValidation } from "./catalog/bootstrap-cli.js";
import { runBootstrapProbes } from "./catalog/bootstrap-probes.js";
const args = process.argv.slice(2);
const result = args[0] === "probe" ? await runBootstrapProbes(args.slice(1))
: args[0] === "bootstrap" ? runBootstrapValidation(args.slice(1)) : runWorkspaceDocuments(args);
console.log(result.output);
process.exitCode = result.status;
+4 -2
View File
@@ -9,6 +9,7 @@ import { WorkspaceSecretStore } from "./workspaces/secret-store.js";
import { WorkspacePreprocessingService, type WorkspaceOperationResult } from "./workspaces/preprocessing-service.js";
import { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js";
import { guardedPreprocessingCommand } from "./workspaces/preprocessing-owner.js";
export interface WorkspaceMaintenanceIo {
stdin: string;
@@ -238,7 +239,7 @@ export function createProductionWorkspacePreprocessingService(
active.releaseSecrets();
}
},
runChild: async ({ argv, configPath }) => {
runChild: async ({ argv, configPath, guard }) => {
const configFd = openSync(configPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
try {
return await new Promise((resolve) => {
@@ -254,7 +255,8 @@ export function createProductionWorkspacePreprocessingService(
"THT_CATALOG_MIGRATOR_USER",
"THT_CATALOG_MIGRATOR_PASSWORD_FILE",
]) delete childEnvironment[name];
const child = spawn(config.thtBin, argv, {
const command = guard ? guardedPreprocessingCommand(guard, config.thtBin, argv) : { executable: config.thtBin, args: argv };
const child = spawn(command.executable, command.args, {
cwd: config.harnessDir,
env: { ...childEnvironment, ...(config.dataRoot ? { THT_DATA_ROOT: config.dataRoot } : {}) },
stdio: ["ignore", "pipe", "pipe", configFd],
+3 -3
View File
@@ -44,8 +44,8 @@ const catalogSchema = z.object({
});
});
function safeCatalogError(): Error {
return new Error("Workspace catalog is invalid");
function safeCatalogError(cause?: unknown): Error {
return new Error("Workspace catalog is invalid", { cause });
}
export function parseWorkspaceCatalogYaml(source: string): WorkspaceCatalog {
@@ -57,7 +57,7 @@ export function parseWorkspaceCatalogYaml(source: string): WorkspaceCatalog {
return catalogSchema.parse(document.toJSON()) as WorkspaceCatalog;
} catch (error) {
if (error instanceof Error && error.message === "Workspace catalog is invalid") throw error;
throw safeCatalogError();
throw safeCatalogError(error);
}
}
+222
View File
@@ -0,0 +1,222 @@
import { closeSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { parseAllDocuments, stringify } from "yaml";
import { ZodError } from "zod";
import { CATALOG_PATH, parseWorkspaceCatalogYaml, assertCatalogMatchesDescriptor } from "./catalog.js";
import { parseWorkspaceYaml, type WorkspaceDescriptor } from "./schema.js";
interface Issue { document: string; field: string; code: string; correction: string; line?: number }
interface Report {
schema_version: 1;
scope: "local-documents";
ok: boolean;
workspaces: { id: string; evidence: "absent" | "local-files" | "remote-deferred" }[];
issues: Issue[];
deferred_checks: string[];
}
const MAX_DOCUMENT_BYTES = 1024 * 1024;
const usage = "tht workspace prepare --directory NEW_PATH --id ID --name NAME [--language en|it] [--json]\ntht workspace validate --directory PATH [--json]";
export class DocumentError extends Error {
constructor(readonly issue: Issue) { super(issue.correction); }
}
function fail(document: string, field: string, code: string, correction: string): never {
throw new DocumentError({ document, field, code, correction });
}
/** Never include parser messages or submitted values: YAML and Zod errors can contain secrets. */
export function decode<T>(source: string, document: string, parser: (text: string) => T, contract = "workspace schema v4 or catalog schema v1"): T {
try {
const documents = parseAllDocuments(source, { uniqueKeys: true });
if (documents.length !== 1) fail(document, "$", "yaml_documents", "Keep exactly one YAML document in this file.");
const problem = [...documents[0].errors, ...documents[0].warnings][0];
if (problem) {
throw new DocumentError({ document, field: "$", code: "yaml_syntax", line: problem.linePos?.[0].line,
correction: "Correct YAML syntax, remove duplicate keys and unsupported tags at the indicated line." });
}
return parser(source);
} catch (error) {
if (error instanceof DocumentError) throw error;
const cause = error instanceof Error && error.cause instanceof ZodError ? error.cause : error;
if (cause instanceof ZodError) {
const issue = cause.issues[0];
// Strict schemas produce paths containing schema-defined keys and array indices only.
fail(document, issue.path.join(".") || "$", "schema_invalid",
issue.code === "unrecognized_keys" ? "Remove fields not defined by the current workspace/catalog contract."
: `Correct this field using ${contract}; check type, required value, uniqueness and allowed values.`);
}
fail(document, "$", "schema_invalid", "Use an authored workspace v4 descriptor; remove database configuration and keep it in the PostgreSQL Metadata Catalog.");
}
}
function stat(root: string, document: string, directory: boolean) {
let info;
try { info = lstatSync(join(root, document)); }
catch { fail(document, "$", "missing_reference", "Create the referenced local file or directory and grant read access."); }
if (info.isSymbolicLink() || (directory ? !info.isDirectory() : !info.isFile())) {
fail(document, "$", "unsafe_reference", "Use a regular local file or directory, without symbolic links or special files.");
}
return info;
}
function readDocument(root: string, document: string): string {
if (stat(root, document, false).size > MAX_DOCUMENT_BYTES) {
fail(document, "$", "document_too_large", "Keep YAML documents below the 1 MiB local validation limit.");
}
try { return readFileSync(join(root, document), "utf8"); }
catch { fail(document, "$", "unreadable", "Grant read access to this document and retry validation."); }
}
function directories(root: string, document: string) {
stat(root, document, true);
try { return readdirSync(join(root, document), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)); }
catch { fail(document, "$", "unreadable", "Grant read and traversal access to this directory and retry validation."); }
}
function inspectEvidence(root: string, descriptor: WorkspaceDescriptor): "absent" | "local-files" | "remote-deferred" {
const evidence = descriptor.evidence;
if (!evidence) return "absent";
if (evidence.source.type !== "filesystem") return "remote-deferred";
const base = evidence.source.uri;
stat(root, base, true);
if (evidence.schema_version === 2) stat(root, `${base}/curated`, true);
const patterns = evidence.source.patterns ?? ["**/*.md"];
const literals = patterns.filter((pattern) => !/[?*\[]/.test(pattern));
for (const pattern of literals) {
const parts = pattern.split("/");
for (let index = 1; index < parts.length; index++) stat(root, `${base}/${parts.slice(0, index).join("/")}`, true);
stat(root, `${base}/${pattern}`, false);
}
// Inventory without following links; curated-unit interpretation remains a runtime check.
const pending = [base];
let count = 0;
while (pending.length) {
const current = pending.pop()!;
for (const entry of directories(root, current)) {
if (++count > 100_000) fail(base, "evidence.source", "inventory_limit", "Reduce the Evidence tree below 100,000 entries before local validation.");
const path = `${current}/${entry.name}`;
if (entry.isDirectory()) pending.push(path);
else {
const info = stat(root, path, false);
const relative = path.slice(base.length + 1);
// Only apply content checks to selections whose meaning is unambiguous locally.
// Arbitrary globs are expanded by the canonical Python adapter after startup.
const curated = evidence.schema_version === 2 && relative.startsWith("curated/") && relative.endsWith(".md");
const selected = curated || literals.includes(relative) || (patterns.includes("**/*.md") && relative.endsWith(".md"));
if (selected && info.size > evidence.source.max_bytes) fail(path, "evidence.source.max_bytes", "evidence_too_large", "Reduce the source file or increase the declared max_bytes limit deliberately.");
try { closeSync(openSync(join(root, path), "r")); }
catch { fail(path, "$", "unreadable", "Grant read access to this Evidence file and retry validation."); }
if (curated) {
const text = readDocument(root, path);
const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
if (!frontmatter) fail(path, "$", "evidence_frontmatter", "Add a YAML frontmatter block delimited by --- to the curated Markdown unit; follow the Curated Evidence contract.");
decode(frontmatter[1], path, (source) => parseAllDocuments(source)[0].toJSON());
}
}
}
}
return "local-files";
}
function validate(root: string, report: Report): void {
directories(root, ".");
const catalog = decode(readDocument(root, CATALOG_PATH), CATALOG_PATH, parseWorkspaceCatalogYaml);
const ids = new Set(catalog.workspaces.map((entry) => entry.id));
for (const entry of directories(root, ".")) {
if (entry.name === ".git") continue;
if (entry.isSymbolicLink()) fail(".", "$", "unsafe_reference", "Replace repository-root symbolic links with regular files or directories.");
if (entry.isDirectory() && entry.name !== "workspace-docs" && !ids.has(entry.name)) {
fail(".", "workspaces", "unlisted_directory", "Every root directory except workspace-docs must match a catalog workspace id; remove or register the extra directory.");
}
if (entry.name === "workspace-docs") {
for (const docs of directories(root, "workspace-docs")) {
if (!ids.has(docs.name)) fail("workspace-docs", "$", "unlisted_documentation", "Keep documentation only for workspace ids listed in the catalog.");
for (const file of directories(root, `workspace-docs/${docs.name}`)) {
const path = `workspace-docs/${docs.name}/${file.name}`;
if (!["README.md", "contract.env.example"].includes(file.name)) fail(`workspace-docs/${docs.name}`, "$", "unsupported_documentation", "Keep only README.md and contract.env.example in workspace-docs/<id>. Place Evidence inside the workspace directory.");
stat(root, path, false);
}
}
}
}
for (const entry of catalog.workspaces) {
const document = `${entry.id}/workspace.yaml`;
try {
stat(root, entry.id, true);
const descriptor = decode(readDocument(root, document), document, parseWorkspaceYaml);
try { assertCatalogMatchesDescriptor(entry, descriptor); }
catch { fail(document, "workspace", "catalog_mismatch", "Make id, name and description identical in the catalog, descriptor and workspace directory name."); }
const evidence = inspectEvidence(root, descriptor);
report.workspaces.push({ id: entry.id, evidence });
if (evidence !== "absent") report.deferred_checks.push(`${entry.id}:evidence-source-selection`, `${entry.id}:evidence-content-provenance-and-indexing`);
if (evidence === "remote-deferred") report.deferred_checks.push(`${entry.id}:remote-evidence-access`);
} catch (error) {
if (error instanceof DocumentError) report.issues.push(error.issue);
else throw error;
}
}
}
function prepare(root: string, options: Map<string, string>): void {
const id = options.get("--id");
const name = options.get("--name");
const language = options.get("--language") ?? "en";
const catalog = stringify({ schema_version: 1, workspaces: [{ id, name }] });
const descriptor = stringify({ workspace: { schema_version: 4, id, name, language } });
decode(catalog, CATALOG_PATH, parseWorkspaceCatalogYaml);
decode(descriptor, "workspace.yaml", parseWorkspaceYaml);
try { mkdirSync(root); }
catch (error) {
if ((error as NodeJS.ErrnoException).code === "EEXIST") fail(".", "--directory", "destination_exists", "Choose a new directory; preparation never overwrites an existing directory or its documents.");
fail(".", "--directory", "destination_unavailable", "Create the parent directory and grant write access, then choose a new destination.");
}
try {
mkdirSync(join(root, id!));
mkdirSync(join(root, "workspace-docs", id!), { recursive: true });
writeFileSync(join(root, CATALOG_PATH), "# Index of workspace identities. Keep metadata identical to each descriptor.\n" + catalog, { flag: "wx" });
writeFileSync(join(root, id!, "workspace.yaml"), "# Authored workspace v4: optional Evidence; database binding belongs to the Metadata Catalog.\n" + descriptor, { flag: "wx" });
writeFileSync(join(root, "workspace-docs", id!, "README.md"),
"# Workspace documents / Documenti workspace\n\n" +
"EN: Edit thoth-workspaces.yaml and <id>/workspace.yaml together. Evidence is optional and absent by default. Add reviewed source material under <id>/evidence only when configured. Database connections and schema belong to the installation Metadata Catalog. No example databases are downloaded.\n\n" +
"IT: Modificare insieme thoth-workspaces.yaml e <id>/workspace.yaml. Le Evidence sono facoltative e inizialmente assenti. Inserire materiale verificato in <id>/evidence solo quando configurato. Connessioni e schema dei database appartengono al Metadata Catalog dell'installazione. Nessun database di esempio viene scaricato.\n\n" +
"Repeat / Ripetere: `tht workspace validate --directory <repository>`. Local success does not establish runtime readiness or semantic truth / Il successo locale non certifica readiness o verità semantica.\n", { flag: "wx" });
} catch {
rmSync(root, { recursive: true, force: true });
fail(".", "$", "prepare_failed", "Preparation could not write the documents; check disk space and permissions, then retry with a new directory.");
}
}
export function runWorkspaceDocuments(args: string[]): { status: number; output: string } {
const report: Report = { schema_version: 1, scope: "local-documents", ok: false, workspaces: [], issues: [], deferred_checks: ["catalog-database-binding", "database-connectivity", "runtime-preprocessing"] };
const json = args.includes("--json");
let status = 1;
try {
const [command, ...rest] = args;
if ((command === "prepare" || command === "validate") && rest.length === 1 && rest[0] === "--help") return { status: 0, output: usage };
const allowed = command === "prepare" ? ["--directory", "--id", "--name", "--language"] : command === "validate" ? ["--directory"] : [];
const options = new Map<string, string>();
const seen = new Set<string>();
for (let index = 0; index < rest.length; index++) {
const key = rest[index];
if (seen.has(key)) fail("CLI", "$", "usage", usage);
seen.add(key);
if (key === "--json") continue;
if (!allowed.includes(key) || !rest[index + 1] || rest[index + 1].startsWith("--")) fail("CLI", "$", "usage", usage);
options.set(key, rest[++index]);
}
if (!allowed.length || !options.has("--directory") || (command === "prepare" && (!options.has("--id") || !options.has("--name")))) fail("CLI", "$", "usage", usage);
const root = resolve(options.get("--directory")!);
if (command === "prepare") prepare(root, options);
validate(root, report);
report.ok = report.issues.length === 0;
status = report.ok ? 0 : 1;
} catch (error) {
report.issues.push(error instanceof DocumentError ? error.issue : { document: ".", field: "$", code: "io_error", correction: "Check local permissions and regular files, then retry; no services were started." });
if (report.issues[0].code === "usage") status = 2;
}
const output = json ? JSON.stringify(report) : [
report.ok ? "Workspace documents pass local validation." : "Workspace documents require corrections.",
...report.issues.map((issue) => `${issue.document}${issue.line ? `:${issue.line}` : ""} [${issue.field}] ${issue.code}: ${issue.correction}`),
...report.workspaces.map((entry) => `${entry.id}: Evidence ${entry.evidence}`),
`Deferred until runtime: ${report.deferred_checks.join(", ")}.`,
].join("\n");
return { status, output };
}
+33
View File
@@ -3,6 +3,7 @@ import { lstatSync, mkdirSync } from "node:fs";
import { mkdir } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { promisify, TextDecoder } from "node:util";
import { createHash } from "node:crypto";
import type { WorkspaceErrorCode, WorkspaceRegistryConfig } from "./types.js";
const execFileAsync = promisify(execFile);
@@ -29,6 +30,13 @@ export interface EvidenceTreeObject {
posixPath: string;
}
export interface PreparedWorkspaceSource {
remote: string;
branch: string;
revision: string;
files: Record<string, string>;
}
export class WorkspaceRegistryError extends Error {
constructor(readonly code: WorkspaceErrorCode, message: string) {
super(message);
@@ -187,6 +195,31 @@ export class GitWorkspaceRepository {
return await this.status();
}
/** Installation consumes exactly prepared contents; it never resets or retargets a checkout. */
async verifyPrepared(expected: PreparedWorkspaceSource): Promise<string> {
const mismatch = () => new WorkspaceRegistryError("workspace_stale", "Prepared workspace source differs from the configured repository.");
if (!this.config.remoteUrl || expected.branch !== this.config.branch || expected.remote !== this.config.remoteUrl) throw mismatch();
await this.ensureLayout();
if (isMissing(this.repoPath)) await this.clone();
const origin = (await this.git(["remote", "get-url", "origin"])).trim();
if (origin !== this.config.remoteUrl) throw mismatch();
if ((await this.git(["symbolic-ref", "--short", "HEAD"])).trim() !== expected.branch ||
(await this.git(["status", "--porcelain"])).trim()) throw mismatch();
const head = (await this.git(["rev-parse", "HEAD"])).trim();
if (expected.revision !== "content-snapshot" && expected.revision !== head) throw mismatch();
const entries = (await this.git(["ls-tree", "-r", "-z", head])).split("\0").filter(Boolean);
if (entries.length !== Object.keys(expected.files).length || entries.length > 10000) throw mismatch();
let total = 0;
for (const entry of entries) {
const match = /^(100644|100755) blob ([a-f0-9]{40})\t(.+)$/s.exec(entry);
if (!match || !Object.hasOwn(expected.files, match[3])) throw mismatch();
const bytes = await this.gitBlobBytes(match[2], 32 << 20, "prepared");
total += bytes.length;
if (total > 256 << 20 || createHash("sha256").update(bytes).digest("hex") !== expected.files[match[3]]) throw mismatch();
}
return head;
}
async pull(): Promise<GitStatus> {
await this.ensureLayout();
if (isMissing(this.repoPath)) return await this.bootstrap();
@@ -0,0 +1,43 @@
import { readFileSync } from "node:fs";
import { PreprocessingStateError, PreprocessingStateStore } from "./preprocessing-state.js";
export interface PreprocessingChildGuard {
lockPath: string;
tokenPath: string;
token: string;
}
// The parent lock excludes live orchestrators. Worker locks survive parent death;
// rotating the generation under their exclusive lock fences children not yet started.
export async function acquirePreprocessingOwner(dataRoot: string, workspaceId: string) {
const state = new PreprocessingStateStore({ dataRoot, workspaceId });
const owner = await state.acquireWriterLock();
try {
const workers = await state.acquireWriterLock("workers");
try {
const token = state.rotateOwnerToken();
return { guard: { lockPath: state.workerLockPath(), tokenPath: state.ownerTokenPath(), token }, release: owner.release,
assertOwned: () => {
if (!owner.isHeld() || readFileSync(state.ownerTokenPath(), "utf8") !== token) throw new PreprocessingStateError("preprocessing_conflict", "Preprocessing ownership was lost");
} };
} finally { await workers.release(); }
} catch (error) { await owner.release(); throw error; }
}
const guardedExec = [
"import fcntl, os, sys",
"fd = os.open(sys.argv[1], os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0))",
"try:",
" fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)",
"except BlockingIOError:",
" sys.exit(73)",
"token_fd = os.open(sys.argv[2], os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))",
"with os.fdopen(token_fd) as token_file:",
" if token_file.read(65) != sys.argv[3]: sys.exit(73)",
"os.set_inheritable(fd, True)",
"os.execvp(sys.argv[4], sys.argv[4:])",
].join("\n");
export function guardedPreprocessingCommand(guard: PreprocessingChildGuard, executable: string, args: string[]) {
return { executable: "python3", args: ["-c", guardedExec, guard.lockPath, guard.tokenPath, guard.token, executable, ...args] };
}
+63 -11
View File
@@ -16,6 +16,7 @@ import {
import type { DeterministicRuntimeConfigLease } from "./runtime-config-lease.js";
import { buildCatalogMetadataSnapshot } from "../catalog/metadata-snapshot.js";
import type { CatalogRepository } from "../catalog/types.js";
import { acquirePreprocessingOwner, type PreprocessingChildGuard } from "./preprocessing-owner.js";
export interface WorkspaceOperationResult {
schemaVersion: 1;
@@ -47,6 +48,7 @@ export interface WorkspaceOperationResult {
export interface ChildProcessRequest {
argv: string[];
configPath: string;
guard?: PreprocessingChildGuard;
}
interface ActiveRuntime {
@@ -79,6 +81,7 @@ export interface WorkspacePreprocessingServiceDeps {
}
interface RunScope {
owner: Awaited<ReturnType<typeof acquirePreprocessingOwner>>;
runtime: ActiveRuntime;
state: PreprocessingStateStore;
job: PreprocessingJobState;
@@ -205,13 +208,39 @@ export class WorkspacePreprocessingService {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
return baseResult(runtime, "preprocess run", "failed", "catalog_not_ready");
}
return await this.runFromCatalog(options);
const owner = await acquirePreprocessingOwner(this.deps.dataRoot, options.workspaceId);
try {
const previous = await this.deps.catalogRepository.getByWorkspace(options.workspaceId);
// Only runs created under this guard protocol can be reclaimed automatically.
const lastJob = this.state(options.workspaceId).readLatestJob();
if (previous?.preprocessingStatus === "running" && previous.preprocessingInputFingerprint
&& (lastJob?.ownerProtocol !== 1 || !previous.preprocessingRunId || lastJob.runId !== previous.preprocessingRunId)) {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
return baseResult(runtime, "preprocess run", "failed", "preprocessing_conflict",
{ warnings: ["An older preprocessing owner cannot be recovered automatically."] });
}
if (previous?.preprocessingStatus === "running" && previous.preprocessingInputFingerprint && lastJob?.ownerProtocol === 1) {
owner.assertOwned();
await this.deps.catalogRepository.finishPreprocessing(options.workspaceId,
previous.metadataContentRevision, previous.preprocessingInputFingerprint,
{ status: "failed", errorCode: "preprocessing_interrupted" }, previous.preprocessingRunId);
}
owner.assertOwned();
return await this.runFromCatalog(options, owner);
} finally { await owner.release(); }
}
async clear(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
const owner = await acquirePreprocessingOwner(this.deps.dataRoot, options.workspaceId);
try { return await this.clearOwned(options, owner); }
finally { await owner.release(); }
}
private async clearOwned(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
const repository = this.deps.catalogRepository;
if (!repository) return baseResult(runtime, "preprocess clear", "failed", "catalog_not_ready");
owner.assertOwned();
const cleared = await repository.clearPreprocessing(runtime.workspaceId);
if (cleared.kind !== "cleared") {
return baseResult(
@@ -224,7 +253,9 @@ export class WorkspacePreprocessingService {
const result = await this.deps.runChild({
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
configPath: runtime.configLease.path,
guard: owner.guard,
});
owner.assertOwned();
if (result.exitCode !== 0) {
return baseResult(runtime, "preprocess clear", "failed", "preprocessing_clear_failed");
}
@@ -234,11 +265,13 @@ export class WorkspacePreprocessingService {
});
}
private async runFromCatalog(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
const scope = await this.startRun(options.workspaceId);
private async runFromCatalog(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
const scope = await this.startRun(options.workspaceId, owner);
const repository = this.deps.catalogRepository!;
const fingerprint = scope.runtime.configLease.inputFingerprint;
const started = await repository.beginPreprocessing(scope.runtime.workspaceId, fingerprint);
owner.assertOwned();
const started = await repository.beginPreprocessing(scope.runtime.workspaceId, fingerprint, scope.job.runId);
owner.assertOwned();
if (started.kind !== "started") {
scope.job.status = "failed";
scope.state.writeJob(scope.job);
@@ -260,19 +293,23 @@ export class WorkspacePreprocessingService {
scope.runtime.workspaceId,
revision,
);
owner.assertOwned();
const snapshotPath = this.publishCatalogSnapshot(
scope.runtime.workspaceId,
JSON.stringify(snapshot),
);
this.completeStages(scope, "catalog_snapshot");
const semantic = await this.deps.semanticPreflight(scope.runtime.workspace);
owner.assertOwned();
if (!semantic.ok) {
await repository.finishPreprocessing(
scope.runtime.workspaceId,
revision,
fingerprint,
{ status: "failed", errorCode: semantic.code },
scope.job.runId,
);
owner.assertOwned();
scope.job.status = "failed";
scope.state.writeJob(scope.job);
finished = true;
@@ -280,7 +317,7 @@ export class WorkspacePreprocessingService {
}
failureCode = "schema_index_failed";
const payload = await this.runJsonStage(scope.runtime, [
const payload = await this.runJsonStage(scope, [
"preprocess",
"catalog",
"--catalog-metadata",
@@ -301,12 +338,15 @@ export class WorkspacePreprocessingService {
this.evidenceDependencies(scope),
);
if (!["succeeded", "unchanged"].includes(outcome.status)) {
owner.assertOwned();
await repository.finishPreprocessing(
scope.runtime.workspaceId,
revision,
fingerprint,
{ status: "failed", errorCode: outcome.code },
scope.job.runId,
);
owner.assertOwned();
scope.job.status = "failed";
scope.state.writeJob(scope.job);
finished = true;
@@ -319,29 +359,35 @@ export class WorkspacePreprocessingService {
revision,
fingerprint,
{ status: "succeeded" },
scope.job.runId,
);
owner.assertOwned();
if (!completed) throw new Error("catalog preprocessing completion lost its lease");
scope.job.status = "succeeded";
scope.state.writeJob(scope.job);
finished = true;
return this.evidenceResult(scope, outcome);
} catch (error) {
owner.assertOwned();
if (!finished) {
await repository.finishPreprocessing(
scope.runtime.workspaceId,
revision,
fingerprint,
{ status: "failed", errorCode: failureCode },
scope.job.runId,
);
}
owner.assertOwned();
scope.job.status = "failed";
scope.state.writeJob(scope.job);
throw error;
}
}
private async startRun(workspaceId: string): Promise<RunScope> {
private async startRun(workspaceId: string, owner: RunScope["owner"]): Promise<RunScope> {
const runtime = await this.deps.acquireActiveRuntime(workspaceId);
owner.assertOwned();
const state = this.state(runtime.workspaceId);
const job = await state.beginJob({
operation: "preprocess run",
@@ -353,7 +399,10 @@ export class WorkspacePreprocessingService {
embeddingId: runtime.configLease.effectiveConfig.embedding.id,
embeddingDimensions: runtime.configLease.effectiveConfig.embedding.dimensions,
});
return { runtime, state, job };
owner.assertOwned();
job.ownerProtocol = 1;
state.writeJob(job);
return { runtime, state, job, owner };
}
private state(workspaceId: string): PreprocessingStateStore {
@@ -361,6 +410,7 @@ export class WorkspacePreprocessingService {
}
private completeStages(scope: RunScope, ...stages: string[]): void {
scope.owner.assertOwned();
for (const stage of stages) {
if (!scope.job.completedStages.includes(stage)) scope.job.completedStages.push(stage);
}
@@ -384,8 +434,8 @@ export class WorkspacePreprocessingService {
private evidenceDependencies(scope: RunScope): EvidencePreprocessingDependencies {
return {
runStage: async (argv) => await this.runJsonStage(scope.runtime, argv),
persistJob: () => this.state(scope.runtime.workspaceId).writeJob(scope.job),
runStage: async (argv) => await this.runJsonStage(scope, argv),
persistJob: () => { scope.owner.assertOwned(); this.state(scope.runtime.workspaceId).writeJob(scope.job); },
evidencePreflight: async () => await this.deps.evidencePreflight(scope.runtime.workspace),
requireRunId: (value) => this.requireRunId(value),
numberRecord: (value) => this.numberRecord(value),
@@ -400,8 +450,10 @@ export class WorkspacePreprocessingService {
return baseResult(scope.runtime, "preprocess run", status, code, extra);
}
private async runJsonStage(runtime: ActiveRuntime, argv: string[]): Promise<Record<string, unknown>> {
const result = await this.deps.runChild({ argv, configPath: runtime.configLease.path });
private async runJsonStage(scope: RunScope, argv: string[]): Promise<Record<string, unknown>> {
scope.owner.assertOwned();
const result = await this.deps.runChild({ argv, configPath: scope.runtime.configLease.path, guard: scope.owner.guard });
scope.owner.assertOwned();
if (result.exitCode !== 0) throw new Error("workspace child failed");
return JSON.parse(result.stdout) as Record<string, unknown>;
}
+16 -3
View File
@@ -34,6 +34,7 @@ export interface SessionInventoryRow {
export interface WriterLockLease {
holderPid: number;
isHeld(): boolean;
release(): Promise<void>;
}
@@ -66,6 +67,7 @@ export interface PreprocessingJobState {
status: "active" | "succeeded" | "blocked" | "failed";
candidateDigest?: string;
reviewDigest?: string;
ownerProtocol?: 1;
}
export interface FkReviewRecord {
@@ -195,6 +197,14 @@ export class PreprocessingStateStore {
}
writerLockPath(): string { return join(this.root, "writer.lock"); }
workerLockPath(): string { return join(this.root, "workers.lock"); }
ownerTokenPath(): string { return join(this.root, "owner-token"); }
rotateOwnerToken(): string {
this.ensureLayout();
const token = randomBytes(32).toString("hex");
writeAtomicFile(this.ownerTokenPath(), token, 0o600);
return token;
}
runtimeConfigDirectory(): string { return join(this.root, "runtime-config"); }
runtimeConfigManifestDirectory(): string { return join(this.root, "runtime-config-manifests"); }
jobsDirectory(): string { return join(this.root, "jobs"); }
@@ -216,9 +226,9 @@ export class PreprocessingStateStore {
]) ensureDirectory(directory);
}
async acquireWriterLock(): Promise<WriterLockLease> {
async acquireWriterLock(kind: "writer" | "workers" = "writer"): Promise<WriterLockLease> {
this.ensureLayout();
const lockPath = this.writerLockPath();
const lockPath = kind === "writer" ? this.writerLockPath() : this.workerLockPath();
try {
const entry = lstatSync(lockPath);
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("invalid writer lock path");
@@ -257,11 +267,14 @@ export class PreprocessingStateStore {
let released = false;
return {
holderPid: holder.pid ?? 0,
isHeld: () => !released && holder.exitCode === null && holder.signalCode === null,
release: async () => {
if (released) return;
released = true;
if (holder.exitCode !== null || holder.signalCode !== null) return;
const exited = new Promise<void>((resolve) => holder.once("exit", () => resolve()));
if (!holder.stdin.destroyed) holder.stdin.end();
await new Promise<void>((resolve) => holder.once("exit", () => resolve()));
await exited;
},
};
}
+14
View File
@@ -13,6 +13,7 @@ import {
WorkspaceRepositoryLock,
normalizeRepositoryIdentity,
type GitStatus,
type PreparedWorkspaceSource,
} from "./git-repository.js";
import {
parseWorkspaceYaml,
@@ -121,6 +122,19 @@ export class WorkspaceRegistry {
});
}
async prepareInstallation(expected: PreparedWorkspaceSource): Promise<{ revision: string }> {
await this.repository.ensureLayout();
return await this.lock.run(async () => {
const head = await this.repository.verifyPrepared(expected);
const active = await this.tryActiveState();
if (active && active.head !== head) {
throw new WorkspaceRegistryError("workspace_stale", "Reconcile the active workspace revision before installation.");
}
if (!active) await this.activate(head);
return { revision: head };
});
}
async pull(): Promise<GitStatus> {
await this.repository.ensureLayout();
return await this.lock.run(async () => {
+16 -1
View File
@@ -11,7 +11,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { basename, join } from "node:path";
const STORE_ERROR = "Workspace secret store is unavailable.";
@@ -122,6 +122,21 @@ export class WorkspaceSecretStore {
return this.readVault().entries[entryKey(workspaceId, requirementId)] !== undefined;
}
/** Compare without exposing plaintext or a reusable digest to an API consumer. */
matches(workspaceId: string, requirementId: string, value: string): boolean {
const materialized = this.materialize(workspaceId, [requirementId]);
let current: Buffer | undefined;
const expected = Buffer.from(value, "utf8");
try {
const path = materialized.files.get(requirementId);
if (!path) return false;
current = readFileSync(path);
return current.length === expected.length && timingSafeEqual(current, expected);
} finally {
current?.fill(0); expected.fill(0); materialized.release();
}
}
generation(workspaceId: string): number {
assertIdentifier(workspaceId, "workspace identifier");
const vault = this.readVault();
@@ -0,0 +1,22 @@
import { expect, test } from "vitest";
import { MemoryCatalogRepository } from "../src/catalog/memory-repository.js";
test("the in-memory Catalog enforces the same attempt identity as PostgreSQL", async () => {
const repository = new MemoryCatalogRepository();
const database = await repository.create({ workspaceId: "retry", engine: "postgres",
databaseName: "warehouse", schema: "public",
binding: { transport: "postgres_direct", host: "db", port: 5432, username: "reader" } });
await repository.applySchemaSync(database.id, database.version, "all", [], {
schemaVersion: 1, capabilities: { tables: "available", columns: "available", relationships: "available" },
tables: [], columns: [], relationships: [],
});
const revision = (await repository.get(database.id))!.metadataContentRevision;
const fingerprint = "sha256:" + "1".repeat(64);
await repository.beginPreprocessing("retry", fingerprint, "old");
await repository.finishPreprocessing("retry", revision, fingerprint,
{ status: "failed", errorCode: "preprocessing_interrupted" }, "old");
await repository.beginPreprocessing("retry", fingerprint, "replacement");
expect(await repository.finishPreprocessing("retry", revision, fingerprint, { status: "succeeded" }, "old")).toBeUndefined();
expect(await repository.finishPreprocessing("retry", revision, fingerprint, { status: "succeeded" }, "replacement"))
.toMatchObject({ preprocessingStatus: "succeeded" });
});
@@ -1,5 +1,8 @@
import { spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { PostgreSqlContainer } from "@testcontainers/postgresql";
import { CamelCasePlugin, Kysely, PostgresDialect, sql } from "kysely";
import { Pool } from "pg";
@@ -19,6 +22,13 @@ import { up as upCanonicalModelIds } from "../src/catalog/migrations/010_canonic
import { up as upLocalSensitivityAnalysis } from "../src/catalog/migrations/011_local_sensitivity_analysis.js";
import { up as upSensitivityReason } from "../src/catalog/migrations/012_sensitivity_reason.js";
import { up as upCatalogPreprocessingState } from "../src/catalog/migrations/013_catalog_preprocessing_state.js";
import { up as upInstallationBindingImports } from "../src/catalog/migrations/014_installation_binding_imports.js";
import { up as upPreprocessingRunIdentity } from "../src/catalog/migrations/015_preprocessing_run_identity.js";
import { InstallationBindings } from "../src/catalog/installation-bindings.js";
import { CatalogService } from "../src/catalog/service.js";
import { CatalogOperationCoordinator } from "../src/catalog/operation-coordinator.js";
import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js";
import type { WorkspaceRegistry } from "../src/workspaces/registry.js";
const dockerAvailable = spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0;
@@ -60,6 +70,8 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
await upLocalSensitivityAnalysis(db);
await upSensitivityReason(db);
await upCatalogPreprocessingState(db);
await upInstallationBindingImports(db);
await upPreprocessingRunIdentity(db);
await expect(db.selectFrom("sensitiveDataSuggestionRuns")
.select(["engine", "modelId", "policyVersion", "unknown"])
.where("id", "=", historicalSuggestionRunId)
@@ -302,6 +314,16 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
preprocessingStatus: "succeeded",
preprocessedMetadataRevision: beforePreprocessing.metadataContentRevision,
});
const fingerprint = "sha256:" + "1".repeat(64);
await repository.beginPreprocessing("preprocessing-lock", fingerprint, "old-run");
await repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
fingerprint, { status: "failed", errorCode: "preprocessing_interrupted" }, "old-run");
await repository.beginPreprocessing("preprocessing-lock", fingerprint, "replacement-run");
// Identical inputs must not let a late completion finish the replacement run.
await expect(repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
fingerprint, { status: "failed", errorCode: "late-owner" }, "old-run")).resolves.toBeUndefined();
await expect(repository.finishPreprocessing("preprocessing-lock", beforePreprocessing.metadataContentRevision,
fingerprint, { status: "succeeded" }, "replacement-run")).resolves.toMatchObject({ preprocessingStatus: "succeeded" });
await db.insertInto("catalogTables").values({
id: randomUUID(),
databaseId: lockedDatabase.id,
@@ -319,6 +341,37 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
expect(await repository.delete(created.id, 2)).toBe(true);
expect(await repository.list()).toEqual([]);
expect(await repository.listTables(created.id)).toEqual([]);
// Installation import uses the real transactional Catalog and a read-only PostgreSQL login.
await sql`CREATE ROLE installation_reader LOGIN PASSWORD 'installation-test-password'`.execute(db);
await sql`GRANT USAGE ON SCHEMA public TO installation_reader`.execute(db);
const secretRoot = mkdtempSync(join(tmpdir(), "catalog-installation-"));
try {
const secrets = new WorkspaceSecretStore({ root: secretRoot, installationId: "integration" });
const revision = "a".repeat(40);
const registry = { read: async () => ({ workspace: { workspace: { schema_version: 4, id: "installation-test", name: "Test", language: "en" } },
revision: { commit: revision } }) } as unknown as WorkspaceRegistry;
const operations = new CatalogOperationCoordinator();
const service = new CatalogService(repository, registry, secrets, [], 5000, undefined, operations);
const importer = new InstallationBindings(repository, service, registry, secrets, operations, "integration");
const request = { schemaVersion: 1, revision, configuration: {
workspaceId: "installation-test", engine: "postgres", databaseName: container.getDatabase(), schema: "public",
binding: { transport: "postgres_direct", host: container.getHost(), port: container.getPort(), username: "installation_reader" },
}, secrets: { password: "installation-test-password" }, evidenceSecrets: {} };
const applied = await importer.apply(request);
expect(applied).toMatchObject({ status: "applied", connectionStatus: "reachable", version: 2 });
const generation = secrets.generation("installation-test");
expect(await importer.apply(request)).toEqual({ ...applied, status: "unchanged" });
expect(secrets.generation("installation-test")).toBe(generation);
expect(await repository.update(applied.databaseId, 1, request.configuration as never)).toBeUndefined();
await repository.touch(applied.databaseId, applied.version);
secrets.put("installation-test", "catalog.dwh.password", "administrative-change");
await expect(importer.apply(request)).rejects.toThrow("Reconcile");
expect(secrets.matches("installation-test", "catalog.dwh.password", "administrative-change")).toBe(true);
const currentImport = (await repository.get(applied.databaseId))!;
expect(await repository.delete(applied.databaseId, currentImport.version)).toBe(true);
await expect(importer.apply(request)).rejects.toThrow("Workspace database already exists");
expect(await repository.getByWorkspace("installation-test")).toBeUndefined();
} finally { rmSync(secretRoot, { recursive: true, force: true }); }
} finally {
await db.destroy();
await container.stop();
@@ -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"] },
@@ -0,0 +1,49 @@
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { afterEach, expect, test } from "vitest";
import { validateDatabaseBootstrap } from "../src/catalog/bootstrap-documents.js";
import { runBootstrapValidation } from "../src/catalog/bootstrap-cli.js";
const roots: string[] = [];
afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })));
function fixture() {
const root = mkdtempSync(join(tmpdir(), "bootstrap-documents-")); roots.push(root);
mkdirSync(join(root, "practice"));
writeFileSync(join(root, "thoth-workspaces.yaml"), "schema_version: 1\nworkspaces: [{id: practice, name: Practice}]\n");
writeFileSync(join(root, "practice/workspace.yaml"), "workspace: {schema_version: 4, id: practice, name: Practice, language: en}\n");
return root;
}
const entry = { workspaceId: "practice", engine: "postgres", databaseName: "practice", schema: "public", binding: { transport: "postgres_direct", host: "db.internal", port: 5432, username: "reader" }, secretFiles: { password: "/private/operator/db-password" } };
test("bootstrap reuses Catalog configuration and requires one complete binding per workspace", () => {
const root = fixture();
const valid = validateDatabaseBootstrap({ schemaVersion: 1, databases: [entry] }, root);
expect(valid.secretFiles).toContainEqual({ field: "databases.0.secretFiles.password", path: "/private/operator/db-password" });
for (const databases of [[], [entry, entry], [{ ...entry, workspaceId: "unknown" }], [{ ...entry, secretFiles: {} }], [{ ...entry, engine: "mysql" }], [{ ...entry, binding: { ...entry.binding, port: 70000 } }]]) {
expect(() => validateDatabaseBootstrap({ schemaVersion: 1, databases }, root)).toThrow();
}
});
test("REST authentication, SSH credentials and optional Evidence use their declared contracts", () => {
const root = fixture();
const rest = { ...entry, binding: { transport: "rest_api", baseUrl: "https://data.internal", restPath: "/query", restAuth: "none" }, secretFiles: {} };
expect(validateDatabaseBootstrap({ schemaVersion: 1, databases: [rest] }, root).secretFiles).toEqual([]);
expect(() => validateDatabaseBootstrap({ schemaVersion: 1, databases: [{ ...rest, binding: { ...rest.binding, restAuth: "bearer" } }] }, root)).toThrow();
const ssh = { ...entry, binding: { transport: "ssh_tunnel", username: "reader", sshHost: "bastion", sshPort: 22, sshUsername: "tunnel", sshTargetHost: "database", sshTargetPort: 5432 }, secretFiles: { password: "/password", sshPrivateKey: "/key", sshKnownHosts: "/hosts" } };
expect(validateDatabaseBootstrap({ schemaVersion: 1, databases: [ssh] }, root).warnings[0]).toContain("not NL-to-SQL");
writeFileSync(join(root, "practice/workspace.yaml"), "workspace: {schema_version: 4, id: practice, name: Practice, language: en}\nevidence:\n source:\n type: http\n uris: [https://docs.internal/manual.md]\n authentication: signed_urls_file\n");
expect(() => validateDatabaseBootstrap({ schemaVersion: 1, databases: [entry] }, root)).toThrow();
expect(validateDatabaseBootstrap({ schemaVersion: 1, databases: [{ ...entry, evidenceSecretFiles: { "evidence.signed_urls": "/urls.json" } }] }, root).secretFiles).toContainEqual({ field: "databases.0.evidenceSecretFiles.evidence.signed_urls", path: "/urls.json" });
});
test("bootstrap CLI never echoes arbitrary keys from submitted secret references", () => {
const root = fixture();
const path = join(root, "bootstrap.yaml");
for (const field of ["secretFiles", "evidenceSecretFiles"]) {
writeFileSync(path, JSON.stringify({ schemaVersion: 1, databases: [{ ...entry, [field]: { PRIVATE_CREDENTIAL_SENTINEL: "/path" } }] }));
const result = runBootstrapValidation(["--directory", root, "--bootstrap", path, "--json"]);
expect(result.status).toBe(1);
expect(result.output).not.toContain("PRIVATE_CREDENTIAL_SENTINEL");
}
});
+166
View File
@@ -0,0 +1,166 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn } from "node:child_process";
import { createLocalAuthFixture, localPassword } from "./auth-test-fixtures.js";
import { afterEach, expect, test, vi } from "vitest";
import { buildApp } from "../src/app.js";
import { loadConfig } from "../src/config.js";
import { MemoryCatalogRepository } from "../src/catalog/memory-repository.js";
import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js";
import type { WorkspaceRegistry } from "../src/workspaces/registry.js";
const roots: string[] = [];
afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })));
const commit = "a".repeat(40);
const configuration = { workspaceId: "chinook", engine: "postgres", databaseName: "chinook", schema: "public",
binding: { transport: "postgres_direct", host: "database", port: 5432, username: "reader" } };
function setup(environment: Record<string, string> = {}) {
const root = mkdtempSync(join(tmpdir(), "installation-binding-")); roots.push(root);
const secrets = new WorkspaceSecretStore({ root, installationId: "installation" });
const repository = new MemoryCatalogRepository();
const registry = {
read: vi.fn(async () => ({ workspace: { workspace: { schema_version: 4, id: "chinook", name: "Chinook", language: "en" } },
revision: { id: "chinook", commit, blob: "b".repeat(40) } })),
} as unknown as WorkspaceRegistry;
const app = buildApp(loadConfig({ NODE_ENV: "test", THT_HARNESS_DIR: "/missing", ...environment }), {
workspaceRegistry: registry, workspaceSecretStore: secrets, catalogRepository: repository,
catalogPostgresAccess: { connect: async () => ({ query: async () => ({ rows: [{ database: "chinook", schema: "public" }] }), end: async () => {} }) } as never,
});
const apply = (values = { password: "private-test-password" }) => app.inject({ method: "POST", url: "/installation/bindings",
payload: { schemaVersion: 1, revision: commit, configuration, secrets: values, evidenceSecrets: {} } });
return { app, apply, repository, secrets, registry };
}
test("prepared binding is imported once and equivalent rerun preserves credentials and version", async () => {
const { app, apply, repository, secrets } = setup();
try {
const first = await apply(); expect(first.statusCode).toBe(200);
expect(first.json()).toMatchObject({ status: "applied", connectionStatus: "reachable" });
const generation = secrets.generation("chinook");
const before = await repository.getByWorkspace("chinook");
const second = await apply(); expect(second.statusCode).toBe(200);
expect(second.json()).toMatchObject({ status: "unchanged", databaseId: before!.id, version: before!.version });
expect(secrets.generation("chinook")).toBe(generation);
expect(await repository.list()).toHaveLength(1);
expect(second.body).not.toContain("private-test-password");
} finally { await app.close(); }
});
test("released pipe client uses real local login, CSRF and logout without exposing credentials", async () => {
const original = setup(); await original.app.close();
const registry = original.registry;
registry.prepareInstallation = async () => ({ revision: commit });
const fixture = await createLocalAuthFixture({ workspaceRegistry: registry,
workspaceSecretStore: original.secrets, catalogRepository: original.repository,
catalogPostgresAccess: { connect: async () => ({ query: async () => ({ rows: [{ database: "chinook", schema: "public" }] }), end: async () => {} }) } as never,
});
try {
const address = await fixture.app.listen({ host: "127.0.0.1", port: 0 });
const payload = { username: "Admin", password: localPassword, origin: fixture.publicUrl,
source: { remote: "https://example.invalid/workspaces.git", branch: "main", revision: commit,
files: { "thoth-workspaces.yaml": "a".repeat(64) } },
databases: [{ schemaVersion: 1, configuration, secrets: { password: "private-test-password" }, evidenceSecrets: {} }] };
const run = () => new Promise<{ code: number | null; output: string }>((resolve, reject) => {
const child = spawn(process.execPath, ["--input-type=module", "-e",
`import { importPreparedBindings } from '../tools/tht/internal/installapply/import-bindings.mjs'; await importPreparedBindings(${JSON.stringify(address)});`], {
env: process.env, stdio: ["pipe", "pipe", "pipe"],
});
let output = ""; child.stdout.on("data", data => { output += data; }); child.stderr.on("data", data => { output += data; });
child.once("error", reject); child.once("close", code => resolve({ code, output }));
child.stdin.end(JSON.stringify(payload));
});
for (let i = 0; i < 2; i++) {
const result = await run();
expect(result).toEqual({ code: 0, output: JSON.stringify({ ok: true, code: "bindings_ready", completed: 1 }) });
}
expect(await original.repository.list()).toHaveLength(1);
} finally { await fixture.close(); }
});
test("administrative binding and credential changes require reconciliation without overwriting", async () => {
const { app, apply, repository, secrets } = setup();
try {
expect((await apply()).statusCode).toBe(200);
const current = (await repository.getByWorkspace("chinook"))!;
secrets.put("chinook", "catalog.dwh.password", "changed-by-administrator");
expect((await apply()).statusCode).toBe(409);
expect(secrets.matches("chinook", "catalog.dwh.password", "changed-by-administrator")).toBe(true);
const modified = { ...current, binding: { ...current.binding, host: "different-database" } };
await repository.update(current.id, current.version, modified);
expect((await apply()).statusCode).toBe(409);
expect((await repository.get(current.id))!.binding.host).toBe("different-database");
} finally { await app.close(); }
});
test("a manually configured binding is never silently adopted", async () => {
const { app, apply, repository } = setup();
try {
const created = await app.inject({ method: "POST", url: "/catalog/databases", payload: configuration });
expect(created.statusCode).toBe(201);
expect((await apply()).statusCode).toBe(409);
expect(await repository.list()).toHaveLength(1);
} finally { await app.close(); }
});
test("administrative deletion remains a reconciliation stop rather than recreating a binding", async () => {
const { app, apply, repository, secrets } = setup();
try {
expect((await apply()).statusCode).toBe(200);
const database = (await repository.getByWorkspace("chinook"))!;
const deleted = await app.inject({ method: "DELETE", url: `/catalog/databases/${database.id}?version=${database.version}` });
expect(deleted.statusCode).toBe(204);
expect((await apply()).statusCode).toBe(409);
expect(await repository.list()).toHaveLength(0);
expect(secrets.has("chinook", "catalog.dwh.password")).toBe(false);
} finally { await app.close(); }
});
test("interruption after Catalog commit resumes the same identity without a host journal", async () => {
const { app, apply, repository } = setup();
const create = repository.create.bind(repository);
vi.spyOn(repository, "create").mockImplementationOnce(async (...args) => {
await create(...args); throw new Error("simulated connection loss after commit");
});
try {
expect((await apply()).statusCode).toBe(503);
const current = (await repository.getByWorkspace("chinook"))!;
expect((await apply()).json()).toMatchObject({ databaseId: current.id, connectionStatus: "reachable" });
expect(await repository.list()).toHaveLength(1);
} finally { await app.close(); }
});
test("concurrent imports cannot duplicate or replace credentials", async () => {
const { app, apply, repository, secrets } = setup();
let entered!: () => void;
let release!: () => void;
const started = new Promise<void>(resolve => { entered = resolve; });
const continueCreation = new Promise<void>(resolve => { release = resolve; });
const create = repository.create.bind(repository);
vi.spyOn(repository, "create").mockImplementationOnce(async (...args) => {
entered(); await continueCreation; return create(...args);
});
try {
const first = apply();
await started;
const second = await apply();
release();
const results = [await first, second];
expect(results.map(result => result.statusCode).sort()).toEqual([200, 409]);
expect(await repository.list()).toHaveLength(1);
expect(secrets.matches("chinook", "catalog.dwh.password", "private-test-password")).toBe(true);
} finally { release(); await app.close(); }
});
test("imports and source activation require an authenticated administrator", async () => {
const { app, repository } = setup({ AUTH_MODE: "upstream" });
try {
for (const url of ["/installation/bindings", "/installation/workspace-source"]) {
expect((await app.inject({ method: "POST", url, payload: {} })).statusCode).toBe(401);
expect((await app.inject({ method: "POST", url, payload: {}, headers: {
"x-thoth-principal-issuer": "portal", "x-thoth-principal-subject": "reader", "x-thoth-is-admin": "0",
} })).statusCode).toBe(403);
}
expect(await repository.list()).toHaveLength(0);
} finally { await app.close(); }
});
@@ -0,0 +1,67 @@
import { spawnSync } from "node:child_process";
import { chmodSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { rootCertificates } from "node:tls";
import { afterEach, expect, test } from "vitest";
const binary = process.env.THT_INSTALLATION_TEST_CLI;
const roots: string[] = [];
afterEach(() => roots.splice(0).forEach((path) => rmSync(path, { recursive: true, force: true })));
function run(...args: string[]) {
return spawnSync(binary!, [...args, "--json"], { encoding: "utf8", env: { ...process.env, PATH: "" }, input: "" });
}
test.skipIf(!binary)("operator prepares, completes and repeatedly validates before any stack exists", () => {
const root = realpathSync(mkdtempSync(join(tmpdir(), "application-documents-"))); roots.push(root);
const workspace = join(root, "workspaces"), directory = join(root, "installation");
expect(run("workspace", "prepare", "--directory", workspace, "--id", "practice", "--name", "Practice").status).toBe(0);
expect(run("installation", "prepare", "--directory", directory).status).toBe(0);
const installation = join(directory, "thothii-installation.yaml");
const validate = () => run("--installation", installation, "installation", "validate", "--workspaces", workspace);
expect(validate().status).toBe(1); // Visible placeholders cannot be approved.
expect(run("installation", "credentials", "--directory", directory).status).toBe(0);
for (const name of ["thothii-installation.yaml", "operator.env", "database-bootstrap.yaml"]) {
const path = join(directory, name);
writeFileSync(path, readFileSync(path, "utf8").replaceAll("CHANGE_ME", "practice"));
}
for (const [name, contents] of Object.entries({ "secrets.env": "OPENAI_API_KEY=PRIVATE_PROVIDER_VALUE\n", "database-password": "PRIVATE_DATABASE_VALUE", "git-credentials": "", "git-ca.pem": rootCertificates[0] })) {
writeFileSync(join(directory, "secrets", name), contents, { mode: 0o600 });
}
const before = readFileSync(installation, "utf8");
for (let index = 0; index < 2; index++) {
const checked = validate();
expect(checked.stderr).toBe("");
expect(checked.stdout).not.toContain("PRIVATE_");
expect(checked.status, checked.stdout).toBe(0);
expect(JSON.parse(checked.stdout).deferred_checks).toContain("release-assets");
}
expect(readFileSync(installation, "utf8")).toBe(before);
writeFileSync(installation, before.replace("interaction: openai/gpt-4.1-mini", "interaction: openai/nonexistent"));
expect(validate().status).toBe(1);
writeFileSync(installation, before);
const authFile = join(directory, "secrets/pi-auth.json");
writeFileSync(authFile, "not-json");
expect(validate().status).toBe(1);
writeFileSync(installation, before.replace("{mode: secret_env, apiKeyEnv: OPENAI_API_KEY}", "{mode: pi_auth}"));
writeFileSync(authFile, JSON.stringify({ openai: { unrelated: true } }));
expect(validate().status).toBe(1);
writeFileSync(authFile, JSON.stringify({ " OpenAI ": { type: "api_key", key: "PRIVATE_PI_KEY" } }));
expect(validate().status).toBe(1);
writeFileSync(authFile, JSON.stringify({ openai: { type: "api_key", key: "PRIVATE_PI_KEY" } }));
expect(validate().status).toBe(0);
writeFileSync(installation, before);
writeFileSync(authFile, "{}");
const bootstrap = join(directory, "database-bootstrap.yaml");
const originalBootstrap = readFileSync(bootstrap, "utf8");
writeFileSync(join(workspace, "practice", "private-password"), "PRIVATE_DATABASE_VALUE", { mode: 0o600 });
writeFileSync(bootstrap, originalBootstrap.replace(join(directory, "secrets/database-password"), join(workspace, "practice/private-password")));
expect(validate().status).toBe(1);
writeFileSync(bootstrap, originalBootstrap);
chmodSync(join(directory, "secrets/database-password"), 0o644);
expect(validate().status).toBe(1);
chmodSync(join(directory, "secrets/database-password"), 0o600);
const env = join(directory, "operator.env");
writeFileSync(env, readFileSync(env, "utf8") + "THOTH_HTTP_PORT=8081\n");
expect(validate().status).toBe(1);
}, 15_000);
@@ -0,0 +1,43 @@
import { createServer } from "node:http";
import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import { probeBootstrapDependencies } from "../src/catalog/bootstrap-probes.js";
import { probePublicEvidenceUrl } from "../src/catalog/evidence-probe-http.js";
it("refuses loopback literals and DNS answers before sending an Evidence GET", async () => {
for (const hostname of ["[::1]", "127.0.0.1", "localhost", "[::ffff:127.0.0.1]"]) {
await expect(probePublicEvidenceUrl(new URL(`http://${hostname}/private`))).rejects.toThrow("Evidence network policy refused");
}
});
it("authenticates a bounded read-only REST probe and blocks unavailable credentials/services", async () => {
const directory = mkdtempSync(join(tmpdir(), "tht-probe-"));
const secret = join(directory, "key");
writeFileSync(secret, "PRIVATE_SENTINEL", { mode: 0o600 });
let status = 200;
const requests: string[] = [];
const server = createServer((req, res) => {
requests.push(`${req.method} ${req.url}`);
res.writeHead(req.headers.authorization === "Bearer PRIVATE_SENTINEL" ? status : 401);
res.end("PRIVATE_SERVER_RESPONSE");
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as { port: number };
const document = { schemaVersion: 1, databases: [{ workspaceId: "demo", engine: "postgres", databaseName: "demo", schema: "public", binding: { transport: "rest_api", baseUrl: `http://127.0.0.1:${address.port}`, restPath: "/health", restAuth: "bearer" }, secretFiles: { apiKey: secret } }] };
try {
expect((await probeBootstrapDependencies(document)).ok).toBe(true);
status = 503;
const failed = await probeBootstrapDependencies(document);
expect(failed.ok).toBe(false);
expect(JSON.stringify(failed)).not.toContain("PRIVATE");
status = 200;
writeFileSync(secret, "rotated-but-invalid");
expect((await probeBootstrapDependencies(document)).ok).toBe(false);
expect(requests).toEqual(["GET /health", "GET /health", "GET /health"]);
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
rmSync(directory, { recursive: true });
}
});
@@ -0,0 +1,89 @@
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, importBinding } from "../../tools/tht/internal/installapply/import-bindings.mjs";
const revision = "a".repeat(40);
test("a stranded preprocessing state requests guarded recovery, then verifies fresh readiness", async () => {
let state = "running";
const request = async (path: string, body?: unknown): Promise<Response> => {
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")) {
if (body) { expect(body).toEqual({ recoverInterrupted: true }); state = "ready"; }
return Response.json({ state });
}
throw Error("unexpected operation");
};
expect(await prepareWorkspace(request, "chinook", revision, async () => {})).toEqual({ workspaceId: "chinook", state: "ready" });
});
test("retry reaches a pending human schema review even when its reservation blocks binding import", async () => {
const request = async (path: string) => {
if (path === "/installation/bindings") return Response.json({ code: "installation_operation_pending" }, { status: 409 });
if (path === "/catalog/databases") return Response.json([{ workspaceId: "chinook", activeSyncRun: { id: "run-id", state: "awaiting_confirmation" } }]);
throw Error("unexpected operation");
};
await expect(importBinding(request, { configuration: { workspaceId: "chinook" } }, revision, async () => {})).rejects.toMatchObject({ code: "schema_review_required", runId: "run-id" });
});
test.each(["blocked", "failed"])("configured Evidence/index failure (%s) remains a real stop", async state => {
const request = async (path: string, body?: unknown): Promise<Response> => {
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"]);
});
@@ -0,0 +1,34 @@
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, test } from "vitest";
import { WorkspaceRegistry } from "../src/workspaces/registry.js";
const roots: string[] = [];
afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })));
test("activates only the prepared source contents and never retargets an existing checkout", async () => {
const root = mkdtempSync(join(tmpdir(), "installation-source-")); roots.push(root);
const remote = join(root, "source"); mkdirSync(join(remote, "chinook"), { recursive: true });
const files: Record<string, string> = {
"thoth-workspaces.yaml": "schema_version: 1\nworkspaces: [{id: chinook, name: Chinook}]\n",
"chinook/workspace.yaml": "workspace:\n schema_version: 4\n id: chinook\n name: Chinook\n language: en\n",
};
for (const [path, value] of Object.entries(files)) writeFileSync(join(remote, path), value);
const git = (args: string[], cwd = remote) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
git(["init", "-b", "main"]); git(["add", "."]);
git(["-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-m", "fixture"]);
const revision = git(["rev-parse", "HEAD"]);
const config = { root: join(root, "registry"), remoteUrl: remote, branch: "main", installationId: "test", secretRoots: [] };
const registry = new WorkspaceRegistry(config);
const expected = { remote, branch: "main", revision, files: Object.fromEntries(Object.entries(files).map(([path, value]) => [path, createHash("sha256").update(value).digest("hex")])) };
await expect(registry.prepareInstallation({ ...expected, files: { ...expected.files, "chinook/workspace.yaml": "0".repeat(64) } })).rejects.toThrow();
await expect(registry.verifyStoredState()).rejects.toThrow();
await expect(registry.prepareInstallation(expected)).resolves.toMatchObject({ revision });
await expect(registry.prepareInstallation(expected)).resolves.toMatchObject({ revision });
const checkout = join(config.root, "repo");
git(["remote", "set-url", "origin", join(root, "another")], checkout);
await expect(registry.prepareInstallation(expected)).rejects.toThrow();
expect(git(["remote", "get-url", "origin"], checkout)).toBe(join(root, "another"));
expect(readFileSync(join(checkout, "chinook/workspace.yaml"), "utf8")).toBe(files["chinook/workspace.yaml"]);
});
+14
View File
@@ -36,6 +36,10 @@ vi.mock("../src/tht/tht-runner.js", () => ({
vi.mock("../src/workspaces/registry.js", () => ({
WorkspaceRegistry: class {
async pull() {
return { branch: "main", head: "a".repeat(40), ahead: 0, behind: 0, degraded: false };
}
async listRetainedSnapshots() {
return [{ snapshotPath: "/data/workspace-registry/snapshots/revision/workspace.yaml" }];
}
@@ -98,3 +102,13 @@ test("workflow doctor gives schema-v4 runtime rendering a live Catalog repositor
expect(fakes.releaseWorkspaceRuntime).toHaveBeenCalledOnce();
expect(fakes.catalogRepository.close).toHaveBeenCalledOnce();
});
test("workspace pull exposes only safe Git status", async () => {
await expect(runOperatorAction("workspace-pull", config)).resolves.toEqual({
ready: true,
status: "succeeded",
branch: "main",
head: "a".repeat(40),
degraded: false,
});
});
+11
View File
@@ -54,6 +54,17 @@ const modelCatalog: RuntimeModelCatalog = {
hasSession: (id) => id === "zai/glm-5.2",
};
test("a fresh installation can smoke-test its catalog default without saved user settings", async () => {
const smokeProvider = vi.fn(async () => undefined);
const service = createPiManagement(configFor(), {
modelCatalog, execute: successfulExec([]), readSettings: () => ({}), smokeProvider,
});
expect(await service.test()).toMatchObject({ ready: true });
expect(smokeProvider).toHaveBeenCalledWith(expect.objectContaining({
provider: "zai", model: "glm-5.2", reasoning: "low",
}));
});
function successfulExec(calls: Array<{ command: string; args: string[]; timeout: number }>): PiExecFile {
return async (command, args, options) => {
calls.push({ command, args, timeout: options.timeout });
+25
View File
@@ -0,0 +1,25 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { expect, test } from "vitest";
import { acquirePreprocessingOwner, guardedPreprocessingCommand } from "../src/workspaces/preprocessing-owner.js";
test("orphan worker prevents recovery; delayed old worker is fenced after recovery", async () => {
const root = mkdtempSync(join(tmpdir(), "preprocess-owner-"));
let worker;
try {
const owner = await acquirePreprocessingOwner(root, "chinook");
const command = guardedPreprocessingCommand(owner.guard, "python3", ["-c", "import time; print('ready',flush=True); time.sleep(30)"]);
worker = spawn(command.executable, command.args, { stdio: ["ignore", "pipe", "pipe"] });
await new Promise<void>((resolve, reject) => { worker!.stdout!.once("data", () => resolve()); worker!.once("error", reject); worker!.once("exit", () => reject(Error("worker stopped early"))); });
await owner.release();
await expect(acquirePreprocessingOwner(root, "chinook")).rejects.toMatchObject({ code: "preprocessing_conflict" });
const exited = new Promise(resolve => worker!.once("exit", resolve)); worker.kill("SIGKILL"); await exited;
const replacement = await acquirePreprocessingOwner(root, "chinook");
try {
const stale = guardedPreprocessingCommand(owner.guard, "python3", ["-c", "raise Exception('must never run')"]);
expect(spawnSync(stale.executable, stale.args).status).toBe(73);
} finally { await replacement.release(); }
} finally { worker?.kill("SIGKILL"); rmSync(root, { recursive: true, force: true }); }
});
@@ -0,0 +1,119 @@
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, expect, test } from "vitest";
import { parseWorkspaceCatalogYaml } from "../src/workspaces/catalog.js";
import { parseWorkspaceYaml } from "../src/workspaces/schema.js";
const roots: string[] = [];
function directory() {
const root = mkdtempSync(join(tmpdir(), "tht-documents-"));
roots.push(root);
return join(root, "workspaces");
}
afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })));
function cli(...args: string[]) {
const packaged = process.env.THT_WORKSPACE_TEST_CLI;
const result = spawnSync(packaged ?? process.execPath, [...(packaged ? ["workspace"] : ["--import", "tsx", resolve("src/workspace-documents-cli.ts")]), ...args, "--json"], {
encoding: "utf8", env: { ...process.env, PATH: "" },
});
return { ...result, report: result.stdout.trim() ? JSON.parse(result.stdout) : null };
}
const descriptor = "workspace:\n schema_version: 4\n id: practice\n name: Practice\n language: en\n";
const catalog = "schema_version: 1\nworkspaces:\n - id: practice\n name: Practice\n";
const corpus = [
{ name: "minimal", descriptor, catalog, valid: true },
{ name: "optional Evidence", descriptor: descriptor + "evidence:\n source:\n type: http\n uris: [https://example.com/manual.md]\n", catalog, valid: true },
{ name: "duplicate YAML key", descriptor: descriptor + " id: practice\n", catalog, valid: false },
{ name: "ambiguous document", descriptor: descriptor + "---\n" + descriptor, catalog, valid: false },
{ name: "unknown workspace field", descriptor: descriptor + " secret: VERY_SECRET_VALUE\n", catalog, valid: false },
{ name: "database binding in authored descriptor", descriptor: descriptor + "dwh: {password: VERY_SECRET_VALUE}\n", catalog, valid: false },
{ name: "duplicate catalog id", descriptor, catalog: catalog + " - id: practice\n name: Practice\n", valid: false },
{ name: "unknown catalog field", descriptor, catalog: catalog + "secret: VERY_SECRET_VALUE\n", valid: false },
{ name: "invalid catalog YAML", descriptor, catalog: catalog + "schema_version: 1\n", valid: false },
{ name: "unsafe Evidence URI", descriptor: descriptor + "evidence:\n source:\n type: http\n uris: [https://user:VERY_SECRET_VALUE@example.com/file]\n", catalog, valid: false },
];
test.each(corpus)("CLI and runtime agree: $name", (fixture) => {
const root = directory();
mkdirSync(join(root, "practice"), { recursive: true });
writeFileSync(join(root, "thoth-workspaces.yaml"), fixture.catalog);
writeFileSync(join(root, "practice/workspace.yaml"), fixture.descriptor);
let accepted = true;
try { parseWorkspaceCatalogYaml(fixture.catalog); parseWorkspaceYaml(fixture.descriptor); }
catch { accepted = false; }
expect(accepted).toBe(fixture.valid);
const checked = cli("validate", "--directory", root);
expect(checked.status).toBe(fixture.valid ? 0 : 1);
expect(checked.report.ok).toBe(accepted);
expect(checked.stdout + checked.stderr).not.toContain("VERY_SECRET_VALUE");
if (!fixture.valid) {
expect(checked.report.issues[0].document).not.toBe(".");
expect(checked.report.issues[0].correction.length).toBeGreaterThan(10);
}
});
test("prepare refuses existing directories and invalid options without changing documents", () => {
const root = directory();
expect(cli("prepare", "--directory", root, "--id", "practice", "--name", "Practice").status).toBe(0);
const before = readFileSync(join(root, "thoth-workspaces.yaml"), "utf8");
expect(cli("prepare", "--directory", root, "--id", "other", "--name", "Other").report.issues[0].code).toBe("destination_exists");
expect(readFileSync(join(root, "thoth-workspaces.yaml"), "utf8")).toBe(before);
expect(cli("validate", "--directory", root, "--typo", "VERY_SECRET_VALUE").status).toBe(2);
});
test("validation rejects directory mismatches, missing references and symlinks without following them", () => {
const root = directory();
cli("prepare", "--directory", root, "--id", "practice", "--name", "Practice");
mkdirSync(join(root, "unlisted"));
expect(cli("validate", "--directory", root).report.issues.some((i: {code: string}) => i.code === "unlisted_directory")).toBe(true);
rmSync(join(root, "unlisted"), { recursive: true });
writeFileSync(join(root, "practice/workspace.yaml"), descriptor.replace("name: Practice", "name: Different"));
expect(cli("validate", "--directory", root).report.issues[0].code).toBe("catalog_mismatch");
writeFileSync(join(root, "practice/workspace.yaml"), descriptor + "evidence:\n source:\n type: filesystem\n uri: practice/evidence\n");
expect(cli("validate", "--directory", root).report.issues[0].code).toBe("missing_reference");
symlinkSync(roots[roots.length - 1], join(root, "practice/evidence"), "dir");
expect(cli("validate", "--directory", root).report.issues[0].code).toBe("unsafe_reference");
});
test("local Evidence checks references and YAML frontmatter, and explicitly defers canonical content validation", () => {
const root = directory();
cli("prepare", "--directory", root, "--id", "practice", "--name", "Practice");
writeFileSync(join(root, "practice/workspace.yaml"), descriptor + "evidence:\n schema_version: 2\n source:\n type: filesystem\n uri: practice/evidence\n patterns: ['curated/**/*.md']\n");
mkdirSync(join(root, "practice/evidence/curated/domain"), { recursive: true });
const evidence = join(root, "practice/evidence/curated/domain/rule.md");
writeFileSync(evidence, "---\nschema_version: 4\nid: evidence:rule\nkind: domain\nlanguage: en\npurposes: [sql_generation]\n---\n# Rule\n\n## Rule\nUse the order number.\n");
const checked = cli("validate", "--directory", root);
expect(checked.status).toBe(0);
expect(checked.report.workspaces).toEqual([{ id: "practice", evidence: "local-files" }]);
expect(checked.report.deferred_checks).toContain("practice:evidence-content-provenance-and-indexing");
writeFileSync(evidence, "---\nid: first\nid: VERY_SECRET_VALUE\n---\n# Rule\n");
const invalid = cli("validate", "--directory", root);
expect(invalid.status).toBe(1);
expect(invalid.report.issues[0].document).toBe("practice/evidence/curated/domain/rule.md");
expect(invalid.stdout).not.toContain("VERY_SECRET_VALUE");
writeFileSync(join(root, "practice/workspace.yaml"), descriptor + "evidence:\n source:\n type: filesystem\n uri: practice/evidence\n patterns: [missing.md]\n");
expect(cli("validate", "--directory", root).report.issues[0].code).toBe("missing_reference");
});
test("prepare creates documents accepted by the runtime and validate is repeatable without installation or services", () => {
const root = directory();
const prepared = cli("prepare", "--directory", root, "--id", "practice", "--name", "Practice");
expect(prepared.stderr).toBe("");
expect(prepared.status).toBe(0);
expect(prepared.report.ok).toBe(true);
const catalog = readFileSync(join(root, "thoth-workspaces.yaml"), "utf8");
const descriptor = readFileSync(join(root, "practice/workspace.yaml"), "utf8");
expect(parseWorkspaceCatalogYaml(catalog).workspaces[0].id).toBe("practice");
expect(parseWorkspaceYaml(descriptor).evidence).toBeUndefined();
for (let index = 0; index < 2; index++) {
const checked = cli("validate", "--directory", root);
expect(checked.status).toBe(0);
expect(checked.report.workspaces).toEqual([{ id: "practice", evidence: "absent" }]);
}
expect(readFileSync(join(root, "thoth-workspaces.yaml"), "utf8")).toBe(catalog);
expect(readFileSync(join(root, "practice/workspace.yaml"), "utf8")).toBe(descriptor);
});
@@ -8,6 +8,7 @@ import {
type WorkspacePreprocessingRouteDeps,
} from "../src/routes/workspace-preprocessing.js";
import type { WorkspaceRegistry } from "../src/workspaces/registry.js";
import { PreprocessingStateError } from "../src/workspaces/preprocessing-state.js";
const admin: PrincipalContext = {
issuer: "test",
@@ -17,6 +18,22 @@ const admin: PrincipalContext = {
isAdmin: true,
};
test("explicit interrupted-run recovery is guarded and never steals an active owner", async () => {
const run = vi.fn(async () => { throw new PreprocessingStateError("preprocessing_conflict", "private owner details"); });
const deps = routeDeps(() => database({ preprocessingStatus: "running" }), { service: { run, clear: vi.fn() } });
const app = Fastify();
app.addHook("preHandler", async request => { request.principal = admin; });
workspacePreprocessingRoutes(app, deps);
try {
const response = await app.inject({ method: "POST", url: "/workspaces/catalog-workspace/preprocessing", payload: { recoverInterrupted: true } });
expect(response.statusCode).toBe(409);
expect(response.json()).toMatchObject({ code: "preprocessing_conflict", state: "running" });
expect(response.body).not.toContain("private owner");
expect(run).toHaveBeenCalledOnce();
expect(deps.service.clear).not.toHaveBeenCalled();
} finally { await app.close(); }
});
function database(overrides: Partial<WorkspaceDatabase> = {}): WorkspaceDatabase {
return {
id: "49b6491a-78bb-4cee-b27b-0efaf4419774",
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, test, vi } from "vitest";
import { validateWorkspaceDescriptor } from "../src/workspaces/schema.js";
import { PreprocessingStateStore, type WriterLockLease } from "../src/workspaces/preprocessing-state.js";
import {
WorkspacePreprocessingService,
type ChildProcessRequest,
@@ -10,6 +11,64 @@ import {
const roots: string[] = [];
test("a legacy running lease is never silently adopted by repeated recovery attempts", async () => {
const catalog = repository({ getByWorkspace: vi.fn(async () => ({ ...database, preprocessingInputFingerprint: "sha256:legacy" })) });
const instance = service({ repository: catalog });
for (let attempt = 0; attempt < 2; attempt++) {
expect(await instance.run({ workspaceId: "catalog-workspace" })).toMatchObject({ status: "failed", code: "preprocessing_conflict" });
}
expect(catalog.beginPreprocessing).not.toHaveBeenCalled();
expect(catalog.finishPreprocessing).not.toHaveBeenCalled();
expect(catalog.clearPreprocessing).not.toHaveBeenCalled();
});
test("retry after loss of Catalog completion restarts guarded preprocessing without clearing data", async () => {
let stranded = false;
let runId: string | undefined;
const catalog = repository({ getByWorkspace: vi.fn(async () => ({ ...database,
...(stranded ? { preprocessingInputFingerprint: "sha256:" + "f".repeat(64), preprocessingRunId: runId } : {}) })),
beginPreprocessing: vi.fn(async (_workspace, _fingerprint, id) => {
runId = id; return { kind: "started", database };
}),
});
catalog.finishPreprocessing.mockRejectedValueOnce(Error("Catalog connection lost"))
.mockRejectedValueOnce(Error("Catalog still unavailable"));
const instance = service({ repository: catalog, runChild: async () => {
stranded = true;
return { exitCode: 0, stdout: JSON.stringify({ counts: { tables: 1 } }), stderr: "" };
} });
await expect(instance.run({ workspaceId: "catalog-workspace" })).rejects.toThrow();
const second = await instance.run({ workspaceId: "catalog-workspace" });
expect(second.status).toBe("succeeded");
expect(catalog.finishPreprocessing).toHaveBeenCalledWith("catalog-workspace", 9, "sha256:" + "f".repeat(64),
{ status: "failed", errorCode: "preprocessing_interrupted" }, expect.any(String));
expect(catalog.clearPreprocessing).not.toHaveBeenCalled();
});
test("loss of the real owner during semantic preflight cannot complete or rewrite the job", async () => {
let lease: WriterLockLease | undefined;
const original = PreprocessingStateStore.prototype.acquireWriterLock;
const spy = vi.spyOn(PreprocessingStateStore.prototype, "acquireWriterLock")
.mockImplementation(async function (kind) {
const acquired = await original.call(this, kind);
if (kind !== "workers") lease = acquired;
return acquired;
});
const catalog = repository();
const instance = service({ repository: catalog, semanticPreflight: async () => {
process.kill(lease!.holderPid, "SIGKILL");
for (let i = 0; i < 100 && lease!.isHeld(); i++) await new Promise(resolve => setTimeout(resolve, 10));
expect(lease!.isHeld()).toBe(false);
return { ok: false, code: "semantic_index_incompatible" };
} });
try {
await expect(instance.run({ workspaceId: "catalog-workspace" })).rejects.toMatchObject({ code: "preprocessing_conflict" });
expect(catalog.finishPreprocessing).not.toHaveBeenCalled();
const latest = new PreprocessingStateStore({ dataRoot: roots.at(-1)!, workspaceId: "catalog-workspace" }).readLatestJob();
expect(latest?.status).toBe("active");
} finally { spy.mockRestore(); }
});
test("Evidence consolidation runs only its stage and preserves blocked Catalog readiness", async () => {
const catalog = repository();
const runChild = vi.fn(async () => ({ exitCode: 0, stdout: JSON.stringify({ status: "succeeded", counts: { documents: 2 } }), stderr: "" }));
@@ -219,6 +278,7 @@ test("complete preprocessing snapshots Catalog metadata and commits its PostgreS
9,
"sha256:" + "f".repeat(64),
{ status: "succeeded" },
expect.any(String),
);
});
@@ -257,6 +317,7 @@ test("preprocessing records a failed PostgreSQL state when its hidden worker fai
9,
"sha256:" + "f".repeat(64),
{ status: "failed", errorCode: "schema_index_failed" },
expect.any(String),
);
});
@@ -273,6 +334,7 @@ test("semantic preflight failure is persisted before returning", async () => {
9,
"sha256:" + "f".repeat(64),
{ status: "failed", errorCode: "semantic_index_incompatible" },
expect.any(String),
);
});
@@ -310,6 +372,7 @@ test("clear invalidates Catalog readiness before clearing only derived worker da
expect(runChild).toHaveBeenCalledWith({
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
configPath: expect.any(String),
guard: { lockPath: expect.any(String), tokenPath: expect.any(String), token: expect.stringMatching(/^[a-f0-9]{64}$/) },
});
expect(result).toMatchObject({
status: "succeeded",
+3 -1
View File
@@ -12,6 +12,7 @@ services:
THT_HARNESS_DIR: /app/harness
THT_BIN: /opt/venv/bin/tht
THT_DATA_ROOT: /data
THT_HOME: /data/sessions/.thothii
SETTINGS_FILE: /data/settings/settings.json
THT_EVIDENCE_HOST_REGISTRY_ROOT: ${THT_WORKSPACE_REGISTRY_ROOT:-}
THT_MAINTENANCE_FILE: /data/settings/maintenance.json
@@ -86,7 +87,7 @@ services:
test:
- CMD-SHELL
- >-
pg_isready -U thothii_catalog_migrate -d thothii_catalog
pg_isready -h 127.0.0.1 -U thothii_catalog_migrate -d thothii_catalog
&& test "$(psql -U thothii_catalog_migrate -d thothii_catalog -Atqc
"select count(*) from pg_catalog.pg_roles where rolname = 'thothii_catalog_runtime'")" = "1"
interval: 5s
@@ -124,6 +125,7 @@ services:
THT_HARNESS_DIR: /app/harness
THT_BIN: /opt/venv/bin/tht
THT_DATA_ROOT: /data
THT_HOME: /data/sessions/.thothii
THT_WORKSPACE_REGISTRY_ROOT: /data/workspace-registry
THT_WORKSPACE_GIT_REMOTE: ${THT_WORKSPACE_GIT_REMOTE:?set THT_WORKSPACE_GIT_REMOTE}
THT_WORKSPACE_GIT_BRANCH: ${THT_WORKSPACE_GIT_BRANCH:-main}
+11 -3
View File
@@ -1,16 +1,24 @@
services:
# Long-running local services restart after a Docker or Mac restart, unless stopped with stop.
# One-shot services (embedding-model-init, catalog-migrate) and workspace-maintenance keep "no".
catalog-db:
restart: unless-stopped
embedding:
restart: unless-stopped
core:
environment:
NODE_ENV: development
THT_WORKSPACE_INSTALLATION_ID: ${THT_WORKSPACE_INSTALLATION_ID:-local}
ports:
- "127.0.0.1:${THOTH_CORE_HTTP_PORT:-8787}:8787"
restart: "no"
restart: unless-stopped
frontend:
ports:
- "127.0.0.1:${THOTH_HTTP_PORT:-8080}:8080"
restart: "no"
restart: unless-stopped
workspace-maintenance:
environment:
@@ -22,4 +30,4 @@ services:
qdrant:
ports:
- "127.0.0.1:6333:6333"
restart: "no"
restart: unless-stopped
+10
View File
@@ -8,6 +8,11 @@ cp deploy/secrets/thothii.secrets.example deploy/secrets/thothii.secrets
chmod 600 deploy/secrets/thothii.secrets
```
For a normal local installation, `tht setup --complete` creates the active bundle at
`deploy/local/secrets/thothii.secrets` and creates the two Catalog password files beside it. The
generated `deploy/local/operator.env` contains only absolute paths to those files; never copy
secret values into `operator.env`.
The file uses strict `KEY=VALUE` lines (comments and blank lines are allowed). The supported
installation keys are `THT_MODEL_API_KEY`, `THT_DWH_API_KEY`, `THT_CA`, `THT_SSL_CA`,
`THT_OIDC_CLIENT_SECRET`, and `THT_AUTHENTIK_API_TOKEN`. Installation Model Catalog providers may
@@ -29,6 +34,11 @@ Session and metadata-generation runtimes read only the provider key named by
credential reference, not their execution lifecycle. Pi-owned authentication remains available only
to session-only built-in providers through `authentication.mode: pi_auth`.
Workspace database credentials are intentionally not part of this global bundle. Configure each
workspace's database binding, password/token, tunnel key and CA in Database Management; the
installation stores those values in its encrypted workspace secret store. The workspace Git
repository may declare database identity and Evidence, but must never contain these credentials.
Do not add vector or embedding endpoint credentials to the bundle. Active operator manuals use
internal Qdrant and Ollama services, so vector/embedding runtime endpoint secrets are not part of
the supported installation contract.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,247 @@
{
"schema_version": 1,
"diagram_type": "sequence",
"meta": {
"title": "ThothII — login OIDC e richieste autenticate",
"locale": "it",
"output": "docs/architecture/thothii-auth-oidc.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"participants": [
{
"id": "browser",
"type": "frontend",
"label": "Browser",
"sublabel": "frontend React",
"sources": [
{
"path": "frontend/src/api/auth.ts",
"line": 71,
"end_line": 105,
"label": "config e beginOidcLogin"
}
]
},
{
"id": "backend",
"type": "backend",
"label": "Backend",
"sublabel": "route /auth",
"sources": [
{
"path": "backend/src/auth/routes.ts",
"line": 247,
"end_line": 286,
"label": "GET /auth/oidc/login"
},
{
"path": "backend/src/auth/routes.ts",
"line": 288,
"end_line": 349,
"label": "GET /auth/oidc/callback"
},
{
"path": "backend/src/auth/auth.ts",
"line": 76,
"end_line": 110,
"label": "authenticateSession"
}
]
},
{
"id": "store",
"type": "database",
"label": "Auth state",
"sublabel": "file, volume auth-state",
"sources": [
{
"path": "backend/src/auth/session-store.ts",
"line": 389,
"end_line": 395,
"label": "createFileAuthSessionStore"
},
{
"path": "compose.yaml",
"line": 30,
"end_line": 30
}
]
},
{
"id": "idp",
"type": "security",
"label": "Identity provider",
"sublabel": "OIDC",
"sources": [
{
"path": "backend/src/auth/oidc-client.ts",
"line": 24,
"end_line": 27,
"label": "OidcProtocol"
}
]
}
],
"segments": [
{
"from": 160,
"to": 342,
"label": "Avvio login"
},
{
"from": 352,
"to": 444,
"label": "Provider"
},
{
"from": 454,
"to": 738,
"label": "Callback"
},
{
"from": 748,
"to": 870,
"label": "Richieste"
}
],
"messages": [
{
"from": "browser",
"to": "backend",
"y": 170,
"label": "GET /auth/config"
},
{
"from": "backend",
"to": "browser",
"y": 200,
"label": "mode: oidc",
"variant": "return"
},
{
"from": "browser",
"to": "backend",
"y": 230,
"label": "GET /auth/oidc/login",
"variant": "emphasis"
},
{
"from": "backend",
"to": "store",
"y": 260,
"label": "createOidcState",
"note": "nonce e code verifier PKCE"
},
{
"from": "backend",
"to": "browser",
"y": 326,
"label": "302 verso il provider",
"variant": "return"
},
{
"from": "browser",
"to": "idp",
"y": 362,
"label": "authorize + PKCE",
"variant": "security",
"note": "login sul provider"
},
{
"from": "idp",
"to": "browser",
"y": 428,
"label": "302 callback con code",
"variant": "return"
},
{
"from": "browser",
"to": "backend",
"y": 464,
"label": "GET /auth/oidc/callback",
"variant": "emphasis"
},
{
"from": "backend",
"to": "store",
"y": 494,
"label": "consumeOidcState",
"note": "verifica transazione, revisione e issuer"
},
{
"from": "backend",
"to": "idp",
"y": 560,
"label": "scambio code",
"variant": "security",
"note": "firma, audience, scadenza, nonce"
},
{
"from": "idp",
"to": "backend",
"y": 626,
"label": "identità + gruppi",
"variant": "return"
},
{
"from": "backend",
"to": "store",
"y": 656,
"label": "crea sessione",
"note": "ruoli dai gruppi, TTL limitato al token"
},
{
"from": "backend",
"to": "browser",
"y": 722,
"label": "cookie + redirect /",
"variant": "return"
},
{
"from": "browser",
"to": "backend",
"y": 758,
"label": "API con cookie",
"variant": "emphasis"
},
{
"from": "backend",
"to": "store",
"y": 788,
"label": "resolve + touch",
"note": "sessione revocata se cambia la config"
},
{
"from": "backend",
"to": "browser",
"y": 854,
"label": "risposta",
"variant": "return"
}
],
"cards": [
{
"dot": "cyan",
"title": "Tre modalità",
"items": [
"local: utenti con hash Argon2id in users.yaml",
"oidc: questo flusso (Authorization Code + PKCE)",
"upstream: il proxy del portale (Omics) passa l'identità negli header; niente login né cookie ThothII"
]
},
{
"dot": "rose",
"title": "Autorizzazione",
"items": [
"I gruppi OIDC sono mappati esattamente sui ruoli user e admin",
"I permessi si ricalcolano dai ruoli a ogni richiesta",
"Le richieste che modificano dati richiedono origine esatta e token CSRF"
]
}
]
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,45 @@
{
"schema_version": 3,
"diagram_type": "lifecycle",
"meta": { "title": "ThothII — sincronizzazione schema del Metadata Catalog", "locale": "it", "output": "docs/architecture/thothii-catalog-sync.html", "quality_profile": "showcase", "repository": {"url": "https://git.tylconsulting.it/mptyl/ThothII.git", "link_mode": "local-only", "revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"} },
"mainPath": ["queued", "running", "applying", "succeeded"],
"states": [
{ "id": "queued", "type": "start", "label": "queued", "sublabel": "un run attivo per database", "step": "01",
"sources": [ { "path": "backend/src/catalog/migrations/003_catalog_schema_sync.ts", "line": 102, "end_line": 104, "label": "indice un solo attivo" } ] },
{ "id": "running", "type": "active", "label": "running", "sublabel": "scan DWH + piano delle modifiche", "step": "02",
"sources": [ { "path": "backend/src/catalog/sync-worker.ts", "line": 175, "end_line": 175, "label": "claimSyncRun" }, { "path": "backend/src/catalog/sync-worker.ts", "line": 210, "end_line": 220, "label": "scan + plan" } ] },
{ "id": "applying", "type": "active", "label": "applying", "sublabel": "modifiche in una transazione", "tag": "non cancellabile", "step": "03",
"sources": [ { "path": "backend/src/catalog/sync-worker.ts", "line": 243, "end_line": 250, "label": "applySchemaSync" } ] },
{ "id": "succeeded", "type": "success", "label": "succeeded", "sublabel": "catalogo aggiornato", "step": "04",
"sources": [ { "path": "backend/src/catalog/sync-worker.ts", "line": 300, "end_line": 300 } ] },
{ "id": "awaiting", "type": "waiting", "label": "awaiting_confirmation", "sublabel": "cancellazioni da confermare", "tag": "admin",
"sources": [ { "path": "backend/src/catalog/sync-worker.ts", "line": 222, "end_line": 240, "label": "diff distruttivo" }, { "path": "backend/src/catalog/sync-worker.ts", "line": 96, "end_line": 112, "label": "confirm" } ] },
{ "id": "cancelled", "type": "neutral", "label": "cancelled", "sublabel": "annullato dall'utente",
"sources": [ { "path": "backend/src/catalog/sync-worker.ts", "line": 114, "end_line": 136, "label": "cancel" } ] },
{ "id": "failed", "type": "failure", "label": "failed", "sublabel": "errore o timeout",
"sources": [ { "path": "backend/src/catalog/sync-worker.ts", "line": 260, "end_line": 272 } ] },
{ "id": "interrupted", "type": "failure", "label": "interrupted", "sublabel": "riavvio del servizio",
"sources": [ { "path": "backend/src/catalog/repository.ts", "line": 1896, "end_line": 1896, "label": "interruptActiveSyncRuns" } ] }
],
"transitions": [
{ "id": "q-r", "from": "queued", "to": "running", "label": "claim" },
{ "id": "r-a", "from": "running", "to": "applying", "label": "piano pronto" },
{ "id": "a-s", "from": "applying", "to": "succeeded", "label": "commit", "variant": "emphasis" },
{ "id": "r-w", "from": "running", "to": "awaiting", "label": "diff distruttivo", "variant": "security" },
{ "id": "w-q", "from": "awaiting", "to": "queued", "label": "confirm" },
{ "id": "w-c", "from": "awaiting", "to": "cancelled", "label": "cancel" },
{ "id": "q-c", "from": "queued", "to": "cancelled", "label": "cancel" },
{ "id": "r-f", "from": "running", "to": "failed", "label": "errore", "variant": "security" },
{ "id": "r-i", "from": "running", "to": "interrupted", "label": "restart", "variant": "dashed" }
],
"cards": [
{ "dot": "amber", "title": "Conferma", "items": [
"Se il piano rimuove tabelle, colonne o relazioni il run si ferma e chiede conferma",
"La conferma vale solo per lo stesso snapshot: se il DWH cambia, si richiede di nuovo"
] },
{ "dot": "cyan", "title": "Altri run", "items": [
"I run di generazione descrizioni seguono stati analoghi: queued, running, completed, completed_with_errors, cancelled, failed, interrupted",
"Un run terminato può essere rilanciato con retry"
] }
]
}
@@ -1,230 +0,0 @@
{
"schema_version": 1,
"diagram_type": "sequence",
"meta": {
"title": "Sequenza runtime del core ThothII",
"output": "thothii-core-sequence.html",
"quality_profile": "showcase",
"column_fit": "spread",
"viewBox": [1080, 540]
},
"participants": [
{
"id": "reviewer",
"type": "external",
"label": "Revisore",
"sublabel": "browser"
},
{
"id": "frontend",
"type": "frontend",
"label": "Frontend",
"sublabel": "React + SSE"
},
{
"id": "api",
"type": "backend",
"label": "Core API",
"sublabel": "Fastify + SseHub"
},
{
"id": "runtime",
"type": "backend",
"label": "Runtime",
"sublabel": "manager + bridge"
},
{
"id": "pi",
"type": "backend",
"label": "Pi + tht-gate",
"sublabel": "RPC per sessione"
},
{
"id": "model",
"type": "external",
"label": "Modello AI",
"sublabel": "provider configurato"
},
{
"id": "tht",
"type": "backend",
"label": "tht CLI",
"sublabel": "workflow persistito"
},
{
"id": "state",
"type": "database",
"label": "Stato e dati",
"sublabel": "workspace + dati"
}
],
"segments": [
{
"from": 150,
"to": 300,
"label": "Avvio o ripresa"
},
{
"from": 305,
"to": 395,
"label": "Turno Pi e workflow persistito"
},
{
"from": 400,
"to": 475,
"label": "Evento SSE e gate umano"
}
],
"messages": [
{
"id": "askQuestion",
"from": "reviewer",
"to": "frontend",
"y": 160,
"label": "domanda o decisione gate",
"variant": "emphasis"
},
{
"id": "createSession",
"from": "frontend",
"to": "api",
"y": 185,
"label": "POST /sessions o /response",
"variant": "emphasis"
},
{
"id": "newManifest",
"from": "api",
"to": "tht",
"y": 210,
"label": "sessionNew o sessionShow/reopen"
},
{
"id": "persistQuestion",
"from": "tht",
"to": "state",
"y": 235,
"label": "manifest, artifact e ledger"
},
{
"id": "createRuntime",
"from": "api",
"to": "runtime",
"y": 260,
"label": "createFor + bind; configure + searchPack",
"note": "configure(...) e searchPack(...) terminano in parallelo prima dell’avvio del modello."
},
{
"id": "startPi",
"from": "runtime",
"to": "pi",
"y": 285,
"label": "/nuova-domanda o /riprendi-sessione",
"variant": "emphasis",
"note": "In ripresa usa /riprendi-sessione <id> dopo aver riletto provider, modello e thinking dal manifest."
},
{
"id": "modelRequest",
"from": "pi",
"to": "model",
"y": 315,
"label": "turno modello; token e tool call"
},
{
"id": "phaseCommand",
"from": "pi",
"to": "tht",
"y": 345,
"label": "comandi phase / session / evidence",
"variant": "emphasis"
},
{
"id": "readWriteTruth",
"from": "tht",
"to": "state",
"y": 375,
"label": "legge/scrive artifact e ledger",
"note": "Il workspace persistito è la verità; DWH è read-only e Qdrant serve il retrieval."
},
{
"id": "rpcEvents",
"from": "pi",
"to": "runtime",
"y": 405,
"label": "text_delta / ui_request"
},
{
"id": "sseEvent",
"from": "runtime",
"to": "frontend",
"y": 430,
"label": "SSE via SseHub: text · info · widget",
"variant": "return"
},
{
"id": "showResult",
"from": "frontend",
"to": "reviewer",
"y": 455,
"label": "testo o widget di revisione",
"variant": "return"
}
],
"activations": [
{
"participant": "frontend",
"from": 155,
"to": 460,
"type": "frontend"
},
{
"participant": "api",
"from": 180,
"to": 290,
"type": "backend"
},
{
"participant": "runtime",
"from": 255,
"to": 440,
"type": "backend"
},
{
"participant": "pi",
"from": 280,
"to": 415,
"type": "backend"
},
{
"participant": "model",
"from": 310,
"to": 335,
"type": "external"
},
{
"participant": "tht",
"from": 205,
"to": 390,
"type": "backend"
},
{
"participant": "state",
"from": 230,
"to": 390,
"type": "database"
}
],
"cards": [
{
"dot": "cyan",
"title": "Bootstrap",
"items": [
"La sessione viene persistita prima dell’avvio di Pi; configurazione e retrieval terminano prima del primo prompt.",
"La ripresa rifiuta sessioni finalizzate o archiviate e usa sempre /riprendi-sessione <id>.",
"Il modello propone; il revisore decide tramite reviewer_select, reviewer_decide o reviewer_confirm.",
"La risposta percorre POST /sessions/:id/response → bridge.respond → extension_ui_response; stale/duplicate ricevono 409.",
"La fase avanza solo dopo append della decisione esplicita e fold del ledger persistito."
]
}
]
}
@@ -0,0 +1,529 @@
{
"schema_version": 1,
"diagram_type": "architecture",
"meta": {
"title": "ThothII — deployment Docker Compose",
"locale": "it",
"output": "docs/architecture/thothii-deployment.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"components": [
{
"id": "operator",
"type": "external",
"label": "Operatore",
"sublabel": "host",
"pos": [
40,
40
],
"size": [
150,
64
]
},
{
"id": "thtcli",
"type": "backend",
"label": "tht (host)",
"sublabel": "CLI Go: setup, start, stop",
"pos": [
290,
40
],
"size": [
170,
64
],
"sources": [
{
"path": "tools/tht/cmd/tht/main.go",
"line": 223,
"end_line": 237,
"label": "start / stop"
},
{
"path": "tools/tht/internal/config/installation.go",
"line": 548,
"end_line": 548,
"label": "docker compose"
}
]
},
{
"id": "browser",
"type": "external",
"label": "Browser",
"sublabel": "o proxy del portale",
"pos": [
40,
340
],
"size": [
150,
64
]
},
{
"id": "frontend",
"type": "frontend",
"label": "frontend",
"sublabel": "nginx :8080",
"tag": "unica porta pubblica",
"pos": [
290,
340
],
"size": [
160,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 190,
"end_line": 208
},
{
"path": "docker/nginx.conf.template",
"line": 13,
"end_line": 20,
"label": "/api → core"
},
{
"path": "deploy/compose.server.yaml",
"line": 32,
"end_line": 34,
"label": "porta server"
}
]
},
{
"id": "core",
"type": "backend",
"label": "core",
"sublabel": "backend + Pi + tht :8787",
"tag": "MAX_PI_PROCESSES",
"pos": [
540,
340
],
"size": [
190,
84
],
"sources": [
{
"path": "compose.yaml",
"line": 4,
"end_line": 72
},
{
"path": "docker/core.Dockerfile",
"line": 1,
"end_line": 5
}
]
},
{
"id": "catalogdb",
"type": "database",
"label": "catalog-db",
"sublabel": "PostgreSQL 17",
"tag": "volume catalog-data",
"pos": [
820,
340
],
"size": [
170,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 74,
"end_line": 98
}
]
},
{
"id": "migrate",
"type": "backend",
"label": "catalog-migrate",
"sublabel": "one-shot",
"pos": [
1080,
340
],
"size": [
160,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 100,
"end_line": 117
}
]
},
{
"id": "qdrant",
"type": "database",
"label": "qdrant",
"sublabel": "vector store :6333",
"tag": "volume qdrant-data",
"pos": [
820,
490
],
"size": [
170,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 210,
"end_line": 228
}
]
},
{
"id": "maint",
"type": "backend",
"label": "workspace-maintenance",
"sublabel": "one-shot, preprocessing",
"pos": [
1080,
490
],
"size": [
190,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 119,
"end_line": 188
},
{
"path": "backend/src/workspace-maintenance.ts",
"line": 22,
"end_line": 22,
"label": "comandi"
}
]
},
{
"id": "embedding",
"type": "backend",
"label": "embedding",
"sublabel": "Ollama :11434",
"tag": "volume embedding-models",
"pos": [
820,
640
],
"size": [
170,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 230,
"end_line": 249
}
]
},
{
"id": "modelinit",
"type": "backend",
"label": "embedding-model-init",
"sublabel": "one-shot, scarica il modello",
"pos": [
1080,
640
],
"size": [
190,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 251,
"end_line": 264
}
]
},
{
"id": "volumes",
"type": "database",
"label": "Volumi core",
"sublabel": "sessions, settings, pi-state, auth-state",
"tag": "+ workspace-registry/secrets",
"pos": [
500,
560
],
"size": [
270,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 42,
"end_line": 50
},
{
"path": "compose.yaml",
"line": 269,
"end_line": 278
}
]
},
{
"id": "secrets",
"type": "security",
"label": "Secret + config",
"sublabel": "thothii.secrets, installation.yaml",
"pos": [
230,
560
],
"size": [
230,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 51,
"end_line": 57
},
{
"path": "compose.yaml",
"line": 280,
"end_line": 290
}
]
},
{
"id": "git",
"type": "cloud",
"label": "Git remote workspace",
"sublabel": "THT_WORKSPACE_GIT_REMOTE",
"pos": [
290,
190
],
"size": [
200,
64
],
"sources": [
{
"path": "backend/src/workspaces/git-repository.ts",
"line": 185,
"end_line": 195,
"label": "clone / refresh"
}
]
},
{
"id": "dwh",
"type": "cloud",
"label": "DWH",
"sublabel": "Postgres o REST, sola lettura",
"pos": [
820,
190
],
"size": [
190,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 36,
"end_line": 37
}
]
},
{
"id": "llm",
"type": "cloud",
"label": "Provider LLM",
"sublabel": "THT_LLM_URL",
"pos": [
820,
40
],
"size": [
170,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 38,
"end_line": 38
}
]
}
],
"boundaries": [
{
"kind": "region",
"label": "rete Compose thothii",
"wraps": [
"frontend",
"core",
"catalogdb",
"migrate",
"qdrant",
"maint",
"embedding",
"modelinit",
"volumes",
"secrets"
]
}
],
"connections": [
{
"id": "op-cli",
"from": "operator",
"to": "thtcli",
"label": "comandi"
},
{
"id": "cli-core",
"from": "thtcli",
"to": "core",
"label": "compose up",
"variant": "dashed"
},
{
"id": "br-fe",
"from": "browser",
"to": "frontend",
"label": "HTTPS",
"variant": "emphasis"
},
{
"id": "fe-core",
"from": "frontend",
"to": "core",
"label": "/api",
"variant": "emphasis"
},
{
"id": "core-db",
"from": "core",
"to": "catalogdb",
"label": "SQL",
"variant": "emphasis"
},
{
"id": "mig-db",
"from": "migrate",
"to": "catalogdb",
"label": "migra"
},
{
"id": "core-qd",
"from": "core",
"to": "qdrant",
"label": "HTTP"
},
{
"id": "core-emb",
"from": "core",
"to": "embedding",
"label": "embed"
},
{
"id": "maint-qd",
"from": "maint",
"to": "qdrant",
"label": "reindicizza"
},
{
"id": "init-emb",
"from": "modelinit",
"to": "embedding",
"label": "pull"
},
{
"id": "core-vol",
"from": "core",
"to": "volumes",
"label": "monta"
},
{
"id": "sec-core",
"from": "secrets",
"to": "core",
"label": "/run/secrets",
"variant": "security"
},
{
"id": "core-git",
"from": "core",
"to": "git",
"label": "clone"
},
{
"id": "core-dwh",
"from": "core",
"to": "dwh",
"label": "read-only"
},
{
"id": "core-llm",
"from": "core",
"to": "llm",
"label": "API modelli"
}
],
"cards": [
{
"dot": "cyan",
"title": "Avvio",
"items": [
"tht start sul host esegue docker compose con base + profilo (local o server)",
"catalog-migrate ed embedding-model-init girano una volta prima del core",
"Il core parte solo con catalog-db e qdrant sani e il modello di embedding scaricato"
]
},
{
"dot": "amber",
"title": "Profili",
"items": [
"local: porte solo su 127.0.0.1 (frontend 8080, core 8787, Qdrant 6333)",
"server: espone solo il frontend dietro il proxy autenticato",
"workspace-maintenance gira on demand: preprocessing ed Evidence"
]
},
{
"dot": "rose",
"title": "Confini",
"items": [
"DWH, provider LLM e Git remote sono esterni alla rete Compose",
"I secret arrivano come Docker secrets, mai in variabili o YAML"
]
}
]
}
File diff suppressed because one or more lines are too long
+88
View File
@@ -0,0 +1,88 @@
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Diagrammi ThothII</title>
<style>
:root {
--bg: #f6f7f9; --surface: #ffffff; --text: #18202b; --muted: #5b6676;
--border: #e1e5eb; --accent: #0e7490; --chip: #eef6f8;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #11151b; --surface: #1a2028; --text: #e7ebf0; --muted: #9aa5b3;
--border: #2a323d; --accent: #5ec4d8; --chip: #1d2a31; }
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text);
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
main { max-width: 1080px; margin: 0 auto; padding: 40px 16px 64px; }
h1 { font-size: 26px; margin: 0 0 6px; }
.intro { color: var(--muted); margin: 0 0 32px; max-width: 70ch; }
h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted);
margin: 32px 0 12px; }
.grid { display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); }
a.card { display: block; text-decoration: none; color: inherit; background: var(--surface);
border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; }
a.card:hover { border-color: var(--accent); }
.title { font-weight: 600; }
.kind { display: inline-block; font-size: 11px; font-family: ui-monospace, monospace;
background: var(--chip); color: var(--accent); border-radius: 4px; padding: 1px 6px; margin-left: 6px; }
.desc { color: var(--muted); font-size: 14px; margin-top: 4px; }
footer { margin-top: 40px; color: var(--muted); font-size: 13px; }
</style>
</head>
<body>
<main>
<h1>Diagrammi dell'architettura ThothII</h1>
<p class="intro">Diagrammi interattivi generati con Archify a partire dal codice. Ogni elemento
rimanda ai file e alle righe da cui deriva. Il sorgente JSON di ogni diagramma è nella stessa
cartella, con lo stesso nome.</p>
<h2>Panoramica</h2>
<div class="grid">
<a class="card" href="thothii-runtime.html"><span class="title">Architettura runtime</span><span class="kind">architecture</span>
<div class="desc">Frontend, backend, Pi, estensione gate, CLI tht e servizi collegati.</div></a>
<a class="card" href="thothii-deployment.html"><span class="title">Deployment Docker Compose</span><span class="kind">architecture</span>
<div class="desc">Servizi, one-shot, volumi, secret, endpoint esterni e CLI host.</div></a>
<a class="card" href="thothii-modules.html"><span class="title">Struttura dei moduli</span><span class="kind">tree</span>
<div class="desc">Cartelle principali del repository e loro ruolo.</div></a>
</div>
<h2>Workflow e sessioni</h2>
<div class="grid">
<a class="card" href="thothii-phases.html"><span class="title">Workflow in 8 fasi</span><span class="kind">workflow</span>
<div class="desc">F1–F8, gate del reviewer, salti automatici e ritorno indietro.</div></a>
<a class="card" href="thothii-session-lifecycle.html"><span class="title">Ciclo di vita della sessione</span><span class="kind">lifecycle</span>
<div class="desc">open, closed, failed, finalized, archiviazione e cancellazione.</div></a>
<a class="card" href="thothii-new-question.html"><span class="title">Avvio di una nuova domanda</span><span class="kind">sequence</span>
<div class="desc">Dalla domanda al primo turno F1 con streaming SSE.</div></a>
<a class="card" href="thothii-gate-roundtrip.html"><span class="title">Andata e ritorno di un gate</span><span class="kind">sequence</span>
<div class="desc">Widget, risposta del reviewer, decisione nel ledger.</div></a>
<a class="card" href="thothii-resume.html"><span class="title">Ripresa di una sessione</span><span class="kind">sequence</span>
<div class="desc">Riapertura e ricostruzione del contesto dallo stato su disco.</div></a>
</div>
<h2>Backend e sicurezza</h2>
<div class="grid">
<a class="card" href="thothii-session-runtime.html"><span class="title">Classi del runtime di sessione</span><span class="kind">class</span>
<div class="desc">PiProcessManager, SessionBridge, RpcClient, SseHub, ThtRunner.</div></a>
<a class="card" href="thothii-auth-oidc.html"><span class="title">Login OIDC e richieste autenticate</span><span class="kind">sequence</span>
<div class="desc">Authorization Code + PKCE, sessione browser e controlli per richiesta.</div></a>
</div>
<h2>Dati e Metadata Catalog</h2>
<div class="grid">
<a class="card" href="thothii-metadata-flow.html"><span class="title">Dai metadati al contesto di sessione</span><span class="kind">dataflow</span>
<div class="desc">DWH, catalogo, preprocessing, indici LSH e Qdrant, search pack, memoria.</div></a>
<a class="card" href="thothii-metadata-catalog.html"><span class="title">Schema del Metadata Catalog</span><span class="kind">erd</span>
<div class="desc">14 tabelle PostgreSQL ricostruite dalle migrazioni.</div></a>
<a class="card" href="thothii-catalog-sync.html"><span class="title">Sincronizzazione dello schema</span><span class="kind">lifecycle</span>
<div class="desc">Stati dei run di sync, conferma delle modifiche distruttive.</div></a>
</div>
<footer>Per rigenerare un diagramma: modificare il suo JSON e rieseguire
<code>archify finalize</code> con <code>--repo-root</code> sulla radice del repository.</footer>
</main>
</body>
</html>
File diff suppressed because one or more lines are too long
@@ -0,0 +1,332 @@
{
"schema_version": 1,
"diagram_type": "sequence",
"meta": {
"title": "ThothII — andata e ritorno di un gate reviewer",
"locale": "it",
"output": "docs/architecture/thothii-gate-roundtrip.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"participants": [
{
"id": "reviewer",
"type": "external",
"label": "Reviewer",
"sublabel": "browser"
},
{
"id": "frontend",
"type": "frontend",
"label": "Frontend",
"sublabel": "React",
"sources": [
{
"path": "frontend/src/store/sessionStore.ts",
"line": 76,
"end_line": 90,
"label": "pendingWidget"
},
{
"path": "frontend/src/widgets/registry.ts",
"line": 5,
"end_line": 13,
"label": "registry widget"
},
{
"path": "frontend/src/api/sessions.ts",
"line": 130,
"end_line": 134,
"label": "postResponse"
}
]
},
{
"id": "backend",
"type": "backend",
"label": "Backend",
"sublabel": "SessionBridge",
"sources": [
{
"path": "backend/src/bridge/session-bridge.ts",
"line": 63,
"end_line": 71,
"label": "ui_request"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 634,
"end_line": 662,
"label": "POST /response"
},
{
"path": "backend/src/bridge/session-bridge.ts",
"line": 178,
"end_line": 188,
"label": "respond"
}
]
},
{
"id": "pi",
"type": "backend",
"label": "Pi",
"sublabel": "--mode rpc"
},
{
"id": "gate",
"type": "backend",
"label": "tht-gate.js",
"sublabel": "reviewer_select",
"sources": [
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 924,
"end_line": 942,
"label": "execute"
},
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 597,
"end_line": 603,
"label": "emitAndWait"
},
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 465,
"end_line": 468,
"label": "advanceIfReady"
}
]
},
{
"id": "tht",
"type": "backend",
"label": "tht CLI",
"sublabel": "ledger",
"sources": [
{
"path": "harness/tht/decisions.py",
"line": 98,
"end_line": 120,
"label": "append_decision"
},
{
"path": "harness/tht/phase.py",
"line": 60,
"end_line": 79,
"label": "current_phase"
}
]
},
{
"id": "llm",
"type": "cloud",
"label": "Provider LLM",
"sublabel": "modello di sessione"
}
],
"segments": [
{
"from": 160,
"to": 420,
"label": "Proposta"
},
{
"from": 428,
"to": 600,
"label": "Decisione"
},
{
"from": 608,
"to": 790,
"label": "Persistenza"
}
],
"messages": [
{
"id": "call",
"from": "llm",
"to": "pi",
"y": 170,
"label": "tool call",
"variant": "return"
},
{
"id": "exec",
"from": "pi",
"to": "gate",
"y": 200,
"label": "reviewer_select"
},
{
"id": "input",
"from": "gate",
"to": "pi",
"y": 230,
"label": "ctx.ui.input",
"note": "descrittore widget come JSON"
},
{
"id": "uireq",
"from": "pi",
"to": "backend",
"y": 290,
"label": "extension_ui_request",
"variant": "dashed",
"note": "con l'id RPC di Pi"
},
{
"id": "sse",
"from": "backend",
"to": "frontend",
"y": 350,
"label": "SSE ui_request",
"variant": "dashed",
"note": "il bridge ricorda l'id di Pi"
},
{
"id": "widget",
"from": "frontend",
"to": "reviewer",
"y": 410,
"label": "widget",
"variant": "return"
},
{
"id": "pick",
"from": "reviewer",
"to": "frontend",
"y": 440,
"label": "scelta"
},
{
"id": "post",
"from": "frontend",
"to": "backend",
"y": 470,
"label": "POST /response",
"variant": "emphasis",
"note": "409 se il gate non è quello in attesa"
},
{
"id": "ok",
"from": "backend",
"to": "frontend",
"y": 530,
"label": "204",
"variant": "return"
},
{
"id": "uiresp",
"from": "backend",
"to": "pi",
"y": 560,
"label": "extension_ui_response",
"variant": "emphasis"
},
{
"id": "value",
"from": "pi",
"to": "gate",
"y": 620,
"label": "risposta",
"variant": "return"
},
{
"id": "add",
"from": "gate",
"to": "tht",
"y": 650,
"label": "decision add",
"variant": "emphasis",
"note": "accoda a review_decisions.jsonl"
},
{
"id": "advance",
"from": "gate",
"to": "tht",
"y": 720,
"label": "phase advance --auto",
"variant": "dashed"
},
{
"id": "result",
"from": "gate",
"to": "pi",
"y": 750,
"label": "risultato tool",
"variant": "return"
},
{
"id": "next",
"from": "pi",
"to": "llm",
"y": 780,
"label": "turno successivo",
"variant": "emphasis"
}
],
"activations": [
{
"participant": "pi",
"from": 165,
"to": 786,
"type": "backend"
},
{
"participant": "gate",
"from": 198,
"to": 756,
"type": "backend"
},
{
"participant": "backend",
"from": 288,
"to": 566,
"type": "backend"
},
{
"participant": "frontend",
"from": 348,
"to": 536,
"type": "frontend"
},
{
"participant": "tht",
"from": 648,
"to": 726,
"type": "backend"
}
],
"cards": [
{
"dot": "cyan",
"title": "Correlazione",
"items": [
"Pi correla la risposta sul proprio id RPC, non sull'id del descrittore",
"Il bridge rimanda l'id di Pi; il valore contiene l'id del descrittore per il controllo del gate"
]
},
{
"dot": "emerald",
"title": "Persistenza",
"items": [
"Un'opzione con payload decision è già la conferma: il gate la scrive con tht decision add",
"Un'opzione senza payload chiede soltanto e non scrive nulla",
"phase advance --auto avanza solo se la fase è completa"
]
},
{
"dot": "amber",
"title": "Altri widget",
"items": [
"reviewer_decide (scelta multipla) e reviewer_confirm (artefatto o fase) seguono lo stesso percorso"
]
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,388 @@
{
"schema_version": 1,
"diagram_type": "dataflow",
"meta": {
"title": "ThothII — dai metadati del DWH al contesto di sessione",
"locale": "it",
"output": "docs/architecture/thothii-metadata-flow.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"stages": [
{
"label": "Fonti"
},
{
"label": "Catalogo"
},
{
"label": "Preprocessing"
},
{
"label": "Indici"
},
{
"label": "Sessione"
}
],
"nodes": [
{
"id": "dwh",
"type": "database",
"label": "DWH",
"sublabel": "sola lettura",
"stage": 0,
"row": 0,
"sources": [
{
"path": "backend/src/catalog/sync-worker.ts",
"line": 210,
"end_line": 220,
"label": "scan schema"
},
{
"path": "backend/src/catalog/description-source-sampler.ts",
"line": 153,
"end_line": 160,
"label": "campionamento"
}
]
},
{
"id": "gitws",
"type": "cloud",
"label": "Workspace Git",
"sublabel": "fonti Evidence",
"stage": 0,
"row": 2,
"sources": [
{
"path": "backend/src/workspaces/git-repository.ts",
"line": 185,
"end_line": 195
}
]
},
{
"id": "catalog",
"type": "database",
"label": "Metadata Catalog",
"sublabel": "PostgreSQL",
"stage": 1,
"row": 0,
"sources": [
{
"path": "backend/src/catalog/repository.ts",
"line": 488,
"end_line": 488,
"label": "KyselyCatalogRepository"
}
]
},
{
"id": "descgen",
"type": "backend",
"label": "Descrizioni AI",
"sublabel": "helper LiteLLM",
"stage": 1,
"row": 1,
"sources": [
{
"path": "backend/src/catalog/model-completer.ts",
"line": 67,
"end_line": 74
},
{
"path": "backend/src/catalog/migrations/005_description_generation_runs.ts",
"line": 5,
"end_line": 5,
"label": "run"
}
]
},
{
"id": "memdb",
"type": "database",
"label": "Card memoria",
"sublabel": "schema thoth_memory",
"stage": 4,
"row": 0,
"sources": [
{
"path": "harness/tht/memory/repository.py",
"line": 15,
"end_line": 15,
"label": "MemoryRepository"
},
{
"path": "harness/tht/memory/migrate.py",
"line": 46,
"end_line": 50
}
]
},
{
"id": "snapshot",
"type": "backend",
"label": "Snapshot catalogo",
"sublabel": "JSON immutabile",
"stage": 2,
"row": 0,
"sources": [
{
"path": "backend/src/workspaces/preprocessing-service.ts",
"line": 289,
"end_line": 301
}
]
},
{
"id": "prep",
"type": "backend",
"label": "preprocess catalog",
"sublabel": "tht + embedding",
"stage": 2,
"row": 1,
"sources": [
{
"path": "backend/src/workspaces/preprocessing-service.ts",
"line": 321,
"end_line": 329
},
{
"path": "harness/tht/cli/preprocess_cmd.py",
"line": 523,
"end_line": 545
}
]
},
{
"id": "evprep",
"type": "backend",
"label": "preprocess Evidence",
"sublabel": "corpus + embedding",
"stage": 2,
"row": 2,
"sources": [
{
"path": "backend/src/workspaces/preprocessing-service.ts",
"line": 330,
"end_line": 339
}
]
},
{
"id": "lsh",
"type": "database",
"label": "Indice LSH",
"sublabel": "valori delle colonne",
"stage": 3,
"row": 1,
"sources": [
{
"path": "harness/tht/cli/preprocess_cmd.py",
"line": 167,
"end_line": 193
}
]
},
{
"id": "qref",
"type": "database",
"label": "Qdrant reference",
"sublabel": "schema + Evidence",
"stage": 3,
"row": 2,
"sources": [
{
"path": "harness/tht/adapters/vector/qdrant.py",
"line": 327,
"end_line": 327,
"label": "upsert"
}
]
},
{
"id": "qmem",
"type": "database",
"label": "Qdrant memory",
"sublabel": "dense + BM25",
"stage": 3,
"row": 0,
"sources": [
{
"path": "harness/tht/memory/repository.py",
"line": 225,
"end_line": 235,
"label": "proiezioni"
}
]
},
{
"id": "pack",
"type": "backend",
"label": "search pack",
"sublabel": "retrieval_pack.md",
"stage": 4,
"row": 2,
"sources": [
{
"path": "harness/tht/cli/search_cmd.py",
"line": 351,
"end_line": 420
}
]
},
{
"id": "session",
"type": "frontend",
"label": "Sessione F1–F8",
"sublabel": "search find in F4",
"stage": 4,
"row": 1,
"sources": [
{
"path": "harness/tht/cli/search_cmd.py",
"line": 129,
"end_line": 131,
"label": "search find"
},
{
"path": "harness/tht/cli/search_cmd.py",
"line": 219,
"end_line": 226,
"label": "usa LSH"
}
]
}
],
"flows": [
{
"id": "dwh-catalog",
"from": "dwh",
"to": "catalog",
"label": "sync schema",
"variant": "emphasis"
},
{
"id": "dwh-desc",
"from": "dwh",
"to": "descgen",
"label": "campioni",
"variant": "security"
},
{
"id": "desc-catalog",
"from": "descgen",
"to": "catalog",
"label": "descrizioni"
},
{
"id": "catalog-snap",
"from": "catalog",
"to": "snapshot",
"label": "metadati",
"variant": "emphasis"
},
{
"id": "snap-prep",
"from": "snapshot",
"to": "prep",
"label": "file snapshot"
},
{
"id": "prep-lsh",
"from": "prep",
"to": "lsh",
"label": "MinHash"
},
{
"id": "prep-qref",
"from": "prep",
"to": "qref",
"label": "vettori schema",
"variant": "emphasis"
},
{
"id": "git-ev",
"from": "gitws",
"to": "evprep",
"label": "fonti Evidence"
},
{
"id": "ev-qref",
"from": "evprep",
"to": "qref",
"label": "vettori Evidence"
},
{
"id": "mem-qmem",
"from": "memdb",
"to": "qmem",
"label": "proiezione",
"variant": "dashed"
},
{
"id": "qref-pack",
"from": "qref",
"to": "pack",
"label": "ricerca ibrida",
"variant": "emphasis"
},
{
"id": "qmem-pack",
"from": "qmem",
"to": "pack",
"label": "domande risolte"
},
{
"id": "pack-session",
"from": "pack",
"to": "session",
"label": "contesto F1",
"variant": "emphasis"
},
{
"id": "lsh-session",
"from": "lsh",
"to": "session",
"label": "valori"
},
{
"id": "session-mem",
"from": "session",
"to": "memdb",
"label": "promozione F8",
"variant": "dashed"
}
],
"cards": [
{
"dot": "cyan",
"title": "Autorità",
"items": [
"Il Metadata Catalog è l'unica fonte dei metadati di database per tutto il core",
"Il preprocessing lavora su uno snapshot immutabile del catalogo, non sul DWH"
]
},
{
"dot": "amber",
"title": "Collezioni separate",
"items": [
"reference (schema, relazioni, Evidence) può essere svuotata e ricostruita dal preprocessing",
"memory si ricostruisce dalle card PostgreSQL e non viene toccata dal preprocessing"
]
},
{
"dot": "rose",
"title": "Prerequisito",
"items": [
"Senza preprocessing completato il core non ammette nuove sessioni"
]
}
]
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+384
View File
@@ -0,0 +1,384 @@
{
"schema_version": 1,
"diagram_type": "tree",
"meta": {
"title": "ThothII — struttura dei moduli",
"locale": "it",
"output": "docs/architecture/thothii-modules.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"layout": {
"direction": "right"
},
"nodes": [
{
"id": "root",
"label": "ThothII",
"sublabel": "monorepo, tre layer + operatore",
"sources": [
{
"path": "AGENTS.md",
"line": 1
}
]
},
{
"id": "frontend",
"label": "frontend/",
"parent": "root",
"sublabel": "React 18 + Vite",
"sources": [
{
"path": "frontend/src/main.tsx",
"line": 1
}
]
},
{
"id": "fe_api",
"label": "src/api",
"parent": "frontend",
"sublabel": "client HTTP verso /api",
"sources": [
{
"path": "frontend/src/api/client.ts",
"line": 1
}
]
},
{
"id": "fe_shell",
"label": "src/shell",
"parent": "frontend",
"sublabel": "AppShell e pagine admin",
"sources": [
{
"path": "frontend/src/shell/AppShell.tsx",
"line": 1
}
]
},
{
"id": "fe_store",
"label": "src/store + stream",
"parent": "frontend",
"sublabel": "transcript live da SSE",
"sources": [
{
"path": "frontend/src/store/sessionStore.ts",
"line": 1
}
]
},
{
"id": "fe_widgets",
"label": "src/widgets",
"parent": "frontend",
"sublabel": "widget dei gate reviewer",
"sources": [
{
"path": "frontend/src/widgets/registry.ts",
"line": 1
}
]
},
{
"id": "fe_i18n",
"label": "src/i18n",
"parent": "frontend",
"sublabel": "cataloghi EN/IT"
},
{
"id": "backend",
"label": "backend/",
"parent": "root",
"sublabel": "Fastify + TypeScript",
"sources": [
{
"path": "backend/src/server.ts",
"line": 1
}
]
},
{
"id": "be_routes",
"label": "src/routes",
"parent": "backend",
"sublabel": "API REST e SSE",
"sources": [
{
"path": "backend/src/routes/sessions.ts",
"line": 1
}
]
},
{
"id": "be_bridge",
"label": "src/pi + rpc + bridge",
"parent": "backend",
"sublabel": "processi Pi e bridge RPC",
"sources": [
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 1
}
]
},
{
"id": "be_sse",
"label": "src/sse",
"parent": "backend",
"sublabel": "SseHub con replay",
"sources": [
{
"path": "backend/src/sse/sse-hub.ts",
"line": 1
}
]
},
{
"id": "be_tht",
"label": "src/tht",
"parent": "backend",
"sublabel": "ThtRunner: shell del CLI",
"sources": [
{
"path": "backend/src/tht/tht-runner.ts",
"line": 1
}
]
},
{
"id": "be_auth",
"label": "src/auth",
"parent": "backend",
"sublabel": "local, OIDC, upstream",
"sources": [
{
"path": "backend/src/auth/auth.ts",
"line": 1
}
]
},
{
"id": "be_catalog",
"label": "src/catalog",
"parent": "backend",
"sublabel": "Metadata Catalog, sync, descrizioni",
"sources": [
{
"path": "backend/src/catalog/service.ts",
"line": 1
}
]
},
{
"id": "be_ws",
"label": "src/workspaces",
"parent": "backend",
"sublabel": "registry Git e preprocessing",
"sources": [
{
"path": "backend/src/workspaces/preprocessing-service.ts",
"line": 1
}
]
},
{
"id": "harness",
"label": "harness/",
"parent": "root",
"sublabel": "workflow NL→SQL",
"sources": [
{
"path": "harness/README.md",
"line": 1
}
]
},
{
"id": "h_wf",
"label": "workflow.yaml",
"parent": "harness",
"sublabel": "fasi F1–F8",
"sources": [
{
"path": "harness/workflow.yaml",
"line": 1
}
]
},
{
"id": "h_pi",
"label": ".pi/",
"parent": "harness",
"sublabel": "estensione gate, skill, prompt",
"sources": [
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 1
}
]
},
{
"id": "h_cli",
"label": "tht/cli",
"parent": "harness",
"sublabel": "sottocomandi del CLI tht",
"sources": [
{
"path": "harness/tht/cli/__init__.py",
"line": 1
}
]
},
{
"id": "h_session",
"label": "tht/session + phase",
"parent": "harness",
"sublabel": "manifest, ledger, fase",
"sources": [
{
"path": "harness/tht/session/store.py",
"line": 1
}
]
},
{
"id": "h_adapters",
"label": "tht/adapters",
"parent": "harness",
"sublabel": "DWH e Qdrant",
"sources": [
{
"path": "harness/tht/adapters/factory.py",
"line": 1
}
]
},
{
"id": "h_search",
"label": "tht/search + vectorstore",
"parent": "harness",
"sublabel": "retrieval ibrido",
"sources": [
{
"path": "harness/tht/vectorstore/embeddings.py",
"line": 1
}
]
},
{
"id": "h_memory",
"label": "tht/memory",
"parent": "harness",
"sublabel": "card e domande risolte",
"sources": [
{
"path": "harness/tht/memory/repository.py",
"line": 1
}
]
},
{
"id": "h_evidence",
"label": "tht/evidence",
"parent": "harness",
"sublabel": "corpus Evidence",
"sources": [
{
"path": "harness/tht/evidence/preprocessing.py",
"line": 1
}
]
},
{
"id": "h_mschema",
"label": "tht/mschema",
"parent": "harness",
"sublabel": "snapshot e schema per il modello",
"sources": [
{
"path": "harness/tht/mschema/catalog_snapshot.py",
"line": 1
}
]
},
{
"id": "tools",
"label": "tools/tht",
"parent": "root",
"sublabel": "CLI host in Go",
"sources": [
{
"path": "tools/tht/README.md",
"line": 1
}
]
},
{
"id": "t_cmd",
"label": "cmd/tht",
"parent": "tools",
"sublabel": "comandi operatore",
"sources": [
{
"path": "tools/tht/cmd/tht/main.go",
"line": 1
}
]
},
{
"id": "t_internal",
"label": "internal/",
"parent": "tools",
"sublabel": "compose, setup, doctor, auth",
"sources": [
{
"path": "tools/tht/internal/compose/runner.go",
"line": 1
}
]
},
{
"id": "deploy",
"label": "docker/ + deploy/",
"parent": "root",
"sublabel": "immagini e profili Compose",
"sources": [
{
"path": "compose.yaml",
"line": 1
}
]
},
{
"id": "docs",
"label": "docs/",
"parent": "root",
"sublabel": "MkDocs, ADR, contratti",
"sources": [
{
"path": "mkdocs.yml",
"line": 1
}
]
}
],
"cards": [
{
"dot": "cyan",
"title": "Lettura",
"items": [
"Le linee indicano contenimento, non chiamate",
"Alcuni nodi raggruppano più cartelle sorelle con lo stesso ruolo",
"Test, script e cartelle generate sono omessi"
]
}
]
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,381 @@
{
"schema_version": 1,
"diagram_type": "sequence",
"meta": {
"title": "ThothII — avvio di una nuova domanda",
"locale": "it",
"output": "docs/architecture/thothii-new-question.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"participants": [
{
"id": "reviewer",
"type": "external",
"label": "Reviewer",
"sublabel": "browser"
},
{
"id": "frontend",
"type": "frontend",
"label": "Frontend",
"sublabel": "React",
"sources": [
{
"path": "frontend/src/api/sessions.ts",
"line": 96,
"end_line": 115,
"label": "createSession"
},
{
"path": "frontend/src/stream/useSessionStream.ts",
"line": 117,
"end_line": 121,
"label": "EventSource"
}
]
},
{
"id": "backend",
"type": "backend",
"label": "Backend",
"sublabel": "Fastify",
"sources": [
{
"path": "backend/src/routes/sessions.ts",
"line": 481,
"end_line": 487,
"label": "precheck DWH"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 513,
"end_line": 570,
"label": "POST /sessions"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 334,
"end_line": 350,
"label": "bootstrap"
}
]
},
{
"id": "tht",
"type": "backend",
"label": "tht CLI",
"sublabel": "harness",
"sources": [
{
"path": "backend/src/tht/tht-runner.ts",
"line": 484,
"end_line": 500,
"label": "session new"
},
{
"path": "backend/src/tht/tht-runner.ts",
"line": 514,
"end_line": 518,
"label": "search pack"
},
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 277,
"end_line": 280,
"label": "execFileSync"
}
]
},
{
"id": "pi",
"type": "backend",
"label": "Pi",
"sublabel": "--mode rpc",
"sources": [
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 143,
"end_line": 146,
"label": "spawn"
},
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 263,
"end_line": 280,
"label": "configure"
},
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 283,
"end_line": 290,
"label": "prompt iniziale"
}
]
},
{
"id": "gate",
"type": "backend",
"label": "tht-gate.js",
"sublabel": "estensione Pi",
"sources": [
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 780,
"end_line": 795,
"label": "hook input"
},
{
"path": "harness/.pi/prompts/nuova-domanda.md",
"line": 1,
"end_line": 10,
"label": "template prompt"
}
]
},
{
"id": "llm",
"type": "cloud",
"label": "Provider LLM",
"sublabel": "modello di sessione"
}
],
"segments": [
{
"from": 160,
"to": 470,
"label": "Creazione sessione"
},
{
"from": 476,
"to": 595,
"label": "Bootstrap"
},
{
"from": 605,
"to": 875,
"label": "Primo turno (F1)"
}
],
"messages": [
{
"id": "ask",
"from": "reviewer",
"to": "frontend",
"y": 170,
"label": "domanda"
},
{
"id": "post",
"from": "frontend",
"to": "backend",
"y": 200,
"label": "POST /sessions",
"variant": "emphasis"
},
{
"id": "new",
"from": "backend",
"to": "tht",
"y": 230,
"label": "session new",
"note": "scrive il manifest e fissa la lingua"
},
{
"id": "new-ok",
"from": "tht",
"to": "backend",
"y": 315,
"label": "id sessione",
"variant": "return"
},
{
"id": "spawn",
"from": "backend",
"to": "pi",
"y": 345,
"label": "spawn processo",
"note": "un processo Pi per sessione"
},
{
"id": "id",
"from": "backend",
"to": "frontend",
"y": 395,
"label": "{ id }",
"variant": "return"
},
{
"id": "sse",
"from": "frontend",
"to": "backend",
"y": 425,
"label": "GET /events (SSE)",
"note": "l'hub conserva gli eventi già emessi per la riconnessione"
},
{
"id": "model",
"from": "backend",
"to": "pi",
"y": 485,
"label": "set_model + thinking"
},
{
"id": "pack",
"from": "backend",
"to": "tht",
"y": 515,
"label": "search pack",
"note": "in parallelo al modello"
},
{
"id": "prompt",
"from": "backend",
"to": "pi",
"y": 585,
"label": "prompt /nuova-domanda",
"variant": "emphasis"
},
{
"id": "hook",
"from": "pi",
"to": "gate",
"y": 615,
"label": "hook input"
},
{
"id": "turn",
"from": "pi",
"to": "llm",
"y": 645,
"label": "turno modello",
"variant": "emphasis"
},
{
"id": "tokens",
"from": "llm",
"to": "pi",
"y": 675,
"label": "token + tool call",
"variant": "return"
},
{
"id": "tool",
"from": "pi",
"to": "gate",
"y": 705,
"label": "tool call"
},
{
"id": "cli",
"from": "gate",
"to": "tht",
"y": 735,
"label": "tht phase / session",
"note": "scrive artefatti e ledger"
},
{
"id": "event",
"from": "pi",
"to": "backend",
"y": 805,
"label": "eventi RPC",
"variant": "dashed"
},
{
"id": "push",
"from": "backend",
"to": "frontend",
"y": 835,
"label": "SSE text_delta",
"variant": "dashed"
},
{
"id": "render",
"from": "frontend",
"to": "reviewer",
"y": 865,
"label": "transcript live",
"variant": "return"
}
],
"activations": [
{
"participant": "frontend",
"from": 195,
"to": 871,
"type": "frontend"
},
{
"participant": "backend",
"from": 200,
"to": 841,
"type": "backend"
},
{
"participant": "tht",
"from": 228,
"to": 321,
"type": "backend"
},
{
"participant": "tht",
"from": 513,
"to": 545,
"type": "backend"
},
{
"participant": "tht",
"from": 733,
"to": 775,
"type": "backend"
},
{
"participant": "pi",
"from": 343,
"to": 811,
"type": "backend"
},
{
"participant": "gate",
"from": 613,
"to": 779,
"type": "backend"
},
{
"participant": "llm",
"from": 643,
"to": 681,
"type": "cloud"
}
],
"cards": [
{
"dot": "cyan",
"title": "Ordine di avvio",
"items": [
"La sessione esiste su disco prima che Pi parta: il manifest è la fonte di verità",
"Il primo prompt parte solo dopo configurazione del modello e search pack"
]
},
{
"dot": "amber",
"title": "Precheck DWH",
"items": [
"In installazione locale il backend verifica il DWH prima di creare la sessione e risponde 503 se non è raggiungibile"
]
},
{
"dot": "emerald",
"title": "Stream",
"items": [
"Il bridge traduce gli eventi Pi in text_delta, info e ui_request",
"Il transcript vive solo nel browser; non viene salvato"
]
}
]
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,104 @@
{
"schema_version": 2,
"diagram_type": "workflow",
"meta": {
"title": "ThothII — workflow NL→SQL in 8 fasi",
"locale": "it",
"output": "docs/architecture/thothii-phases.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"lanes": [
{ "id": "domanda", "label": "Domanda" },
{ "id": "schema", "label": "Schema e sintesi" },
{ "id": "sql", "label": "SQL" },
{ "id": "chiusura", "label": "Chiusura" },
{ "id": "eccezioni", "label": "Ritorno indietro", "variant": "exception" }
],
"mainPath": ["f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "finalizzata"],
"nodes": [
{ "id": "f1", "lane": "domanda", "col": 0, "type": "frontend", "label": "F1 chiarimento", "sublabel": "concetti e ambiguità", "tag": "gate fase",
"sources": [
{ "path": "harness/workflow.yaml", "line": 13, "end_line": 18 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 57, "end_line": 57 }
] },
{ "id": "f2", "lane": "domanda", "col": 1, "type": "database", "label": "F2 memoria", "sublabel": "memorie e esempi risolti", "tag": "auto se vuota",
"sources": [
{ "path": "harness/workflow.yaml", "line": 19, "end_line": 24 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 58, "end_line": 58 }
] },
{ "id": "f3", "lane": "domanda", "col": 2, "type": "frontend", "label": "F3 riscrittura", "sublabel": "question.md", "tag": "si chiude da sola",
"sources": [
{ "path": "harness/workflow.yaml", "line": 25, "end_line": 31 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 59, "end_line": 59 }
] },
{ "id": "f4", "lane": "schema", "col": 2, "type": "frontend", "label": "F4 schema linking", "sublabel": "schema_linking.json", "tag": "reviewer_decide",
"sources": [
{ "path": "harness/workflow.yaml", "line": 32, "end_line": 39 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 60, "end_line": 60 }
] },
{ "id": "f5", "lane": "schema", "col": 3, "type": "frontend", "label": "F5 sintesi", "sublabel": "valida SchemaLinking", "tag": "gate fase",
"sources": [
{ "path": "harness/workflow.yaml", "line": 40, "end_line": 46 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 61, "end_line": 61 }
] },
{ "id": "f6", "lane": "sql", "col": 3, "type": "backend", "label": "F6 CTE", "sublabel": "piano, CTE e test", "tag": "ultima CTE chiude",
"sources": [
{ "path": "harness/workflow.yaml", "line": 47, "end_line": 55 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 62, "end_line": 62 }
] },
{ "id": "f7", "lane": "sql", "col": 4, "type": "backend", "label": "F7 SQL finale", "sublabel": "sql_final.sql", "tag": "kind sql chiude",
"sources": [
{ "path": "harness/workflow.yaml", "line": 56, "end_line": 62 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 63, "end_line": 63 }
] },
{ "id": "f8", "lane": "chiusura", "col": 4, "type": "database", "label": "F8 datamart", "sublabel": "promozione memorie", "tag": "si chiude da sola",
"sources": [
{ "path": "harness/workflow.yaml", "line": 63, "end_line": 72 },
{ "path": "harness/.pi/skills/tht-sessione/SKILL.md", "line": 64, "end_line": 64 }
] },
{ "id": "finalizzata", "lane": "chiusura", "col": 5, "type": "external", "label": "Sessione finalizzata", "sublabel": "tht session finalize",
"sources": [
{ "path": "harness/.pi/extensions/tht-gate.js", "line": 1650, "end_line": 1666, "label": "advancePhaseAndFinalize" }
] },
{ "id": "riapertura", "lane": "eccezioni", "col": 1, "type": "security", "label": "Riapertura fase", "sublabel": "/torna → phase reopen", "tag": "phase_reopened",
"sources": [
{ "path": "harness/.pi/extensions/tht-gate.js", "line": 1775, "end_line": 1814, "label": "comando /torna" },
{ "path": "harness/tht/phase.py", "line": 60, "end_line": 79, "label": "fold con reopen" }
] }
],
"edges": [
{ "id": "f1-f2", "from": "f1", "to": "f2", "variant": "emphasis" },
{ "id": "f2-f3", "from": "f2", "to": "f3", "variant": "emphasis" },
{ "id": "f3-f4", "from": "f3", "to": "f4", "variant": "emphasis" },
{ "id": "f4-f5", "from": "f4", "to": "f5", "variant": "emphasis" },
{ "id": "f5-f6", "from": "f5", "to": "f6", "variant": "emphasis" },
{ "id": "f6-f7", "from": "f6", "to": "f7", "variant": "emphasis" },
{ "id": "f7-f8", "from": "f7", "to": "f8", "variant": "emphasis" },
{ "id": "f8-fin", "from": "f8", "to": "finalizzata", "label": "finalize", "variant": "emphasis" },
{ "id": "torna", "from": "f7", "to": "riapertura", "label": "/torna", "variant": "dashed", "role": "error" },
{ "id": "riapre", "from": "riapertura", "to": "f1", "label": "fase N < corrente", "variant": "dashed", "role": "return" }
],
"cards": [
{ "dot": "cyan", "title": "Chi decide", "items": [
"Il modello propone, il reviewer decide tramite widget, tht persiste",
"Gate fase (F1, F2 con memorie, F5): il reviewer conferma che la fase è completa",
"F3, F4, ultima CTE di F6, F7 e F8: l'approvazione sostanziale chiude la fase da sola"
] },
{ "dot": "emerald", "title": "Fase corrente", "items": [
"Non è salvata: si calcola ripercorrendo il ledger review_decisions.jsonl",
"phase_approved avanza solo la fase corrente; phase_reopened riporta indietro"
] },
{ "dot": "amber", "title": "Salti automatici", "items": [
"F2 avanza da sola se non ci sono memorie pertinenti",
"F6 può essere saltata (phase_skipped) o essere vuota"
] },
{ "dot": "rose", "title": "Ritorno indietro", "items": [
"/torna è disponibile da qualunque fase verso una fase precedente; qui è mostrato da F7 come esempio"
] }
]
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,256 @@
{
"schema_version": 1,
"diagram_type": "sequence",
"meta": {
"title": "ThothII — ripresa di una sessione",
"locale": "it",
"output": "docs/architecture/thothii-resume.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"participants": [
{
"id": "reviewer",
"type": "external",
"label": "Reviewer",
"sublabel": "browser"
},
{
"id": "frontend",
"type": "frontend",
"label": "Frontend",
"sublabel": "React"
},
{
"id": "backend",
"type": "backend",
"label": "Backend",
"sublabel": "Fastify",
"sources": [
{
"path": "backend/src/routes/sessions.ts",
"line": 685,
"end_line": 698,
"label": "409 se in sola lettura"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 774,
"end_line": 809,
"label": "reopen + nuovo runtime"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 820,
"end_line": 829,
"label": "bootstrap senza search pack"
}
]
},
{
"id": "tht",
"type": "backend",
"label": "tht CLI",
"sublabel": "sessione su disco",
"sources": [
{
"path": "backend/src/tht/tht-runner.ts",
"line": 569,
"end_line": 569,
"label": "session reopen"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 206,
"end_line": 216,
"label": "locateSession"
}
]
},
{
"id": "pi",
"type": "backend",
"label": "Pi",
"sublabel": "nuovo processo",
"sources": [
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 283,
"end_line": 290,
"label": "/riprendi-sessione"
},
{
"path": "harness/.pi/skills/tht-sessione/SKILL.md",
"line": 164,
"end_line": 185,
"label": "Phase 0 Resume"
}
]
},
{
"id": "llm",
"type": "cloud",
"label": "Provider LLM",
"sublabel": "modello salvato"
}
],
"segments": [
{
"from": 160,
"to": 438,
"label": "Richiesta"
},
{
"from": 448,
"to": 540,
"label": "Bootstrap"
},
{
"from": 550,
"to": 858,
"label": "Ricostruzione"
}
],
"messages": [
{
"from": "reviewer",
"to": "frontend",
"y": 170,
"label": "riprendi sessione"
},
{
"from": "frontend",
"to": "backend",
"y": 200,
"label": "POST /sessions/:id/resume",
"variant": "emphasis"
},
{
"from": "backend",
"to": "tht",
"y": 230,
"label": "session show",
"note": "409 se finalizzata o archiviata"
},
{
"from": "tht",
"to": "backend",
"y": 296,
"label": "manifest",
"variant": "return"
},
{
"from": "backend",
"to": "tht",
"y": 326,
"label": "session reopen"
},
{
"from": "backend",
"to": "pi",
"y": 356,
"label": "spawn",
"note": "sostituisce il runtime fermo"
},
{
"from": "backend",
"to": "frontend",
"y": 422,
"label": "200 { id }",
"variant": "return"
},
{
"from": "backend",
"to": "pi",
"y": 458,
"label": "set_model + thinking",
"note": "niente search pack: il contesto è su disco"
},
{
"from": "backend",
"to": "pi",
"y": 524,
"label": "prompt /riprendi-sessione",
"variant": "emphasis"
},
{
"from": "pi",
"to": "llm",
"y": 560,
"label": "turno modello",
"variant": "emphasis"
},
{
"from": "llm",
"to": "pi",
"y": 590,
"label": "tool call",
"variant": "return"
},
{
"from": "pi",
"to": "tht",
"y": 620,
"label": "tht session show",
"note": "fase corrente, stato e lingua"
},
{
"from": "pi",
"to": "tht",
"y": 686,
"label": "tht session documents",
"note": "artefatti già prodotti"
},
{
"from": "tht",
"to": "pi",
"y": 752,
"label": "artefatti + ledger",
"variant": "return"
},
{
"from": "pi",
"to": "backend",
"y": 782,
"label": "gate della fase N",
"variant": "dashed"
},
{
"from": "backend",
"to": "frontend",
"y": 812,
"label": "SSE ui_request",
"variant": "dashed"
},
{
"from": "frontend",
"to": "reviewer",
"y": 842,
"label": "riprende dalla fase N",
"variant": "return"
}
],
"cards": [
{
"dot": "cyan",
"title": "Stato su disco",
"items": [
"Pi riparte senza conversazione: manifest, artefatti e ledger sono l'unico contesto",
"La fase corrente si ricalcola dal ledger"
]
},
{
"dot": "amber",
"title": "Casi particolari",
"items": [
"Se il runtime è ancora attivo la risposta è alreadyActive e non si riavvia nulla",
"La lingua di interazione resta quella salvata; non si può cambiare alla ripresa",
"Il prompt sbagliato (/nuova-domanda) trasformerebbe la ripresa in una nuova domanda"
]
}
]
}
@@ -2,265 +2,550 @@
"schema_version": 1,
"diagram_type": "architecture",
"meta": {
"title": "ThothII Runtime Architecture",
"locale": "en",
"output": "thothii-runtime.html",
"title": "ThothII — architettura runtime NL→SQL",
"locale": "it",
"output": "docs/architecture/thothii-runtime.html",
"quality_profile": "showcase",
"viewBox": [1360, 800]
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "c77957af93ec77897e0c1f360091b156f3e2424b"
}
},
"components": [
{
"id": "reviewer",
"type": "external",
"label": "User / Reviewer",
"sublabel": "Browser",
"pos": [20, 300],
"size": [145, 72]
"label": "Reviewer",
"sublabel": "browser",
"pos": [
40,
200
],
"size": [
120,
64
]
},
{
"id": "frontend",
"type": "frontend",
"label": "Frontend",
"sublabel": "React 18 + Vite",
"tag": "in-memory transcript",
"pos": [205, 295],
"size": [165, 82]
"sublabel": "React 18 + nginx",
"tag": "widget gate",
"pos": [
260,
200
],
"size": [
150,
64
],
"sources": [
{
"path": "docker/nginx.conf.template",
"line": 13,
"end_line": 20,
"label": "proxy /api → core"
},
{
"path": "frontend/src/stream/useSessionStream.ts",
"line": 121,
"end_line": 121,
"label": "EventSource SSE"
},
{
"path": "frontend/src/widgets/registry.ts",
"line": 5,
"end_line": 13,
"label": "registry widget"
}
]
},
{
"id": "backend",
"type": "backend",
"label": "Backend",
"sublabel": "Fastify + TypeScript",
"tag": "session bridge",
"pos": [410, 295],
"size": [175, 82]
"sublabel": "Fastify :8787",
"tag": "SessionBridge + SseHub",
"pos": [
510,
200
],
"size": [
170,
64
],
"sources": [
{
"path": "backend/src/routes/sessions.ts",
"line": 634,
"end_line": 663,
"label": "POST risposta gate"
},
{
"path": "backend/src/bridge/session-bridge.ts",
"line": 63,
"end_line": 71,
"label": "RPC → ui_request"
},
{
"path": "backend/src/sse/sse-hub.ts",
"line": 107,
"end_line": 113,
"label": "publish SSE"
}
]
},
{
"id": "pi",
"type": "backend",
"label": "Pi",
"sublabel": "RPC process per session",
"tag": "inside core",
"pos": [625, 295],
"size": [170, 82]
"sublabel": "--mode rpc, 1 per sessione",
"pos": [
790,
200
],
"size": [
170,
64
],
"sources": [
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 143,
"end_line": 146,
"label": "spawn pi --mode rpc"
},
{
"id": "harness",
"path": "backend/src/pi/pi-process-manager.ts",
"line": 283,
"end_line": 290,
"label": "nuova-domanda / riprendi"
}
]
},
{
"id": "gate",
"type": "backend",
"label": "tht / Harness",
"sublabel": "8-phase NL→SQL workflow",
"tag": "workflow owner",
"pos": [835, 295],
"size": [190, 82]
"label": "tht-gate.js",
"sublabel": "estensione Pi, fasi F1–F8",
"tag": "reviewer tools",
"pos": [
1060,
200
],
"size": [
170,
64
],
"sources": [
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 597,
"end_line": 603,
"label": "ctx.ui.input"
},
{
"id": "workspace",
"type": "database",
"label": "Workspace Repository",
"sublabel": "sessions + phase artifacts",
"tag": "source of truth",
"pos": [1065, 295],
"size": [205, 82]
"path": "harness/.pi/extensions/tht-gate.js",
"line": 889,
"end_line": 895,
"label": "reviewer_select"
},
{
"id": "auth",
"path": "harness/.pi/skills/tht-sessione/SKILL.md",
"line": 40,
"end_line": 66,
"label": "regole di fase"
}
]
},
{
"id": "tht",
"type": "backend",
"label": "tht CLI",
"sublabel": "harness Python",
"tag": "fase = fold ledger",
"pos": [
1335,
200
],
"size": [
160,
64
],
"sources": [
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 277,
"end_line": 280,
"label": "execFileSync tht"
},
{
"path": "harness/tht/phase.py",
"line": 60,
"end_line": 79,
"label": "current_phase"
},
{
"path": "harness/workflow.yaml",
"line": 12,
"end_line": 72,
"label": "workflow F1–F8"
}
]
},
{
"id": "llm",
"type": "cloud",
"label": "Provider LLM",
"sublabel": "catalogo modelli installazione",
"pos": [
790,
400
],
"size": [
170,
64
],
"sources": [
{
"path": "backend/src/pi/managed-config.ts",
"line": 120,
"end_line": 128,
"label": "models.json di Pi"
},
{
"path": "backend/src/catalog/model-completer.ts",
"line": 67,
"end_line": 74,
"label": "helper LiteLLM"
},
{
"path": "harness/tht/internal/litellm_completion.py",
"line": 186,
"end_line": 195
}
]
},
{
"id": "idp",
"type": "security",
"label": "Authentication",
"sublabel": "local registry or OIDC",
"pos": [410, 70],
"size": [170, 76]
"label": "Identity provider",
"sublabel": "OIDC / upstream",
"pos": [
260,
30
],
"size": [
150,
64
],
"sources": [
{
"path": "backend/src/auth/oidc-client.ts",
"line": 24,
"end_line": 27,
"label": "OidcProtocol"
}
]
},
{
"id": "modelProvider",
"type": "external",
"label": "AI Model Provider",
"sublabel": "installation-selected APIs",
"pos": [615, 70],
"size": [190, 76]
"id": "embedding",
"type": "backend",
"label": "Embedding",
"sublabel": "Ollama :11434",
"pos": [
1335,
30
],
"size": [
160,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 230,
"end_line": 249
},
{
"path": "harness/tht/vectorstore/embeddings.py",
"line": 65,
"end_line": 75,
"label": "embed()"
}
]
},
{
"id": "qdrant",
"type": "database",
"label": "Qdrant",
"sublabel": "vector store :6333",
"pos": [
1580,
200
],
"size": [
150,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 210,
"end_line": 228
},
{
"path": "harness/tht/adapters/vector/qdrant.py",
"line": 141,
"end_line": 141,
"label": "search"
},
{
"path": "harness/tht/adapters/vector/qdrant.py",
"line": 327,
"end_line": 327,
"label": "upsert"
}
]
},
{
"id": "sessions",
"type": "database",
"label": "Sessioni",
"sublabel": "manifest + artefatti + ledger",
"tag": "fonte di verità",
"pos": [
1335,
400
],
"size": [
160,
64
],
"sources": [
{
"path": "harness/tht/session/repository.py",
"line": 74,
"end_line": 92,
"label": "filesystem o Postgres"
},
{
"path": "harness/tht/session/filesystem_repository.py",
"line": 134,
"end_line": 142,
"label": "append decisioni"
},
{
"path": "harness/tht/decisions.py",
"line": 10,
"end_line": 10,
"label": "review_decisions.jsonl"
}
]
},
{
"id": "dwh",
"type": "database",
"label": "DWH",
"sublabel": "Postgres o REST",
"tag": "sola lettura",
"pos": [
1580,
400
],
"size": [
170,
64
],
"sources": [
{
"path": "harness/tht/adapters/dwh/postgres.py",
"line": 29,
"end_line": 33,
"label": "verifica read-only"
},
{
"path": "harness/tht/adapters/dwh/thoth_rest.py",
"line": 22,
"end_line": 29,
"label": "REST read_only"
},
{
"path": "backend/src/catalog/description-source-sampler.ts",
"line": 153,
"end_line": 160,
"label": "campionamento"
}
]
},
{
"id": "catalog",
"type": "database",
"label": "Metadata Catalog",
"sublabel": "PostgreSQL + Kysely",
"tag": "backend-owned",
"pos": [410, 545],
"size": [180, 82]
"sublabel": "PostgreSQL 17",
"pos": [
510,
400
],
"size": [
170,
64
],
"sources": [
{
"path": "compose.yaml",
"line": 74,
"end_line": 98
},
{
"id": "embedding",
"type": "backend",
"label": "Embedding Service",
"sublabel": "Ollama",
"pos": [800, 545],
"size": [170, 76]
},
{
"id": "qdrant",
"type": "database",
"label": "Vector Store",
"sublabel": "Qdrant",
"pos": [1010, 545],
"size": [160, 76]
},
{
"id": "dwh",
"type": "external",
"label": "Data Warehouse",
"sublabel": "external, read-only",
"pos": [1070, 70],
"size": [180, 82]
"path": "backend/src/catalog/repository.ts",
"line": 2054,
"end_line": 2068,
"label": "pool + repository"
}
]
}
],
"boundaries": [
{
"kind": "region",
"label": "Local Docker Compose runtime",
"wraps": ["frontend", "backend", "pi", "harness", "catalog", "embedding", "qdrant"],
"pad": 26
},
{
"kind": "security-group",
"label": "core container",
"wraps": ["pi", "harness"],
"pad": 18
},
{
"kind": "security-group",
"label": "operator-controlled persisted state",
"wraps": ["workspace"],
"pad": 18
"label": "container core",
"wraps": [
"backend",
"pi",
"gate",
"tht"
]
}
],
"connections": [
{
"id": "reviewerInput",
"id": "rev-fe",
"from": "reviewer",
"to": "frontend",
"label": "question / gate decision",
"variant": "emphasis",
"labelAt": [185, 391]
},
{
"id": "restRequests",
"from": "frontend",
"to": "backend",
"label": "REST",
"label": "HTTPS",
"variant": "emphasis"
},
{
"id": "sseEvents",
"from": "backend",
"to": "frontend",
"label": "SSE: text · info · widget",
"variant": "dashed",
"labelAt": [390, 415]
"id": "fe-be",
"from": "frontend",
"to": "backend",
"label": "/api + SSE",
"variant": "emphasis"
},
{
"id": "piRpc",
"id": "be-pi",
"from": "backend",
"to": "pi",
"label": "JSON-RPC stdio",
"variant": "emphasis",
"labelAt": [605, 391]
"label": "RPC stdio",
"variant": "emphasis"
},
{
"id": "gateCommands",
"id": "pi-gate",
"from": "pi",
"to": "harness",
"label": "phase / gate commands",
"variant": "emphasis",
"labelAt": [815, 391]
"to": "gate",
"label": "tool call",
"variant": "emphasis"
},
{
"id": "persistArtifacts",
"from": "harness",
"to": "workspace",
"label": "artifacts + decision ledger",
"variant": "emphasis",
"labelAt": [1045, 391]
"id": "gate-tht",
"from": "gate",
"to": "tht",
"label": "execFileSync",
"variant": "emphasis"
},
{
"id": "authenticate",
"from": "auth",
"to": "backend",
"label": "local session / OIDC callback",
"variant": "security",
"fromSide": "bottom",
"toSide": "top"
"id": "tht-sessions",
"from": "tht",
"to": "sessions",
"label": "scrive"
},
{
"id": "sessionModel",
"id": "tht-dwh",
"from": "tht",
"to": "dwh",
"label": "SQL read-only"
},
{
"id": "tht-qdrant",
"from": "tht",
"to": "qdrant",
"label": "ricerca"
},
{
"id": "tht-embedding",
"from": "tht",
"to": "embedding",
"label": "embed"
},
{
"id": "pi-llm",
"from": "pi",
"to": "modelProvider",
"label": "session model API",
"fromSide": "top",
"toSide": "bottom",
"labelAt": [755, 185]
"to": "llm",
"label": "prompt"
},
{
"id": "catalogState",
"id": "be-llm",
"from": "backend",
"to": "catalog",
"label": "catalog CRUD + runs",
"fromSide": "bottom",
"toSide": "top"
},
{
"id": "metadataModel",
"from": "backend",
"to": "modelProvider",
"label": "short-lived LiteLLM calls",
"to": "llm",
"label": "descrizioni",
"variant": "dashed"
},
{
"id": "readOnlySql",
"from": "harness",
"to": "dwh",
"label": "introspection + read-only SQL"
"id": "be-idp",
"from": "backend",
"to": "idp",
"label": "OIDC",
"variant": "security"
},
{
"id": "embedRequests",
"from": "harness",
"to": "embedding",
"label": "embedding requests",
"fromSide": "bottom",
"toSide": "top",
"labelAt": [830, 490]
"id": "be-catalog",
"from": "backend",
"to": "catalog",
"label": "SQL"
},
{
"id": "vectorAccess",
"from": "harness",
"to": "qdrant",
"label": "index + vector retrieval",
"fromSide": "bottom",
"toSide": "top",
"labelAt": [1165, 475]
"id": "be-tht",
"from": "backend",
"to": "tht",
"label": "ThtRunner"
}
],
"cards": [
{
"dot": "cyan",
"title": "Primary session path",
"title": "Flusso di una sessione",
"items": [
"The browser sends questions and reviewer decisions over REST; the backend returns text, information, and widget descriptors over SSE.",
"One Pi RPC process drives each active session and delegates deterministic phase operations to tht / Harness."
"Il backend avvia un processo Pi per sessione e invia /nuova-domanda o /riprendi-sessione",
"tht-gate.js guida le fasi F1–F8 e chiama il CLI tht per ogni passo deterministico",
"I gate reviewer arrivano al browser come ui_request via SSE; la risposta torna con POST /sessions/:id/response"
]
},
{
"dot": "emerald",
"title": "State ownership",
"title": "Persistenza",
"items": [
"Harness owns the eight-phase workflow and persists session_manifest.yaml, phase artifacts, and review_decisions.jsonl.",
"Backend owns the separate installation-local metadata catalog; the live frontend transcript is not persisted."
"Lo stato è nei documenti di fase e nel ledger review_decisions.jsonl, non nella chat",
"La fase corrente si calcola ripiegando il ledger (phase.py), non viene salvata",
"Repository sessioni su filesystem oppure PostgreSQL, secondo la configurazione"
]
},
{
"dot": "amber",
"title": "Catalogo metadati",
"items": [
"Il backend gestisce il Metadata Catalog PostgreSQL",
"Le descrizioni AI campionano il DWH in sola lettura e usano un helper Python LiteLLM, senza Pi"
]
},
{
"dot": "rose",
"title": "Trust boundaries",
"title": "Sicurezza",
"items": [
"Catalog DB, Qdrant, and Ollama stay inside Compose; workspace state is operator controlled and mounted into core.",
"The DWH and AI provider remain external endpoints; DWH access is constrained to introspection, tests, bounded samples, and read-only SQL."
"Login OIDC o identità upstream dal portale (Omics embedded)",
"Qdrant ed Embedding sono servizi interni della rete Compose; DWH e LLM sono endpoint esterni"
]
}
]
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,229 @@
{
"schema_version": 3,
"diagram_type": "lifecycle",
"meta": {
"title": "ThothII — ciclo di vita di una sessione",
"locale": "it",
"output": "docs/architecture/thothii-session-lifecycle.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"mainPath": [
"open",
"finalized",
"archived"
],
"states": [
{
"id": "open",
"type": "start",
"label": "open",
"sublabel": "fasi F1–F8 in corso",
"tag": "riprendibile",
"step": "01",
"sources": [
{
"path": "harness/tht/session/models.py",
"line": 107,
"end_line": 107,
"label": "status"
},
{
"path": "harness/tht/session/store.py",
"line": 524,
"end_line": 533,
"label": "reopen_session"
}
]
},
{
"id": "finalized",
"type": "success",
"label": "finalized",
"sublabel": "SQL verificato sul DWH",
"tag": "sola lettura",
"step": "02",
"sources": [
{
"path": "harness/tht/session/store.py",
"line": 570,
"end_line": 592,
"label": "persist_verified_finalization"
},
{
"path": "harness/.pi/extensions/tht-gate.js",
"line": 1650,
"end_line": 1666,
"label": "finalize automatico"
}
]
},
{
"id": "archived",
"type": "neutral",
"label": "archiviata",
"sublabel": "flag archived",
"tag": "nascosta",
"step": "03",
"sources": [
{
"path": "harness/tht/session/store.py",
"line": 556,
"end_line": 562,
"label": "set_archived"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 928,
"end_line": 937,
"label": "POST /archive"
}
]
},
{
"id": "closed",
"type": "waiting",
"label": "closed",
"sublabel": "processo Pi fermato",
"tag": "riprendibile",
"sources": [
{
"path": "harness/tht/session/store.py",
"line": 506,
"end_line": 512,
"label": "close_session"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 832,
"end_line": 850,
"label": "POST /close"
}
]
},
{
"id": "failed",
"type": "failure",
"label": "failed",
"sublabel": "bootstrap o Pi falliti",
"tag": "riprendibile",
"sources": [
{
"path": "harness/tht/session/store.py",
"line": 515,
"end_line": 521,
"label": "fail_session"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 355,
"end_line": 366,
"label": "bootstrap fallito"
}
]
},
{
"id": "deleted",
"type": "neutral",
"label": "cancellata",
"sublabel": "directory rimossa",
"sources": [
{
"path": "harness/tht/session/store.py",
"line": 564,
"end_line": 568,
"label": "delete_session"
},
{
"path": "backend/src/routes/sessions.ts",
"line": 948,
"end_line": 968,
"label": "DELETE /sessions/:id"
}
]
}
],
"transitions": [
{
"id": "open-finalized",
"from": "open",
"to": "finalized",
"label": "F8 chiusa",
"variant": "emphasis"
},
{
"id": "finalized-archived",
"from": "finalized",
"to": "archived",
"label": "archive"
},
{
"id": "open-closed",
"from": "open",
"to": "closed",
"label": "close"
},
{
"id": "closed-open",
"from": "closed",
"to": "open",
"label": "resume (reopen)"
},
{
"id": "open-failed",
"from": "open",
"to": "failed",
"label": "errore runtime",
"variant": "security"
},
{
"id": "failed-open",
"from": "failed",
"to": "open",
"label": "resume (reopen)"
},
{
"id": "closed-deleted",
"from": "closed",
"to": "deleted",
"label": "delete",
"variant": "dashed"
},
{
"id": "archived-finalized",
"from": "archived",
"to": "finalized",
"label": "unarchive"
}
],
"cards": [
{
"dot": "cyan",
"title": "Ripresa",
"items": [
"Si riprendono solo sessioni open, closed o failed: reopen le riporta a open",
"Il backend risponde 409 se la sessione è finalized o archiviata"
]
},
{
"dot": "amber",
"title": "Archiviazione",
"items": [
"archived è un flag separato dallo status: si può archiviare anche una sessione chiusa",
"Archiviare non cambia lo status; una sessione archiviata non si riprende finché non viene ripristinata",
"delete è possibile da qualunque stato e ferma il runtime; nel diagramma è mostrato solo da closed"
]
},
{
"dot": "emerald",
"title": "Fase e status",
"items": [
"Lo status descrive la sessione; la fase F1–F8 si ricalcola dal ledger delle decisioni"
]
}
]
}
@@ -0,0 +1,359 @@
{
"schema_version": 1,
"diagram_type": "class",
"meta": {
"title": "ThothII — classi del runtime di sessione (backend)",
"locale": "it",
"output": "docs/architecture/thothii-session-runtime.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.tylconsulting.it/mptyl/ThothII.git",
"link_mode": "local-only",
"revision": "31e6d3a162e9e5ac71fc2d8da4fe44b16c06aae3"
}
},
"layout": {
"mode": "grid"
},
"types": [
{
"id": "mgr",
"label": "PiProcessManager",
"kind": "class",
"sublabel": "un processo Pi per sessione",
"row": 0,
"col": 0,
"methods": [
{
"name": "createFor",
"returns": "SessionRuntime",
"visibility": "public",
"parameters": "sessionId, options"
},
{
"name": "configure",
"returns": "Promise<void>",
"visibility": "public",
"parameters": "rt, options"
},
{
"name": "start",
"returns": "void",
"visibility": "public",
"parameters": "sessionId, rt, options"
},
{
"name": "get",
"returns": "SessionRuntime?",
"visibility": "public",
"parameters": "id"
},
{
"name": "teardownIfCurrent",
"returns": "boolean",
"visibility": "public",
"parameters": "id, expected"
}
],
"sources": [
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 46,
"end_line": 46
},
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 178,
"end_line": 178,
"label": "createFor"
},
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 283,
"end_line": 290,
"label": "start"
}
]
},
{
"id": "rt",
"label": "SessionRuntime",
"kind": "interface",
"sublabel": "runtime vivo di una sessione",
"row": 0,
"col": 1,
"attributes": [
{
"name": "rpc",
"type": "RpcClient",
"visibility": "public"
},
{
"name": "bridge",
"type": "SessionBridge",
"visibility": "public"
},
{
"name": "child",
"type": "ChildProcess",
"visibility": "public"
}
],
"sources": [
{
"path": "backend/src/pi/pi-process-manager.ts",
"line": 19,
"end_line": 25
}
]
},
{
"id": "rpc",
"label": "RpcClient",
"kind": "class",
"sublabel": "JSON lines su stdin/stdout di Pi",
"row": 1,
"col": 1,
"methods": [
{
"name": "send",
"returns": "void",
"visibility": "public",
"parameters": "cmd"
},
{
"name": "request",
"returns": "Promise<any>",
"visibility": "public",
"parameters": "cmd"
},
{
"name": "on",
"returns": "void",
"visibility": "public",
"parameters": "\"event\", cb"
}
],
"sources": [
{
"path": "backend/src/rpc/rpc-client.ts",
"line": 6,
"end_line": 37
}
]
},
{
"id": "bridge",
"label": "SessionBridge",
"kind": "class",
"sublabel": "eventi Pi → eventi client",
"row": 1,
"col": 2,
"attributes": [
{
"name": "state",
"type": "TurnState",
"visibility": "private"
},
{
"name": "pendingPiId",
"type": "string?",
"visibility": "private"
}
],
"methods": [
{
"name": "onClientEvent",
"returns": "void",
"visibility": "public",
"parameters": "cb"
},
{
"name": "respond",
"returns": "boolean",
"visibility": "public",
"parameters": "uiResponse"
},
{
"name": "steer",
"returns": "void",
"visibility": "public",
"parameters": "text"
},
{
"name": "pendingWidget",
"returns": "object?",
"visibility": "public"
},
{
"name": "turnState",
"returns": "TurnState",
"visibility": "public"
}
],
"sources": [
{
"path": "backend/src/bridge/session-bridge.ts",
"line": 52,
"end_line": 71
},
{
"path": "backend/src/bridge/session-bridge.ts",
"line": 154,
"end_line": 195
}
]
},
{
"id": "hub",
"label": "SseHub",
"kind": "class",
"sublabel": "buffer e replay per sessione",
"row": 0,
"col": 2,
"methods": [
{
"name": "subscribe",
"returns": "void",
"visibility": "public",
"parameters": "sessionId, …"
},
{
"name": "publish",
"returns": "string",
"visibility": "public",
"parameters": "sessionId, event, data"
},
{
"name": "clear",
"returns": "void",
"visibility": "public",
"parameters": "sessionId"
},
{
"name": "forget",
"returns": "void",
"visibility": "public",
"parameters": "sessionId"
}
],
"sources": [
{
"path": "backend/src/sse/sse-hub.ts",
"line": 47,
"end_line": 47
},
{
"path": "backend/src/sse/sse-hub.ts",
"line": 78,
"end_line": 145
}
]
},
{
"id": "runner",
"label": "ThtRunner",
"kind": "class",
"sublabel": "esegue il CLI tht",
"row": 1,
"col": 0,
"methods": [
{
"name": "sessionNew",
"returns": "Promise",
"visibility": "public",
"parameters": "options"
},
{
"name": "sessionShow",
"returns": "Promise",
"visibility": "public",
"parameters": "id"
},
{
"name": "searchPack",
"returns": "Promise<void>",
"visibility": "public",
"parameters": "question, id"
},
{
"name": "reopenSession",
"returns": "Promise",
"visibility": "public",
"parameters": "id"
},
{
"name": "buildArgv",
"returns": "string[]",
"visibility": "public",
"parameters": "args, workspace"
}
],
"sources": [
{
"path": "backend/src/tht/tht-runner.ts",
"line": 111,
"end_line": 114
},
{
"path": "backend/src/tht/tht-runner.ts",
"line": 392,
"end_line": 394,
"label": "buildArgv"
},
{
"path": "backend/src/tht/tht-runner.ts",
"line": 484,
"end_line": 569
}
]
}
],
"relationships": [
{
"from": "mgr",
"to": "rt",
"kind": "composition",
"label": "runtimes"
},
{
"from": "rt",
"to": "rpc",
"kind": "composition"
},
{
"from": "rt",
"to": "bridge",
"kind": "composition"
},
{
"from": "bridge",
"to": "rpc",
"kind": "association",
"label": "ascolta"
},
{
"from": "mgr",
"to": "runner",
"kind": "dependency",
"label": "resume"
}
],
"cards": [
{
"dot": "cyan",
"title": "Collegamento",
"items": [
"Le route di sessione (sessionRoutes) collegano bridge e hub: ogni evento del bridge viene pubblicato con SseHub.publish",
"app.ts crea un solo ThtRunner, SseHub e PiProcessManager per processo"
]
},
{
"dot": "amber",
"title": "Selezione",
"items": [
"Sono mostrati solo i membri usati nei flussi di sessione"
]
}
]
}
File diff suppressed because one or more lines are too long
@@ -153,6 +153,30 @@ Core admission requires all of the following:
Failure leaves the workspace unavailable to the core. There is no rollback: fix the cause and run
the complete command again.
## Interrupted owner recovery
Current preprocessing runs also hold a kernel writer lock on the shared workspace
volume. Every mutating worker inherits a separate shared kernel lock and validates
an owner generation before starting. Recovery takes both locks exclusively before
rotating that generation: a surviving orphan worker blocks recovery, while a delayed
worker from the old generation cannot start. These guards establish process ownership;
PostgreSQL remains the readiness authority.
A repeated `preprocess run` can mark an orphaned current-protocol Catalog lease as
`preprocessing_interrupted` through the version/fingerprint/run-identity-checked completion
operation, then restart the entire pipeline. It does not resume internal stages or
clear Memory, sessions, curated descriptions or canonical Evidence. Older running jobs
without this ownership protocol are not automatically adopted; inspect their original
owner during upgrade instead of deleting data or resetting leases speculatively.
Each attempt records its unique run identity in PostgreSQL (migration 015). A late
completion from the previous attempt cannot finish its replacement, even when the
metadata revision and input fingerprint are unchanged.
The installer requests this guarded recovery when status remains running. An active
owner returns a conflict and the installer waits. A pending destructive Catalog Sync
Run is preserved for human review, including when its reservation temporarily blocks
binding import. Interrupted synchronization is retried through the existing domain API.
## Administration sidebar
The Administration sidebar exposes the same one-shot operation for the workspace selected in the
+41 -42
View File
@@ -1,64 +1,63 @@
# Install and first start
Use one complete procedure for a fresh installation:
Use the guided procedure for a fresh installation:
- [Italian manual installation](standalone-manual-it.md)
- [English manual installation](standalone-manual-en.md)
- [Italian guided installation](standalone-manual-it.md)
- [English guided installation](standalone-manual-en.md)
Both cover macOS, Windows through Ubuntu WSL2, and Linux. They use a Gitea clone,
protected local configuration and manual terminal commands, without an application
installer or launcher. See their verification matrix for tests still pending.
The procedure covers Windows through Ubuntu WSL2, macOS, and Linux including an Omarchy/Arch-like
host. It uses the application clone, one installation secret bundle, protected repository
credentials when needed, and a terminal command. No host Node.js, Python or Pi installation is
required.
## What must be ready
You need Docker with Compose, the host operator command `tht`, access to the workspace
repository, and the credentials and network routes for the configured DWH and model
providers. Pi runs inside the application runtime; no host Pi installation is needed.
You need Docker with Compose v2, Git, Bash, curl, OpenSSL and shasum. You also need access to the
workspace repository and the values supplied by its owner: repository URL/branch, DWH endpoint,
database/schema, transport, credentials or certificates, Evidence credentials when applicable,
and LLM provider/API-key information.
The stack includes `frontend`, `core`, `catalog-db`, `qdrant`, `embedding`, plus the
one-shot `embedding-model-init` and `catalog-migrate` services. DWH and generative-model
endpoints remain separate installation settings.
The workspace repository and the THothII application repository are different. A workspace
descriptor may declare Evidence, but database passwords and installation bindings are stored in
the installation Catalog, not in Git.
Secrets, certificates, Pi authentication and endpoint bindings are protected local files.
Do not commit them or copy the configuration of another machine unchanged.
## One guided command
## Follow the ordered procedure
After cloning THothII, checking prerequisites and installing tht, run:
The bilingual guides provide the exact commands for:
~~~
tht setup --complete --profile local --shell-mode full --shell-default-locale en
~~~
1. Cloning the selected revision and checking prerequisites.
2. Bootstrapping the native host command.
3. Preparing catalog passwords and using
`tht setup --profile local --shell-mode full --shell-default-locale en --configure-only`.
4. Completing model, authentication and workspace credentials.
5. Generating configuration, building images and explicitly running `catalog-migrate`.
6. Starting the installation and checking health and readiness.
Do not run setup alone as a substitute for that sequence. Migrations are not an
implicit effect of backend startup or `tht start`. Do not mix this installation's
descriptor/project with a different low-level Compose environment.
The first run creates protected placeholders under deploy/local/secrets/. Fill the required
credential files and rerun the same command. The command validates the local files and paths,
renders Compose, builds the images, starts catalog-db, runs catalog-migrate, starts the full
stack, and pulls/activates the workspace repository. Evidence source files declared by the
workspace are imported during activation.
For an already configured installation:
```sh
~~~
tht --installation /absolute/path/thothii-installation.yaml status
tht --installation /absolute/path/thothii-installation.yaml doctor --json
```
tht --installation /absolute/path/thothii-installation.yaml workspace test --json
~~~
`/health` checks application-process readiness. Doctor also checks configuration,
workspace, workflow and Pi prerequisites; a healthy web page alone does not prove
that a real database question can complete.
doctor --json is the non-destructive general core test. workspace test also probes the configured
database, Evidence, Qdrant and embedding service for every active workspace. It requires the
workspace database to have been configured in Database Management first.
## After startup
## Installer-only completion
Prepare [workspaces](../operations/workspaces.md), configure a database in
[Database Management](../operations/database-management.md), and complete the functional
checks in the installation guide before using real data.
The installer must still decide which LLMs and API keys are approved, configure and test each
workspace database, synchronize its schema, generate and consolidate descriptions, create Qdrant
entries, review naming-based FK suggestions alongside schema FKs, and load the approved
relationships. The final declaration of completeness requires green doctor and workspace test
results plus one real natural-language question completed through final SQL.
See [display mode and language](shell-and-language.md), [local authentication](authentication-local.md),
[OIDC](authentication-oidc.md) and [model configuration](../general/pi-configuration.md)
for later changes. Embedded portal integration is separate from a fresh standalone setup.
Migrations are part of setup --complete. Do not mix this installation’s descriptor or volumes with
a different Compose environment. Preserve the descriptor, credentials, Catalog and persistent
volumes; do not use docker compose down --volumes as a routine stop.
Use the installation's normal `tht start`, `tht stop` and diagnostic commands.
Preserve its descriptor, credentials, database and persistent volumes; do not use
`down --volumes` as a routine stop or upgrade.
See the guides for the Windows/macOS/Linux prerequisite matrix, workspace repository explanation,
secret layout and Gate A/Gate B acceptance checks.
+145
View File
@@ -0,0 +1,145 @@
# Installation preflight and release manifest
The native operator protocol is version 1. `installation preflight` is the independent
step-3 host check. `installation plan` repeats document validation, performs step-5
live checks and writes an owner-only JSON plan plus a separate owner-only `.key` file.
Neither command creates containers, imports bindings, modifies a database or invokes
model generation. Exit codes are 0 (checks passed), 1 (blocking error), and 2 (usage).
JSON stdout contains only the report. Checks carry stable `id`, `outcome`, `field`
and `action`; outcomes are `passed`, `error`, `warning`, `deferred-to-runtime`.
## Release manifest schema 1
The manifest is a local JSON file shipped with the verified operator/release bundle.
Required keys:
| Key | Contract |
| --- | --- |
| `schema_version` | `1` |
| `version` | Semantic release version, optionally prerelease |
| `revision` | 40 lowercase hexadecimal Git commit characters |
| `validator_protocol` | `1`; incompatible consumers refuse the manifest |
| `requirements` | `cpus`, `memory_bytes`, `disk_bytes`; at least 2 CPUs, 4 GiB Docker memory and 10 GiB installation filesystem space |
| `components` | Includes `pi`, `catalog-migrations`, `workspace-maintenance` |
| `images` | Exactly `core`, `frontend`, `catalog`, `qdrant`, `embedding`; each maps `linux/amd64` and/or `linux/arm64` to a `docker.io/...@sha256:...` **single-platform image digest** |
| `files` | Relative packaged resource paths to SHA-256; no traversal, links or absolute paths; maximum 256 files, 32 MiB per resource |
| `compose` | Ordered relative Compose file paths present in `files` for this release configuration |
Include the selected `deploy/compose.git-https.yaml` or `deploy/compose.git-ssh.yaml`
transport overlay in `files`. Standard transport overlays are resolved from the
release while absent in the installation directory; existing authored overrides
remain input files. Compose must resolve all eight services: core, frontend,
catalog-db, catalog-migrate, workspace-maintenance, qdrant, embedding and
embedding-model-init. The two maintenance services share the core digest; embedding
initialization shares the embedding digest. Source builds and undeclared services
are rejected in this prebuilt path. The explicit source path is a separate ticket.
`docker manifest inspect --verbose` checks each selected immutable image and its
platform without pulling layers. `docker compose config --format json` checks the
effective service configuration. Compose receives only Docker connection/trust,
proxy and executable-discovery host variables; application parameters come from
the prepared environment file. Raw Docker output is never copied into reports.
Each preflight Docker command has a 15-second bound. Public image publication is
verified separately; controlled manifest tests alone do not certify host acceptance.
## External checks and bounds
- Git HTTPS: authenticated `GET /info/refs?service=git-upload-pack`, configured CA,
no redirects, selected branch advertised, 1 MiB response and 5-second bound.
Git SSH uses its prepared key/known-hosts and `git-upload-pack --advertise-refs`
with the same response/time bounds; no checkout or push occurs.
- PostgreSQL: the existing Catalog diagnostic adapter authenticates and reads
`current_database()` plus schema `USAGE`; no user tables are modified.
- REST database transport: existing Catalog diagnostic `GET` with the configured
bearer/API-key header and status validation. SSH database bindings cannot pass
this NL-to-SQL installation plan because runtime sessions do not support them.
- Evidence: local paths were already validated. HTTP performs bounded GET requests
and cancels response bodies; signed URL identities must match authored provenance.
S3 performs one `ListObjectsV2` request with `MaxKeys: 1`, no retries, explicit
file credentials and the canonical Evidence egress policy. These metadata requests
can incur normal remote-service request charges; they do not run LLM generation.
Each external request has a 5-second bound; the native database/Evidence helper
has a 60-second aggregate bound. Correct unavailable services before repeating.
- Explicit model endpoints: DNS/TCP/TLS origin reachability, without generating
tokens. Built-in endpoint resolution, provider authentication and model smoke
operations use the bundled Pi SDK at runtime; the report never claims those
operations have already passed.
No unreachable configured external dependency is converted to a deferred success.
Runtime obligations have explicit identities: `container-network`,
`catalog-initialization`, `pi-operation`, `local-embedding`,
`workspace-preprocessing`, `workspace-readiness`. These must be discharged by the
execution/readiness tickets before final success. Host disk inspection cannot prove
Docker Desktop VM free storage; its separate storage warning remains explicit.
## Input identity and freshness
The plan records normalized installation configuration, release digests, validator
build identity, verified input paths, local workspace content and its Git HEAD when
available (otherwise a content snapshot). Files are bounded to 32 MiB each and
256 MiB total; workspace/auth trees to 10,000 entries, without links or special files.
Credential contents are never serialized. An HMAC covers the private inputs and
plan using a separate random 32-byte owner-only key; no public unkeyed secret hash
is generated. Credential rotation invalidates the plan. Added/deleted/changed
workspace files invalidate it as well. Changes during the checks abort publication.
Plan output never overwrites an existing plan or key.
Execution and resumption call `ReadExecutionPlan` **and repeat live checks and
credential reads before mutations**. A valid seal alone does not certify current
network availability, Docker state or runtime readiness. Keep both plan files
private and outside the workspace repository; they are installation-local artifacts.
## Non-interactive platform execution
`tht --installation ABS_DESCRIPTOR installation apply --plan ABS_PLAN [--json]`
requires an operator whose version and revision match the manifest. Plans must
include the manifest and bootstrap paths; regenerate older plans. The only permitted
absent-input transition is materialization of a standard release transport overlay
with exactly its packaged digest. All other input changes invalidate execution.
The local profile uses the preparing non-root Unix operator's UID/GID for core,
maintenance, migrations and PostgreSQL. Original private authentication directory
and credential mounts remain authoritative. A pinned, offline one-shot helper seeds
only installation-owned volumes, retaining a root-owned initialization marker for
interruption recovery. Existing ready volumes are never recursively chowned.
Account collisions and foreign volumes stop execution. This requires local Docker;
Windows runs inside WSL2 rather than the native Windows shell.
The lifecycle lock excludes concurrent operations. Asset publication and journal
updates are atomic. Every retry repeats reconciliation, even after a completed
journal stage. Pull and service startup have 30-minute bounds; Catalog startup and
migration have 5-minute bounds; final health inspection has a 1-minute bound.
Cancellation cleans up named one-shot containers and releases the lock. Hard-killed
processes require explicit stale-owner inspection; automatic destructive repair is
not performed. Errors contain a stage/action without raw Docker output or secrets.
Binding import uses a named, bounded one-shot client on the Compose network. Protected
bootstrap material travels through stdin, never arguments or journals. The client logs
in through local authentication, obtains CSRF protection, calls permission-checked
administration services, and logs out. Prepare `authentication.username` and
`authentication.passwordFile` in `database-bootstrap.yaml`; offline validation checks
the account/password against the private local registry and seals that file too.
The registry consumes the exact prepared Git file inventory and optional commit, without
retargeting or refreshing an existing checkout. Binding creation and its durable import
receipt commit together in the Catalog. The receipt survives administrative deletion.
Reruns compare live configuration and encrypted-store contents, retain equivalent values,
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: true`.
The bounded `binding_import` report distinguishes authentication, workspace reconciliation,
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.
+115
View File
@@ -0,0 +1,115 @@
# Pubblicare immagini e pacchetto operatore / Publish images and operator bundle
## Italiano
Per l'avvio automatico usare la
[preview.5](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5):
include `installation apply`, immagini e bundle Linux amd64/arm64. L'avvio della
piattaforma è stato verificato dal pacchetto pubblico; import dei binding, readiness
dei workspace e collaudi sui sistemi operativi restano passi successivi.
Questo comando è riservato al manutentore. L'utente finale scarica il pacchetto e
le immagini già compilati. La prima prerelease riguarda **Linux amd64**, utilizzato
da Ubuntu WSL2 su Windows e successivamente da Omarchy; non certifica ancora il
percorso completo di installazione o i collaudi manuali.
Prerequisiti del manutentore: Git, Node 24/npm, Go indicato in `tools/tht/go.mod`,
Docker con Buildx e capacità di eseguire Linux amd64, `tar`. Bun viene installato
dal lock npm e serve soltanto per compilare il pacchetto. Il commit da pubblicare
deve essere già disponibile sul repository Gitea pubblico.
Eseguire il produttore su Linux, WSL2 o macOS; la shell Windows nativa non è supportata.
La prima [prerelease Linux amd64](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1)
è disponibile: `0.1.0-install-preview.1`, con immagini pubbliche
[core](https://hub.docker.com/r/tylconsulting/thothii-core) e
[frontend](https://hub.docker.com/r/tylconsulting/thothii-frontend).
1. Eseguire `docker login` sul computer di pubblicazione con un account autorizzato
a creare repository pubblici e pubblicare immagini nel namespace scelto.
Usare un credential store Docker: il token non va passato sulla riga di comando,
scritto nel repository o copiato nel pacchetto.
2. Predisporre nel credential helper Git l'accesso al repository Gitea con diritto
di creare rilasci e allegati. Il comando riusa quelle credenziali senza stamparle.
3. Installare le dipendenze del produttore con `cd backend && npm ci`, poi eseguire:
```bash
node scripts/publish-installation.mjs \
--revision COMMIT_GIA_PUBBLICATO \
--version 0.1.0-install-preview.1 \
--namespace tylconsulting \
--platforms linux/amd64 \
--output /percorso/privato/rilascio-0.1.0-install-preview.1
```
La directory di output deve essere nuova o vuota e avere un genitore esistente.
Diventa privata e contiene stato di ripresa, log del produttore, archivi e checksum.
Non è una directory di installazione. Il produttore usa un worktree temporaneo al
commit richiesto, così modifiche locali, segreti e workspace non entrano nelle build.
Il comando prepara `tylconsulting/thothii-core` e `tylconsulting/thothii-frontend`
come repository pubblici, costruisce e pubblica le immagini versionate, risolve i
digest di tutte le immagini e crea gli archivi del comando nativo con Compose e
risorse di inizializzazione. Catalog migration e workspace maintenance usano lo
stesso digest core. PostgreSQL, Qdrant e Ollama restano immagini upstream.
Prima di rendere pubblico il rilascio Gitea, vengono verificati pull anonimi delle
immagini, smoke test senza rete di core/frontend, checksum e download degli allegati.
Una build o un upload incompleto lascia il rilascio **in bozza**. Per riprovare,
rieseguire lo stesso comando con gli stessi parametri e la stessa directory.
Immagini già presenti devono appartenere allo stesso commit/versione; allegati
esistenti devono avere lo stesso checksum. Il produttore non sostituisce versioni
pubblicate con contenuti diversi. Conservare la directory fino al completamento.
Il risultato pubblico comprende `thothii-VERSION-linux-amd64.tar.gz` e
`SHA256SUMS.txt`. L'archivio contiene `bin/tht`, il validatore affiancato,
`release-manifest.json`, Compose, SQL/script di inizializzazione e guide. Non
contiene credenziali, dati dei workspace o database di esempio. La verifica su
questa macchina di pubblicazione non sostituisce il successivo collaudo Windows.
## English
Use [preview.5](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.5)
for automatic platform startup: it includes `installation apply`, Linux amd64/arm64
images and native bundles. Platform startup was verified from the public archive;
binding import, workspace readiness and operating-system acceptance remain later steps.
This is a maintainer command. Consumers download precompiled images and the native
operator bundle. The first prerelease targets **Linux amd64** for Ubuntu WSL2 and
later Omarchy; full installation and real-host acceptance remain separate work.
The maintainer needs Git, Node 24/npm, the Go toolchain from `tools/tht/go.mod`,
Docker Buildx with Linux amd64 execution support, and `tar`. The npm lock supplies
Bun for producer builds only. Push the selected source commit to the public Gitea
repository before publication. Use Docker's credential store for `docker login`
and Git's credential helper for Gitea release/attachment permissions. Never pass
tokens as command arguments or include them in a checkout or archive.
Run the producer on Linux, WSL2 or macOS, not a native Windows shell.
The first [Linux amd64 prerelease](https://git.tylconsulting.it/mptyl/ThothII/releases/tag/installation-v0.1.0-install-preview.1)
is available as `0.1.0-install-preview.1`, with public Docker Hub core/frontend images.
From `backend`, run `npm ci`, then the command above with an explicit revision,
version, namespace, platforms and a new private output directory. A temporary Git
worktree isolates the selected commit. The producer publishes core/frontend to
Docker Hub and retains PostgreSQL, Qdrant and Ollama upstream. All runtime and
maintenance services use resolved immutable platform digests.
The Gitea release stays a draft until images, anonymous pulls, network-isolated
smoke checks and uploaded bundle checksums pass. An interrupted run can be retried
with the same arguments and output directory. Existing images must match the
source/version, and existing attachments must match their checksum; published
versions are not overwritten. Producer logs and retry state stay local.
Download the matching `.tar.gz` and `SHA256SUMS.txt` from the public Gitea prerelease,
verify the archive checksum, then extract it. Keep the two executables together.
The bundle needs no application checkout, Node, Bun, Python or compiler on the
consumer host. It carries the manifest, Compose and initialization assets, but no
installation credentials, workspace data or example databases. Linux arm64 can be
selected explicitly for later release work; it does not imply macOS acceptance.
Developer regression checks:
```bash
cd backend
node --test scripts/release-*.test.mjs
```
+491 -254
View File
@@ -1,324 +1,561 @@
# Manual standalone installation
# Guided standalone installation
[Versione italiana](standalone-manual-it.md)
This is the verification procedure for preparing THothII as a standalone application in `full`
mode on macOS, Windows, and Linux.
This is the fresh-machine installation procedure for THothII. THothII receives a natural-language
question, queries an enterprise database read-only, and guides the user through SQL review. The
core, PostgreSQL catalog, Qdrant, embedding service, and Pi run in Docker; Node.js, Python, and Pi
are not required on the host.
In this document, “standalone” means that the user does not need to install Node.js, Python or Pi
on the host: the application services and local semantic
services run through Docker. DWH and LLM providers remain external endpoints configured by the
installation; this is not an offline package.
## Prepare and validate workspace documents before starting the stack
This path uses no graphical installer, native launcher, or Docker Hub image. It starts from a Gitea
clone and uses explicit terminal commands. Publishing pre-built images is a later step.
The first two steps of the new flow work without Docker, Node, Python, Pi or an
installation descriptor. Use the platform bundle with **both** `tht` and
`tht-workspace-documents` in the same directory (`.exe` on Windows). Put that directory
on `PATH`, or invoke the absolute executable path. Older packages containing only
`tht` do not provide this capability. Download bundles from the
[public releases](https://git.tylconsulting.it/mptyl/ThothII/releases); core and frontend
images are published on Docker Hub. `installation apply` requires a bundle containing
that command: the first preview provided preparation and preflight only. On Windows,
use the Linux bundle inside Ubuntu WSL2.
## Verification matrix
| System | Recommended terminal | Runtime | Test architecture |
| --- | --- | --- | --- |
| macOS supported by the installed Docker Desktop version | Bash in Terminal | Docker Desktop | Apple Silicon (`arm64`) |
| Windows 11 | Ubuntu inside WSL2 | Docker Desktop with WSL2 integration | x64 (`amd64`) |
| Ubuntu Linux 22.04 or 24.04 | Bash | Docker Engine + Compose v2 | x64 (`amd64`) |
Intel macOS is excluded from the first verification campaign. ARM Linux may be tested when the
machine’s Docker runtime reports `arm64`, but it is not part of the minimum matrix.
Documentation and Mac prerequisite checks have passed. Complete fresh installations on all three
systems remain pending; this matrix describes the tests to perform, not completed certification.
## Before you start
You need:
- access to the THothII Gitea repository and the workspace Git repository;
- Git;
- Docker Desktop on macOS and Windows, or Docker Engine with the Compose v2 plugin on Linux;
- Bash, `curl`, OpenSSL and `shasum` (Ubuntu package: `libdigest-sha-perl`);
- enough disk space to build the images and download the embedding model;
- the DWH and LLM endpoints, plus the credentials required by the installation.
On Linux, the current user must be able to run Docker. If the system requires `sudo`, add the user
to the Docker group according to local policy and open a new session before continuing.
On Windows, run every command in this guide from Ubuntu under WSL2. In Docker Desktop, enable WSL2
integration for that distribution. Clone the project inside the WSL2 Linux filesystem, for example
under `~/src`, rather than under `/mnt/c`: this avoids slow builds and path/line-ending issues. Pi
does not need to be installed on the host.
Check the runtime before or immediately after cloning:
1. Choose a new directory outside the application checkout, with an existing parent:
```sh
docker version
docker compose version
docker version --format '{{.Server.Arch}}'
tht workspace prepare --directory ./my-workspaces --id practice --name "Practice" --language en
```
The last command must return `amd64`, `x86_64`, `arm64`, or `aarch64`.
## 1. Clone a project revision
Use the project repository on Gitea:
This creates `thoth-workspaces.yaml`, `practice/workspace.yaml` and
`workspace-docs/practice/README.md`. Existing destinations, even empty ones, are
refused. No services start, Git is not initialized and no remote is contacted.
Example databases remain a deferred subproject. For a curator-supplied repository,
use a separate local copy and go straight to step 3; read access to the origin is
sufficient.
2. Edit the catalog (schema v1) and workspace descriptor (schema v4) at your own pace.
Keep `id`, `name` and optional `description` identical in both; the id must match
the directory name. Root directories must match catalog entries, except
`workspace-docs` and the local `.git` directory. Database connections, schema and
credentials belong to the installation Metadata Catalog. Evidence is optional
and initially absent.
3. Validate, correct the reported document/field, and repeat:
```sh
tht workspace validate --directory ./my-workspaces
tht workspace validate --directory ./my-workspaces --json
```
PowerShell uses the same arguments, for example
`C:\ThothII\bin\tht.exe workspace validate --directory C:\ThothII\my-workspaces`.
Validation changes no files. It rejects multiple/malformed YAML documents,
duplicate keys/ids, unknown fields, catalog/directory/descriptor mismatches,
missing local references and symbolic links. Fix the first error in each document
and repeat to reveal any subsequent errors.
Evidence `absent` is valid. Filesystem checks cover directories, accessibility and
literal references; standard Markdown selections also check declared size limits.
Evidence v2 requires `curated/` and syntactically valid YAML frontmatter. Local limits
are 1 MiB per document read and 100,000 entries per Evidence tree. Arbitrary patterns,
the complete curated-unit contract, provenance, HTTP/S3 access and indexing remain
explicit runtime checks. See the [Evidence guide](../evidence.md).
JSON includes `schema_version`, `scope: local-documents`, `ok`, `workspaces`, `issues`
and `deferred_checks`. Issues identify document, field, code, correction and YAML
line where available, without printing document values. Exit statuses: `0` local
success, `1` documents/access/bundle need correction, `2` invalid arguments. Local
success does not certify semantic truth, connectivity or readiness. The Git revision
activated later must contain the checked documents; this command does not publish
uncommitted files or empty directories.
## Prepare and validate application documents
After validating workspaces, create a local directory **outside their repository**:
```sh
tht installation prepare --directory ./my-installation
```
This creates private, commented `thothii-installation.yaml`, `operator.env`,
`database-bootstrap.yaml` and `README.md`. The destination must be new and its parent
must exist. It starts no services and does not implicitly generate passwords.
1. Choose models and providers in the descriptor. The template proposes
`openai/gpt-4.1-mini` for interaction and `ollama/qwen3-embedding:0.6b` with 1024
dimensions for embedding. Edit these before setup. `modelCatalog.defaults.interaction`
must support sessions and metadata generation when the latter is configured.
The template omits optional metadata generation. See
[model configuration](../general/pi-configuration.md) for custom providers.
2. Replace the Git remote in both the descriptor and `operator.env`; keep branch and
transport consistent. Paths are absolute and machine-local. `operator.env` accepts
one literal `KEY=value` assignment per line, without duplicate keys or shell
interpolation. Credentials belong in referenced protected files.
3. Complete `database-bootstrap.yaml` with exactly one entry per workspace. A complete
direct-connection example is:
```yaml
schemaVersion: 1
authentication:
username: admin
passwordFile: /private/path/my-installation/secrets/admin-password
databases:
- workspaceId: practice
engine: postgres
databaseName: sales
schema: public
binding:
transport: postgres_direct
host: db.intranet
port: 5432
username: thoth_reader
secretFiles:
password: /private/path/my-installation/secrets/database-password
```
Use a read-only DWH account. `rest_api` requires `baseUrl`, `restPath`, `restAuth`
(`none`, `bearer`, `x-api-key`) and `secretFiles.apiKey` when authenticated.
`ssh_tunnel` requires `username`, `sshHost`, `sshPort`, `sshUsername`,
`sshTargetHost`, `sshTargetPort` and files `password`, `sshPrivateKey`,
`sshKnownHosts`; it supports Catalog diagnostics, not NL-to-SQL sessions.
`tlsCa` and `sshPrivateKeyPassphrase` are optional. Signed HTTP Evidence needs
`evidenceSecretFiles` with key `evidence.signed_urls`; static S3 credentials need
`evidence.access_key`, `evidence.secret_key` and optional `evidence.session_token`.
All values are private file paths. Workspace descriptors remain schema v4;
this bootstrap input is not a second runtime Catalog. The document also includes
`authentication.username: admin` and `authentication.passwordFile` pointing to
private `secrets/admin-password`. Update these references before validation if
selecting another administrator. Execution uses ordinary login and administrative
permissions, without asking for a password during setup.
4. Explicitly generate technical credentials in the standard layout:
```sh
tht installation credentials --directory ./my-installation
```
This creates separate random Catalog runtime/migrator and administrator passwords,
`auth/auth.yaml`, `auth/users.yaml`, a `secrets/secrets.env` template and
`secrets/pi-auth.json`. Existing files are retained; invalid ones stop the command.
The initial administrator is `admin`; its password stays in private
`secrets/admin-password` and is never printed. The default is local authentication
at `http://127.0.0.1:8080`: review and edit `auth/auth.yaml` before validation.
This increment does not validate offline OIDC bootstrap for the existing path.
5. Fill the provider key in `secrets/secrets.env` and create the DWH password file.
For Git HTTPS supply the referenced credentials and CA files; empty credentials
are allowed for a public remote, and the CA file must be available. For SSH supply
a key and known_hosts and select the matching descriptor override. `pi_auth`
providers require prepared Pi credentials. Keep every secret outside workspace
Git with installer-only access (0600 on Unix, equivalent Windows ACLs).
6. Validate and repeat after each correction:
```sh
tht --installation /absolute/path/my-installation/thothii-installation.yaml installation validate --workspaces /absolute/path/my-workspaces --json
```
The default bootstrap is beside the descriptor; `--bootstrap PATH` selects another.
Validation changes no documents, generates no projections, uses no network and
writes no database. It rejects placeholders, inconsistencies, missing/non-private
files and secrets inside workspace Git. Reports identify document, field and
correction without secret values. Exit statuses: 0 local success, 1 corrections
needed, 2 invalid arguments.
Standard release Compose assets may still be absent at this stage; custom overrides
must already exist. Release assets, external connectivity, Catalog import and runtime
readiness remain explicit deferred checks. Success prepares the next preflight;
it neither skips those checks nor establishes a completed installation.
## Check prerequisites and produce the plan
At step 3, before completing all application parameters, check the machine and
the private installation directory already prepared:
```bash
tht installation preflight --directory /path/installation --json
```
This requires a reachable Linux Docker daemon, Compose 2.24 or newer, at least
2 CPUs, 4 GiB allocated to Docker and 10 GiB free on the installation filesystem.
A release may require more resources. On Windows run the Linux executable in
Ubuntu WSL2 with Docker Desktop integration; Pi is bundled in the core image.
At step 5, after `installation validate`, select the published release manifest
with its downloaded bundle resources and produce a new plan:
```bash
tht --installation /path/installation/thothii-installation.yaml installation plan \
--workspaces /path/workspaces \
--release /path/release/release-manifest.json \
--output /path/installation/installation-plan.json --json
```
This repeats document checks, verifies image digests and Compose, Git, available
external databases and Evidence, then saves the plan and its separate private
`.key` file. It does not execute setup. Missing images and unavailable existing
dependencies block the plan. The manifest and executables must belong to the same
release; an invented manifest cannot bypass these checks.
Correct `error` outcomes and read `warning` outcomes. `deferred-to-runtime` entries
are mandatory checks after startup, not readiness already achieved. After changing
documents or rotating credentials, produce a new plan; existing files are never
overwritten. Keep both plan files outside workspace Git. External probes perform
bounded database authentication/schema reads, Git/HTTP/S3 reads and explicit model
endpoint reachability checks. They invoke no LLM generation; HTTP/S3 requests may
incur ordinary service request charges. See the
[preflight reference](installation-preflight.md) for limits, the manifest
format and runtime obligations.
## Start the platform from verified documents
Use the same non-root operator that prepared the documents, with access to local
Docker. The command asks no questions and accepts closed stdin:
```sh
tht --installation /path/installation/thothii-installation.yaml installation apply \
--plan /path/installation/installation-plan.json --json
```
It repeats live checks and plan verification, copies verified assets, pulls images,
initializes new installation volumes, starts PostgreSQL, applies Catalog and Memory
migrations, and starts services. It never builds sources. The initial administrator
comes from the prepared authentication documents. Secrets retain private permissions;
services that read them run with the operator's UID. This path does not convert an
existing stack with incompatible volume ownership.
Execution then imports bindings through authenticated Catalog services and the existing
secret store. It verifies the remote, branch, revision and exact contents against the
prepared plan, without silently retargeting an existing checkout. Database connectivity
is tested again by the application in the containers.
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
with Administration and preserve the intended change. Do not remove volumes or Catalog
receipts to bypass this check. `workspace_reconciliation_required` identifies a source
mismatch; `authentication_required` requires correcting the prepared administrator;
`container_connection_failed` means the DWH cannot be reached or authenticated from the
application network. Scalar credential files ignore outer whitespace, matching preflight
probes; PEM and known-host files retain their exact bytes.
With the default configuration, open `http://127.0.0.1:8080` to sign in. The browser
origin must match `publicUrl`; do not substitute `localhost` for `127.0.0.1`.
For HTTPS Git, supply the server's specific CA in PEM format, within the 64 KiB
protected-file limit. A complete operating-system CA bundle may exceed that limit.
After a failure, correct the cause and repeat `apply`. The private journal under
`.tht/<installation>/installation-apply.json` records stages; actual service state is
checked again. Retries preserve data, never reset volumes and never fall back to
building sources. Changed documents or credentials require a new plan. Ctrl+C releases
the lock; after a forcibly killed process, confirm that its owner is no longer running
before explicitly removing a stale lock. A different release requires the upgrade
path rather than this command.
If apply is interrupted during synchronization or preprocessing, repeat the same command.
Persisted Catalog runs are read again and pending human decisions remain pending. Active
preprocessing is awaited. If its owner has exited, recovery also checks that no orphan
worker is still running before restarting the complete pipeline. It never clears sessions,
curated Evidence, descriptions or Memory. Do not use `workspace preprocess clear` or volume
deletion as a recovery remedy. Older jobs without the ownership protocol require inspection
during an upgrade.
A changed credential or endpoint invalidates the old plan. Correct the documents, repeat
`validate`, then `plan` with a new filename. If a binding was already imported, apply the
intended correction in Administration too: bootstrap inputs must agree with the Catalog
and never overwrite administrative changes. Other stages reconcile actual Docker/Catalog
state without recreating existing data.
## 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
commands over an installation created with `installation apply`.
There are two separate repositories:
1. the application repository cloned by the user:
https://git.tylconsulting.it/mptyl/ThothII.git;
2. the workspace repository supplied by the curator/installer. It is not the THothII repository
and must not be cloned inside the application directory.
The workspace repository normally contains:
~~~
thoth-workspaces.yaml
<workspace-id>/workspace.yaml
<workspace-id>/evidence/** # when Evidence is declared
~~~
workspace.yaml contains workspace identity, language and optional Evidence source. By design it does
not contain database passwords. Database identity, transport (PostgreSQL, REST, or tunnel), user,
password, token and certificates are installation-local settings stored encrypted by the Catalog.
This prevents credentials from being committed to the workspace repository.
## 0. Machine prerequisites
### Windows
- Windows 10/11 with Docker Desktop running and the WSL2 backend enabled.
- Ubuntu in WSL2, with Docker Desktop integration enabled for that distribution.
- Git, Bash, curl, OpenSSL and shasum inside WSL2.
- Do not install Node.js, Python or Pi on the host for this procedure.
If WSL2 is not installed, use the company procedure or, in PowerShell:
~~~
wsl --install -d Ubuntu
~~~
Run all commands inside Ubuntu WSL2, in a Linux directory such as $HOME/src, not under /mnt/c.
scripts/install-tht.ps1 exists for advanced native PowerShell scenarios; use WSL2 for the
reproducible test.
### macOS
- Docker Desktop installed and running, with several GB free for images and the embedding model.
- Git, Bash, curl, OpenSSL and shasum.
- Intel and Apple Silicon Macs are supported when Docker Desktop supports the architecture
reported by the Docker server.
- Do not install Node.js, Python or Pi on the host for this procedure.
### Linux, including Omarchy
- Git, Bash, curl, OpenSSL and shasum.
- Docker Engine and the Docker Compose v2 plugin. On Omarchy, check first:
~~~
command -v docker
docker compose version
docker info
~~~
If Docker is missing, install Docker and Compose using the distribution-approved package procedure,
then start the service. On an Arch-like distribution the typical route is:
~~~
sudo pacman -S docker docker-compose
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"
~~~
After adding the group, open a new session and repeat docker info. Node.js, Python and Pi are not
needed on the host: they are in the Docker images.
On every system run:
~~~
bash scripts/check-standalone-prerequisites.sh
docker version --format '{{.Server.Arch}}'
~~~
The architecture must be amd64, x86_64, arm64, or aarch64. You also need access to the
application Gitea repository, the workspace repository URL/branch and credentials, container
reachability to DWH/LLM endpoints, and the credentials, tokens or certificates associated with
the databases.
## 1. What to clone
Clone only the application:
~~~
mkdir -p "$HOME/src"
cd "$HOME/src"
git clone https://git.tylconsulting.it/mptyl/ThothII.git
cd ThothII
git rev-parse --short HEAD
```
~~~
For an SSH clone, when the key is already authorized on Gitea:
Record the revision. tht setup --complete downloads the workspace repository into a persistent
Docker volume using the URL, branch and transport supplied during setup.
```sh
git clone git@git.tylconsulting.it:mptyl/ThothII.git
```
Record the hash printed by `git rev-parse` for a repeatable test. In a later campaign, use the
maintainer-approved revision/tag rather than implicitly following a mutable `main` branch.
## 2. Check prerequisites and install the operator command
## 2. Install the terminal command
From the clone root:
```sh
~~~
bash scripts/check-standalone-prerequisites.sh
export PATH="$HOME/.local/bin:$PATH"
mkdir -p "$HOME/.local/bin"
THT_INSTALL_DIRECTORY="$HOME/.local/bin" bash scripts/install-tht.sh
export PATH="$HOME/.local/bin:$PATH"
tht version
```
~~~
`install-tht.sh` bootstraps only the native `tht` operator command; it does not install a desktop
version of THothII. It uses the repository’s Docker builder, installs the binary for the current
terminal environment, and installs it in the user directory. Persist `$HOME/.local/bin` in your
shell PATH for new terminals too. An existing `tht` in this directory will be updated.
tht is the only native component to install. It builds the binary with Docker and orchestrates
Compose; it is not a second application runtime.
On Windows, run these commands inside WSL2. The installed `tht` binary is the Linux binary inside
WSL2; the application runtime remains Docker Desktop. Do not use `scripts/install-tht.ps1` as the
primary path for this test.
## 3. Prepare a few secrets and run complete setup
## 3. Configure and start the local installation
The first execution creates protected placeholders under deploy/local/secrets/ and stops if a
required credential is missing. Fill in the requested files and rerun the same command; compatible
configuration files are reused.
Run the remaining blocks in one Bash session from the physical clone root (`pwd -P`).
First create two distinct catalog passwords, preserving any existing files:
~~~
tht setup --complete --profile local --shell-mode full --shell-default-locale en
~~~
```bash
umask 077
mkdir -p deploy/local/secrets
for name in catalog-runtime-password catalog-migrator-password; do
target="deploy/local/secrets/$name"
if [ ! -e "$target" ]; then
(set -C; openssl rand -hex 32 > "$target") || exit 1
fi
done
export THT_CATALOG_RUNTIME_PASSWORD_SOURCE="$(pwd -P)/deploy/local/secrets/catalog-runtime-password"
export THT_CATALOG_MIGRATOR_PASSWORD_SOURCE="$(pwd -P)/deploy/local/secrets/catalog-migrator-password"
```
The setup asks only for information the computer cannot know:
Do not regenerate passwords for an initialized catalog. Configure without starting services:
```sh
tht setup --profile local --shell-mode full --shell-default-locale en --configure-only
```
Answer the prompts as follows:
| Prompt | Value or rule |
| Request | What to provide |
| --- | --- |
| Installation ID | `local`, unless one clone hosts multiple installations |
| Deployment profile | `local` |
| DWH API endpoint | An `http(s)` URL without user, password, query, or fragment; may be empty for a smoke-only test |
| LLM API endpoint | An `http(s)` URL without credentials; may be empty for a smoke-only test |
| Workspace repository URL | The workspace repository URL, not the THothII source clone |
| Workspace branch | Normally `main` |
| Workspace access | `ssh` with a deploy key, or `https` with a protected credential file |
| File paths | Accept the default paths under `deploy/local/secrets/` for the first test |
| Secret templates | Answer `yes` when protected files do not exist yet |
| Authentication | Configure the local login required by the installation; never put passwords on a command line |
| Workspace repository | Data/configuration repository URL, not ThothII.git |
| Branch | normally main |
| Access | ssh with key and known_hosts, or https with credential file and CA |
| DWH/LLM URL | endpoint without a token in the URL |
| Local login | initial user and password requested by the prompt |
The generated configuration is local and ignored by Git:
The setup generates random Catalog passwords and writes their paths, never their values, to
operator.env. It runs docker compose config, builds images, starts the Catalog, runs
catalog-migrate, starts the stack, and pulls the workspace repository. The pull also activates
declared Evidence; at minimum source files present in the workspace are materialized locally.
```text
deploy/local/thothii-installation.yaml
deploy/local/operator.env
deploy/local/auth/
deploy/local/secrets/
```
### The file the user fills in
Edit secrets only in protected local files; never commit them. `deploy/env/local.env.example` is a tracked reference; the
generated path `deploy/local/operator.env` is the active path for this installation.
The main file is:
### Complete protected files
~~~
deploy/local/secrets/thothii.secrets
~~~
If setup created blank templates, enter the values with a local editor:
Add only NAME=VALUE lines needed by modelCatalog and installation adapters, such as an LLM API key
(DEEPSEEK_API_KEY, OPENAI_API_KEY, or the key declared by the catalog) and, when applicable,
THT_DWH_API_KEY. Allowed names are documented in deploy/secrets/README.md. Never put tokens in
URLs, the repository, or copied shell commands.
```sh
chmod 600 deploy/local/secrets/*
"${EDITOR:-vi}" deploy/local/secrets/thothii.secrets
```
Two distinctions prevent common errors:
The bundle must contain only `KEY=VALUE` lines for credentials actually used by `modelCatalog`. The
allowed names and credential boundary are documented in the local file
`deploy/secrets/README.md`. Do not put tokens in URLs, the YAML
descriptor, the Git repository, or commands copied into the shell.
- when the catalog uses pi_auth, the LLM token belongs in the Pi pi-auth.json file created by
setup; {} is only a placeholder and does not enable a model;
- workspace database credentials (PostgreSQL password, REST API token, tunnel SSH key,
known_hosts, CA) do not belong in the workspace repository. Enter them per workspace in
Database Management, which stores them encrypted in the Catalog. The workspace declares
database/schema and transport; the installer must obtain the actual values from the database owner.
For SSH workspace access, also provide the private key and `known_hosts` file requested by setup.
For HTTPS access, provide the Git credential file and any required CA. Both must remain protected
and outside version control.
A private workspace repository also needs the Git files required by its transport: an SSH key and
known_hosts, or an HTTPS credential file and CA. These are transport files, not a second bundle to
commit. To minimize manual files, use SSH with an already-authorized deploy key.
Before starting, complete these additional configuration steps:
## 4. Automatic checks and terminal tests
1. Add `THT_CATALOG_RUNTIME_PASSWORD_SOURCE` and `THT_CATALOG_MIGRATOR_PASSWORD_SOURCE` to
`deploy/local/operator.env`, with the same absolute paths exported above. Setup does not persist
these two variables. Store paths, not passwords.
2. Replace the descriptor's generic `modelCatalog` with the approved provider/model configuration.
The generated defaults do not replicate the existing Mac. See [Pi/model configuration](../general/pi-configuration.md)
and the local example `deploy/psd/thothii-installation.yaml.example`.
3. Populate the keys referenced by `authentication.apiKeyEnv` in `thothii.secrets`. Providers using
`pi_auth` need valid credentials at `PI_AUTH_FILE`; the `{}` template is not authentication.
4. Complete the workspace Git files. SSH requires an authorized deploy key and verified known-hosts;
HTTPS requires the credential file and CA bundle expected by the overlay. Blank templates cannot
provide repository access.
Setup verifies files, permissions, descriptor, Compose, Docker, authentication, services, Pi and
the workspace. After startup, run these commands at any time:
After editing generated configuration, do not rerun setup: it rejects different existing content.
Generate the projections and run the explicit migration below. Use `THT_GIT_ACCESS=https` if that
was selected during setup. This block targets the fresh `local` descriptor with only the Git overlay;
custom installations must include their extra descriptor overlays in the same order.
~~~
INSTALLATION="$PWD/deploy/local/thothii-installation.yaml"
tht --installation "$INSTALLATION" doctor --json
tht --installation "$INSTALLATION" workspace pull --json
tht --installation "$INSTALLATION" workspace test --json
~~~
```bash
INSTALLATION="$(pwd -P)/deploy/local/thothii-installation.yaml"
tht --installation "$INSTALLATION" installation generate
THT_PROJECT="thothii-$(printf '%s' "$INSTALLATION" | shasum -a 256 | cut -c 1-12)"
THT_GIT_ACCESS=ssh
compose=(
docker compose --project-name "$THT_PROJECT" --project-directory "$(pwd -P)"
--env-file "$(pwd -P)/deploy/local/operator.env"
-f compose.yaml -f deploy/compose.local.yaml
-f "deploy/compose.git-$THT_GIT_ACCESS.yaml"
-f deploy/local/generated/compose.models.yaml
)
"${compose[@]}" config --quiet
"${compose[@]}" build core frontend
"${compose[@]}" up -d catalog-db
"${compose[@]}" run --rm catalog-migrate
tht --installation "$INSTALLATION" start
```
workspace test checks, for every active workspace, database binding and credentials, Evidence,
Qdrant, and the embedding service. It exits non-zero when the database binding is missing or a
connection is unusable. Before running it, the installer must configure the database in Database
Management: the workspace repository cannot contain the password by itself.
Stop if a command fails. The project name matches the hash used by `tht`, preserving volume
identity. `catalog-migrate` applies Catalog and Memory migrations; `tht start` does not run it
automatically. Initial embedding-model download may take time. Use this installation-specific
sequence, not `run-stack.sh` with a different environment/project name.
doctor --json is the repeatable, non-destructive core verification. The final functional test must
also open http://127.0.0.1:8080, sign in, and complete a real question through final SQL.
## 4. Verify the installation
## Activities only the installer can complete
The descriptor generated for the default ID is:
The procedure automates bootstrap, but it cannot invent enterprise decisions or authorizations.
The installer must complete and record:
```sh
INSTALLATION="$(pwd -P)/deploy/local/thothii-installation.yaml"
test -f "$INSTALLATION"
bash scripts/verify-standalone-install.sh "$INSTALLATION"
```
1. usable LLMs, the modelCatalog, and linked API keys; then run tht pi test and tht doctor;
2. database configuration, connection test, schema synchronization, and description generation;
3. human consolidation of generated descriptions;
4. Qdrant semantic entries through workspace preprocess run;
5. naming-based FK suggestions as a complement to schema FKs, human review, and loading approved
relationships into Qdrant;
6. recurring tht doctor --json and tht workspace test --json checks;
7. one real question completed successfully without connection or model errors.
The verifier is read-only: it runs `tht doctor --json` and `tht status` without restarting the
stack, regenerating configuration, or printing secret contents.
Configuration is complete only when all applicable activities are done, decisions are recorded, and
the two terminal tests are green. The core is usable only after the real question, not merely
because the frontend answers /health.
### Gate A — platform smoke test on all three computers
## Gate A and Gate B
Record the following for each machine:
### Gate A — platform
```sh
~~~
uname -a
docker version --format '{{.Server.Version}} {{.Server.Arch}}'
tht version
bash scripts/check-standalone-prerequisites.sh
bash scripts/verify-standalone-install.sh "$INSTALLATION"
```
~~~
The gate passes when the clone is intact, Docker and Compose are reachable, `tht doctor` is OK, the
stack is running, and the frontend responds at the default local URL `http://127.0.0.1:8080`.
Doctor also checks workspace and Pi: record their failures separately rather than labeling every
failure as a platform problem. Check HTTP readiness with:
### Gate B — usability
```sh
curl --fail --silent --show-error http://127.0.0.1:8080/health
```
### Gate B — functional verification
Run this on at least one machine with available endpoints and credentials:
First follow [Workspace operations](../operations/workspaces.md) to import/prepare the workspace
and configure the Database and local binding. The source clone does not transfer catalog data,
secrets or sessions from the Mac. Connect any VPN required by DWH/model endpoints and verify
that their names are reachable from containers too.
1. open `http://127.0.0.1:8080`;
2. sign in with the configured local account;
3. verify that the configured workspace is readable;
4. start a real question and complete the review gates through final SQL;
5. stop and restart the installation, then run `verify-standalone-install.sh` again.
A Gate B failure involving DWH, the LLM provider, workspace Git, or credentials does not by itself
prove a Docker portability problem: record the failed endpoint or component separately.
## Daily lifecycle
Use the explicit descriptor when more than one installation may be discoverable:
```sh
INSTALLATION="$PWD/deploy/local/thothii-installation.yaml"
tht --installation "$INSTALLATION" status
tht --installation "$INSTALLATION" start
tht --installation "$INSTALLATION" start --build
tht --installation "$INSTALLATION" logs
~~~
tht --installation "$INSTALLATION" doctor --json
tht --installation "$INSTALLATION" stop
```
tht --installation "$INSTALLATION" workspace test --json
curl --fail --silent --show-error http://127.0.0.1:8080/health
~~~
Use `start --build` after source changes or to rebuild images from the current checkout. `stop`
preserves volumes, sessions, the catalog, Pi state, Qdrant data, and the embedding model. Do not
use `docker compose down --volumes` during a normal test: it is destructive and removes local data.
For upgrades requiring migrations, follow the release runbook before starting the new application.
Then run a real question and stop/restart with tht stop and tht start. Do not use docker compose
down --volumes: it deletes the Catalog, sessions, Qdrant data and the embedding model.
## Quick diagnosis
| Symptom | Check |
| Symptom | Action |
| --- | --- |
| `Docker Engine is not reachable` | start Docker Desktop or the Docker service and rerun `docker info` |
| Windows sees Docker but Bash fails | run the guide inside Ubuntu WSL2 and enable that distribution in Docker Desktop |
| `tht: command not found` | open a new shell and check `command -v tht`; rerun the bootstrap if needed |
| line-ending or executable-script errors | use a clone in the WSL2/Linux filesystem and rerun `bash scripts/...` |
| unsupported architecture | check `docker version --format '{{.Server.Arch}}'`; the test requires `amd64` or `arm64` |
| missing descriptor or env file | use `deploy/local/...` generated by `tht setup`, not an arbitrary copied file |
| healthy stack but workflow failure | check external URLs, the credential bundle, workspace Git, and authentication separately |
| data appears missing | check that `down --volumes` was not used; `stop` does not remove volumes |
## Acceptance checklist
- [ ] The clone comes from the expected Gitea repository and the revision is recorded.
- [ ] Docker Desktop/Engine and Compose v2 are available.
- [ ] The runtime reports an allowed architecture.
- [ ] `tht` was built from the repository and responds to `tht version`.
- [ ] Setup uses `profile: local`, `shell.mode: full`, and `shell.defaultLocale: en`.
- [ ] The descriptor, `operator.env`, authentication, and secrets exist only under `deploy/local/`.
- [ ] No secret appears in Git, URLs, public YAML, or recorded commands.
- [ ] Gate A passes on Apple Silicon macOS, x64 Windows WSL2, and x64 Linux.
- [ ] Gate B runs on at least one machine with DWH and LLM available.
- [ ] Stop/start and final verification complete without deleting volumes.
## Out of scope for this release
The following remain future work:
- publishing pre-built images on Docker Hub;
- reducing prompts through a dedicated non-interactive configuration;
- creating DMG, MSI/EXE, AppImage, or other native installers;
- providing an offline runtime or bundling a local DWH/LLM into the application.
| Docker Engine is not reachable | start Docker Desktop or systemctl and repeat docker info |
| Omarchy cannot find docker | install Docker/Compose, enable the service and open a new session |
| Windows sees Docker but Bash fails | use Ubuntu WSL2 and enable its Docker Desktop integration |
| workspace pull fails | check URL, branch, key/credential file and known_hosts from the container |
| workspace test reports a missing binding | configure database, token/password and CA in Database Management |
| Pi is not ready | fill pi-auth.json or the key declared by modelCatalog, then run tht pi test |
## Related documents
- [Install and first start](first-start.md)
- [Shell and localization](shell-and-language.md)
- [Workspace operations](../operations/workspaces.md)
- `deploy/secrets/README.md` (runtime secrets)
- [Database Management](../operations/database-management.md)
- [Model configuration](../general/pi-configuration.md)
- deploy/secrets/README.md
Publishing images on Docker Hub and native DMG/MSI/AppImage installers remain later work: this
procedure starts from the Gitea clone and does not require pre-published Docker Hub images.
+510 -261
View File
@@ -1,329 +1,578 @@
# Installazione manuale standalone
# Installazione standalone guidata
[English version](standalone-manual-en.md)
Questa è la procedura di prova per predisporre THothII come applicazione autonoma in modalità
`full` su macOS, Windows e Linux.
Questa è la procedura per installare THothII da zero. THothII riceve una domanda in linguaggio
naturale, interroga in sola lettura un database aziendale e accompagna l’utente nella revisione
della SQL risultante. Il core, il catalogo PostgreSQL, Qdrant, il servizio di embedding e Pi vengono
eseguiti in Docker; sul computer non servono Node.js, Python o Pi.
In questo documento “autonoma” significa che l’utente non deve installare Node.js, Python o Pi
sull'host: i servizi applicativi e i servizi semantici
locali vengono eseguiti con Docker. DWH e provider LLM restano endpoint esterni configurati
dall’installazione; questa procedura non è un pacchetto offline.
## Preparazione e verifica dei workspace prima dello stack
Il percorso non usa installer grafici, launcher nativi o immagini Docker Hub. Si parte da un clone
Gitea e si usano comandi espliciti da terminale. La pubblicazione di immagini pre-costruite è una
fase successiva.
I primi due passi del nuovo percorso funzionano senza Docker, Node, Python, Pi o
un file di installazione. Usare il bundle della propria piattaforma con **entrambi**
gli eseguibili `tht` e `tht-workspace-documents` nella stessa cartella (`.exe` su
Windows). Aggiungere la cartella al `PATH`, oppure usare il percorso completo.
Il vecchio pacchetto con il solo `tht` non contiene questa capacità. Il bundle è
scaricabile dai [rilasci pubblici](https://git.tylconsulting.it/mptyl/ThothII/releases).
Le immagini core e frontend sono pubblicate su Docker Hub. Per `installation apply`
occorre un bundle che includa questo comando: la prima preview conteneva solo
preparazione e preflight. Su Windows usare il bundle Linux in Ubuntu WSL2.
## Matrice di verifica
| Sistema | Terminale raccomandato | Runtime | Architettura della prova |
| --- | --- | --- | --- |
| macOS supportato dalla versione Docker Desktop installata | Bash nel Terminale | Docker Desktop | Apple Silicon (`arm64`) |
| Windows 11 | Ubuntu dentro WSL2 | Docker Desktop con integrazione WSL2 | x64 (`amd64`) |
| Linux Ubuntu 22.04 o 24.04 | Bash | Docker Engine + Compose v2 | x64 (`amd64`) |
Intel macOS non fa parte della prima campagna di verifica. ARM Linux può essere provato quando il
runtime Docker della macchina restituisce `arm64`, ma non è un requisito della matrice minima.
Le verifiche documentali e dei prerequisiti Mac sono passate. Le installazioni complete da zero
sui tre sistemi restano da eseguire: la matrice indica le prove previste, non una certificazione.
## Cosa serve prima di iniziare
Servono:
- accesso al repository Gitea di THothII e al repository Git dei workspace;
- Git;
- Docker Desktop su macOS e Windows, oppure Docker Engine con il plugin Compose v2 su Linux;
- Bash, `curl`, OpenSSL e `shasum` (su Ubuntu, pacchetto `libdigest-sha-perl`);
- spazio disco sufficiente per compilare le immagini e scaricare il modello di embedding;
- gli endpoint DWH e LLM, più le credenziali che l’installazione deve usare.
Su Linux l’utente corrente deve poter eseguire Docker. Se il sistema richiede `sudo`, aggiungere
l’utente al gruppo Docker secondo la policy locale e aprire una nuova sessione prima di continuare.
Su Windows usare Ubuntu in WSL2 per tutti i comandi di questa guida. In Docker Desktop attivare
l’integrazione WSL2 per quella distribuzione. Clonare il progetto nel filesystem Linux di WSL2,
per esempio sotto `~/src`, e non sotto `/mnt/c`: si evitano rallentamenti e problemi di permessi o
line ending. Non è necessario installare Pi sull’host.
Verificare il runtime prima del clone o subito dopo:
1. Scegliere una cartella nuova, esterna all'applicazione, con padre già esistente:
```sh
docker version
docker compose version
docker version --format '{{.Server.Arch}}'
tht workspace prepare --directory ./miei-workspace --id pratica --name "Pratica" --language it
```
L’ultima istruzione deve restituire `amd64`, `x86_64`, `arm64` o `aarch64`.
## 1. Clonare una revisione del progetto
Usare il repository di progetto su Gitea:
Sono creati `thoth-workspaces.yaml`, `pratica/workspace.yaml` e
`workspace-docs/pratica/README.md`. Una destinazione esistente, anche vuota, viene
rifiutata. Nessun servizio viene avviato; Git non viene inizializzato, nessun remoto
viene contattato. I database di esempio restano un sottoprogetto differito. Per
un repository fornito dal curatore, usare una copia locale separata e passare al
punto 3: è sufficiente accesso in lettura all'origine.
2. Modificare con calma catalogo (schema v1) e descrittore workspace (schema v4).
Mantenere uguali `id`, `name` e l'eventuale `description` nei due file; l'id deve
coincidere con la cartella. Ogni cartella alla radice deve corrispondere a un
workspace elencato, salvo `workspace-docs` e la directory locale `.git`.
Connessioni, schema e credenziali dei database appartengono al Metadata Catalog
dell'installazione. Le Evidence sono facoltative e inizialmente assenti.
3. Verificare, correggere il documento/campo indicato e ripetere:
```sh
tht workspace validate --directory ./miei-workspace
tht workspace validate --directory ./miei-workspace --json
```
Su PowerShell usare gli stessi argomenti, ad esempio
`C:\ThothII\bin\tht.exe workspace validate --directory C:\ThothII\miei-workspace`.
Il controllo non modifica file. Rifiuta YAML multipli o malformati, chiavi/id
duplicati, campi sconosciuti, incoerenze tra catalogo, cartelle e descrittori,
riferimenti locali mancanti e link simbolici. Correggere il primo errore del
documento e ripetere per vedere eventuali errori successivi.
Evidence `absent` è valido. Per filesystem si verificano directory, accessibilità e
riferimenti letterali; per le selezioni Markdown standard anche i limiti dichiarati.
Evidence v2 richiede `curated/` e frontmatter con sintassi YAML valida. I limiti locali
sono 1 MiB per documento letto e 100.000 elementi per albero Evidence. Pattern
arbitrari, contratto completo delle unità curate, provenienza, accesso HTTP/S3 e
indicizzazione restano controlli runtime espliciti. Vedere la [guida Evidence](../evidence.md).
Il JSON espone `schema_version`, `scope: local-documents`, `ok`, `workspaces`, `issues`
e `deferred_checks`. I problemi riportano documento, campo, codice, correzione e,
quando disponibile, riga YAML, senza stampare i valori del documento. Exit status:
`0` successo locale, `1` documenti/accesso/bundle da correggere, `2` argomenti errati.
Il successo locale non certifica verità semantica, connettività o readiness. La
revisione Git attivata in seguito deve contenere i documenti verificati; il comando
non pubblica file non committati o directory vuote.
## Predisporre e verificare i documenti applicativi
Dopo la verifica dei workspace, creare una cartella locale **esterna al loro repository**:
```sh
tht installation prepare --directory ./mia-installazione
```
Il comando crea file privati commentati: `thothii-installation.yaml`, `operator.env`,
`database-bootstrap.yaml` e `README.md`. La cartella deve essere nuova e il padre
deve esistere. Non avvia servizi e non genera implicitamente password.
1. Nel descrittore, scegliere modelli e provider. Il template propone
`openai/gpt-4.1-mini` per l'interazione e `ollama/qwen3-embedding:0.6b` con 1024
dimensioni per l'embedding. Sono valori modificabili, non una selezione richiesta
durante il setup. `modelCatalog.defaults.interaction` deve essere utilizzabile
nelle sessioni e anche nella generazione metadati, se quest'ultima è configurata.
Il template omette la generazione metadati, che è facoltativa. Consultare la
[configurazione dei modelli](../general/pi-configuration.md) per provider personalizzati.
2. Sostituire il remoto Git sia nel descrittore sia in `operator.env`; mantenere
coerenti branch e trasporto. I percorsi sono assoluti e riferiti a questa macchina.
`operator.env` accetta una sola assegnazione letterale `KEY=value` per riga, senza
duplicati o interpolazioni shell. Le credenziali restano nei file referenziati.
3. Compilare `database-bootstrap.yaml`: una voce per ciascun workspace, senza
duplicati. Questo esempio mostra il contratto completo di un collegamento diretto:
```yaml
schemaVersion: 1
authentication:
username: admin
passwordFile: /percorso/privato/mia-installazione/secrets/admin-password
databases:
- workspaceId: pratica
engine: postgres
databaseName: vendite
schema: public
binding:
transport: postgres_direct
host: db.intranet
port: 5432
username: thoth_reader
secretFiles:
password: /percorso/privato/mia-installazione/secrets/database-password
```
Usare le credenziali di un utente DWH in sola lettura. Per `rest_api`, il binding
richiede `baseUrl`, `restPath` e `restAuth` (`none`, `bearer`, `x-api-key`); quando
serve autenticazione, aggiungere `secretFiles.apiKey`. `ssh_tunnel` richiede
`username`, `sshHost`, `sshPort`, `sshUsername`, `sshTargetHost`, `sshTargetPort` e
i file `password`, `sshPrivateKey`, `sshKnownHosts`; abilita diagnostica Catalog,
non sessioni NL→SQL. Sono facoltativi `tlsCa` e `sshPrivateKeyPassphrase`.
Le Evidence HTTP firmate richiedono `evidenceSecretFiles` con chiave
`evidence.signed_urls`; S3 con credenziali statiche richiede `evidence.access_key`
e `evidence.secret_key`, con `evidence.session_token` facoltativo. Tutti i valori
sono percorsi di file privati. I workspace rimangono nello schema v4: il bootstrap
è un input iniziale, non un secondo Catalog runtime. Il documento include anche
`authentication.username: admin` e `authentication.passwordFile` con il percorso
privato di `secrets/admin-password`. Se si cambia amministratore, aggiornare questi
riferimenti prima della validazione: il setup usa il login ordinario e i permessi
amministrativi, senza richiedere una password durante l'esecuzione.
4. Generare esplicitamente le credenziali tecniche nel layout standard:
```sh
tht installation credentials --directory ./mia-installazione
```
Sono creati password casuali separate per Catalog runtime/migrator e amministratore,
il relativo `auth/auth.yaml` con `auth/users.yaml`, un template `secrets/secrets.env`
e `secrets/pi-auth.json`. I file esistenti vengono conservati; se non validi, il
comando si ferma. L'amministratore iniziale è `admin`, la password è nel file
privato `secrets/admin-password` e non viene stampata. Il default è autenticazione
locale con URL pubblico `http://127.0.0.1:8080`: verificare e, se necessario,
modificare `auth/auth.yaml` prima del controllo. Questo incremento non valida il
bootstrap OIDC del percorso esistente.
5. Inserire la chiave del provider in `secrets/secrets.env` e creare il file della
password DWH. Per HTTPS Git fornire i file referenziati per credenziali e CA:
credenziali vuote sono ammesse per un remoto pubblico, la CA deve essere disponibile.
Fornire la CA specifica del server in PEM, entro 64 KiB; l'intero bundle CA del
sistema può superare il limite dei file protetti.
Per SSH fornire chiave e known_hosts, scegliendo il relativo override nel descrittore.
I provider `pi_auth` richiedono credenziali Pi già preparate. Conservare tutti
questi file fuori dal repository workspace e proteggere l'accesso al solo utente
installatore (0600 su Unix, ACL equivalenti su Windows). Non committarli.
6. Verificare e ripetere dopo ogni correzione:
```sh
tht --installation /percorso/assoluto/mia-installazione/thothii-installation.yaml installation validate --workspaces /percorso/assoluto/miei-workspace --json
```
Il bootstrap viene cercato accanto al descrittore; `--bootstrap PERCORSO` ne
seleziona uno diverso. Il controllo non cambia documenti, non genera proiezioni,
non usa la rete e non scrive database. Rifiuta placeholder, incoerenze, file
mancanti/non privati e segreti situati nel repository workspace. Il report indica
documento, campo e correzione senza valori riservati. Exit status: 0 successo
locale, 1 correzioni necessarie, 2 argomenti errati.
Gli asset Compose standard del rilascio possono ancora mancare in questa fase;
gli override personalizzati devono già esistere. Il report distingue i controlli
differiti: asset del rilascio, connettività esterna, import Catalog e readiness.
Un esito positivo prepara il successivo preflight: non autorizza a saltare tali
controlli e non equivale a un'installazione completata.
## Verificare le precondizioni e produrre il piano
Al passo 3, prima di completare tutti i parametri applicativi, controllare la
macchina e la directory privata già preparata:
```bash
tht installation preflight --directory /percorso/installazione --json
```
Servono Docker Linux raggiungibile, Compose 2.24 o successivo, almeno 2 CPU,
4 GiB assegnati a Docker e 10 GiB liberi nella directory di installazione. Il
rilascio può richiedere risorse maggiori. Su Windows eseguire il binario Linux
in Ubuntu WSL2 con integrazione Docker Desktop; Pi è incluso nell'immagine core.
Al passo 5, dopo `installation validate`, selezionare il manifest del rilascio
pubblicato, con le risorse del bundle già scaricate, e produrre un piano nuovo:
```bash
tht --installation /percorso/installazione/thothii-installation.yaml installation plan \
--workspaces /percorso/workspaces \
--release /percorso/rilascio/release-manifest.json \
--output /percorso/installazione/installation-plan.json --json
```
Il comando ripete i controlli dei documenti, verifica immagini/digest e Compose,
Git, database ed Evidence esterne disponibili, poi salva il piano e il suo file
privato `.key`. Non esegue il setup. Le immagini assenti e le dipendenze esterne
irraggiungibili bloccano il piano. Il manifest deve provenire dallo stesso rilascio
degli eseguibili; un manifest inventato non permette di aggirare queste verifiche.
Correggere gli esiti `error`; leggere gli `warning`. Gli esiti
`deferred-to-runtime` identificano controlli obbligatori dopo l'avvio, non una
readiness già ottenuta. Un piano valido non sostituisce questi gate. Dopo una
correzione o rotazione di credenziali produrre un nuovo piano; i file esistenti
non vengono sovrascritti. Conservare piano e chiave fuori dal Git dei workspace.
Le prove esterne sono letture limitate: autenticazione/schema del database,
letture Git e HTTP/S3, raggiungibilità degli endpoint modello espliciti. Nessuna
generazione LLM viene invocata; le richieste HTTP/S3 possono avere i normali costi
del servizio. Limiti, manifest e obblighi sono nel
[riferimento di preflight](installation-preflight.md).
## Avviare la piattaforma dai documenti verificati
Eseguire come lo stesso utente non root che ha preparato i documenti, con Docker
locale accessibile. Il comando non pone domande e funziona anche con stdin chiuso:
```sh
tht --installation /percorso/installazione/thothii-installation.yaml installation apply \
--plan /percorso/installazione/installation-plan.json --json
```
Ripete le verifiche live e del piano, copia gli asset verificati, scarica le immagini,
inizializza i volumi della nuova installazione, avvia PostgreSQL, applica le migrazioni
Catalog e Memory e avvia i servizi. Non compila sorgenti. L'amministratore iniziale
proviene dai documenti di autenticazione già preparati. I segreti mantengono i
permessi privati: i servizi interessati usano l'UID dell'operatore. Questo percorso
non converte stack preesistenti con proprietari o volumi incompatibili.
L'esecuzione importa poi i binding tramite i servizi autenticati del Catalog e il
secret store esistente. Verifica che remoto, branch, revisione e contenuti coincidano
con i documenti del piano; non cambia implicitamente un checkout già presente.
La connessione al DWH viene riprovata dall'applicazione nei container.
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:
confrontare il bootstrap con la configurazione in Amministrazione e preservare la
modifica voluta. Non cancellare volumi o ricevute Catalog per aggirare il controllo.
`workspace_reconciliation_required` indica una differenza nella sorgente workspace;
`authentication_required` richiede di correggere l'amministratore predisposto;
`container_connection_failed` indica un DWH non raggiungibile o non autenticabile
dalla rete applicativa. I segreti scalari letti dai file ignorano spazi e ritorni a
capo esterni, come i probe preliminari; PEM e known-hosts restano invariati.
Con il valore predefinito, aprire `http://127.0.0.1:8080` per l'accesso: l'origine
del browser deve coincidere con `publicUrl`, quindi non sostituire `127.0.0.1` con
`localhost`.
In caso di errore, correggere la causa e ripetere `apply`: il journal privato in
`.tht/<installazione>/installation-apply.json` registra gli stadi, mentre lo stato
reale dei servizi viene ricontrollato. Il retry conserva i dati; non elimina volumi
e non ricorre a una build. Dopo modifiche ai documenti o alle credenziali serve un
nuovo piano. Ctrl+C rilascia il lock; dopo un arresto forzato del processo verificare
che non sia più attivo prima di rimuovere esplicitamente il suo lock residuo.
Un rilascio differente richiede il percorso di aggiornamento, non questo comando.
Se `apply` viene interrotto durante sync o preprocessing, ripetere lo stesso comando.
I run Catalog persistiti vengono riletti; una decisione umana pendente resta pendente.
Il preprocessing in corso viene atteso. Se il suo proprietario è terminato, la ripresa
verifica anche l'assenza di processi figli ancora attivi e riesegue la pipeline completa
con il contratto esistente. Non cancella sessioni, Evidence curate, descrizioni o Memory.
Non usare `workspace preprocess clear` o la cancellazione dei volumi come rimedio.
I vecchi job senza il protocollo di ownership richiedono un'ispezione durante upgrade.
Una credenziale o un endpoint modificato rende il piano vecchio inutilizzabile.
Correggere i documenti e ripetere `validate` e `plan` con un nome di piano nuovo.
Se il binding era già importato, applicare la correzione voluta anche in Amministrazione:
il bootstrap deve corrispondere al Catalog, non sovrascrive modifiche amministrative.
Le altre fasi vengono riconciliate con Docker e Catalog senza ricreare dati già presenti.
## 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
suoi comandi di build o setup sopra un'installazione creata con `installation apply`.
Servono due repository distinti:
1. il repository dell’applicazione, che l’utente clona:
https://git.tylconsulting.it/mptyl/ThothII.git;
2. il repository dei workspace, indicato dal curatore/installatore. Non è il repository di
THothII e non va clonato manualmente nella directory dell’applicazione.
Il repository workspace contiene il catalogo e una directory per ogni workspace, normalmente:
~~~
thoth-workspaces.yaml
<workspace-id>/workspace.yaml
<workspace-id>/evidence/** # se il workspace dichiara Evidence
~~~
Il file workspace.yaml descrive identità, lingua e, opzionalmente, la sorgente Evidence. Per scelta
architetturale non contiene password del database. L’identità del database, il trasporto
(PostgreSQL, REST o tunnel), username, password, token e certificati sono configurazione locale
dell’installazione, conservata cifrata dal Catalog. Questo evita di committare credenziali nel
repository workspace.
## 0. Prerequisiti della macchina
### Windows
- Windows 10/11 con Docker Desktop avviato e backend WSL2 abilitato.
- Ubuntu in WSL2, con integrazione Docker Desktop abilitata per quella distribuzione.
- Git, Bash, curl, OpenSSL e shasum nella distribuzione WSL2.
- Non installare Node.js, Python o Pi sull’host per questa procedura.
In PowerShell, se WSL2 non esiste ancora, usare la procedura aziendale oppure:
~~~
wsl --install -d Ubuntu
~~~
Eseguire poi tutti i comandi dentro Ubuntu WSL2, in una directory Linux come $HOME/src, non sotto
/mnt/c. Il percorso nativo scripts/install-tht.ps1 esiste per scenari PowerShell avanzati; per la
prova riproducibile usare WSL2.
### macOS
- Docker Desktop installato, avviato e con alcuni GB liberi per immagini e modello di embedding.
- Git, Bash, curl, OpenSSL e shasum.
- Sono supportati Mac Intel e Apple Silicon se Docker Desktop supporta l’architettura restituita
dal Docker server.
- Non installare Node.js, Python o Pi sull’host per questa procedura.
### Linux, incluso Omarchy
- Git, Bash, curl, OpenSSL e shasum.
- Docker Engine e il plugin Docker Compose v2. Su Omarchy verificare prima:
~~~
command -v docker
docker compose version
docker info
~~~
Se Docker manca, installare Docker e Compose con il gestore pacchetti/procedura approvata dalla
distribuzione, poi avviare il servizio. Su una distribuzione Arch-like il percorso tipico è:
~~~
sudo pacman -S docker docker-compose
sudo systemctl enable --now docker
sudo usermod -aG docker "$USER"
~~~
Dopo l’aggiunta al gruppo aprire una nuova sessione e ripetere docker info. Non installare Node.js,
Python o Pi sull’host: sono dentro le immagini Docker.
Su tutti i sistemi il controllo finale è:
~~~
bash scripts/check-standalone-prerequisites.sh
docker version --format '{{.Server.Arch}}'
~~~
L’architettura deve essere amd64, x86_64, arm64 o aarch64. Servono inoltre accesso al repository
Gitea dell’applicazione, URL/branch e credenziali del repository workspace, raggiungibilità dal
container degli endpoint DWH/LLM e le credenziali, token o certificati associati ai database.
## 1. Cosa clonare
Clonare solo l’applicazione:
~~~
mkdir -p "$HOME/src"
cd "$HOME/src"
git clone https://git.tylconsulting.it/mptyl/ThothII.git
cd ThothII
git rev-parse --short HEAD
```
~~~
Per un clone SSH usare, se la chiave è già autorizzata su Gitea:
Annotare la revisione. Il repository workspace verrà scaricato da tht setup --complete dentro un
volume Docker persistente, usando URL, branch e trasporto indicati durante il setup.
```sh
git clone git@git.tylconsulting.it:mptyl/ThothII.git
```
Per una prova ripetibile annotare l’hash stampato da `git rev-parse`. In una campagna successiva
usare la revisione/tag approvata dal maintainer invece di seguire implicitamente una `main` che
può cambiare.
## 2. Verificare i prerequisiti e installare il comando operatore
## 2. Installare il comando terminale
Dal root del clone:
```sh
~~~
bash scripts/check-standalone-prerequisites.sh
export PATH="$HOME/.local/bin:$PATH"
mkdir -p "$HOME/.local/bin"
THT_INSTALL_DIRECTORY="$HOME/.local/bin" bash scripts/install-tht.sh
export PATH="$HOME/.local/bin:$PATH"
tht version
```
~~~
`install-tht.sh` è un bootstrap del solo comando operatore nativo `tht`; non installa una versione
desktop di THothII. Usa il builder Docker del repository, installa il binario adatto all’ambiente
del terminale e lo installa nella directory utente. Aggiungere `$HOME/.local/bin` al PATH della
shell anche per i terminali successivi. Un `tht` già presente in quella directory viene aggiornato.
Il comando tht è l’unico componente nativo da installare. Costruisce il binario con Docker e
orchestra Compose; non è un secondo runtime dell’applicazione.
Su Windows, eseguire questi comandi dentro WSL2. Il binario `tht` installato è quello Linux di WSL2;
il runtime dell’applicazione rimane Docker Desktop. Non usare `scripts/install-tht.ps1` come percorso
principale di questa prova.
## 3. Preparare pochi segreti e avviare il setup completo
## 3. Configurare e avviare l’installazione locale
La prima esecuzione crea i placeholder protetti sotto deploy/local/secrets/ e si ferma se manca
una credenziale necessaria. Compilare i file indicati e rilanciare lo stesso comando: i file di
configurazione già compatibili vengono riutilizzati.
Eseguire i blocchi successivi nella stessa sessione Bash dal root fisico del clone (`pwd -P`).
Creare prima le due password distinte del catalogo, conservando eventuali file già esistenti:
~~~
tht setup --complete --profile local --shell-mode full --shell-default-locale en
~~~
```bash
umask 077
mkdir -p deploy/local/secrets
for name in catalog-runtime-password catalog-migrator-password; do
target="deploy/local/secrets/$name"
if [ ! -e "$target" ]; then
(set -C; openssl rand -hex 32 > "$target") || exit 1
fi
done
export THT_CATALOG_RUNTIME_PASSWORD_SOURCE="$(pwd -P)/deploy/local/secrets/catalog-runtime-password"
export THT_CATALOG_MIGRATOR_PASSWORD_SOURCE="$(pwd -P)/deploy/local/secrets/catalog-migrator-password"
```
Durante il setup servono solo le informazioni operative che il computer non può conoscere:
Non rigenerare le password di un catalogo già inizializzato. Configurare senza avviare i servizi:
```sh
tht setup --profile local --shell-mode full --shell-default-locale en --configure-only
```
Rispondere ai prompt nel seguente modo:
| Prompt | Valore o regola |
| Richiesta | Cosa inserire |
| --- | --- |
| Installation ID | `local`, salvo necessità di più installazioni nello stesso clone |
| Deployment profile | `local` |
| DWH API endpoint | URL `http(s)` senza user, password, query o fragment; può restare vuoto per il solo smoke test |
| LLM API endpoint | URL `http(s)` senza credenziali; può restare vuoto per il solo smoke test |
| Workspace repository URL | URL del repository dei workspace, non il clone sorgente di THothII |
| Workspace branch | normalmente `main` |
| Workspace access | `ssh` se si usa una chiave deploy; altrimenti `https` con credential file protetto |
| Percorsi dei file | accettare i percorsi predefiniti sotto `deploy/local/secrets/` nella prima prova |
| Secret templates | rispondere `yes` quando i file protetti non esistono ancora |
| Autenticazione | configurare il login locale richiesto dall’installazione; non inserire password in una riga di comando |
| Repository workspace | URL del repository dati/configurazione, non ThothII.git |
| Branch | normalmente main |
| Accesso | ssh con chiave e known_hosts, oppure https con credential file e CA |
| DWH/LLM URL | endpoint senza token nella URL |
| Login locale | utente e password iniziale richiesti dal prompt |
La configurazione generata è locale e ignorata da Git:
Il setup crea automaticamente le password casuali del Catalog e le scrive in operator.env come
percorsi, non come valori. Esegue docker compose config, costruisce le immagini, avvia il Catalog,
esegue catalog-migrate, avvia lo stack e importa il repository workspace. L’import attiva anche
l’Evidence dichiarata: almeno i file source presenti nel workspace vengono materializzati nel
registro locale.
```text
deploy/local/thothii-installation.yaml
deploy/local/operator.env
deploy/local/auth/
deploy/local/secrets/
```
### Il file da compilare
Modificare i segreti solo nei file locali protetti; non committarli. Il file `deploy/env/local.env.example` è un riferimento
tracciato; il percorso generato da `tht setup`, `deploy/local/operator.env`, è quello da usare per
questa installazione.
Il file principale è:
### Completare i file protetti
~~~
deploy/local/secrets/thothii.secrets
~~~
Se il setup ha creato template vuoti, inserire i valori con un editor locale:
Inserire solo righe NOME=VALORE necessarie al modelCatalog e agli adapter, per esempio una API key
LLM (DEEPSEEK_API_KEY, OPENAI_API_KEY o quella dichiarata dal catalogo) ed eventualmente
THT_DWH_API_KEY. I nomi ammessi sono documentati in deploy/secrets/README.md. Non mettere token
nelle URL, nel repository o nei comandi.
```sh
chmod 600 deploy/local/secrets/*
"${EDITOR:-vi}" deploy/local/secrets/thothii.secrets
```
Due precisazioni evitano gli errori più comuni:
Il bundle deve contenere solo righe `KEY=VALUE` per le credenziali effettivamente usate dal
`modelCatalog`. I nomi ammessi e il confine delle credenziali sono descritti nel file locale
`deploy/secrets/README.md`. Non mettere token nelle URL, nel
descriptor YAML, nel repository Git o nei comandi copiati nella shell.
- se il catalogo usa pi_auth, il token LLM va nel file Pi pi-auth.json creato dal setup; {} è solo
un placeholder e non abilita alcun modello;
- le credenziali specifiche di un database workspace (password PostgreSQL, API token REST, chiave
SSH del tunnel, known_hosts, CA) non vanno nel repository workspace: si inseriscono per workspace
in Database Management, che le conserva nel Catalog cifrato. Il workspace indica database/schema
e trasporto; l’installatore deve ottenere dal proprietario il valore corretto.
Per accesso workspace SSH, predisporre anche la chiave privata e il file `known_hosts` indicati dal
setup. Per accesso HTTPS, predisporre il credential file Git e l’eventuale CA. Entrambi devono
restare protetti e fuori dal controllo versione.
Per un repository workspace privato sono inoltre indispensabili i file Git richiesti dal trasporto:
una chiave SSH e known_hosts, oppure credential file HTTPS e CA. Sono file di trasporto, non un
secondo bundle da committare. Per ridurre i file da compilare, usare SSH con una deploy key già
autorizzata.
Prima dell'avvio completare anche questi passaggi:
## 4. Controlli automatici e test da terminale
1. Aggiungere `THT_CATALOG_RUNTIME_PASSWORD_SOURCE` e `THT_CATALOG_MIGRATOR_PASSWORD_SOURCE` a
`deploy/local/operator.env`, con gli stessi percorsi assoluti esportati sopra. Il setup non salva
queste due variabili. Inserire i percorsi, non le password.
2. Sostituire il `modelCatalog` generico nel descriptor con la configurazione provider/modelli
approvata. I default generati non replicano il Mac esistente. Vedere [configurazione Pi/modelli](../general/pi-configuration.md)
e l'esempio locale `deploy/psd/thothii-installation.yaml.example`.
3. Inserire in `thothii.secrets` le chiavi referenziate da `authentication.apiKeyEnv`. I provider
`pi_auth` richiedono credenziali valide nel file `PI_AUTH_FILE`; il template `{}` non autentica.
4. Completare i file Git del workspace. SSH richiede una chiave deploy autorizzata e known-hosts
verificato; HTTPS richiede il credential file e il bundle CA previsti dall'overlay. I template
vuoti non consentono l'accesso al repository.
Il setup verifica file, permessi, descriptor, Compose, Docker, autenticazione, servizi, Pi e
workspace. Dopo l’avvio usare questi comandi in qualunque momento:
Dopo aver modificato la configurazione generata, non rilanciare setup: rifiuta file esistenti con
contenuti diversi. Generare le proiezioni ed eseguire la migrazione esplicita indicata sotto.
Impostare `THT_GIT_ACCESS=https` se scelto nel setup. Il blocco usa il nuovo descriptor `local`
con il solo overlay Git; per installazioni personalizzate includere gli overlay aggiuntivi
nello stesso ordine del descriptor.
~~~
INSTALLATION="$PWD/deploy/local/thothii-installation.yaml"
tht --installation "$INSTALLATION" doctor --json
tht --installation "$INSTALLATION" workspace pull --json
tht --installation "$INSTALLATION" workspace test --json
~~~
```bash
INSTALLATION="$(pwd -P)/deploy/local/thothii-installation.yaml"
tht --installation "$INSTALLATION" installation generate
THT_PROJECT="thothii-$(printf '%s' "$INSTALLATION" | shasum -a 256 | cut -c 1-12)"
THT_GIT_ACCESS=ssh
compose=(
docker compose --project-name "$THT_PROJECT" --project-directory "$(pwd -P)"
--env-file "$(pwd -P)/deploy/local/operator.env"
-f compose.yaml -f deploy/compose.local.yaml
-f "deploy/compose.git-$THT_GIT_ACCESS.yaml"
-f deploy/local/generated/compose.models.yaml
)
"${compose[@]}" config --quiet
"${compose[@]}" build core frontend
"${compose[@]}" up -d catalog-db
"${compose[@]}" run --rm catalog-migrate
tht --installation "$INSTALLATION" start
```
workspace test prova, per ogni workspace attivo, il binding del database e le credenziali, Evidence,
Qdrant e il servizio embedding. Restituisce exit code diverso da zero se manca il binding del
database o una connessione non è utilizzabile. Prima di eseguirlo l’installatore deve aver
configurato il database in Database Management: il workspace repository da solo non può contenere
la password.
Fermarsi se un comando fallisce. Il nome progetto coincide con l'hash usato da `tht`, preservando
l'identità dei volumi. `catalog-migrate` applica le migrazioni Catalog e Memory; `tht start` non
lo esegue automaticamente. Il primo download del modello embedding può richiedere tempo.
Usare questa sequenza legata all'installazione, non `run-stack.sh` con env/progetto diversi.
Per una verifica generale del core, doctor --json è il test ripetibile e non distruttivo. Il test
funzionale finale deve inoltre aprire http://127.0.0.1:8080, autenticarsi e completare una domanda
reale fino alla SQL finale.
## 4. Verificare l’installazione
## Attività che può svolgere solo l’installatore
Il descriptor generato per l’ID predefinito è:
La procedura automatizza il bootstrap, non può inventare decisioni o autorizzazioni aziendali.
L’installatore deve completare e registrare:
```sh
INSTALLATION="$(pwd -P)/deploy/local/thothii-installation.yaml"
test -f "$INSTALLATION"
bash scripts/verify-standalone-install.sh "$INSTALLATION"
```
1. quali LLM sono utilizzabili, il relativo modelCatalog e le API key collegate; poi eseguire
tht pi test e tht doctor;
2. per ogni database: configurazione, test connessione, sincronizzazione dello schema e
generazione delle descrizioni;
3. consolidamento umano delle descrizioni generate;
4. generazione delle entry semantiche in Qdrant tramite workspace preprocess run;
5. generazione delle FK suggerite dal naming, come complemento alle FK lette dallo schema, revisione
umana delle proposte e caricamento delle relazioni approvate in Qdrant;
6. verifica periodica con tht doctor --json e tht workspace test --json;
7. una domanda reale completata con successo, senza errori di connessione o modello.
Il verificatore è read-only: esegue `tht doctor --json` e `tht status`, senza ristartare lo stack,
rigenerare la configurazione o stampare il contenuto dei segreti.
La configurazione è dichiarata completa solo quando tutti i punti applicabili sono stati eseguiti,
le decisioni sono state registrate e i due test terminali sono verdi. Il core è dichiarato usabile
solo dopo la domanda reale, non perché il frontend risponde a /health.
### Gate A — smoke di piattaforma, su tutti e tre i computer
## Gate A e Gate B
Registrare per ogni macchina:
### Gate A — piattaforma
```sh
~~~
uname -a
docker version --format '{{.Server.Version}} {{.Server.Arch}}'
tht version
bash scripts/check-standalone-prerequisites.sh
bash scripts/verify-standalone-install.sh "$INSTALLATION"
```
~~~
Il gate passa quando il clone è integro, Docker e Compose sono raggiungibili, `tht doctor` è OK,
lo stack è avviato e il frontend risponde sulla porta locale predefinita `http://127.0.0.1:8080`.
Il doctor controlla anche workspace e Pi: registrare separatamente i loro errori senza attribuire
ogni fallimento alla piattaforma. Verificare la disponibilità HTTP con:
### Gate B — usabilità
```sh
curl --fail --silent --show-error http://127.0.0.1:8080/health
```
### Gate B — verifica funzionale
Eseguire almeno su una macchina con endpoint e credenziali disponibili:
Seguire prima [Workspace operations](../operations/workspaces.md) per importare/preparare il
workspace e configurare Database e binding locale. Il clone sorgente non trasferisce catalogo,
segreti o sessioni del Mac. Connettere l'eventuale VPN richiesta da DWH/modelli e verificare
che i relativi nomi siano raggiungibili anche dai container.
1. aprire `http://127.0.0.1:8080`;
2. autenticarsi con l’account locale configurato;
3. verificare che il workspace configurato sia leggibile;
4. avviare una domanda reale e completare i gate di revisione fino alla SQL finale;
5. fermare e riavviare l’installazione, poi ripetere `verify-standalone-install.sh`.
Un fallimento del Gate B per DWH, provider LLM, Git workspace o credenziali non dimostra da solo un
problema di portabilità Docker: registrare separatamente l’endpoint o il componente fallito.
## Ciclo di vita quotidiano
Usare il descriptor esplicito quando più installazioni possono essere scoperte:
```sh
INSTALLATION="$PWD/deploy/local/thothii-installation.yaml"
tht --installation "$INSTALLATION" status
tht --installation "$INSTALLATION" start
tht --installation "$INSTALLATION" start --build
tht --installation "$INSTALLATION" logs
~~~
tht --installation "$INSTALLATION" doctor --json
tht --installation "$INSTALLATION" stop
```
tht --installation "$INSTALLATION" workspace test --json
curl --fail --silent --show-error http://127.0.0.1:8080/health
~~~
`start --build` è necessario dopo una modifica al codice o per ricostruire le immagini dal clone
corrente. `stop` conserva volumi, sessioni, catalogo, stato Pi, dati Qdrant e modello embedding.
Non usare `docker compose down --volumes` durante una prova normale: è un’operazione distruttiva
che cancella i dati locali.
Per aggiornamenti che richiedono migrazioni, seguire il runbook della release prima dell'avvio.
Poi eseguire una domanda reale e fermare/riavviare con tht stop e tht start. Non usare docker
compose down --volumes: cancella Catalog, sessioni, Qdrant e il modello embedding.
## Diagnosi rapida
| Sintomo | Controllo |
| Sintomo | Azione |
| --- | --- |
| `Docker Engine is not reachable` | avviare Docker Desktop oppure il servizio Docker e ripetere `docker info` |
| Windows vede Docker ma Bash fallisce | eseguire la guida dentro Ubuntu WSL2 e abilitare l’integrazione della distribuzione in Docker Desktop |
| `tht: command not found` | aprire una nuova shell e verificare `command -v tht`; se necessario ripetere il bootstrap |
| line ending o script non eseguibile | usare un clone nel filesystem WSL2/Linux e rieseguire `bash scripts/...` |
| architettura non supportata | verificare `docker version --format '{{.Server.Arch}}'`; la prova richiede `amd64` o `arm64` |
| descriptor o env file mancanti | usare il percorso `deploy/local/...` generato da `tht setup`, non un file copiato casualmente |
| stack sano ma workflow fallisce | controllare separatamente URL, credential bundle, workspace Git e autenticazione |
| dati apparentemente persi | verificare che non sia stato usato `down --volumes`; `stop` non rimuove i volumi |
## Checklist di accettazione
- [ ] Il clone proviene dal repository Gitea atteso e la revisione è stata annotata.
- [ ] Docker Desktop/Engine e Compose v2 sono disponibili.
- [ ] Il runtime restituisce un’architettura ammessa.
- [ ] `tht` è stato costruito dal repository e risponde a `tht version`.
- [ ] Il setup usa `profile: local`, `shell.mode: full` e `shell.defaultLocale: en`.
- [ ] Descriptor, `operator.env`, autenticazione e segreti sono presenti solo in `deploy/local/`.
- [ ] Nessun segreto compare in Git, URL, YAML pubblico o comandi registrati.
- [ ] Gate A superato su macOS Apple Silicon, Windows WSL2/x64 e Linux x64.
- [ ] Gate B eseguito almeno su una macchina con DWH e LLM disponibili.
- [ ] Stop/start e verifica finale completati senza cancellare i volumi.
## Fuori perimetro di questa release
Restano attività successive:
- pubblicare immagini pre-costruite su Docker Hub;
- ridurre ulteriormente i prompt tramite una configurazione non interattiva dedicata;
- creare pacchetti DMG, MSI/EXE, AppImage o altri installer nativi;
- fornire un runtime offline o un DWH/LLM locale incluso nell’applicazione.
| Docker Engine is not reachable | avviare Docker Desktop o systemctl e ripetere docker info |
| Omarchy non trova docker | installare Docker/Compose, abilitare il servizio e riaprire la sessione |
| Windows vede Docker ma Bash fallisce | usare Ubuntu WSL2 e abilitarne l’integrazione in Docker Desktop |
| pull workspace fallisce | controllare URL, branch, chiave/credential file e known_hosts dal container |
| workspace test segnala binding mancante | configurare database, token/password e CA in Database Management |
| Pi non è pronto | compilare pi-auth.json o la chiave dichiarata dal modelCatalog, poi eseguire tht pi test |
## Documenti collegati
- [Install and first start](first-start.md)
- [Shell and localization](shell-and-language.md)
- [Workspace operations](../operations/workspaces.md)
- `deploy/secrets/README.md` (runtime secrets)
- [Installazione e primo avvio](first-start.md)
- [Operazioni sui workspace](../operations/workspaces.md)
- [Database Management](../operations/database-management.md)
- [Configurazione dei modelli](../general/pi-configuration.md)
- deploy/secrets/README.md
La pubblicazione di immagini su Docker Hub e gli installer nativi DMG/MSI/AppImage restano attività
successive: questa procedura parte dal clone Gitea e non richiede immagini Docker Hub pre-pubblicate.
+1 -1
View File
@@ -54,7 +54,7 @@ Omics. Le preferenze non modificano il descrittore installato.
Per una nuova installazione autonoma, selezionare esplicitamente full:
```bash
tht setup --profile local --shell-mode full --shell-default-locale en
tht setup --complete --profile local --shell-mode full --shell-default-locale en
```
Il setup senza opzioni shell conserva per compatibilità il default embedded.

Some files were not shown because too many files have changed in this diff Show More