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 Opus 5.5 8bd1f3e793 docs: retrofit domain docs to GLOSSARY.md and chronological ADRs
Publish documentation / publish (push) Successful in 29s
Align domain documentation with the mattpocock-skills v1.3.1 format.

- GLOSSARY.md (Italian) replaces CONTEXT.md and describes the implemented
  system (Phase F1–F8, Gate, Reviewer widget). The unimplemented 2026-08-23
  modular-workflow vocabulary (Workflow Kernel, Stage, Module outcome,
  Extension point, Question Admission, ...) is removed.
- docs/adr/ renumbered chronologically, in English, with status/date
  frontmatter. Retroactive decisions recovered from deleted specs and the
  Evidence ADRs deleted in a54d4769 are restored.
- docs/agents/domain.md regenerated; references updated across docs.

New ADRs:
  0001–0016  retroactive decisions, 2026-06-25 → 2026-08-20
  0017–0024  Evidence ADRs of 2026-08-24 (old 0001–0008, deleted in a54d4769)

Renumbered ADRs (old → new):
  0001 → 0025  postgres-metadata-catalog
  0002 → 0026  workspace-database-secret-references
  0003 → 0027  installation-local-database-bindings
  0004 → 0028  fastify-kysely-metadata-catalog
  0005 → 0029  hard-delete-catalog-tables-during-synchronization
  0006 → 0030  separate-physical-and-logical-relationships
  0007 → 0031  durable-authoritative-schema-synchronization
  0008 → 0032  allow-manual-catalog-metadata-cleanup
  0009 → 0033  use-one-sequential-description-generation-run
  0010 → 0034  allow-bounded-real-source-samples-for-description-generation
  0011 → 0035  gate-source-samples-with-a-sensitive-data-flag
  0012 → 0036  use-the-catalog-as-the-logical-relationship-authority
  0013 → 0037  use-one-installation-model-catalog-with-runtime-projections
  0014 → 0038  assess-sensitive-columns-locally-from-source-content
  0015 → 0039  use-progressive-sampling-for-sensitive-columns
  0016 → 0040  use-postgres-metadata-for-all-core-consumers
  0017 → 0041  separate-reference-vectors-from-runtime-memory
  0018 → 0042  use-postgres-for-memory-and-qdrant-for-retrieval
  0019 → 0043  author-evidence-in-app... → maintain-local-evidence-with-external-editors
  0020 → 0044  unify-administration-pages-and-use-namespaced-routes
  0021 → 0045  separate-shell-modes-and-replaceable-portal-adapter
  0022 → 0046  separate-ui-locale-from-session-interaction-language
  0023 → 0047  separate-delivery-operations-from-finalized-sessions

Commits and Gitea issues before this commit cite the old numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:23:25 +02:00
CodexandClaude Opus 5.5 3222713ec6 docs: add ETL delivery vocabulary, ADR 0023 and two study plans
- CONTEXT.md: Delivery Destination, SQL Delivery, Delivery Operation, ETL Activation
- ADR 0023: separate delivery operations from finalized sessions (#41)
- ETL integration study and SaaS/MCP feasibility study

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:23:17 +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
User 2f53512e4d docs: record server release and hand off remaining acceptance checks
Publish documentation / publish (push) Successful in 32s
2026-09-27 00:41:37 +02:00
Codex 497ab84031 docs: pin server handoff to released main revision
Publish documentation / publish (push) Successful in 33s
2026-09-26 16:42:36 +02:00
Codex 67ee52624c wip: guided standalone installation and workspace checks 2026-09-26 16:41:15 +02:00
Codex 0d2e573e0d fix(ui): reset session view on stop and exit 2026-09-26 16:40:37 +02:00
Codex bd416f7327 Fix new-question landing and question-language HITL
Publish documentation / publish (push) Successful in 34s
Reset the activity panel when starting a new question so the landing navigation is restored. Detect and persist the original question language, pass it through runtime and widget descriptors, and scope HITL controls to that language.

Validated with gate, session, backend and frontend tests, TypeScript checks, Ruff and strict docs build. Rebuilt and restarted local core/frontend; both healthy and serving HTTP successfully.
2026-09-21 19:47:22 +02:00
Codex 23e52c80de Record verified Qwen documentation publication
Publish documentation / publish (push) Successful in 23s
2026-09-21 16:27:10 +02:00
Codex 84084bba37 Fix Qwen session tool calls and expose thinking compatibility
Publish documentation / publish (push) Successful in 30s
2026-09-21 16:23:51 +02:00
pinoricci1956 efd7d788d9 correzione scroller verticale pagina di configurazione catalogo 2026-09-16 11:59:51 +02:00
Codex b1c510a097 fix(docs): preserve theme assets in deny-by-default publication
Publish documentation / publish (push) Successful in 36s
2026-09-16 09:36:30 +02:00
Codex 5f3680a0fb docs: record verified live manual publication
Publish documentation / publish (push) Successful in 28s
2026-09-15 14:39:46 +02:00
Codex 4ff91e8d6e docs: consolidate historical records and verify public manual publication
Publish documentation / publish (push) Successful in 29s
2026-09-15 14:37:29 +02:00
Codex 5f3a7f5975 docs: record stale public site publication blocker
Publish documentation / publish (push) Successful in 23s
2026-09-15 10:28:49 +02:00
Codex 043ffdfad6 docs: separate public manual from internal project documentation
Publish documentation / publish (push) Successful in 27s
2026-09-15 10:26:35 +02:00
Codex 6a4634dcf1 Merge manual standalone installation documentation
Publish documentation / publish (push) Successful in 35s
2026-09-15 10:06:33 +02:00
Codex 84804be9f8 docs: publish bilingual manual standalone installation guides 2026-09-15 10:06:28 +02:00
User c3caba94dd fix(ui): expand session dialogs and repeat confirmation actions
Publish documentation / publish (push) Successful in 24s
2026-09-14 18:13:53 +02:00
User b1723c34c4 docs: record server rollout of session and memory fixes
Publish documentation / publish (push) Successful in 32s
2026-09-14 17:25:23 +02:00
User d6cdffea62 fix: keep embedded session controls visible and handle empty memory
Publish documentation / publish (push) Successful in 34s
Cap the embedded shell at its portal container height so steering and stop controls remain accessible. Skip vector retrieval for an empty authoritative Memory archive and compute SQL-rule embeddings lazily.

Validated with 54 Memory tests, 90 frontend tests, five browser scenarios, frontend and Docker builds, and a read-only comparison against the real empty Memory archive.
2026-09-14 17:15:00 +02:00
Codex 49333a2d35 Merge full and embedded shell, administration UI and server handoff
Publish documentation / publish (push) Successful in 1m21s
2026-09-14 15:08:47 +02:00
Codex b006b94479 docs: prepare server Codex deployment handoff for ThothII and Omics 2026-09-14 15:08:46 +02:00
Codex bdcd8fcd28 fix(ui): open one session accordion panel at a time 2026-09-14 01:09:45 +02:00
Codex cf90c1bd51 fix(ui): collapse session lists and scope selection controls to panels 2026-09-13 18:12:27 +02:00
Codex 571a4bcaa2 fix(ui): show workspace readiness dot and bounded session accordions 2026-09-13 17:39:33 +02:00
Codex 9051463654 docs: document full and embedded rendering with server authentication 2026-09-13 17:28:10 +02:00
Codex 26c5605ff7 fix(ui): unify Memory and Evidence reading typography 2026-09-13 17:07:37 +02:00
Codex 3535fda958 fix(ui): improve knowledge reading and add isolated formatting examples 2026-09-13 16:52:53 +02:00
Codex 2953f6b608 fix(ui): unify Session navigation and restore uniform tab borders 2026-09-13 16:22:20 +02:00
Codex 45db3a239b fix(ui): simplify login and suppress pointer focus ring on locale select 2026-09-13 15:57:57 +02:00
Codex 7d826e46c0 fix(ui): match Omics header and compact workspace layout 2026-09-13 15:36:08 +02:00
Codex 648434a32e docs: record approved Omics GitHub to PSD relay handoff 2026-09-13 15:22:30 +02:00
Codex 023b822f83 Merge visual review into full shell and preserve bilingual layout 2026-09-13 14:55:58 +02:00
Codex d8a29bfbdd Add full shell, replaceable Omics adapter and bilingual interaction
Implement approved specification #32 and tickets #33-#37. Keep host authentication server-verified and pin session interaction language. Compile scoped base selectors for browser compatibility and retain full gutters during CSS pruning.
2026-09-13 14:26:39 +02:00
Codex a59624a68f style: align global context panel and simplify selection copy 2026-09-13 10:43:42 +02:00
Codex 5af4408194 style: unify database block gutters and content alignment 2026-09-13 10:32:55 +02:00
Codex e088abd60a style: align catalog status with summary grid 2026-09-13 01:44:48 +02:00
Codex 803e9e9201 fix: remeasure composer after hidden Core becomes visible 2026-09-13 01:39:19 +02:00
Codex 8c81996896 style: place catalog status indicators after their labels 2026-09-13 01:23:46 +02:00
Codex eed398e569 style: restore prominent ThothII application wordmarks 2026-09-13 01:18:06 +02:00
Codex c8d276ddc6 style: unify workbench typography and prepare isolated visual review 2026-09-12 22:51:58 +02:00
Codex 2d1b714ebe fix: resolve admin issue review findings and record verification 2026-09-12 18:24:23 +02:00
Codex c7e5f295e6 fix: address administration layout and navigation issues #28 #29 #30 #31 2026-09-12 18:16:52 +02:00
Codex f52bf22e05 feat: establish unified administration and model context baseline 2026-09-12 18:03:15 +02:00
Codex 840344706f prototype: restore original Core within context shelf alternatives 2026-09-12 14:00:52 +02:00
Codex 41b9fed4d5 prototype: refine context shelf with remembered defaults and session tabs 2026-09-12 12:29:02 +02:00
Codex 36bf659ea9 prototype: explore global context with one operation at a time 2026-09-12 11:53:52 +02:00
Codex 4a67d60233 prototype: revisit five administration workflows after design review 2026-09-10 19:40:21 +02:00
Codex debb63d87b prototype unified administration page layouts 2026-09-10 16:48:25 +02:00
Codex 3943022a97 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	mkdocs.yml
2026-09-10 12:57:43 +02:00
Codex f5ec2d9313 docs: track security evidence and research notes 2026-09-10 12:53:13 +02:00
Codex 82e2c91f42 feat: implement memory and evidence administration with guided repairs
Publish documentation / publish (push) Successful in 1m27s
Add PostgreSQL-backed memory, editable evidence with source review and activation, and human-approved archive repairs across the harness, API, and UI. Include migrations, deployment support, regression coverage, and validation documentation.

Refresh permissions from validated session roles so existing administrator logins can access newly deployed archive management features.
2026-09-10 10:31:34 +02:00
User 8fe526dd6e fix(frontend): show session catalog in pi management 2026-09-08 14:58:18 +02:00
User e68e80a33d fix(frontend): prevent catalog header overlap 2026-09-08 14:35:36 +02:00
Codex 818563c408 fix(core): keep workspace runtime available 2026-09-08 13:37:10 +02:00
Codex 50c546e42d fix(frontend): accept catalog-owned workspace descriptors 2026-09-07 15:01:31 +02:00
Codex 651a5c7902 fix(frontend): isolate administration rail from portal CSS 2026-09-07 11:05:38 +02:00
724 changed files with 223066 additions and 18463 deletions
+5
View File
@@ -17,6 +17,7 @@ frontend/vite.database-management-prototype.config.ts
!deploy/env/*.env.example !deploy/env/*.env.example
deploy/thothii.env deploy/thothii.env
deploy/secrets/ deploy/secrets/
deploy/psd/
harness/workspaces/*.yaml harness/workspaces/*.yaml
!harness/workspaces/local.yaml !harness/workspaces/local.yaml
!harness/workspaces/tht.example.yaml !harness/workspaces/tht.example.yaml
@@ -29,3 +30,7 @@ coverage/
data/ data/
sessions/ sessions/
workspace-registry/ workspace-registry/
.tht/
deploy/local/
+20 -4
View File
@@ -7,6 +7,11 @@ on:
paths: paths:
- "docs/**" - "docs/**"
- "mkdocs.yml" - "mkdocs.yml"
- "scripts/build-docs.sh"
- "scripts/verify-public-docs.py"
- "scripts/test-verify-public-docs.py"
- "scripts/verify-auth-docs.py"
- "scripts/test-verify-auth-docs.py"
- "docs/requirements.txt" - "docs/requirements.txt"
- ".gitea/workflows/publish-docs.yml" - ".gitea/workflows/publish-docs.yml"
workflow_dispatch: workflow_dispatch:
@@ -34,14 +39,25 @@ jobs:
with: with:
python-version: "3.x" python-version: "3.x"
cache: pip cache: pip
cache-dependency-path: docs/requirements.txt cache-dependency-path: docs/requirements.lock
- name: Install MkDocs dependencies - name: Install MkDocs dependencies
run: python -m pip install -r docs/requirements.txt run: python -m pip install -r docs/requirements.lock
- name: Test public documentation boundary
run: python scripts/test-verify-public-docs.py
- name: Test current authentication documentation
run: |
python scripts/verify-auth-docs.py auth
python scripts/verify-auth-docs.py dwh
python scripts/test-verify-auth-docs.py auth
python scripts/test-verify-auth-docs.py dwh
- name: Build documentation - name: Build documentation
# Some documented source files intentionally live outside docs/. run: |
run: mkdocs build mkdocs build --strict
python scripts/verify-public-docs.py
- name: Publish generated site to the pages branch - name: Publish generated site to the pages branch
working-directory: site working-directory: site
+1
View File
@@ -46,6 +46,7 @@ deploy/secrets/*
# Per-installation configuration generated by `tht setup` (examples stay tracked). # Per-installation configuration generated by `tht setup` (examples stay tracked).
deploy/*/thothii-installation.yaml deploy/*/thothii-installation.yaml
deploy/*/operator.env deploy/*/operator.env
deploy/*/auth/
deploy/*/generated/ deploy/*/generated/
deploy/*/secrets/* deploy/*/secrets/*
!deploy/*/secrets/.gitkeep !deploy/*/secrets/.gitkeep
+13 -3
View File
@@ -12,7 +12,7 @@ Use the canonical labels `needs-triage`, `needs-info`, `ready-for-agent`, `ready
### Domain docs ### Domain docs
This is a single-context repository with root `CONTEXT.md` and `docs/adr/`. See `docs/agents/domain.md`. This is a single-context repository with root `GLOSSARY.md` and `docs/adr/`. See `docs/agents/domain.md`.
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository. This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
@@ -98,8 +98,18 @@ frontend (React/SSE) → backend (Fastify) → pi --mode rpc → tht/harness →
- **`tht`'s `-c`/`--config` is a PER-COMMAND option** — it must follow the subcommand, never - **`tht`'s `-c`/`--config` is a PER-COMMAND option** — it must follow the subcommand, never
precede it (`ThtRunner.buildArgv` enforces this; prepending caused live 500s). precede it (`ThtRunner.buildArgv` enforces this; prepending caused live 500s).
- **`--json` output must be pristine** (only valid JSON on stdout) — used as a machine contract. - **`--json` output must be pristine** (only valid JSON on stdout) — used as a machine contract.
- **UI strings are English; document *content* stays the workspace language** (Italian for - **Localization:** deterministic UI uses the EN/IT catalogs with English fallback;
`psd`) because it's the real data. Only chrome/labels are English. model interaction uses the session manifest's immutable `interaction_language`.
Workspace content, SQL, and identifiers remain unchanged. For shell modes, portal
integration, or translations, read `docs/operations/shell-and-localization.md`.
- **Server deployment:** for the coordinated ThothII/Omics upgrade, follow
`docs/operations/server-codex-handoff.md`; it supersedes earlier Omics delivery
instructions. Omics source integration uses GitHub with no repository relay prerequisite.
- **Server identity:** for portal login/logout, proxy headers, or Omics deploy, read
`docs/install/authentication-upstream.md` before changing authentication. Omics
uses embedded/upstream, not a second ThothII OIDC login. Full/embedded rendering
is documented in `docs/architecture/application-shell.md`; release acceptance
is in `docs/testing/authentication-manual-acceptance.md`.
- **Workspace schema v4** defines workspace identity and optional Evidence only. PostgreSQL Metadata - **Workspace schema v4** defines workspace identity and optional Evidence only. PostgreSQL Metadata
Catalog owns database identity, binding, schema, descriptions, sensitivity, and relationships; Catalog owns database identity, binding, schema, descriptions, sensitivity, and relationships;
embedding/model facts come from the installation catalog. The legacy `harness/workspaces/*.yaml` runtime snapshots still use embedding/model facts come from the installation catalog. The legacy `harness/workspaces/*.yaml` runtime snapshots still use
-508
View File
@@ -1,508 +0,0 @@
# Contesto di dominio di ThothII
## Architettura del workflow
**Workflow Kernel** — Il coordinatore deterministico che possiede lo stato del workflow,
le transizioni, il rollback, la finalizzazione e l'applicazione atomica degli esiti dei
moduli.
**Workflow Module** — Una capacità incapsulata che espone un contratto versionato. Un
modulo può partecipare a più stage e non modifica direttamente lo stato del workflow.
**Stage** — Un punto del workflow, identificato semanticamente, nel quale viene invocato
un modulo. L'identità dello stage è indipendente dalla sua posizione visiva.
**Display code** — L'etichetta di presentazione associata a uno stage, per esempio da
`F1` a `F8`. I display code alimentano gli indicatori di avanzamento nel frontend, ma non
sono usati come identità del workflow o chiavi di dipendenza.
**Module outcome** — Il risultato proposto da un modulo: eventi tipizzati, modifiche agli
artifact, un'eventuale richiesta di revisione umana e uno stato di esecuzione. Il
Workflow Kernel valida e applica l'esito.
**Revision request** — La proposta tipizzata con cui un modulo segnala che lo stage
corrente non può concludersi validamente senza rieseguire lo stesso stage o uno stage
precedente. Non produce direttamente una transizione: il Workflow Kernel valida la
richiesta, sospende l'avanzamento e, per riaprire uno stage già completato, attende una
decisione umana tipizzata. Il Kernel, non il modulo, determina gli eventi e gli artifact
causalmente da rendere stale.
**Question Admission** — Il controllo preliminare eseguito prima delle fasi da `F1` a
`F8`. Nella prima release distingue una domanda utilizzabile da input garbage e verifica
che la domanda appartenga allo scope dichiarato dal workspace. Il suo stato è mostrato
separatamente dagli otto indicatori di fase.
**Workspace scope** — La dichiarazione gestita e versionata di ciò che il database di un
workspace rappresenta e delle domande alle quali è destinato a rispondere. Question
Admission la usa come riferimento per valutare la pertinenza di una domanda.
**Datamart Plugin** — Il modulo sostituibile che implementa lo stage semantico
`datamart`, presentato con display code `F8`. La promozione della memory e la
finalizzazione della sessione non appartengono al Datamart Plugin.
**Ordered workflow** — La pipeline deterministica composta dal preflight Admission,
dagli otto stage principali ordinati da `F1` a `F8` e dalla finalizzazione. L'ordine
degli stage è esplicito; il workflow non è un DAG generale.
**Extension point** — Una posizione semantica nel lifecycle dell'Ordered workflow alla
quale possono contribuire uno o più moduli senza diventare nuovi stage visibili. Un
extension point non possiede un display code.
**Stage state** — La proiezione deterministica degli eventi del workflow che descrive
uno stage come `pending`, `ready`, `running`, `awaiting_human`, `completed`, `skipped` o
`failed`. Non è un valore corrente memorizzato separatamente dal ledger.
**Required contribution** — Il contributo di un modulo a un extension point che deve
concludersi o essere esplicitamente saltato secondo policy prima che il workflow possa
avanzare.
**Best-effort contribution** — Il contributo di un modulo il cui fallimento viene
registrato e mostrato come warning, ma non impedisce al workflow di avanzare.
**Blocked workflow** — La proiezione complessiva di un workflow che non può avanzare a
causa di uno stage o di un contributo required fallito o non disponibile. `Blocked` non
è uno Stage state autonomo.
**Module invocation** — Una singola richiesta del Workflow Kernel a un modulo in uno
stage o extension point. Conserva la stessa identità attraverso eventuali retry, che
sono tentativi distinti della medesima invocation.
**Stage skip** — La conclusione esplicita di uno stage senza eseguirne il comportamento.
È ammessa soltanto dalla policy dello stage e registra motivo e attore; un fallimento non
equivale mai implicitamente a uno skip.
**Stage reopen** — La riapertura di uno stage non finalizzato che rende stale gli esiti
causalmente successivi. Gli effetti esterni già prodotti richiedono una marcatura o una
compensazione esplicita e non sono presentati come automaticamente annullati. Può essere
applicata dal Workflow Kernel in seguito all'approvazione di una Revision request, ma
non può essere eseguita direttamente da Pi o da un Workflow Module.
**Completion policy** — La regola con cui uno stage si conclude: `automatic` quando il
kernel può verificarne deterministicamente l'esito, oppure `review_required` quando è
necessaria un'approvazione umana tipizzata.
**Paused session** — Una sessione interrotta intenzionalmente ma resumibile. L'azione
“Stop and save” mette la sessione in pausa; non la completa e non la marca come fallita.
**Finalized session** — Una sessione completata con esito canonico e immutabile. Una
correzione successiva crea una nuova sessione derivata, collegata a quella precedente.
**After-finalize hook** — Una notifica o attività best-effort eseguita tramite outbox
dopo la finalizzazione. Non può modificare il ledger, gli artifact canonici o lo stato
terminale della sessione.
## Evidence
**Evidence Module** — Il modulo autonomo che possiede la preparazione delle Evidence e
la loro consultazione durante il workflow. La preparazione avviene fuori dalle singole
sessioni; il workflow usa soltanto contenuti già pubblicati. A runtime contribuisce agli
stage semantici esistenti, senza diventare uno stage visibile e senza modificare ledger,
artifact o stato del workflow.
**Source Evidence** — Un documento originale del workspace, conservato senza modifiche
come riferimento umano e origine della successiva ristrutturazione.
**Evidence Unit** — La più piccola unità semantica coerente, revisionabile e ricercabile
derivata da una sola Source Evidence. Possiede un identificatore stabile indipendente
dal kind, assegnato una volta nella forma `evidence:<slug>`; fonti diverse non vengono
fuse automaticamente.
**Evidence kind** — La categoria semantica di una Evidence Unit, che ne determina i
campi specifici e ne orienta l'uso. Ogni unità ha un solo kind primario; i tipi iniziali
sono `glossary`, `domain`, `enum`, `example`, `mapping`, `normalization`, `formula` e
`reference`.
**Glossary Evidence** — Una Evidence Unit che definisce il significato linguistico, i
sinonimi o le varianti di un termine.
**Domain Evidence** — Una Evidence Unit che esprime una regola o un vincolo del dominio
non rappresentato da un kind più specifico.
**Enum Evidence** — Una Evidence Unit che collega un insieme finito di valori
memorizzati ai relativi significati.
**Example Evidence** — Una Evidence Unit che associa un input o una domanda alla sua
interpretazione o al risultato atteso.
**Mapping Evidence** — Una Evidence Unit che collega un concetto logico agli elementi
del relativo schema fisico.
**Normalization Evidence** — Una Evidence Unit che descrive la trasformazione di una
rappresentazione in una forma canonica.
**Formula Evidence** — Una Evidence Unit che contiene una singola espressione PostgreSQL
componibile e ne dichiara gli input. Una query SQL completa non è una Formula Evidence.
**Reference Evidence** — Una Evidence Unit che rappresenta un collegamento esterno da
restituire come contenuto autonomo, anziché come semplice provenienza.
**Evidence purpose** — La destinazione dichiarata di una Evidence Unit nel workflow:
disambiguation, rewriting, schema linking o SQL generation. È distinta dall'Evidence
kind: il tipo descrive cosa contiene, il purpose quando può essere utile; durante la
ricerca il purpose richiesto è un filtro obbligatorio. Il recupero di esperienze e
soluzioni precedenti appartiene al Memory Module e non è un Evidence purpose.
**Evidence Search Outcome** — Il risultato tipizzato di una consultazione del modulo
Evidence. Distingue una ricerca disponibile, che può legittimamente non trovare
corrispondenze, da un'indisponibilità tecnica che impedisce allo stage chiamante di
avanzare fino a un retry riuscito.
**Evidence receipt** — La traccia minima di una consultazione disponibile conservata
nella sessione: stage semantico, purpose, generazione interrogata e identificatori delle
Evidence restituite. Non duplica il contenuto delle Evidence.
**Curated Evidence** — Una o più Evidence Unit ristrutturate a partire da una Source
Evidence e conservate nel repository del workspace come proposte per la revisione
umana. Git conserva la versione precedente e rende visibile ogni modifica; una Curated
Evidence non è ancora contenuto autorevole del runtime.
**Published Evidence** — Le Curated Evidence valide appartenenti alla revisione attiva
del workspace e alla generazione Evidence pubblicata. L'approvazione umana precede
l'attivazione, ma non viene duplicata come stato nel manifest.
**Evidence Index** — La proiezione ricercabile e ricostruibile delle Published Evidence.
Accelera il recupero delle informazioni, ma non è una fonte di verità.
**Evidence preparation** — Il processo di authoring che trasforma Source Evidence in
Curated Evidence mediante estrazione e normalizzazione deterministiche, una singola
ristrutturazione assistita dal modello e una validazione finale deterministica. Nella
prima versione accetta Markdown o testo UTF-8 e non acquisisce automaticamente il
contenuto di URL o documenti esterni. Prepara l'intero insieme delle modifiche in
un'area temporanea e lo applica atomicamente soltanto se tutti gli output sono validi;
non ritenta automaticamente una chiamata al modello fallita.
**Supporting excerpt** — Un breve estratto presente nel Source Evidence che sostiene
una Evidence Unit. Il sistema ne verifica deterministicamente la presenza dopo la
normalizzazione meccanica; il curatore resta responsabile di verificarne la sufficienza
semantica.
**Evidence resolution** — L'operazione esplicita con cui un curatore ritira una
Evidence Unit oppure la ricollega a un Source Evidence esistente. Aggiorna documento e
manifest insieme, lascia un diff Git revisionabile e non pubblica né crea commit.
**Review item** — Un blocco di revisione descritto da codice stabile, messaggio umano e
campo opzionale. Finché viene mantenuto nell'Evidence Unit, ne impedisce la
pubblicazione; la sua storia è conservata da Git, non da uno stato interno all'item.
**Retirement candidate** — Una Curated Evidence che il Source Evidence esistente non
sostiene più. Rimane visibile con un Review item e blocca la pubblicazione finché il
curatore non la elimina oppure la rende nuovamente coerente con il sorgente.
**Evidence evaluation set** — Un piccolo insieme versionato di domande rappresentative
e relativi risultati attesi. La baseline è accettabile quando ogni domanda recupera
almeno un risultato atteso nei primi dieci risultati della fusione RRF; il risultato
nei primi cinque è informativo. Comprende almeno un caso lessicale, uno semantico e uno
misto e conserva, a fini diagnostici, le posizioni dense, BM25 e fused.
**Candidate Evidence Generation** — Una generazione completa dell'Evidence Index che
può essere valutata ma non è ancora visibile alle sessioni. Diventa attiva soltanto se
supera l'Evidence evaluation set.
**Evidence manifest** — Il file versionato e gestito dal sistema che collega ogni
Source Evidence al suo hash e alle Evidence Unit derivate. Conserva gli identificatori
stabili, permette l'elaborazione incrementale e segnala le unità rimaste orfane senza
cancellarle automaticamente.
**Orphaned Evidence Unit** — Una Curated Evidence il cui Source Evidence non esiste più.
Rimane disponibile per la revisione, ma blocca la pubblicazione finché non viene
eliminata, ricollegata oppure ne viene ripristinato il sorgente.
**Evidence Fragment** — Una proiezione ricercabile di una sezione semanticamente
coerente di una Published Evidence. La divisione segue intestazioni e confini di
paragrafo; formule, coppie valore/significato, mapping, regole e URL non vengono mai
tagliati. Il testo completo reso per il frammento usa il solo limite esistente
`max_chunk_chars`, pari per default a 4.000 caratteri; un elemento atomico troppo grande
produce un Review item bloccante. Qdrant indicizza i frammenti, mentre l'Evidence Module
li raggruppa per Evidence Unit.
**Evidence Result** — La rappresentazione di una singola Evidence Unit restituita dalla
ricerca con metadati, migliori estratti, provenienza e riferimento al documento completo.
**Hybrid Evidence retrieval** — La ricerca che combina in Qdrant una graduatoria
semantica dense e una graduatoria lessicale BM25 sparse mediante Reciprocal Rank
Fusion. I metadati tipizzati restringono o orientano i risultati senza creare una
collezione separata per ogni Evidence kind.
**Evidence query text** — La rappresentazione deterministica condivisa dalla ricerca
dense e BM25: domanda originale, concetti, tabelle e colonne in ordine fisso. I campi
vuoti sono omessi; domanda e contesto ricevono soltanto normalizzazione Unicode NFC,
conversione degli a-capo e rimozione degli spazi esterni. Gli elementi contestuali sono
poi deduplicati e ordinati senza conversione delle maiuscole, mentre punteggiatura e
spazi interni della domanda non vengono riscritti.
**Reference Vector Collection** — La collezione Qdrant ricostruibile di un workspace che
contiene Schema, relazioni ed Evidence. Possiede il vettore dense predefinito e il vettore
sparse `bm25`; soltanto gli Evidence Fragment ricevono valori BM25. Il preprocessing può
sostituirla o eliminarla integralmente.
**Memory Vector Collection** — La collezione Qdrant persistente di un workspace che contiene
`memory` e `solved_question`. Non è un output del preprocessing e non viene eliminata dal
Preprocessing Clear.
**Preprocessing Clear** — L'operazione amministrativa che elimina Reference Vector Collection,
LSH, corpus e checkpoint derivati e rende il workspace non pronto. Conserva Memory Vector
Collection, sessioni, Catalog Metadata e database sorgente; non offre history o rollback.
**Formula proposal** — Una formula individuata durante una sessione e conservata come
artefatto della sessione. Non diventa Published Evidence finché non viene importata,
revisionata e approvata nel repository del workspace.
**Fail-closed Evidence retrieval** — Il comportamento per cui un indice assente,
incompatibile o non aggiornato produce nessuna Evidence e un avviso esplicito. Il
workflow può continuare, ma non usa mai silenziosamente contenuti di una revisione
precedente o di un altro workspace.
## Configurazione dei modelli
**Workspace Descriptor** — La dichiarazione versionata dell'identità del workspace e dello
scope delle sue Evidence. Non contiene identità o configurazione del Workspace Database,
Database Binding, fatti strutturali o metadati semantici: il Metadata Catalog associa il
workspace al relativo database.
**Installation Model Catalog** — L'insieme dichiarativo, proprio di un'installazione, dei
modelli disponibili, dei loro Model Usage e dei relativi default. È l'unica autorità per i
modelli di sessione, generazione dei metadati ed embedding e non appartiene a un workspace.
_Avoid_: Model Catalog, Metadata Generation Model Configuration
**Model Usage** — Lo scopo per cui un modello dell'Installation Model Catalog può essere
usato: `session`, `metadata_generation` oppure `embedding`. L'ammissibilità e il default
dipendono dall'uso, non dal workspace.
**Model Selection** — La scelta runtime, a livello di installazione, di un modello del
catalogo per uno specifico Model Usage. Riferisce l'identità canonica del modello senza
ridefinirne provider, endpoint o capacità.
**Model Runtime Projection** — La rappresentazione derivata e non autoritativa
dell'Installation Model Catalog richiesta da uno specifico runtime. Può essere rigenerata
integralmente dalla configurazione dell'installazione.
## Distribuzione del prodotto
**Customer-Hosted Installation** — Un'installazione eseguita interamente nel trust boundary
controllato dall'organizzazione cliente, inclusi eventuali tenant cloud privati. Credenziali,
domande, prompt, metadati e risultati non attraversano quel boundary.
_Avoid_: on-premise deployment, self-managed deployment
**Community Edition** — La distribuzione open source utilizzabile gratuitamente anche in
produzione e capace di eseguire il workflow fondamentale completo.
_Avoid_: free tier, trial edition
**Enterprise Edition** — La distribuzione con licenza commerciale che aggiunge governance
organizzativa, esercizio production-grade e industrializzazione alla Community Edition.
_Avoid_: paid tier, pro edition
## Catalogo dei metadati
**Workspace Database** — Il database che appartiene a un solo workspace e non può essere
condiviso con altri workspace; un workspace può averne al massimo uno. È considerato nella
coppia composta dal database PostgreSQL e da un solo schema: tutte le tabelle, le colonne e
le relazioni catalogate appartengono a quello schema. Il Metadata Catalog conserva
l'associazione, ma non crea né possiede l'identità del workspace.
**Database Binding** — La configurazione specifica di un'installazione che seleziona un
trasporto e fornisce i riferimenti necessari a raggiungere un Workspace Database. Non è una
seconda identità del database e non viene condivisa automaticamente fra installazioni.
**Thoth REST Connector** — Il trasporto REST tipizzato con cui ThothII interroga ed
introspeziona un Workspace Database attraverso il contratto RPC DWH supportato. Non è un
client configurabile per API REST arbitrarie.
**Orphaned Workspace Database** — Un Workspace Database il cui workspace non è più presente
nel catalogo autorevole. Rimane conservato per il recupero amministrativo, ma non può essere
usato dal workflow finché non viene riassegnato a un workspace esistente.
**Metadata Catalog** — L'autorità per l'associazione fra workspace e Workspace Database, la
relativa Database Binding, i fatti strutturali osservati e i metadati semantici curati. Ogni
uso downstream dei metadati del database deriva da questo catalogo.
**Database Profile** — L'insieme curato di scope, descrizioni e metadati semantici
associato a un Workspace Database.
**Physical Table** — Una tabella osservata nello schema esterno di un Workspace Database.
La sua identità e il suo nome appartengono al database esterno, non al Metadata Catalog.
**Catalog Table** — La rappresentazione persistita di una Physical Table nel Metadata Catalog.
La sua appartenenza e identità fisica derivano dall'introspezione: non può essere creata o
rinominata manualmente, ma può essere rimossa tramite Catalog Metadata Cleanup.
_Avoid_: SqlTable, managed table
**Physical Column** — Una colonna osservata in una Physical Table, inclusi nome, posizione,
tipo e appartenenza a chiavi dichiarate. La sua identità e i suoi fatti strutturali appartengono
al database esterno.
**Catalog Column** — La rappresentazione persistita di una Physical Column nel Metadata Catalog.
I fatti osservati sono governati dalla sincronizzazione; Description e Generated Description
sono metadati amministrativi modificabili e la rappresentazione può essere rimossa tramite
Catalog Metadata Cleanup.
_Avoid_: SqlColumn, managed column
**Physical Relationship** — Un vincolo foreign key dichiarato nel database esterno. La sua
identità comprende il vincolo e la sequenza ordinata delle coppie di colonne che lo compongono.
**Catalog Relationship** — La rappresentazione persistita di una Physical Relationship nel
Metadata Catalog. Non è creata o modificata manualmente, ma può essere rimossa tramite Catalog
Metadata Cleanup.
_Avoid_: denormalized FK, relationship string
**Logical Relationship** — Una relazione modificabile fra due Catalog Column che non corrisponde
necessariamente a un vincolo fisico. Può essere Generated o Manual e rimane distinta dalla Catalog
Relationship osservata nel database.
**Generated Relationship** — Una Logical Relationship ricavata dai nomi delle colonne, dalle
primary key e dalla compatibilità dei tipi mediante regole deterministiche, senza LLM, embedding o
campionamento dei dati. Una ricostruzione non riattiva una Generated Relationship cancellata
logicamente, ma può ricrearne una cancellata fisicamente.
**Manual Relationship** — Una Logical Relationship aggiunta dall'utente. La ricostruzione delle
Generated Relationship non la modifica.
**Logical Relationship Deletion** — L'esclusione persistente di una Logical Relationship che ne
conserva l'identità per impedirne la ricreazione automatica finché esistono entrambe le Catalog
Column alle quali è collegata.
**Permanent Relationship Deletion** — La rimozione completa di una Logical Relationship. Una
ricostruzione successiva può ricrearla quando soddisfa nuovamente le regole di inferenza. Anche il
cleanup distruttivo di una tabella o colonna endpoint rimuove permanentemente le relative esclusioni.
**Relationship Reconstruction** — L'operazione amministrativa esplicita che scopre e aggiunge le
Generated Relationship mancanti. Conserva le Manual Relationship e le relationship già presenti e
non riattiva quelle cancellate logicamente.
**Relationship Restore** — La riattivazione esplicita di una Logical Relationship cancellata
logicamente.
**Effective Relationship Map** — La vista unificata delle Catalog Relationship fisiche e delle
Logical Relationship, con origine e stato espliciti. È l'interfaccia usata dall'amministrazione e
dalla comprensione dello schema, non un ulteriore modello persistito.
**Catalog Metadata Snapshot** — La proiezione immutabile e versionata della struttura catalogata,
delle descrizioni pubblicabili e delle relazioni effettive attive di un Workspace Database che il
core consuma. È derivata esclusivamente dal Metadata Catalog e non è un archivio autoritativo.
**Schema Index** — La proiezione vettoriale ricostruibile dei metadati del Workspace Database nel
Metadata Catalog. Il preprocessing la sostituisce integralmente e non è una fonte di verità.
**Description** — Il testo curato e consolidato che descrive una Catalog Table o Catalog Column
per gli usi downstream. Quando presente, prevale sulla relativa Generated Description.
**Generated Description** — Il testo modificabile prodotto dall'AI per una Catalog Table o Catalog
Column. È pubblicabile per gli usi downstream quando manca una Description, anche senza essere
prima consolidato, e rimane distinto dal commento osservato nel database.
_Avoid_: generated comment, source comment
**Description Consolidation** — L'azione amministrativa esplicita che copia la Generated
Description di Catalog Table o Catalog Column selezionate nella relativa Description. Opera sulla
selezione corrente, conserva la Generated Description e non modifica il commento osservato o il
database esterno.
**Table Synchronization** — La riconciliazione esplicita che rende le Catalog Table di un
Workspace Database uguali alle Physical Table osservate: crea quelle nuove, aggiorna i metadati
di origine ed elimina definitivamente quelle assenti. Non modifica mai il database esterno.
_Avoid_: table import
**Schema Synchronization** — La riconciliazione esplicita e autorevole di tabelle, colonne e
Catalog Relationship di un Workspace Database. Può operare su uno scope specifico oppure su
un unico snapshot completo tramite Synchronize All.
**Catalog Sync Run** — L'esecuzione durevole in background di una Schema Synchronization, con
scope, stato, avanzamento e log propri. Al massimo un run per Workspace Database può essere attivo.
**Description Generation Run** — L'esecuzione asincrona e sequenziale che usa il modello scelto
per produrre Generated Description di Catalog Table o Catalog Column. Al massimo una run è attiva
nell'intera installazione e ogni risultato valido viene salvato appena disponibile. Dopo
un'interruzione il recupero è manuale tramite una nuova generazione dei soli elementi mancanti.
**Description Generation Event** — Una riga testuale ordinata che registra avanzamento, risultato
o errore di una Description Generation Run e alimenta il log visibile all'amministratore.
**Non-generatable Description** — L'esito valido con cui il modello dichiara di non disporre di
informazioni sufficienti per descrivere il target. Produce una Generated Description standard
nella lingua del workspace e non rappresenta un timeout, un errore del provider o una risposta
non valida.
**Description Generation Unlock** — Il recupero amministrativo che marca come interrotta una
Description Generation Run registrata come attiva quando il backend non ha alcun processo di
generazione vivo. Non è un meccanismo di lock distribuito.
**Catalog Metadata Cleanup** — La rimozione amministrativa esplicita di Catalog Table, Catalog
Column o Catalog Relationship selezionate. Non modifica il Workspace Database, la Database Binding
o i segreti, e può lasciare il Metadata Catalog intenzionalmente incompleto fino alla prossima
Schema Synchronization.
**Catalog Freshness** — La corrispondenza fra uno scope sincronizzato e la versione corrente
della Database Binding. Uno scope rimane consultabile ma è stale finché non viene sincronizzato
con la binding corrente.
**Metadata Content Revision** — La revisione monotona di tutto lo stato del Metadata Catalog che
può modificare il comportamento del core. Ogni mutazione rilevante produce una nuova revisione
nella stessa transazione che la rende durevole.
**Preprocessing State** — Lo stato corrente `running`, `succeeded` o `failed` del preprocessing di
un workspace, insieme all'identità dei suoi input. Il core può usare il workspace soltanto quando
lo stato è `succeeded` e gli input coincidono ancora.
**Catalog Metadata** — I campi mutabili che descrivono database, tabelle, colonne e relazioni,
distinti dai fatti strutturali governati dalla sincronizzazione. Possono essere popolati dall'AI,
o da una modifica amministrativa senza cambiare il database esterno.
**Model Completion Helper** — Il processo Python interno ed effimero che esegue una singola
richiesta LiteLLM per conto del backend. Non è un servizio HTTP, non possiede il lifecycle della
Description Generation Run e non è una CLI esposta agli utenti.
**Catalog Sample** — Un input transitorio composto da un massimo di cinque righe e da valori di
esempio bounded di una Catalog Table per la generazione delle descrizioni. Può contenere valori
reali oppure sintetici in base alla Source Value Disclosure Decision; non viene persistito e non
diventa Catalog Metadata.
**Sensitive Data Flag** — La classificazione binaria umana applicata a una Catalog Column. Può
essere impostata liberamente dall'amministratore anche in contrasto con una valutazione automatica.
**Sensitivity Reason** — La motivazione sanificata persistita insieme al Sensitive Data Flag
quando l'amministratore salva una Sensitivity Review Draft. È Catalog Metadata della colonna, non
history della run; viene rimossa quando il flag torna non-sensitive e può essere assente per una
classificazione manuale priva di valutazione locale.
_Avoid_: AI reasoning, source evidence
**Local Sensitivity Assessment** — La valutazione locale, non autoritativa e priva di LLM di una
Catalog Column, basata su metadati e contenuto sorgente, con esito `sensitive`, `non_sensitive`
oppure `unknown`.
_Avoid_: AI suggestion, automatic flag
**Local NER Detector** — Il componente NLP opzionale e CPU-only che esamina soltanto testo ancora
ambiguo e restituisce evidenze al Local Sensitivity Assessment. Non decide lo stato della colonna,
non usa un LLM generativo e non persiste valori sorgente.
_Avoid_: AI classifier, local LLM fallback
**Model Data Boundary** — La qualificazione amministrativa di un modello come `internal` oppure
`external` rispetto al confine entro cui i valori sorgente possono essere comunicati.
_Avoid_: local model, remote model
**Source Value Disclosure Decision** — L'unica decisione effettiva che stabilisce se un modello
riceve valori sorgente reali oppure sostituti sintetici, combinando Model Data Boundary e Sensitive
Data Flag.
_Avoid_: sample filter, export flag
**Sensitive Data Policy** — L'insieme versionato di regole locali generali e specifiche che produce
una Local Sensitivity Assessment. Un singolo riscontro blocca l'intera colonna e qualsiasi valore
testuale più lungo di 500 caratteri rende sensibile la colonna.
_Avoid_: PII filter, sample filter
**Sensitivity Analysis Run** — Il tentativo amministrativo esplicito e tracciato che valuta una
selezione di colonne mediante la Sensitive Data Policy. Conserva stato, copertura e conteggi
aggregati, ma non valori sorgente né esiti per colonna.
_Avoid_: Sensitive Data Suggestion Run, AI analysis
**Sensitivity Review Draft** — La proposta transitoria che associa alle colonne selezionate una
Local Sensitivity Assessment e le relative evidenze sanificate. Non modifica il Sensitive Data Flag
né la Sensitivity Reason finché l'amministratore non salva le proprie decisioni e viene scartata al
reload.
_Avoid_: automatic flag
**Sensitivity Analysis Event** — Una riga testuale ordinata e sanificata che registra l'avvio,
l'avanzamento per fase e batch, l'esito o l'errore di una Sensitivity Analysis Run senza conservare
contenuti sorgente, output grezzi del detector o proposte per colonna.
_Avoid_: Sensitive Data Suggestion Event
**Introspection Capability** — Una categoria di struttura fisica che una Database Binding
può osservare, come tabelle, colonne, relazioni, indici o enum. Una capability non disponibile
è distinta da una capability osservata che non ha restituito elementi.
+146 -44
View File
@@ -11,50 +11,50 @@ colors:
warm-graphite: "oklch(26.78% 0.0097 355.6)" warm-graphite: "oklch(26.78% 0.0097 355.6)"
muted-graphite: "oklch(51.33% 0.0088 345.6)" muted-graphite: "oklch(51.33% 0.0088 345.6)"
quiet-border: "oklch(90.93% 0.0035 354.7)" quiet-border: "oklch(90.93% 0.0035 354.7)"
success-mint: "oklch(75.77% 0.1581 165)" success-mint: "oklch(46% 0.095 160)"
navigation-active: "oklch(92.5% 0.052 23.2)" navigation-active: "oklch(92.5% 0.052 23.2)"
navigation-active-hover: "oklch(89.5% 0.071 23.2)" navigation-active-hover: "oklch(89.5% 0.071 23.2)"
navigation-active-foreground: "oklch(36.5% 0.11 23.2)" navigation-active-foreground: "oklch(36.5% 0.11 23.2)"
navigation-active-border: "oklch(60% 0.135 23.2)" navigation-active-border: "oklch(60% 0.135 23.2)"
warning-amber: "oklch(85.23% 0.1386 78.9)" warning-amber: "oklch(48% 0.09 70)"
information-blue: "oklch(70.35% 0.1128 221.3)" information-neutral: "oklch(51.33% 0.0088 345.6)"
typography: typography:
display: display:
fontFamily: "Fraunces, Source Serif Pro, Georgia, Times New Roman, serif" fontFamily: "Manrope Variable, Manrope, system-ui, sans-serif"
fontSize: "3rem" fontSize: "1.5rem"
fontWeight: 600 fontWeight: 600
lineHeight: 1.03 lineHeight: 1.03
letterSpacing: "-0.025em" letterSpacing: "-0.025em"
headline: headline:
fontFamily: "Fraunces, Source Serif Pro, Georgia, Times New Roman, serif" fontFamily: "Manrope Variable, Manrope, system-ui, sans-serif"
fontSize: "1.875rem" fontSize: "1.5rem"
fontWeight: 600 fontWeight: 600
lineHeight: 1.15 lineHeight: 1.15
letterSpacing: "-0.015em" letterSpacing: "-0.015em"
title: title:
fontFamily: "Fraunces, Source Serif Pro, Georgia, Times New Roman, serif" fontFamily: "Manrope Variable, Manrope, system-ui, sans-serif"
fontSize: "1.2rem" fontSize: "1.25rem"
fontWeight: 600 fontWeight: 600
lineHeight: 1.25 lineHeight: 1.25
letterSpacing: "-0.01em" letterSpacing: "-0.01em"
body: body:
fontFamily: "Manrope, -apple-system, BlinkMacSystemFont, Segoe UI, system-ui, Arial, sans-serif" fontFamily: "Manrope Variable, Manrope, -apple-system, BlinkMacSystemFont, Segoe UI, system-ui, Arial, sans-serif"
fontSize: "0.9375rem" fontSize: "1rem"
fontWeight: 400 fontWeight: 400
lineHeight: 1.65 lineHeight: 1.65
letterSpacing: "normal" letterSpacing: "normal"
control: control:
fontFamily: "Manrope, -apple-system, BlinkMacSystemFont, Segoe UI, system-ui, Arial, sans-serif" fontFamily: "Manrope Variable, Manrope, -apple-system, BlinkMacSystemFont, Segoe UI, system-ui, Arial, sans-serif"
fontSize: "0.875rem" fontSize: "0.875rem"
fontWeight: 600 fontWeight: 600
lineHeight: 1.25 lineHeight: 1.25
letterSpacing: "0.005em" letterSpacing: "0.005em"
label: label:
fontFamily: "ui-monospace, SF Mono, Cascadia Code, Menlo, Consolas, monospace" fontFamily: "Manrope Variable, Manrope, system-ui, sans-serif"
fontSize: "0.6875rem" fontSize: "0.75rem"
fontWeight: 600 fontWeight: 600
lineHeight: 1.25 lineHeight: 1.25
letterSpacing: "0.06em" letterSpacing: "normal"
rounded: rounded:
xs: "4px" xs: "4px"
sm: "6px" sm: "6px"
@@ -113,6 +113,16 @@ components:
# Design System: ThothII # Design System: ThothII
## Visual review branch, September 2026
The revision on `codex/ui-visual-review` is approved for implementation and Docker visual review,
not yet for adoption on `main`. The previous look remains recoverable from the base commit and
the preserved Docker image. Historical prototypes must remain untouched.
This revision follows Impeccable's product register: one locally bundled Manrope family for the
whole UI, five fixed size roles, red as the sole brand accent and additional color only for meaningful
state. The primary scene remains an analyst reading data and SQL in a well-lit office.
## Overview ## Overview
**Creative North Star: "The Clinical Workbench"** **Creative North Star: "The Clinical Workbench"**
@@ -134,7 +144,7 @@ disciplined and tactile, never playful, sluggish, or visually unstable.
**Key Characteristics:** **Key Characteristics:**
- Warm, restrained surfaces with one scarce red accent. - Warm, restrained surfaces with one scarce red accent.
- Editorial headings paired with highly legible operational body text. - One sans-serif family, with hierarchy expressed through size, weight and spacing.
- Dense information organized through hierarchy, rhythm, and progressive disclosure. - Dense information organized through hierarchy, rhythm, and progressive disclosure.
- Persisted artifacts and reviewer decisions presented as the visual source of truth. - Persisted artifacts and reviewer decisions presented as the visual source of truth.
- Fast state feedback with reduced-motion parity. - Fast state feedback with reduced-motion parity.
@@ -150,6 +160,15 @@ users can scan structure without adding nested containers.
## Colors ## Colors
The full-mode application header matches Omics Portal's `--gsd-red-primary`
(`#CB333B`) in both themes. Its complete wordmark, including `II`, and controls
use a near-white foreground. This header is absent in embedded mode. The sidebar
and welcome wordmarks retain their red suffix. Context editing places workspace,
model and Done in one desktop row, stacking on narrow containers. Session-scope
tabs retain their selected fill and accessible keyboard state with a uniform one-pixel
border on every side, gray when inactive and red when active. Their padding is 11px
horizontal and 3px vertical, with a 38px minimum height and wrapping labels.
The palette combines warm porcelain surfaces, warm graphite text, and an instrument red used only The palette combines warm porcelain surfaces, warm graphite text, and an instrument red used only
for action, focus, and important state. OKLCH values in the frontmatter are normative because the for action, focus, and important state. OKLCH values in the frontmatter are normative because the
frontend uses OKLCH tokens directly. frontend uses OKLCH tokens directly.
@@ -178,7 +197,8 @@ frontend uses OKLCH tokens directly.
foreground. It shares Instrument Red's hue but uses a lighter, lower-chroma fill, so location is foreground. It shares Instrument Red's hue but uses a lighter, lower-chroma fill, so location is
visible without carrying the full weight of a primary action. visible without carrying the full weight of a primary action.
- **Warning Amber** (`warning-amber`): waiting, attention, and in-progress states. - **Warning Amber** (`warning-amber`): waiting, attention, and in-progress states.
- **Information Blue** (`information-blue`): informational state when red would imply action. - **Information**: neutral text and indicators for dates, protocols and ordinary status. The legacy
`--info` token resolves to muted foreground, not an additional blue accent.
The dark theme keeps the same semantic mapping with neutral near-black surfaces and a slightly The dark theme keeps the same semantic mapping with neutral near-black surfaces and a slightly
lighter red accent. Do not introduce a second visual identity for dark mode. lighter red accent. Do not introduce a second visual identity for dark mode.
@@ -191,30 +211,33 @@ for their named states. Color is never the only state indicator.
## Typography ## Typography
**Display Font:** Fraunces, with Source Serif Pro, Georgia, and Times New Roman fallbacks **UI Font:** locally bundled Manrope Variable, with Manrope and native sans-serif fallbacks.
**Body Font:** Manrope, with native system sans-serif fallbacks **Technical Font:** SF Mono or Cascadia Code, with Menlo and Consolas fallbacks.
**Label/Mono Font:** SF Mono or Cascadia Code, with Menlo and Consolas fallbacks
**Character:** Fraunces gives persisted artifacts and key headings editorial authority. Manrope Manrope covers headings, labels, controls, navigation and document reading. Monospace is reserved
keeps dense controls and prose calm and readable. The mono register separates machine identity, for SQL, code, paths and machine identifiers, never for ordinary UI labels or status headings.
metadata, SQL, identifiers, and micro-labels from natural-language content.
### Hierarchy ### Hierarchy
- **Display** (600, `3rem`, `1.03`): authentication and exceptional page-level statements only. - **Headline** (600, `1.5rem`, `1.3`): page or artifact titles, `--text-page`.
- **Headline** (600, `1.875rem`, `1.15`): major page or artifact titles. - **Title** (600, `1.25rem`, `1.4`): section hierarchy, `--text-section`.
- **Title** (600, `1.2rem`, `1.25`): panel and document section hierarchy. - **Body** (400, `1rem`, `1.6`): operational prose, `--text-body`, with a target line length of 65 to 75
- **Body** (400, `0.9375rem`, `1.65`): operational prose, with a target line length of 65 to 75
characters where the surface controls width. characters where the surface controls width.
- **Control** (600, `0.875rem`, `1.25`): buttons, inputs, tabs, and compact actions. - **Control** (400–600, `0.875rem`, `1.5`): buttons, inputs, tables, tabs and compact subheadings,
- **Label** (600, `0.6875rem`, `0.06em` tracking): uppercase micro-labels, state metadata, and panel `--text-control`.
headers. Labels use the mono family. - **Metadata** (400–600, `0.75rem`, `1.5`): secondary status, counts and timestamps, `--text-meta`.
Labels use sentence case and normal tracking. Ordinary operational text never falls below 12px.
Typography uses fixed sizes. Responsive changes happen at structural breakpoints, not through fluid Typography uses fixed sizes. Responsive changes happen at structural breakpoints, not through fluid
type scaling. Numeric data and identifiers use tabular numerals where comparison matters. type scaling. Numeric data and identifiers use tabular numerals where comparison matters.
**The Three Registers Rule.** Serif means authority, sans means interaction and reading, mono means **Application wordmark:** ThothII is a brand mark, not a page title: use Manrope semibold at
machine identity. Do not exchange these roles for novelty. 48px (`3rem`) in the Core welcome area and 32px (`2rem`) in the session sidebar, with the
`II` suffix in brand red. Preserve these sizes across responsive layouts.
**The One Family Rule.** The UI and document readers use sans-serif throughout. The legacy
`--font-heading` alias resolves to `--font-sans`. Preserve technical monospace without turning it
into a second decorative hierarchy. Do not shrink text to solve layout constraints.
**The Read Once Rule.** A heading, label, and body must be distinguishable on first glance through **The Read Once Rule.** A heading, label, and body must be distinguishable on first glance through
size and weight. Do not repeat headings in explanatory copy. size and weight. Do not repeat headings in explanatory copy.
@@ -279,27 +302,70 @@ default, hover, focus, active, disabled, loading, and error behavior where those
- **Focus:** three-pixel Instrument Red ring with a clear border shift. - **Focus:** three-pixel Instrument Red ring with a clear border shift.
- **Error / Disabled:** errors combine destructive color with explanatory text; disabled controls - **Error / Disabled:** errors combine destructive color with explanatory text; disabled controls
retain readable contrast and use 50 percent opacity. retain readable contrast and use 50 percent opacity.
- **Metadata catalog model:** Database Management keeps one compact, installation-level - **Global context:** the collapsible top shelf is the sole workspace/model selector for Core and
metadata-generation LLM selector in the application header. The selection persists across Admin. Preserve independent remembered choices, installation defaults, operation locks and unsaved
database, table, column, and relationship views; when no usable profile is configured, the edit guards. Never introduce a separate metadata-generation default or selector.
disabled control explains: “No metadata-generation LLM model is configured for this installation.”
### Navigation ### Navigation
- **Workspace readiness:** the Workspace navigation button carries an 8px dot to
the right of its label. Green means a selected workspace with confirmed ready
preprocessing and no query error; all other states are red. The button's
tooltip and accessible description retain the translated exact state. Do not
add a separate readiness text row or change the backend readiness gate.
- **Session groups:** one accessible single-open accordion contains Active sessions
and Archive, both initially closed. Below the scope tabs, show only their
adjacent section headers, without a redundant Sessions heading. Selection and
bulk-delete controls belong inside each panel and only appear for nonempty
lists. Select all affects that list only, preserves the other list's selection,
and exposes a mixed state for partial selection. Preserve the existing archived
flag as the grouping rule, independent of whether a Pi process is running.
Opening a section closes the other; either can be collapsed, including both.
Empty lists show only the translated "No sessions yet." message.
The open section uses the rail's remaining height; its list scrolls internally
with a cap of `min(18rem, 35dvh)`, while its trigger remains outside that scroll
area. The mobile navigation dialog supplies a bounded viewport-height container.
Keyboard users can focus and scroll each labelled panel.
- **Session entry:** one Session button returns to the current unfinished session,
including provisional creation, without resetting or reconnecting it. Otherwise
it prepares a new question using the normal readiness and unsaved-work guards.
- **Style:** compact session rows use `8px` corners and restrained vertical padding. - **Style:** compact session rows use `8px` corners and restrained vertical padding.
- **Default / Hover / Active:** porcelain at rest, Sunken Surface on hover, and a muted Navigation - **Default / Hover / Active:** porcelain at rest, Sunken Surface on hover, and a muted Navigation
Active red with a defined border when current. Exactly one top-level navigation control is current. Active red with a defined border when current. Exactly one top-level navigation control is current.
- **Administrative controls:** the admin-only Administration accordion groups Database management, - **Administrative controls:** the admin-only Administration accordion groups Database,
a structural divider, Workspace management, and Pi management in that order. Its trigger exposes Memory, Evidence, a structural divider, Workspace, and Pi configuration in that order. Its trigger exposes
expanded state and starts collapsed by default, while non-admin users do not receive the accordion expanded state and starts collapsed by default, while non-admin users do not receive the accordion
or its navigation actions. or its navigation actions.
- **Responsive:** collapse navigation structurally at the application breakpoint. Do not shrink - **Responsive:** collapse navigation structurally at the application breakpoint. Do not shrink
labels into illegibility. labels into illegibility. Below 768px, Memory and Evidence management use the full content
width; a Navigation button opens the shared accessible dialog. Selecting another archive
page or pressing Escape closes it. Desktop retains the right session sidebar and its My sessions /
All sessions tabs. Core retains question/answer, eight phases, reviewer gates and the left log.
In embedded mode the portal owns the red header and left sidebar; ThothII must not duplicate them. Size to the
actual application container. Narrow session document panels may use the available width.
### Session review and confirmations
Session dialogs use the visible application area, including the portal's header
and side rail. Artifact and schema-column review can grow to 80rem wide and the
available height; short confirmations use up to 40rem and at least 18rem when
space permits. Keep a 24px outer margin on desktop and 8px on small or short
screens. Long review content scrolls internally; on very short screens the
whole dialog can also scroll so every action remains reachable.
Session forms and review gates repeat their existing primary confirmation above
and below the content, sharing selection, validation, pending state and response
handlers. Alternate-response inputs follow the same rule. Reserved navigation
controls remain below the review. Stop/delete initially focus Cancel; rename
initially focuses the name field. Administration dialogs and forms retain their
existing layout and actions.
### Tabs ### Tabs
- **Shape:** compact label tabs sit on a shared baseline with rounded top corners and a two-pixel - **Shape:** compact label tabs sit on a shared baseline with rounded top corners and a two-pixel
lower edge. Inactive labels retain a complete Quiet Border and Porcelain Card surface, so every lower edge, except session-scope tabs which use a uniform one-pixel border, rounded
corners and a 4px gap without a shared border or negative bottom margin.
Inactive labels retain a Quiet Border and Porcelain Card surface, so every
label reads as a tab before interaction; hover feedback reinforces clickability. label reads as a tab before interaction; hover feedback reinforces clickability.
- **Current:** the selected tab uses the muted Navigation Active red for its fill, text, and defined border. - **Current:** the selected tab uses the muted Navigation Active red for its fill, text, and defined border.
It must expose `aria-selected`, participate in a labelled `tablist`/`tabpanel`, and be the only It must expose `aria-selected`, participate in a labelled `tablist`/`tabpanel`, and be the only
@@ -319,9 +385,42 @@ default, hover, focus, active, disabled, loading, and error behavior where those
### Curated Evidence Documents ### Curated Evidence Documents
Memory and Evidence share the `thot-knowledge-reader` reading contract. Use locally
bundled Manrope with normal tracking for prose and labels, and these fixed roles:
- Card title: 24px, weight 600, line-height 1.3 (`thot-knowledge-title`).
- Field/section heading, including Scope and Provenance: 20px, weight 600,
line-height 1.4, 8px clearance below (`thot-knowledge-heading`).
- All narrative text, including scope, lists and provenance: 16px, weight 400,
line-height 1.65. Do not apply compact UI text sizes to these fields.
- Authored Markdown subheadings inside a field: 16px, weight 600, line-height 1.5,
24px above/8px below. They remain subordinate to the enclosing field heading;
their semantic heading levels and original content are preserved.
- Technical metadata labels/values: 14px/1.5, with weight 600 for labels.
Only code, paths and machine identifiers use the technical monospace family at
14px/1.65, identical for inline and fenced code (never compound `em` shrinkage).
Separate reading sections by 24px; keep the first Markdown block flush with its
field heading's 8px bottom gap. The same typography applies in light/dark and at
all responsive widths. Controls and archive indexes retain their compact UI roles.
Memory and Evidence detail readers use the entire available content width, without
the ordinary 72–75ch prose cap. This is the owner's explicit reading-layout choice.
Long unstructured paragraphs are split for display at existing sentence/semicolon
boundaries outside inline code and links; authored Markdown structure and stored
content are unchanged. Paragraph spacing is 1.25em. Scope and provenance share the
available width; provenance excerpts render Markdown rather than literal markers.
Copy actions use the two-overlapping-sheets icon, an accessible name/tooltip and
live success/failure feedback instead of a visible Copy label.
Memory has four explicitly FAKE formatting examples, one per family, in a separate
expandable section. They reuse the real detail reader but never enter persistence,
indexing, link search or model recall, and expose no edit/delete/save actions.
Curated evidence follows a fixed reading order: title, compact type and purpose summary, scope, Curated evidence follows a fixed reading order: title, compact type and purpose summary, scope,
typed content, supporting excerpts, review items, then collapsed technical provenance. Machine typed content, supporting excerpts, review items, then technical provenance. Curated v4 files
metadata stays in invisible comments so GitHub Preview shows only the reviewable document. use short, visible YAML frontmatter for identity and classification. The Markdown title and
body are authoritative; hidden payload comments are a legacy format converted on consolidation.
`applies_to` is rendered as “Ambito di applicazione” with separate bullet lists for concepts, `applies_to` is rendered as “Ambito di applicazione” with separate bullet lists for concepts,
tables, and columns. Enum values also use lists. Tables are forbidden for metadata, scope, or any tables, and columns. Enum values also use lists. Tables are forbidden for metadata, scope, or any
@@ -329,7 +428,9 @@ one-dimensional collection; reserve tables for genuinely two-dimensional dataset
identifiers use inline code. SQL uses fenced code. Supporting excerpts use blockquotes. identifiers use inline code. SQL uses fenced code. Supporting excerpts use blockquotes.
**The Review Surface Rule.** The visible Markdown must be readable without understanding the **The Review Surface Rule.** The visible Markdown must be readable without understanding the
machine contract. Technical metadata belongs in progressive disclosure, not above the title. machine contract. In Administration, explain current and original provenance separately and
keep file-editing templates and Git instructions in progressive disclosure. Show actual host
paths with copy controls, never browser file links to container-only locations.
## Do's and Don'ts ## Do's and Don'ts
@@ -341,7 +442,8 @@ machine contract. Technical metadata belongs in progressive disclosure, not abov
- **Do** preserve information density with headings, rhythm, and progressive disclosure. - **Do** preserve information density with headings, rhythm, and progressive disclosure.
- **Do** keep keyboard focus explicit and pair color with text, shape, icon, or position. - **Do** keep keyboard focus explicit and pair color with text, shape, icon, or position.
- **Do** respect `prefers-reduced-motion` while preserving immediate non-kinetic feedback. - **Do** respect `prefers-reduced-motion` while preserving immediate non-kinetic feedback.
- **Do** use English for interface chrome and the workspace language for persisted document content. - **Do** use the selected interface language (English by default) for chrome and preserve the
workspace language for persisted domain content. Session interaction language remains pinned.
- **Do** render curated metadata and scope as Markdown prose or lists, never as a frontmatter table. - **Do** render curated metadata and scope as Markdown prose or lists, never as a frontmatter table.
- **Do** break long curated rules into paragraphs, labelled subsections, and lists at existing - **Do** break long curated rules into paragraphs, labelled subsections, and lists at existing
punctuation boundaries while preserving the exact canonical text for machines. punctuation boundaries while preserving the exact canonical text for machines.
+591
View File
@@ -0,0 +1,591 @@
# ThothII
ThothII trasforma una domanda in linguaggio naturale in SQL eseguibile su un data warehouse,
attraverso un workflow in cui un modello propone e un revisore umano decide.
## Language
### Sessione e workflow
**Workspace**:
L'ambito di lavoro che associa un database a Evidence e Memory curate per rispondere alle domande
su quel database. Ogni sessione appartiene a un solo workspace.
_Avoid_: progetto, ambiente
**Session**:
Il lavoro su una singola domanda, dalla formulazione al SQL approvato, registrato da documenti di
fase e decisioni. Appartiene all'utente che l'ha creata.
_Avoid_: chat, conversazione
**Phase**:
Uno degli otto passi ordinati del workflow, da `F1` a `F8`: chiarimento, memoria, riscrittura,
schema linking, sintesi, piano CTE, SQL finale, datamart. La fase corrente non è memorizzata ma
derivata dalle decisioni registrate.
_Avoid_: stage, step
**Phase document**:
Un artefatto prodotto da una fase, come la domanda riscritta, lo schema linking o il SQL finale.
Insieme al Decision ledger costituisce l'intero stato persistente della sessione.
_Avoid_: transcript, log della chat
**Decision**:
Una scelta registrata durante la sessione, di contenuto (per esempio una tabella promossa) o di
avanzamento (una fase approvata, saltata o riaperta).
**Decision ledger**:
La sequenza append-only delle decisioni di una sessione. Ciò che non vi è registrato non è
avvenuto.
_Avoid_: history, cronologia
**Reviewer**:
La persona che decide nei gate: accetta, corregge o rifiuta le proposte del modello.
_Avoid_: utente finale, approvatore
**Gate**:
Il punto del workflow in cui il modello si ferma e attende la decisione del revisore. Il modello
non può superarlo da solo.
_Avoid_: checkpoint, pausa
**Reviewer widget**:
La richiesta strutturata con cui un gate presenta una scelta al revisore: scelta singola, scelta
multipla in cui ogni opzione è una decisione, oppure conferma di un artefatto o di una fase.
_Avoid_: popup, form
**Phase approval**:
La decisione che conclude una fase e consente il passaggio alla successiva. Alcune fasi si
concludono automaticamente quando non hanno nulla da proporre.
**Phase skip**:
La conclusione esplicita di una fase senza eseguirne il lavoro, consentita solo dove il workflow lo
prevede.
**Phase reopen**:
Il ritorno a una fase precedente, che rende obsolete le decisioni successive ed elimina i documenti
di fase prodotti dopo quel punto.
_Avoid_: rollback, undo
**Resume**:
La ripresa di una sessione non conclusa dalla sua ultima fase incompleta, ricostruendo il contesto
dai documenti di fase e dal ledger.
_Avoid_: riavvio, nuova domanda
**Paused session**:
Una sessione interrotta intenzionalmente con "Interrompi e salva", che resta riprendibile. Non è
completata né fallita.
_Avoid_: closed session
**Finalized session**:
Una sessione completata, con esito canonico e immutabile. Una correzione successiva richiede una
nuova sessione.
**Archived session**:
Una sessione spostata fuori dall'elenco attivo e di sola lettura, indipendentemente dal suo esito.
Il ripristino la riporta nell'elenco attivo.
**CTE plan**:
La scomposizione della query finale in passaggi intermedi approvati singolarmente dal revisore
prima del SQL finale.
**Datamart**:
L'ultima fase, che decide come rendere disponibile il risultato approvato e quali conoscenze
promuovere in Memory.
**Interaction language**:
La lingua in cui il modello presenta domande, spiegazioni e proposte al revisore. È fissata alla
creazione della sessione e non cambia alla ripresa.
_Avoid_: lingua della UI, lingua del workspace
### Integrazione ETL
**Delivery Destination**:
Una destinazione predisposta per ricevere il SQL oppure integrarlo in un ETL. Le destinazioni
disponibili e il default per workspace dipendono dall'installazione.
**SQL Delivery**:
La consegna di un artefatto SQL alla destinazione scelta. Da sola non attesta l'inclusione del SQL
in un ciclo ETL.
**Delivery Operation**:
Un'operazione tracciata di consegna SQL o integrazione ETL, collegata alla sessione che ha prodotto
il SQL approvato. Ha un esito distinto dalla sessione e può essere riprovata senza riaprirla.
**ETL Activation**:
L'inclusione esplicitamente autorizzata di un modello nel ciclo ETL della destinazione, distinta
dalla consegna dell'artefatto e dalla sua esecuzione immediata.
### Memory
**Memory Module**:
Il modulo che possiede le conoscenze e le esperienze curate per migliorare schema linking e
generazione SQL delle domande future. Le Memory appartengono a un workspace e restano distinte
dalle Evidence.
**Memory Card**:
L'unità di contenuto gestibile del Memory Module, con identità, ambito di applicazione e
provenienza.
_Avoid_: memoria, nota
**Reusable Memory**:
Una Memory Card che esprime un chiarimento di dominio, una regola di costruzione SQL o un errore da
evitare, valida in un ambito esplicito. Non deriva dalla sola approvazione di una scelta occasionale.
**Solved Question**:
Una Memory Card che conserva una domanda risolta con la sua soluzione SQL e il contesto per
interpretarla. È un esempio consultivo: le scelte del caso non diventano regole generali.
_Avoid_: esempio, template
**Memory Link**:
Un collegamento curato fra due card, con significato esplicito, che aiuta a ritrovare contenuti
pertinenti. Trovare una card tramite un link non ne implica l'approvazione.
**Memory Graph**:
L'insieme dei Memory Link di un workspace, usato per il recupero oltre la somiglianza del
contenuto.
### Evidence
**Context specialist**:
La persona competente sul dominio che redige e cura il contenuto delle Evidence. Può essere
diversa da chi amministra l'installazione.
_Avoid_: curatore tecnico
**Evidence draft**:
Il documento iniziale scritto dallo specialista di contesto, che il sistema acquisisce e raffina
in Evidence Unit. Può essere redatto indipendentemente dall'installazione.
**Evidence Module**:
Il modulo che possiede la preparazione delle Evidence e la loro consultazione durante il workflow.
Contribuisce alle fasi esistenti senza essere una fase e senza modificare lo stato della sessione.
**Evidence Unit**:
La più piccola unità di conoscenza di dominio coerente, revisionabile e ricercabile. Ha un
identificatore stabile, che non cambia se ne viene corretto il kind.
_Avoid_: documento, chunk
**Evidence kind**:
La categoria semantica di una Evidence Unit, che ne determina i campi: glossary, domain, enum,
example, mapping, normalization, formula o reference. Ogni unità ha un solo kind.
**Glossary Evidence**:
Una Evidence Unit che definisce il significato, i sinonimi o le varianti di un termine.
**Domain Evidence**:
Una Evidence Unit che esprime una regola o un vincolo del dominio non coperto da un kind più
specifico.
**Enum Evidence**:
Una Evidence Unit che collega un insieme finito di valori memorizzati ai loro significati.
**Example Evidence**:
Una Evidence Unit che associa una domanda o un input alla sua interpretazione o al risultato
atteso.
**Mapping Evidence**:
Una Evidence Unit che collega un concetto logico agli elementi dello schema fisico.
**Normalization Evidence**:
Una Evidence Unit che descrive la trasformazione di una rappresentazione in una forma canonica.
**Formula Evidence**:
Una Evidence Unit che contiene una singola espressione SQL componibile con i suoi input dichiarati.
Una query completa non è una Formula Evidence.
**Reference Evidence**:
Una Evidence Unit che rappresenta un collegamento esterno da restituire come contenuto autonomo,
non come semplice provenienza.
**Evidence purpose**:
L'uso dichiarato di una Evidence Unit nel workflow: disambiguazione, riscrittura, schema linking o
generazione SQL. Il kind dice cosa contiene, il purpose quando serve.
**Source Evidence**:
Il documento o la dichiarazione che sostiene il contenuto corrente di una Evidence Unit.
**Manual Evidence declaration**:
La dichiarazione di un amministratore che sostiene una Evidence creata direttamente o una
correzione del suo significato. Non implica una verifica da parte di una fonte esterna.
**Evidence origin**:
Il documento da cui una Evidence Unit è stata inizialmente derivata, conservato per provenienza
anche quando una dichiarazione manuale ne sostiene il testo corrente.
**Supporting excerpt**:
Un breve estratto della Source Evidence che sostiene una Evidence Unit. Il sistema ne verifica la
presenza; il curatore ne verifica la sufficienza.
**Local Evidence archive**:
Le Evidence curate custodite dall'installazione, distinte dalle draft originali e dagli indici di
ricerca. Comprende correzioni manuali e ritiri deliberati.
**Evidence consolidation**:
L'azione esplicita che verifica le Evidence locali modificate come insieme coerente e le rende
attive.
_Avoid_: pubblicazione, salvataggio
**Active Evidence**:
La versione consolidata delle Evidence consultata dal workflow. Un aggiornamento fallito conserva la
versione attiva precedente.
_Avoid_: Published Evidence
**Evidence preparation**:
Il processo che trasforma Source Evidence in Evidence Unit curate tramite estrazione, una
ristrutturazione assistita dal modello e una validazione finale. Applica le modifiche solo se sono
tutte valide.
**Evidence resolution**:
La decisione con cui un curatore risolve un problema di una Evidence Unit correggendola,
ritirandola o ricollegandola a una fonte adeguata.
**Review item**:
Un problema segnalato su una Evidence Unit che ne impedisce l'attivazione finché non viene risolto.
**Orphaned Evidence Unit**:
Una Evidence Unit la cui Source Evidence non esiste più. Resta visibile per la revisione finché non
viene eliminata, ricollegata o ne viene ripristinata la fonte.
**Source update conflict**:
Un contrasto fra una fonte aggiornata e una correzione manuale già approvata. La correzione resta
in uso finché l'amministratore non risolve il confronto.
**Evidence source refresh**:
La riacquisizione delle fonti esterne richiesta dall'amministratore per rilevarne le modifiche.
Fra due refresh fa fede il contenuto già acquisito.
**Formula proposal**:
Una formula individuata durante una sessione e conservata nella sessione. Non diventa Active
Evidence finché non viene curata e consolidata.
**Evidence Index**:
La proiezione ricercabile e ricostruibile delle Active Evidence. Accelera il recupero ma non è una
fonte di verità.
**Hybrid Evidence retrieval**:
La ricerca che combina una graduatoria semantica e una lessicale in un unico ordinamento
deterministico.
**Evidence Search Outcome**:
Il risultato di una consultazione delle Evidence. Distingue una ricerca riuscita, anche senza
risultati, da un'indisponibilità tecnica che blocca la fase fino a un nuovo tentativo.
**Evidence receipt**:
La traccia minima di una consultazione conservata nella sessione: fase, purpose e Evidence
restituite, senza duplicarne il contenuto.
### Catalogo dei metadati
**Metadata Catalog**:
L'autorità di un'installazione per il database di ogni workspace: binding, struttura osservata,
descrizioni, sensibilità e relazioni. Ogni uso dei metadati del database deriva da qui.
_Avoid_: annotations, schema YAML
**Workspace Database**:
Il database, limitato a un solo schema, che appartiene a un solo workspace. Un workspace ne ha al
massimo uno.
_Avoid_: DWH, datasource
**Database Binding**:
La configurazione propria di un'installazione che indica come raggiungere un Workspace Database.
Non è una seconda identità del database.
_Avoid_: connessione, connection string
**Thoth REST Connector**:
Il trasporto REST tipizzato con cui ThothII interroga e ispeziona un Workspace Database secondo il
contratto DWH supportato. Non è un client per API REST arbitrarie.
**Orphaned Workspace Database**:
Un Workspace Database il cui workspace non esiste più. È conservato per il recupero ma non è
usabile finché non viene riassegnato.
**Introspection Capability**:
Una categoria di struttura fisica che una Database Binding può osservare, come tabelle, colonne o
relazioni. Una capability assente è diversa da una capability che non ha trovato elementi.
**Physical Table**:
Una tabella osservata nello schema esterno di un Workspace Database, la cui identità appartiene al
database esterno.
**Catalog Table**:
La rappresentazione nel catalogo di una Physical Table. Non può essere creata o rinominata a mano,
ma può essere rimossa con una Catalog Metadata Cleanup.
_Avoid_: managed table
**Physical Column**:
Una colonna osservata in una Physical Table, con nome, posizione, tipo e appartenenza a chiavi.
**Catalog Column**:
La rappresentazione nel catalogo di una Physical Column. I fatti osservati seguono la
sincronizzazione; descrizioni e flag di sensibilità sono modificabili.
_Avoid_: managed column
**Physical Relationship**:
Una foreign key dichiarata nel database esterno, identificata dal vincolo e dalla sequenza ordinata
delle sue coppie di colonne.
**Catalog Relationship**:
La rappresentazione nel catalogo di una Physical Relationship. Non è modificabile a mano.
**Logical Relationship**:
Una relazione fra due Catalog Column gestita nel catalogo, che non corrisponde necessariamente a un
vincolo fisico. È Generated oppure Manual.
_Avoid_: FK logica, join suggerita
**Generated Relationship**:
Una Logical Relationship ricavata da nomi, chiavi primarie e compatibilità dei tipi con regole
deterministiche, senza AI né lettura dei dati.
**Manual Relationship**:
Una Logical Relationship aggiunta dall'utente, che la ricostruzione non modifica.
**Logical Relationship Deletion**:
L'esclusione persistente di una Logical Relationship, che ne impedisce la ricreazione automatica
finché esistono entrambe le colonne collegate.
**Permanent Relationship Deletion**:
La rimozione completa di una Logical Relationship, che una ricostruzione successiva può ricreare.
**Relationship Reconstruction**:
L'operazione esplicita che aggiunge le Generated Relationship mancanti senza toccare quelle
esistenti, manuali o escluse.
**Relationship Restore**:
La riattivazione esplicita di una Logical Relationship esclusa.
**Effective Relationship Map**:
La vista unica delle relazioni fisiche e logiche attive, con origine e stato espliciti.
**Catalog Metadata**:
I campi modificabili che descrivono database, tabelle, colonne e relazioni, distinti dai fatti
strutturali governati dalla sincronizzazione.
**Description**:
Il testo curato che descrive una Catalog Table o Catalog Column. Quando presente prevale sulla
Generated Description.
**Generated Description**:
Il testo prodotto dall'AI per una Catalog Table o Catalog Column, usato quando manca una
Description. È distinto dal commento presente nel database.
_Avoid_: generated comment, source comment
**Description Consolidation**:
L'azione che copia la Generated Description degli elementi selezionati nella loro Description.
**Non-generatable Description**:
L'esito valido con cui il modello dichiara di non avere informazioni sufficienti per descrivere un
elemento. Non è un errore.
**Description Generation Run**:
L'esecuzione sequenziale che produce Generated Description con il modello scelto. Ne è attiva al
massimo una per installazione e ogni risultato valido è salvato subito.
**Description Generation Unlock**:
Il recupero amministrativo che segna come interrotta una Description Generation Run rimasta attiva
senza un processo vivo.
**Catalog Sample**:
Un piccolo campione transitorio di righe e valori di una tabella usato per generare descrizioni.
Contiene valori reali o sintetici secondo il Sensitive Data Flag e non viene conservato.
**Table Synchronization**:
La riconciliazione che rende le Catalog Table uguali alle Physical Table osservate, eliminando
definitivamente quelle assenti.
_Avoid_: table import
**Schema Synchronization**:
La riconciliazione esplicita e autorevole di tabelle, colonne e relazioni fisiche, su uno scope o
sull'intero schema.
**Catalog Sync Run**:
L'esecuzione durevole in background di una Schema Synchronization. Ne è attiva al massimo una per
Workspace Database.
**Catalog Metadata Cleanup**:
La rimozione esplicita di tabelle, colonne o relazioni selezionate dal catalogo, senza toccare il
database esterno. Il catalogo può restare incompleto fino alla sincronizzazione successiva.
**Catalog Freshness**:
La corrispondenza fra uno scope sincronizzato e la Database Binding corrente. Uno scope sincronizzato
con una binding precedente è stale.
**Metadata Content Revision**:
La revisione crescente dello stato del catalogo che può cambiare il comportamento del workflow.
Ogni modifica rilevante ne produce una nuova.
**Catalog Metadata Snapshot**:
La proiezione immutabile dei metadati catalogati che il workflow consuma. È derivata dal catalogo e
non è una fonte di verità.
**Sensitive Data Flag**:
La classificazione binaria, decisa da una persona, che indica se una Catalog Column contiene dati
sensibili. Prevale su qualsiasi valutazione automatica.
_Avoid_: PII flag
**Sensitivity Reason**:
La motivazione salvata insieme al Sensitive Data Flag quando l'amministratore accetta una
valutazione. Scompare quando il flag torna non sensibile.
_Avoid_: AI reasoning
**Sensitive Data Policy**:
L'insieme versionato di regole locali che produce una Local Sensitivity Assessment. Un solo
riscontro rende sensibile l'intera colonna.
_Avoid_: PII filter, sample filter
**Local Sensitivity Assessment**:
La valutazione locale e non vincolante di una Catalog Column, basata su metadati e contenuto e senza
modelli generativi. Propone sensibile o non sensibile, con la copertura ottenuta.
_Avoid_: AI suggestion, automatic flag
**Local NER Detector**:
Il riconoscitore opzionale di entità, eseguito localmente, che esamina solo testo ancora ambiguo e
fornisce indizi alla valutazione senza decidere.
_Avoid_: AI classifier, local LLM fallback
**Sensitivity Analysis Run**:
Il tentativo esplicito e tracciato di valutare una selezione di colonne con la Sensitive Data
Policy. Non conserva valori sorgente né esiti per colonna.
_Avoid_: Sensitive Data Suggestion Run
**Sensitivity Review Draft**:
La proposta transitoria di valutazioni per le colonne selezionate, che non cambia nulla finché
l'amministratore non salva le proprie decisioni.
_Avoid_: automatic flag
### Workspace e preprocessing
**Workspace Descriptor**:
La dichiarazione versionata dell'identità di un workspace e delle sue Evidence. Non contiene nulla
del suo database, che è associato dal Metadata Catalog.
**Workspace Readiness**:
La condizione in cui un workspace ha tutti gli artefatti derivati necessari al workflow ed è quindi
utilizzabile dalle sessioni.
**Preprocessing**:
La preparazione completa e non concorrente degli artefatti derivati di un workspace a partire dal
catalogo e dalle Evidence attive. Non modifica la Memory.
**Preprocessing State**:
Lo stato del preprocessing di un workspace (in corso, riuscito, fallito) insieme all'identità dei
suoi input. Le sessioni sono ammesse solo dopo un preprocessing riuscito sugli input correnti.
**Reference index**:
L'indice ricostruibile di un workspace che contiene schema, relazioni ed Evidence, interamente
sostituibile dal preprocessing.
**Memory index**:
L'indice persistente di un workspace che contiene Memory Card e Solved Question. Non è prodotto dal
preprocessing e non viene cancellato da esso.
**Preprocessing Clear**:
L'operazione che elimina tutti gli artefatti derivati di un workspace e lo rende non pronto,
conservando Memory, sessioni, catalogo e database sorgente.
### Modelli
**Installation Model Catalog**:
L'elenco dichiarativo dei modelli disponibili in un'installazione, con i loro usi e default. È
l'unica autorità per i modelli di sessione, di generazione dei metadati e di embedding.
_Avoid_: Model Catalog, Metadata Generation Model Configuration
**Model Usage**:
Lo scopo per cui un modello del catalogo può essere usato: sessione, generazione dei metadati
oppure embedding.
**Model Selection**:
La scelta di un modello del catalogo per uno specifico uso. Si riferisce al modello senza
ridefinirne provider, endpoint o capacità.
**Model Runtime Projection**:
La forma derivata del catalogo modelli richiesta da uno specifico runtime, rigenerabile in ogni
momento.
### Amministrazione e shell
**Administration Surface**:
Un'area amministrativa autonoma: Workspace, Evidence, Memory, Database o Pi. Non dipende da una
sessione attiva.
**Administration Page**:
La rappresentazione a pagina intera di una Administration Surface, con una struttura condivisa fra
tutte.
_Avoid_: management popup, settings modal
**Administrative Page Family**:
L'insieme delle cinque Administration Page, che condividono shell, navigazione e regole
responsive.
**Administration Route**:
L'indirizzo navigabile di una Administration Surface, ripristinabile con refresh e cronologia.
**Shell mode**:
La scelta di installazione fra `embedded` e `full`, che decide chi possiede header, comandi di
identità e preferenze visive. Non cambia workflow né persistenza.
**Embedded Thoth Shell**:
L'esperienza ThothII ospitata dentro un portale host, di cui rispetta geometria, autenticazione e
regole responsive.
**Full Thoth Shell**:
L'esperienza ThothII autonoma, con header e layout propri.
**Portal Shell Adapter**:
Il confine sostituibile che traduce lo stato visivo del portale host per ThothII. Non gestisce
autorizzazione, sessioni o contenuti.
**Host Shell State**:
Lo stato visivo minimo fornito dal portale host: lingua della UI, tema e fullscreen. Non include
identità o autenticazione.
**Fullscreen state**:
Lo stato temporaneo in cui l'applicazione occupa tutto lo schermo del browser. È indipendente dallo
Shell mode.
**UI locale**:
La lingua delle parti deterministiche dell'interfaccia (etichette, messaggi, istruzioni). È
distinta dalla lingua dei contenuti del workspace.
_Avoid_: interaction language
### Installazione e distribuzione
**Installation**:
Una copia in esecuzione di ThothII con configurazione, segreti, catalogo e dati propri.
_Avoid_: deployment, istanza
**Manual standalone installation**:
Un'installazione predisposta per l'uso autonomo da chi possiede il computer, con Full Thoth Shell e
servizi applicativi locali. DWH e provider LLM restano esterni.
**Installation bootstrap**:
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.
**Customer-Hosted Installation**:
Un'installazione eseguita interamente nel perimetro controllato dal cliente. Credenziali, domande,
metadati e risultati non ne escono.
_Avoid_: on-premise deployment, self-managed deployment
**Community Edition**:
La distribuzione open source, gratuita anche in produzione, che esegue l'intero workflow
fondamentale.
_Avoid_: free tier, trial edition
**Enterprise Edition**:
La distribuzione con licenza commerciale che aggiunge governance organizzativa ed esercizio
production-grade alla Community Edition.
_Avoid_: paid tier, pro edition
+142 -291
View File
@@ -1,309 +1,160 @@
# ThothII — Project State # Project state
Last updated: 2026-09-06. 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.
This file is the short operational snapshot. Stable commands and the architecture mental model ## Current contracts
live in `AGENTS.md`; current design and runtime contracts live under `docs/architecture/`,
`docs/contracts/`, `docs/adr/`, and `docs/evidence.md`. Superseded plans and reports are
available from Git history rather than duplicated in the working tree.
The guarded server migration from a legacy checkout to the schema-v2 installation, Gitea source, - Document-first installation ticket #43 provides offline `tht workspace prepare`
Authentik, internal catalog/embedding services, and the PSD workspace repository is documented in and `tht workspace validate` through a native two-executable bundle. Build and
`docs/operations/server-upgrade-gitea-workspace-v2.md`. Treat its operator gates and rollback test instructions are in [the host CLI guide](tools/tht/README.md). Local validation
requirements as mandatory; do not replace the running server stack in place. 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.
## Current product shape - 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
[localization](docs/operations/shell-and-localization.md).
- PostgreSQL Metadata Catalog owns database identity, binding, schema, descriptions,
sensitivity and relationships for all core consumers. Workspace schema v4 contains
identity and optional Evidence only. Installation schema v2 is the authored model
catalog source. See [overview](docs/architecture/overview.md) and
[model configuration](docs/general/pi-configuration.md).
- The harness owns workflow persistence; chat is not the durable session record.
Memory uses PostgreSQL authority and derived Qdrant dense/BM25 search. Editable
Evidence has local archive authority and manual consolidation. File save, search
activation and Git publication have distinct outcomes. See
[Memory](docs/gestione-memory.md), [Evidence](docs/contracts/curated-evidence-v4.md)
and [consolidated release evidence](docs/reports/knowledge-archives-release.md).
- Reference preprocessing must not clear Memory. Use the installation-scoped
`tht --installation /absolute/path/thothii-installation.yaml workspace preprocess run`
and its [contract](docs/contracts/workspace-preprocessing-cli.md).
- DWH sessions are read-only. SSH tunnels support database-management diagnostics
and metadata synchronization, not NL→SQL session creation; use direct or REST
transport for sessions.
ThothII is a human-in-the-loop datamart builder with three independently built layers: ## Installation and workspace boundaries
```text Fresh standalone installations follow the document-first procedures in
frontend (React/SSE) → backend (Fastify) → pi --mode rpc → tht/harness → DWH (read-only) [Italian](docs/install/standalone-manual-it.md) or
``` [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. Document-first apply runs Catalog and Memory migrations
before bringing up application services.
The harness owns the deterministic eight-phase NL→SQL workflow and all session persistence. Descriptors, authentication, provider credentials, certificates and runtime bindings
The backend remains a process/RPC/SSE bridge for sessions and now also owns an isolated PostgreSQL stay in protected installation-local paths. Do not copy secrets into examples or
metadata catalog for administrative database configuration. The frontend renders the review gates workspace Git. Legacy runtime snapshots may use absolute paths and protected
and keeps the live transcript in memory. See `harness/.env`; do not silently relocate them.
`docs/architecture/components.md` for the detailed component and data-flow map.
## Evidence restructuring — accepted PSD authoring is separate at `/Users/mp/projects/tht-workspace-psd`. Its GitHub
repository was copied to private Gitea
[workspace_psd](https://git.tylconsulting.it/mptyl/workspace_psd), preserving both
branches. It is a copy, not automatic synchronization. Running installations were
not repointed to a different workspace remote.
The evidence restructuring and PSD migration completed real acceptance on 2026-08-25. ## Recorded deployments and server authority
- The curated PSD revision contains 35 approved Evidence units and 60 review items. Use the ordered [server handoff](docs/operations/server-codex-handoff.md) for
- The PSD authoring repository publishes all 35 units using Curated unit schema v3. Its table-free coordinated ThothII/Omics upgrades. Omics integration uses GitHub
presentation uses hidden canonical metadata, wrapping Markdown scope lists, list-based enum `Dallavilla-Tiziano/omics_portal`, with no Gitea relay prerequisite. Omics uses
values, and collapsed technical provenance. Long domain rules now have a deterministic embedded/upstream identity, not another ThothII OIDC login. Read
human-readable presentation while retaining their exact canonical text for vector ingestion. [upstream authentication](docs/install/authentication-upstream.md) before changes.
`tht evidence migrate <workspace-root>` performs the deterministic v1/v2 upgrade and older-v3
presentation rewrite without model calls. The structured-rule PSD rewrite is currently local and
pending commit/publication.
- The accepted snapshot is
`psd-clinical-675990d90eae51da6f2bd51b1ae2609f245772ef-snapshot`.
- The active generation is `gen:f968b3bd7a553dbfef3cf47093698f2bc7f95f11`.
- Retrieval acceptance reached 20/20 Hit@10.
- A real session, `20301df7-cad7-403d-a4c1-9f35c9d07b66`, completed F1–F8 with five
receipts, three CTEs, and a final result of 78 patients.
- The durable acceptance record is
`docs/testing/evidence/evidence-restructuring-psd-acceptance-2026-08-25.md`.
The canonical authoring, validation, publication, materialization, and preprocessing flow is Last recorded application deliveries (not a fresh runtime attestation):
documented in `docs/evidence.md`. The governing contracts are
`docs/contracts/workspace-evidence-v3.md` and
`docs/contracts/workspace-preprocessing-cli.md`.
The incremental server procedure for the `260906-preprocessing-complete` release is
`docs/operations/server-handoff-260906-preprocessing-complete.md`.
## Workspace preprocessing and configuration - [Coordinated ThothII/Omics release](docs/reports/2026-09-26-server-release-execution.md):
core/frontend `497ab840-preflight`, Omics proxy fix `928f7e9f` with existing web
image retained. Automated acceptance passed; on September 27 the operator confirmed
browser access, UI controls and session start/stop/resume. Functional browser
acceptance passed; remaining extended checks are handed off in the
[server acceptance follow-up](docs/reports/2026-09-27-server-acceptance-handoff.md).
- [Session dialogs](docs/reports/2026-09-14-session-dialogs-release.md):
`b1723c34-session-dialogs-20260914`, frontend-only.
- [Session layout/Memory fix](docs/reports/2026-09-14-session-layout-memory-fix.md):
`49333a2d-session-memory-fix`, core/frontend.
The native host CLI `tht` is the operator surface. Workspace preprocessing runs through: Keep those reports and rollback instructions while operator gates remain open.
A later deployment does not prove every earlier acceptance item passed.
```sh ## Remaining acceptance and design gates
tht --installation /absolute/path/thothii-installation.yaml \
workspace preprocess run --workspace <workspace-id>
```
This complete one-shot command uses the profile-gated `workspace-maintenance` service. Partial DWH, - The first installation acceptance uses an ad hoc
schema, Evidence, and vector mutation commands are retired. [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.
- [Security hardening](docs/plans/2026-09-08-security-hardening-prd.md) is a draft.
Revalidate SEC01–12 and obtain design approval before implementation or real
server/IdP/DWH mutation.
- Optional NER remains opt-in; labeled Italian quality, benchmark and licensing
acceptance are not implied by document cleanup.
- Semantic aliases, value descriptions, synonyms/concepts, dialect and multi-schema
extensions remain explicit design work. Current sensitivity delivery follows the
Catalog contract; additional policies require their own acceptance.
- Legacy database UI fallback (`?db-ui=legacy`, dev/staging) and prototype removal
remain subject to owner acceptance.
The right Administration sidebar invokes that same operation for the selected workspace. It shows ## Documentation maintenance
only current readiness or the latest bounded failure diagnostic; there is no preprocessing history.
Known non-ready state disables **New session**, while backend admission remains authoritative.
The same control exposes an inline-confirmed **Clear** action to remove replaceable reference
vectors, LSH, corpus, and checkpoints while preserving the separate Memory collection. The host CLI
equivalent is `workspace preprocess clear`.
Each workspace now uses `<workspace>-reference` for Schema, relationships, and Evidence and MkDocs publishes only 22 product/operator pages and five approved assets.
`<workspace>-memory` for `memory` and `solved_question`. Clear and preprocessing own only the former. Architecture, contracts, ADRs, plans, research, tests and release evidence are
LSH ownership additionally binds the Catalog database ID and Metadata Content Revision, so derived excluded from HTML and search. The repository itself is public: editorial exclusion
values cannot be reused across database identities or Catalog revisions. is not confidentiality.
Workspace descriptors use schema v4 and contain only workspace identity and optional Evidence. The [cleanup record](docs/maintenance/2026-09-15-documentation-cleanup.md) records
PostgreSQL Metadata Catalog owns database identity, binding, schema, descriptions, sensitivity, and retired sources and retained gates. Main contains source; Actions generates the
relationships; model, provider, embedding, and vector-store configuration is installation-owned. For `pages` branch. The live site requires the separate explicit deployment described
PSD, workspace content and runtime roots point to the in [public manual publication](docs/operations/public-docs-publication.md).
separate uncommitted repository `/Users/mp/projects/tht-workspace-psd`. Secrets remain outside
Git and are supplied only through installation-local protected files.
## Installation Model Catalog
`thothii-installation.yaml` schema version 2 is the only operator-authored source for session,
metadata-generation, and embedding models. The host `tht` lifecycle validates `modelCatalog` and
regenerates the backend catalog, Pi `models.json`/`settings.json`, and Compose override under the
installation-local `generated/` directory. Those projections are replaceable runtime adapters:
they are not edited, backed up, or treated as configuration.
Session and metadata defaults use canonical `provider/model` IDs. Provider authentication declares
one explicit mode (`secret_env`, `pi_auth`, or `none`); `secret_env` names a protected bundle key.
The backend settings store now owns only the selected workspace and thinking level. Existing v1
installations use the explicit catalog migration command; schema-v3 workspace descriptors are
converted deterministically in their curator-owned repository before commit. Strict runtime loading
does not silently infer or merge legacy sources. ADR 0013 and
`docs/plans/2026-09-02-installation-model-catalog.md` record the decision and implementation.
## Database management
The database, table, and authoritative physical-schema catalog slices are implemented. Database
Management now opens the Fleet Ledger presentation by default inside `AppShell`, lists every YAML
workspace, creates at most one PostgreSQL database configuration per workspace, edits direct
PostgreSQL, REST API, or SSH-tunnel installation bindings, replaces write-only encrypted secrets,
and tests supported connector bindings. The surface keeps one responsive AG Grid visible at a time:
databases lead to tables, tables lead to columns, and relationships are a sibling database view.
Parent navigation remains explicit through the breadcrumb and emphasized back control.
Selection-scoped operations use one action selector plus an explicit **Run** control; ineligible
actions remain visible with their disabled reason, while row-scoped actions stay in the pinned final
column. The KPI strip reads installation-wide or selected-database aggregates from
`GET /catalog/metrics`. Database configuration, metadata editors, synchronization history,
description history, and sensitive-field review/history use the production APIs in right-side
drawers rather than prototype fixtures; closing a history drawer does not stop its background run.
Sensitive-field review is now driven by the versioned local `sensitivity-v4` policy, not by a
catalog model. The backend reads selected source tables through read-only, database-specific
adapters and makes every `sensitive | non_sensitive` draft decision in the TypeScript
`SensitivityClassifier`. A single validated match protects the column. Tables up to 1,000 rows are
fully scanned; larger tables use breadth-first 300, 1,000, and text-only 3,000-value targets, with a
five-second limit per source query and no global request deadline. Source failures fail the run
instead of yielding `unknown`; coverage remains visible separately from the proposal. Draft
assessments remain transient until an administrator explicitly saves them. Optional GLiNER2
evidence is CPU-only, offline, opt-in, and never replaces the deterministic decision point; see
`docs/operations/sensitivity-analysis.md`. The earlier v1 PSD shadow comparison kept NER disabled by
default; see `docs/reports/2026-09-02-psd-sensitivity-shadow.md`. The v2 comparison completed all
2,275 columns: CPU NER added 18 sensitive proposals and increased warm runtime from 50.1 to 61.3
seconds; see `docs/reports/2026-09-03-psd-progressive-sensitivity-shadow.md`.
Version 4 excludes declared `bigint` primary-key columns and conventionally named `pk bigint`
columns before source inspection, reporting both as non-informative structural identifiers while
distinguishing declared constraints from inferred roles.
Physical membership, source
comments, column types/default/nullability/PK positions, and constraint-level ordered FK pairs are
projections of the external schema. They cannot be created, renamed, or structurally edited by
hand, but administrators can explicitly clear catalog tables, columns, or relationships without
touching the source database, binding, configuration, or secrets. Table deletion cascades through
columns and relationships; table-scoped relationship cleanup includes incoming and outgoing
relationships. Curated and generated descriptions are editable; generated descriptions start null
and Database Management can generate or consolidate them for selected tables, selected columns,
all targets, or only targets whose Generated Description is missing.
Relationship Management is now reachable directly from each configured Fleet database. One
Relationship Map shows read-only Physical Relationships together with Generated and Manual Logical
Relationships, with Active, Excluded, and All filters. Administrators can add a single-column
relationship, run deterministic name/PK/type inference, exclude or restore a logical relationship,
or delete it permanently. Exclusion retains a tombstone that a rebuild cannot reactivate; permanent
deletion allows a later rebuild to infer the same endpoints again. Inference uses no LLM, embedding,
or source values. It supports normalized table-qualified names, unique non-generic PK names,
composite-PK source columns, and the `*time_key -> dim_time.<single PK>` warehouse convention while
ignoring bare generic names. Explicit table/column metadata cleanup remains a destructive boundary: it removes
the attached logical relationships and exclusions and requires a full schema synchronization before
inference or runtime publication can continue.
The previous Database Management renderer remains a temporary comparison fallback for development
and staging only: `?db-ui=legacy` is honored in Vite development or when
`VITE_DB_MANAGEMENT_LEGACY=true`; it is not a production presentation. The standalone Fleet Ledger
prototype on port `5173` also remains temporary until owner acceptance of the integrated surface,
after which both migration aids can be removed.
Schema refresh is one durable asynchronous engine with database-table, selected-table-column,
relationship, and full-database actions. Database-level menus expose only the table, relationship,
and full scopes; selecting tables exposes column synchronization plus manual column and relationship cleanup for that subset. Database selections
also expose manual table and relationship cleanup. Cleanup selections are atomic and share the
one-active-operation-per-database exclusion with synchronization. Runs have leases and
restart recovery, atomic apply, destructive-diff confirmation with re-scan, cancellation before
apply, retained history, and a live SSE log with polling fallback. Null metadata renders blank
rather than as a placeholder.
Direct PostgreSQL and strict known-host-verified OpenSSH use `pg_catalog`. REST bindings use the
typed full-snapshot `POST /rpc/schema_snapshot` contract when available. Servers such as the
current PSD endpoint that exposes only `POST /rpc/run_query` use one catalog-owned read-only query
to return the exact same strict v1 snapshot in a single round trip. Both paths remain fail-closed:
an absent capability, query error, partial result, or invalid snapshot applies no catalog changes.
SSH is not yet enabled for NL→SQL session runtime.
The catalog runs in the internal `catalog-db` PostgreSQL service. Kysely migrations are an explicit
one-shot `catalog-migrate` operation; `scripts/run-stack.sh` runs it before local startup. Runtime
sessions consume an immutable Catalog JSON snapshot tied to the runtime-config lease. It contains
the tables, columns, effective descriptions, sensitivity flags, and active relationships used by
the harness; PostgreSQL is the exclusive runtime authority for database metadata. Authored
workspace YAML remains limited to workspace identity and optional Evidence configuration. The
accepted design is recorded in ADR 0016 and the contracts under `docs/contracts/`.
Semantic aliases, value descriptions, synonyms, and concepts remain deferred to their dedicated
slices.
AI Description Generation uses the catalog's human-owned Sensitive Data Flag. The flag defaults to
`false`, including for newly synchronized columns. An administrator may request a local sensitivity
analysis for one selected database, selected tables, or selected columns. One deterministic
TypeScript classifier combines metadata, bounded source-content rules, and optional CPU-only NER;
no generative model decides the result. Its `sensitive` or `non_sensitive` assessments remain an
unsaved draft until the human reviews and saves any chosen flag changes, including a downgrade to
non-sensitive. Coverage is reported separately; interrupted history may count unprocessed columns.
Each started analysis records a separate Sensitivity Analysis Run with aggregate counters and safe
ordered events. The progress drawer opens before the synchronous request completes, polls the run,
and displays sanitized source-scan and local-NER phase/batch activity while classification is in
progress. This operational history never stores per-column assessments, source values,
matched spans, prompts, or free-form diagnostics. Saving a sensitive decision persists a sanitized
Sensitivity Reason as column Catalog Metadata alongside the human-owned flag; clearing the flag
clears that reason. Reloading still discards an unsaved review draft.
For unprotected columns, up to five source rows and five representative non-null values may be sent
transiently to the configured model provider. Protected columns are omitted from source reads and
replaced in the prompt by deterministic plausible values derived only from their metadata. Existing
descriptions are not regenerated when a flag changes.
The accepted AI-description design is recorded in
`docs/plans/2026-08-28-ai-catalog-description-generation.md`, with the formal specification in the
adjacent `-spec.md` document and Gitea issue #4. Gitea issues #5–#11 deliver the implementation.
The runtime deliberately keeps ThothAI's simple operating model: one installation-wide sequential
run owned by the backend, one short-lived Python/LiteLLM completion helper per request, and
persistence limited to the run, its safe ordered text events, and each Generated Description as
soon as it succeeds. The helper performs at most one provider retry and never falls back to another
model. Stop terminates the current helper and retains prior results; three consecutive exhausted
technical batches fail the run. Startup marks stale queued/running work interrupted, and Unlock is
available only when no local start, worker, or helper is live. Runs remain inspectable through a
live SSE log with ordered polling fallback; there is no automatic resume or user-facing generation
CLI. ADRs 0009–0010 record the runtime and source-sampling decisions.
The Installation Model Catalog accepts the protected `DEEPSEEK_API_KEY` and `ZAI_API_KEY`
references for metadata-generation providers.
It also accepts a model with no secret reference only when its OpenAI-compatible endpoint is
explicit; this covers the VPN-only AritmoLab Qwen 3.6 server without creating a fake operator
credential. The Python client supplies only its fixed non-secret compatibility placeholder.
The AritmoLab entry also sets `disableThinking: true`, mapped to the endpoint's chat-template flag,
because its default reasoning prose would violate the worker's exact JSON response contract.
Logical relationship integration with core schema-linking is complete: session creation and resume
materialize the active physical/generated/manual map, retrieval-pack generation and Pi receive the
same runtime config, and snapshot validation fails closed on a declared missing, invalid, or orphaned
endpoint. Broader publication of other Catalog metadata to schema-linking remains a separate future
slice.
**Deferred follow-up — Sensitive Data Policy in schema-linking.** The policy is first delivered
and tested in catalog description generation. Its enforcement for core schema-linking remains
out of scope until the current tickets are closed and the owner has completed the acceptance test.
At that gate, resume the design: `tht` must receive a read-only projection of the current Sensitive
Data Flags and exclude values from columns marked sensitive from every LSH result before it is
given to Pi. Do not start this integration before the owner gives final approval after that test.
## Active deployment work and manual gates
### PSD server deployment program
The approved design and executable entry point are:
- `docs/plans/2026-08-20-psd-server-deployment-program-design.md`
- `docs/plans/2026-08-20-psd-server-deployment-program.md`
- `docs/plans/2026-08-20-psd-server-survey.md`
- `docs/plans/2026-08-20-psd-server-project-a-standalone.md`
- `docs/plans/2026-08-20-psd-server-project-b-authentik.md`
Last recorded state:
- survey: `SURVEY_NO_GO`;
- Project A: `BLOCKED_BY_SURVEY_AND_MUTATION_GATE`;
- Project B: `BLOCKED_BY_PROJECT_A_AND_PRE_B_GATE`.
The deployment is a clean replacement: legacy sessions, indexes, and application configuration
are not migration inputs. The existing stack remains intact until its documented mutation and
rollback gates are explicitly approved. Shared Omics/LocalLLM networks, ETL Evidence, DWH,
`dwh-auth`, Supabase, Authentik, Superset, and Aritmolab are outside cleanup scope.
Human acceptance guides and sanitized report templates live under `docs/testing/` and
`docs/testing/evidence/`. The remediation checklist is
`docs/operations/psd-server-survey-remediation-checklist.md`.
### Authentication
The local/OIDC authentication remediation passed its automated review on 2026-08-18. Release and
PSD mutation gates remain governed by:
- `docs/architecture/authentication.md`;
- `docs/plans/2026-08-18-thothii-authentication-acceptance-and-psd-deployment.md`;
- `docs/operations/psd-dwh-auth-rollout.md`;
- `docs/testing/authentication-manual-acceptance.md`.
Do not infer authorization for server, Nginx, Authentik, database, credential, or cutover changes
from an automated PASS.
## Verification status
- The P1.1 workspace-directory registry and P2–P6 preprocessing workstreams are implemented and
have automated coverage.
- Evidence restructuring has a real PSD acceptance PASS as recorded above.
- AI Description Generation has automated coverage across installation setup, model selection,
generation/consolidation scopes, bounded sampling, cancellation/recovery, history, SSE/polling,
and the LiteLLM helper boundary.
- L2 tests requiring real providers or remote databases remain opt-in.
- Server deployment, release, and owner-operated acceptance steps remain pending wherever the
referenced runbooks require explicit approval.
Run the layer-specific checks documented in `AGENTS.md`. For release-sensitive changes, also run
the repository contract scripts in `scripts/` and build the MkDocs site.
## Operational invariants
- `tht`'s `-c`/`--config` option follows the subcommand; it is not a global option.
- `--json` commands write pristine JSON to stdout.
- Persisted phase documents and the decision ledger are the source of session truth; chat is not.
- UI chrome is English; workspace document content retains the workspace language.
- The backend refuses resume for finalized or archived sessions.
- A resume must send `/riprendi-sessione <id>`; a new session must send `/nuova-domanda`.
- DWH access is read-only.
+38 -58
View File
@@ -4,72 +4,52 @@ ThothII is a human-reviewed NL-to-SQL workflow with a React frontend and a Fasti
core. The portable deployment runs two application services plus the installation-local metadata core. The portable deployment runs two application services plus the installation-local metadata
catalog; DWH and LLM services remain external. Semantic services are bundled in Compose. catalog; DWH and LLM services remain external. Semantic services are bundled in Compose.
Authentication is configured through the single host CLI tht: see the [local authentication guide](docs/install/authentication-local.md), The same frontend supports **full** (its own header) and **embedded** (inside a
[generic OIDC guide](docs/install/authentication-oidc.md), and [manual acceptance matrix](docs/testing/authentication-manual-acceptance.md). portal). This choice is independent of authentication: the Mac uses full/local,
Omics uses embedded/upstream with its existing login, and a standalone server
can use full/OIDC. See [rendering architecture](docs/architecture/application-shell.md)
and [configuration, Omics delivery and deploy](docs/operations/shell-and-localization.md).
## Docker Compose: local startup For the current server upgrade with Omics Portal, follow the ordered
[Codex server handoff](docs/operations/server-codex-handoff.md), including source
integration, embedded/upstream configuration, coordinated rollout and rollback.
Requirements: Docker Engine with Compose v2. The mandatory stack is `frontend`, `core`, Local/OIDC authentication is configured through the host CLI `tht`; portal
`catalog-db`, `qdrant`, `embedding`, and the one-shot `embedding-model-init`. DWH and LLM remain external, authentication is established by the trusted server proxy. See the
configurable endpoints—even when they are co-located with ThothII. [local guide](docs/install/authentication-local.md),
[OIDC guide](docs/install/authentication-oidc.md),
[upstream integration](docs/install/authentication-upstream.md), and
[manual acceptance matrix](docs/testing/authentication-manual-acceptance.md).
From a fresh clone, run these commands from the repository root: For the clone-based manual standalone installation test on macOS, Windows, and Linux, use the
[Italian procedure](docs/install/standalone-manual-it.md) or the
[English procedure](docs/install/standalone-manual-en.md).
```sh The [public manual](https://git.tylconsulting.it/thothii-docs/) covers the product,
cp deploy/env/local.env.example deploy/env/local.env installation, use and administration. Developer architecture, contracts, ADRs, tests,
# Copy docs/install/examples/thothii-installation.local.yaml to a protected operator path, plans and release records remain in this repository but are excluded from MkDocs
# replace its placeholders, chmod it 600, and set that exact THT_INSTALLATION_CONFIG_SOURCE. pages and search. This is an editorial boundary, not an access restriction on the
# Edit deploy/env/local.env, including PI_AUTH_FILE, THT_SECRETS_FILE, and external endpoints. public repository. See the [documentation cleanup review](docs/maintenance/2026-09-15-documentation-cleanup.md)
./scripts/run-stack.sh for the executed consolidation and the inventory of historical sources retained in Git.
```
The launcher builds the core, starts `catalog-db`, runs the explicit one-shot Kysely migrations, ## Docker Compose and installation
then runs the base+local stack in the foreground. Migrations never run implicitly in backend
startup. The core image contains its Pi runtime; no host `pi` executable is used. For a server
installation, build the image, start the catalog, and run the same migration service before the
application rollout:
```sh For a fresh installation, follow the guided terminal procedure in
cp deploy/env/server.env.example deploy/env/server.env [Italian](docs/install/standalone-manual-it.md) or
# Prepare a mode-600 thothii-installation.yaml from the server example and set its exact [English](docs/install/standalone-manual-en.md). The single
# path as THT_INSTALLATION_CONFIG_SOURCE. Edit all remaining storage/secret/endpoint paths. `tht setup --complete` command validates protected files, builds the images, runs
sudo scripts/prepare-server-pi-state.sh /srv/thothii/pi-state 10001 10001 Catalog migration, starts the stack and imports the configured workspace repository.
docker compose --env-file deploy/env/server.env \ There is no graphical installer or native launcher.
-f compose.yaml -f deploy/compose.server.yaml \
-f deploy/compose.session-server.yaml.example build core
docker compose --env-file deploy/env/server.env \
-f compose.yaml -f deploy/compose.server.yaml \
-f deploy/compose.session-server.yaml.example up -d catalog-db
docker compose --env-file deploy/env/server.env \
-f compose.yaml -f deploy/compose.server.yaml \
-f deploy/compose.session-server.yaml.example run --rm catalog-migrate
docker compose --env-file deploy/env/server.env \
-f compose.yaml -f deploy/compose.server.yaml \
-f deploy/compose.session-server.yaml.example up --build -d
```
The initializer is required for an empty or restored server Pi-state bind. It atomically creates The mandatory stack includes frontend, core, PostgreSQL catalog, Qdrant, Ollama
the three regular targets hidden below the writable parent bind; protected Pi auth and tracked and the embedding initializer. DWH and LLM endpoints remain external dependencies.
model/settings sources remain separate read-only mounts. See the server manual before substituting Pi is included in the core image. Credentials and certificates belong in protected
a root other than `/srv/thothii/pi-state`. installation-local files, never in the workspace repository.
Workspace descriptors come from the Git remote configured by `THT_WORKSPACE_GIT_REMOTE`; their For developer topology, overlays and lifecycle details, see the internal
runtime endpoint and secret bindings remain installation-local. Open [Compose reference](docs/operations/compose-reference.md). Ordinary stop/down keeps
<http://127.0.0.1:8080> (set `THOTH_HTTP_PORT` in `deploy/env/local.env` to choose another persistent data; removing volumes is destructive and is not an upgrade step.
loopback port). Process health is distinct from external dependency checks performed by doctor.
Credentials and certificates are local protected files. Do not put them in environment examples,
workspace YAML, URLs, or Compose interpolation values.
Application state is split across the named `settings`, `pi-state`, `workspace-registry`,
`sessions`, `qdrant-data`, and `embedding-models` volumes. `docker compose down` keeps them.
`qdrant-data` is a derived but persistent index store; `embedding-models` is an Ollama model
cache for `qwen3-embedding:0.6b` with fixed `1024`-dimension embeddings. Only an explicit destructive command such as `docker compose
down --volumes` removes them.
The frontend depends on the core health check and proxies `/health` and `/api/*` to it. The
application health endpoint intentionally checks process readiness only; external dependency
diagnostics are exposed by `tht doctor` and do not prevent the UI from starting.
## Git-backed workspace repository ## Git-backed workspace repository
+609
View File
@@ -6,11 +6,13 @@
"": { "": {
"name": "thothii-backend", "name": "thothii-backend",
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "3.1141.0",
"@fastify/cookie": "11.1.2", "@fastify/cookie": "11.1.2",
"@fastify/cors": "^11.2.0", "@fastify/cors": "^11.2.0",
"@fastify/rate-limit": "11.2.0", "@fastify/rate-limit": "11.2.0",
"@types/pg": "^8.20.3", "@types/pg": "^8.20.3",
"fastify": "^5.0.0", "fastify": "^5.0.0",
"ipaddr.js": "2.4.0",
"kysely": "^0.29.5", "kysely": "^0.29.5",
"libphonenumber-js": "1.13.12", "libphonenumber-js": "1.13.12",
"openid-client": "6.8.5", "openid-client": "6.8.5",
@@ -23,11 +25,320 @@
"@testcontainers/postgresql": "^12.1.0", "@testcontainers/postgresql": "^12.1.0",
"@types/node": "24.13.3", "@types/node": "24.13.3",
"@types/validator": "13.15.10", "@types/validator": "13.15.10",
"bun": "1.4.2",
"tsx": "^4.19.0", "tsx": "^4.19.0",
"typescript": "^5.6.0", "typescript": "^5.6.0",
"vitest": "^2.1.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": { "node_modules/@balena/dockerignore": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/@balena/dockerignore/-/dockerignore-1.0.2.tgz", "resolved": "https://registry.npmjs.org/@balena/dockerignore/-/dockerignore-1.0.2.tgz",
@@ -802,6 +1113,174 @@
"node": ">=8" "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": { "node_modules/@pinojs/redact": {
"version": "0.4.0", "version": "0.4.0",
"resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz",
@@ -1235,6 +1714,87 @@
"win32" "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": { "node_modules/@testcontainers/postgresql": {
"version": "12.1.0", "version": "12.1.0",
"resolved": "https://registry.npmjs.org/@testcontainers/postgresql/-/postgresql-12.1.0.tgz", "resolved": "https://registry.npmjs.org/@testcontainers/postgresql/-/postgresql-12.1.0.tgz",
@@ -1821,6 +2381,12 @@
"node": ">= 6" "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": { "node_modules/brace-expansion": {
"version": "2.1.4", "version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
@@ -1876,6 +2442,43 @@
"node": ">=10.0.0" "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": { "node_modules/byline": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/byline/-/byline-5.0.0.tgz", "resolved": "https://registry.npmjs.org/byline/-/byline-5.0.0.tgz",
@@ -4114,6 +4717,12 @@
"node": ">=20" "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": { "node_modules/tsx": {
"version": "4.22.4", "version": "4.22.4",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.22.4.tgz",
+4
View File
@@ -3,6 +3,7 @@
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
"build:workspace-tools": "node scripts/build-workspace-tools.mjs",
"dev": "tsx watch src/server.ts", "dev": "tsx watch src/server.ts",
"prebuild": "node scripts/clean-dist.mjs", "prebuild": "node scripts/clean-dist.mjs",
"build": "tsc -p tsconfig.json", "build": "tsc -p tsconfig.json",
@@ -14,11 +15,13 @@
"test:schema-v3-verifier": "npm run test:schema-v4-verifier" "test:schema-v3-verifier": "npm run test:schema-v4-verifier"
}, },
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "3.1141.0",
"@fastify/cookie": "11.1.2", "@fastify/cookie": "11.1.2",
"@fastify/cors": "^11.2.0", "@fastify/cors": "^11.2.0",
"@fastify/rate-limit": "11.2.0", "@fastify/rate-limit": "11.2.0",
"@types/pg": "^8.20.3", "@types/pg": "^8.20.3",
"fastify": "^5.0.0", "fastify": "^5.0.0",
"ipaddr.js": "2.4.0",
"kysely": "^0.29.5", "kysely": "^0.29.5",
"libphonenumber-js": "1.13.12", "libphonenumber-js": "1.13.12",
"openid-client": "6.8.5", "openid-client": "6.8.5",
@@ -31,6 +34,7 @@
"@testcontainers/postgresql": "^12.1.0", "@testcontainers/postgresql": "^12.1.0",
"@types/node": "24.13.3", "@types/node": "24.13.3",
"@types/validator": "13.15.10", "@types/validator": "13.15.10",
"bun": "1.4.2",
"tsx": "^4.19.0", "tsx": "^4.19.0",
"typescript": "^5.6.0", "typescript": "^5.6.0",
"vitest": "^2.1.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 }); }
});
+22 -1
View File
@@ -7,6 +7,7 @@ import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import type { AppConfig } from "./config.js"; import type { AppConfig } from "./config.js";
import { ThtRunner } from "./tht/tht-runner.js"; import { ThtRunner } from "./tht/tht-runner.js";
import { createMemoryCleanup } from "./catalog/memory-cleanup.js";
import { PiProcessManager } from "./pi/pi-process-manager.js"; import { PiProcessManager } from "./pi/pi-process-manager.js";
import { SseHub } from "./sse/sse-hub.js"; import { SseHub } from "./sse/sse-hub.js";
import { authenticateSession, captureAuthConfigSnapshot, configuredOrigin } from "./auth/auth.js"; import { authenticateSession, captureAuthConfigSnapshot, configuredOrigin } from "./auth/auth.js";
@@ -47,6 +48,8 @@ import { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js"; import type { CatalogRepository } from "./catalog/types.js";
import { CatalogService } from "./catalog/service.js"; import { CatalogService } from "./catalog/service.js";
import { catalogDatabaseRoutes } from "./routes/catalog-databases.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 { CatalogOperationCoordinator } from "./catalog/operation-coordinator.js";
import { ConcreteCatalogPostgresAccess, type CatalogPostgresAccess } from "./catalog/postgres-access.js"; import { ConcreteCatalogPostgresAccess, type CatalogPostgresAccess } from "./catalog/postgres-access.js";
import { CatalogTableService } from "./catalog/table-service.js"; import { CatalogTableService } from "./catalog/table-service.js";
@@ -80,6 +83,8 @@ import { createProductionWorkspacePreprocessingService } from "./workspace-maint
import type { WorkspacePreprocessingService } from "./workspaces/preprocessing-service.js"; import type { WorkspacePreprocessingService } from "./workspaces/preprocessing-service.js";
import { PreprocessingStateStore } from "./workspaces/preprocessing-state.js"; import { PreprocessingStateStore } from "./workspaces/preprocessing-state.js";
import { workspacePreprocessingRoutes } from "./routes/workspace-preprocessing.js"; import { workspacePreprocessingRoutes } from "./routes/workspace-preprocessing.js";
import { memoryRoutes } from "./routes/memory.js";
import { evidenceRoutes } from "./routes/evidence.js";
export interface BuildAppDeps { export interface BuildAppDeps {
thtRunner?: ThtRunner; thtRunner?: ThtRunner;
@@ -93,7 +98,7 @@ export interface BuildAppDeps {
workspaceDiagnoser?: WorkspaceDiagnoser; workspaceDiagnoser?: WorkspaceDiagnoser;
workspaceDatabaseTester?: WorkspaceDatabaseTester; workspaceDatabaseTester?: WorkspaceDatabaseTester;
workspaceSecretStore?: WorkspaceSecretStore; workspaceSecretStore?: WorkspaceSecretStore;
workspacePreprocessingService?: Pick<WorkspacePreprocessingService, "run" | "clear">; workspacePreprocessingService?: Pick<WorkspacePreprocessingService, "run" | "clear"> & Partial<Pick<WorkspacePreprocessingService, "consolidateEvidence" | "evidenceSources">>;
catalogRepository?: CatalogRepository; catalogRepository?: CatalogRepository;
catalogService?: CatalogService; catalogService?: CatalogService;
catalogPostgresAccess?: CatalogPostgresAccess; catalogPostgresAccess?: CatalogPostgresAccess;
@@ -265,6 +270,11 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
catalogSchemaIntrospector, catalogSchemaIntrospector,
catalogOperationCoordinator, catalogOperationCoordinator,
config.catalogSyncTimeoutMs, config.catalogSyncTimeoutMs,
createMemoryCleanup(tht as ThtRunner, {
internalQdrantUrl: config.internalQdrantUrl, internalEmbeddingUrl: config.internalEmbeddingUrl,
internalEmbeddingId: config.internalEmbeddingId, internalEmbeddingModel: config.internalEmbeddingModel,
internalEmbeddingDimensions: config.internalEmbeddingDimensions,
}),
); );
app.addHook("onReady", async () => { await catalogSyncWorker.initialize(); }); app.addHook("onReady", async () => { await catalogSyncWorker.initialize(); });
app.addHook("onReady", async () => { await descriptionGenerationWorker.initialize(); }); app.addHook("onReady", async () => { await descriptionGenerationWorker.initialize(); });
@@ -493,7 +503,16 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
return maintenanceBarrier.status(); return maintenanceBarrier.status();
}); });
sqlRoutes(app, { tht: tht as ThtRunner, getSettings, workspaceRegistry }); sqlRoutes(app, { tht: tht as ThtRunner, getSettings, workspaceRegistry });
memoryRoutes(app, { runner: tht as ThtRunner, registry: workspaceRegistry, runtime: {
internalQdrantUrl: config.internalQdrantUrl,
internalEmbeddingUrl: config.internalEmbeddingUrl,
internalEmbeddingModel: config.internalEmbeddingModel,
internalEmbeddingDimensions: config.internalEmbeddingDimensions,
} });
metaRoutes(app, { harnessDir: config.harnessDir, modelCatalog: runtimeModelCatalog }); metaRoutes(app, { harnessDir: config.harnessDir, modelCatalog: runtimeModelCatalog });
evidenceRoutes(app, { runner: tht as ThtRunner, registry: workspaceRegistry,
registryRoot: config.workspaceRegistry.root, hostRegistryRoot: config.evidenceHostRegistryRoot,
service: workspacePreprocessingService });
workspaceRoutes(app, { workspaceRoutes(app, {
registry: workspaceRegistry, registry: workspaceRegistry,
config: config.workspaceRegistry, config: config.workspaceRegistry,
@@ -513,6 +532,8 @@ export function buildApp(config: AppConfig, deps?: BuildAppDeps): FastifyInstanc
}).readLatestJob(), }).readLatestJob(),
}); });
catalogDatabaseRoutes(app, { repository: catalogRepository, service: catalogService, operations: catalogOperationCoordinator }); catalogDatabaseRoutes(app, { repository: catalogRepository, service: catalogService, operations: catalogOperationCoordinator });
installationRoutes(app, new InstallationBindings(catalogRepository, catalogService, workspaceRegistry,
workspaceSecretStore, catalogOperationCoordinator, config.workspaceRegistry.installationId), workspaceRegistry);
catalogTableRoutes(app, { catalogTableRoutes(app, {
repository: catalogRepository, repository: catalogRepository,
service: catalogTableService, service: catalogTableService,
+3 -1
View File
@@ -119,7 +119,9 @@ export function authenticateSession(deps: AuthDependencies): preHandlerHookHandl
subject: session.subject, subject: session.subject,
...(session.displayName === undefined ? {} : { displayName: session.displayName }), ...(session.displayName === undefined ? {} : { displayName: session.displayName }),
roles: session.roles, roles: session.roles,
permissions: session.permissions, // Sessions can outlive a deployment that changes the role permission catalog.
// resolve() has already checked validity, including current local user roles.
permissions: rolesToPermissions(session.roles),
isAdmin: session.roles.includes("admin"), isAdmin: session.roles.includes("admin"),
}; };
if (STATE_CHANGING_METHODS.has(request.method)) { if (STATE_CHANGING_METHODS.has(request.method)) {
+1 -1
View File
@@ -38,7 +38,7 @@ const MAX_MAPPED_GROUPS = 128;
const ROLES = ["user", "admin"] as const; const ROLES = ["user", "admin"] as const;
export const PERMISSION_CATALOG: readonly Permission[] = [ export const PERMISSION_CATALOG: readonly Permission[] = [
"session.use", "session.read_all", "session.manage_all", "settings.manage", "session.use", "session.read_all", "session.manage_all", "settings.manage",
"workspace.manage", "workspace.secrets.manage", "database.manage", "pi.manage", "auth.diagnostics.read", "workspace.manage", "workspace.secrets.manage", "database.manage", "memory.manage", "evidence.manage", "pi.manage", "auth.diagnostics.read",
]; ];
const invalid = (): Error => new Error("authentication configuration is invalid"); const invalid = (): Error => new Error("authentication configuration is invalid");
+1 -1
View File
@@ -33,7 +33,7 @@ const EMPTY_HKDF_SALT = Buffer.alloc(0);
const ROLES = ["user", "admin"] as const; const ROLES = ["user", "admin"] as const;
const PERMISSIONS = [ const PERMISSIONS = [
"session.use", "session.read_all", "session.manage_all", "settings.manage", "session.use", "session.read_all", "session.manage_all", "settings.manage",
"workspace.manage", "workspace.secrets.manage", "database.manage", "pi.manage", "auth.diagnostics.read", "workspace.manage", "workspace.secrets.manage", "database.manage", "memory.manage", "evidence.manage", "pi.manage", "auth.diagnostics.read",
] as const satisfies readonly Permission[]; ] as const satisfies readonly Permission[];
const invalid = (): Error => new Error("auth_session_store_invalid"); const invalid = (): Error => new Error("auth_session_store_invalid");
+1 -1
View File
@@ -5,7 +5,7 @@ export type Role = "user" | "admin";
export type Permission = export type Permission =
| "session.use" | "session.read_all" | "session.manage_all" | "session.use" | "session.read_all" | "session.manage_all"
| "settings.manage" | "workspace.manage" | "workspace.secrets.manage" | "settings.manage" | "workspace.manage" | "workspace.secrets.manage"
| "database.manage" | "pi.manage" | "auth.diagnostics.read"; | "database.manage" | "memory.manage" | "evidence.manage" | "pi.manage" | "auth.diagnostics.read";
export interface AuthenticationSessionConfig { export interface AuthenticationSessionConfig {
regularTtlSeconds: number; regularTtlSeconds: number;
+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 };
}
}
+23
View File
@@ -0,0 +1,23 @@
import type { ThtRunner } from "../tht/tht-runner.js";
import type { SemanticRuntimeConfig } from "../workspaces/runtime-renderer.js";
import type { CatalogSyncRun, WorkspaceDatabase } from "./types.js";
/** Internal continuation of an applied physical sync, using the harness Memory boundary. */
export function createMemoryCleanup(runner: Pick<ThtRunner, "withPrincipal">, runtime: SemanticRuntimeConfig) {
return async (database: WorkspaceDatabase, run: CatalogSyncRun): Promise<number> => {
if (run.phase !== "memory_cleanup" || !run.plannedDiff) throw new Error("Physical cleanup is not committed");
const result = await runner.withPrincipal({ issuer: "installation", subject: "catalog-sync",
roles: ["admin"], permissions: ["memory.manage"], isAdmin: true,
}).runWithRuntimeSnapshot(["memory", "admin", "--workspace", database.workspaceId], JSON.stringify({
action: "cleanup", runtime, request: { sync_id: run.id, database: database.databaseName,
schema_name: database.schema, removed_tables: run.plannedDiff.deletedTables,
removed_columns: run.plannedDiff.deletedColumns.map(column => ({ table: column.tableName, column: column.columnName })),
},
}));
const payload = JSON.parse(result.stdout);
if (result.code !== 0 || payload.indexed !== true || !Number.isInteger(payload.deleted) || payload.deleted < 0) {
throw new Error("Memory cleanup is incomplete");
}
return payload.deleted;
};
}
+13 -5
View File
@@ -52,6 +52,7 @@ function clone(value: WorkspaceDatabase): WorkspaceDatabase {
/** Deterministic repository used by route tests and local contract consumers. */ /** Deterministic repository used by route tests and local contract consumers. */
export class MemoryCatalogRepository implements CatalogRepository { export class MemoryCatalogRepository implements CatalogRepository {
private readonly records = new Map<string, WorkspaceDatabase>(); private readonly records = new Map<string, WorkspaceDatabase>();
private readonly installationImports = new Set<string>();
private readonly tables = new Map<string, CatalogTable>(); private readonly tables = new Map<string, CatalogTable>();
private readonly columns = new Map<string, CatalogColumn>(); private readonly columns = new Map<string, CatalogColumn>();
private readonly relationships = new Map<string, CatalogPhysicalRelationship>(); private readonly relationships = new Map<string, CatalogPhysicalRelationship>();
@@ -77,6 +78,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
async beginPreprocessing( async beginPreprocessing(
workspaceId: string, workspaceId: string,
inputFingerprint: string, inputFingerprint: string,
runId?: string,
): Promise<CatalogPreprocessingStartResult> { ): Promise<CatalogPreprocessingStartResult> {
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId); const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
if (!database) return { kind: "not_found" }; if (!database) return { kind: "not_found" };
@@ -95,6 +97,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
...database, ...database,
preprocessingStatus: "running", preprocessingStatus: "running",
preprocessingInputFingerprint: inputFingerprint, preprocessingInputFingerprint: inputFingerprint,
preprocessingRunId: runId,
preprocessedMetadataRevision: undefined, preprocessedMetadataRevision: undefined,
preprocessingStartedAt: now, preprocessingStartedAt: now,
preprocessingFinishedAt: undefined, preprocessingFinishedAt: undefined,
@@ -109,12 +112,14 @@ export class MemoryCatalogRepository implements CatalogRepository {
metadataContentRevision: number, metadataContentRevision: number,
inputFingerprint: string, inputFingerprint: string,
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string }, outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
runId?: string,
): Promise<WorkspaceDatabase | undefined> { ): Promise<WorkspaceDatabase | undefined> {
const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId); const database = [...this.records.values()].find((record) => record.workspaceId === workspaceId);
if (!database if (!database
|| database.preprocessingStatus !== "running" || database.preprocessingStatus !== "running"
|| database.metadataContentRevision !== metadataContentRevision || database.metadataContentRevision !== metadataContentRevision
|| database.preprocessingInputFingerprint !== inputFingerprint) return undefined; || database.preprocessingInputFingerprint !== inputFingerprint
|| database.preprocessingRunId !== runId) return undefined;
const updated: WorkspaceDatabase = { const updated: WorkspaceDatabase = {
...database, ...database,
preprocessingStatus: outcome.status, preprocessingStatus: outcome.status,
@@ -175,13 +180,13 @@ export class MemoryCatalogRepository implements CatalogRepository {
...relationships.map((relationship) => relationship.updatedAt), ...relationships.map((relationship) => relationship.updatedAt),
])); ]));
} }
async create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase> { async create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase> {
if ([...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) { if ((creationId && this.installationImports.has(input.workspaceId)) || [...this.records.values()].some((record) => record.workspaceId === input.workspaceId)) {
throw new CatalogConflictError("Workspace database already exists"); throw new CatalogConflictError("Workspace database already exists");
} }
const now = new Date().toISOString(); const now = new Date().toISOString();
const record: WorkspaceDatabase = { const record: WorkspaceDatabase = {
id: randomUUID(), id: creationId ?? randomUUID(),
...structuredClone(input), ...structuredClone(input),
version: 1, version: 1,
createdAt: now, createdAt: now,
@@ -191,6 +196,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
preprocessingStatus: "failed", preprocessingStatus: "failed",
}; };
this.records.set(record.id, record); this.records.set(record.id, record);
if (creationId) this.installationImports.add(input.workspaceId);
return clone(record); return clone(record);
} }
async update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined> { async update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined> {
@@ -926,6 +932,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
scope: CatalogSyncScope, scope: CatalogSyncScope,
tableIds: readonly string[], tableIds: readonly string[],
snapshot: ObservedSchemaSnapshot, snapshot: ObservedSchemaSnapshot,
syncRunId?: string,
): Promise<CatalogSyncCounts | undefined> { ): Promise<CatalogSyncCounts | undefined> {
const database = this.records.get(databaseId); const database = this.records.get(databaseId);
if (!database || database.version !== expectedDatabaseVersion) return undefined; if (!database || database.version !== expectedDatabaseVersion) return undefined;
@@ -1141,6 +1148,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
if (scope === "all") { if (scope === "all") {
this.records.set(databaseId, { ...database, schemaSyncedVersion: expectedDatabaseVersion, schemaSyncedAt: now }); this.records.set(databaseId, { ...database, schemaSyncedVersion: expectedDatabaseVersion, schemaSyncedAt: now });
} }
if (syncRunId) await this.updateSyncRun(syncRunId, { phase: "memory_cleanup" });
return { return {
tables: (await this.listTables(databaseId)).length, tables: (await this.listTables(databaseId)).length,
columns: [...this.columns.values()].filter((column) => this.tables.get(column.tableId)?.databaseId === databaseId).length, columns: [...this.columns.values()].filter((column) => this.tables.get(column.tableId)?.databaseId === databaseId).length,
@@ -1254,7 +1262,7 @@ export class MemoryCatalogRepository implements CatalogRepository {
for (const run of this.syncRuns.values()) { for (const run of this.syncRuns.values()) {
if (["queued", "running", "awaiting_confirmation", "applying"].includes(run.state)) { if (["queued", "running", "awaiting_confirmation", "applying"].includes(run.state)) {
await this.updateSyncRun(run.id, { await this.updateSyncRun(run.id, {
state: "interrupted", phase: "completed", finishedAt: new Date().toISOString(), state: "interrupted", phase: run.phase === "memory_cleanup" ? "memory_cleanup" : "completed", finishedAt: new Date().toISOString(),
errorCode: "SYNC_INTERRUPTED", errorMessage: "Synchronization was interrupted by a service restart", errorCode: "SYNC_INTERRUPTED", errorMessage: "Synchronization was interrupted by a service restart",
}); });
} }
@@ -102,7 +102,7 @@ export function loadMetadataGenerationModels(options: {
...(apiKeyEnv ? { apiKeyEnv, apiKey } : {}), ...(apiKeyEnv ? { apiKeyEnv, apiKey } : {}),
})); }));
} }
const result = new RestartLoadedMetadataGenerationModels(models, catalog.defaultMetadataGeneration); const result = new RestartLoadedMetadataGenerationModels(models, models.size ? catalog.defaultInteraction : null);
const safe = result.catalog(); const safe = result.catalog();
return { return {
catalog: () => ({ catalog: () => ({
+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 localSensitivityAnalysisMigration from "./migrations/011_local_sensitivity_analysis.js";
import * as sensitivityReasonMigration from "./migrations/012_sensitivity_reason.js"; import * as sensitivityReasonMigration from "./migrations/012_sensitivity_reason.js";
import * as catalogPreprocessingStateMigration from "./migrations/013_catalog_preprocessing_state.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 connectionString = process.env.THT_CATALOG_MIGRATOR_DATABASE_URL;
const host = process.env.THT_CATALOG_DB_HOST; const host = process.env.THT_CATALOG_DB_HOST;
@@ -54,6 +56,8 @@ const provider: MigrationProvider = {
"011_local_sensitivity_analysis": localSensitivityAnalysisMigration, "011_local_sensitivity_analysis": localSensitivityAnalysisMigration,
"012_sensitivity_reason": sensitivityReasonMigration, "012_sensitivity_reason": sensitivityReasonMigration,
"013_catalog_preprocessing_state": catalogPreprocessingStateMigration, "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();
}
+16 -3
View File
@@ -76,6 +76,7 @@ interface WorkspaceDatabaseTable {
metadataContentRevision: Generated<number>; metadataContentRevision: Generated<number>;
preprocessingStatus: Generated<WorkspaceDatabase["preprocessingStatus"]>; preprocessingStatus: Generated<WorkspaceDatabase["preprocessingStatus"]>;
preprocessingInputFingerprint: Generated<string | null>; preprocessingInputFingerprint: Generated<string | null>;
preprocessingRunId: Generated<string | null>;
preprocessedMetadataRevision: Generated<number | null>; preprocessedMetadataRevision: Generated<number | null>;
preprocessingStartedAt: NullableTimestamp; preprocessingStartedAt: NullableTimestamp;
preprocessingFinishedAt: NullableTimestamp; preprocessingFinishedAt: NullableTimestamp;
@@ -273,6 +274,7 @@ interface CatalogSyncEventTable {
} }
export interface CatalogDatabase { export interface CatalogDatabase {
installationBindingImports: { workspaceId: string; databaseId: string; createdAt: Generated<Date> };
workspaceDatabases: WorkspaceDatabaseTable; workspaceDatabases: WorkspaceDatabaseTable;
databaseBindings: DatabaseBindingTable; databaseBindings: DatabaseBindingTable;
catalogTables: CatalogTableTable; catalogTables: CatalogTableTable;
@@ -342,6 +344,7 @@ function serialize(row: JoinedRow): WorkspaceDatabase {
metadataContentRevision: Number(row.metadataContentRevision), metadataContentRevision: Number(row.metadataContentRevision),
preprocessingStatus: row.preprocessingStatus, preprocessingStatus: row.preprocessingStatus,
preprocessingInputFingerprint: present(row.preprocessingInputFingerprint), preprocessingInputFingerprint: present(row.preprocessingInputFingerprint),
preprocessingRunId: present(row.preprocessingRunId),
preprocessedMetadataRevision: row.preprocessedMetadataRevision == null preprocessedMetadataRevision: row.preprocessedMetadataRevision == null
? undefined ? undefined
: Number(row.preprocessedMetadataRevision), : Number(row.preprocessedMetadataRevision),
@@ -507,6 +510,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
async beginPreprocessing( async beginPreprocessing(
workspaceId: string, workspaceId: string,
inputFingerprint: string, inputFingerprint: string,
runId?: string,
): Promise<CatalogPreprocessingStartResult> { ): Promise<CatalogPreprocessingStartResult> {
return await this.db.transaction().execute(async (trx) => { return await this.db.transaction().execute(async (trx) => {
const database = await trx.selectFrom("workspaceDatabases") const database = await trx.selectFrom("workspaceDatabases")
@@ -539,6 +543,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
.set({ .set({
preprocessingStatus: "running", preprocessingStatus: "running",
preprocessingInputFingerprint: inputFingerprint, preprocessingInputFingerprint: inputFingerprint,
preprocessingRunId: runId ?? null,
preprocessedMetadataRevision: null, preprocessedMetadataRevision: null,
preprocessingStartedAt: sql`now()`, preprocessingStartedAt: sql`now()`,
preprocessingFinishedAt: null, preprocessingFinishedAt: null,
@@ -556,6 +561,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
metadataContentRevision: number, metadataContentRevision: number,
inputFingerprint: string, inputFingerprint: string,
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string }, outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
runId?: string,
): Promise<WorkspaceDatabase | undefined> { ): Promise<WorkspaceDatabase | undefined> {
const result = await this.db.updateTable("workspaceDatabases") const result = await this.db.updateTable("workspaceDatabases")
.set({ .set({
@@ -569,6 +575,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
.where("preprocessingStatus", "=", "running") .where("preprocessingStatus", "=", "running")
.where("metadataContentRevision", "=", metadataContentRevision) .where("metadataContentRevision", "=", metadataContentRevision)
.where("preprocessingInputFingerprint", "=", inputFingerprint) .where("preprocessingInputFingerprint", "=", inputFingerprint)
.where("preprocessingRunId", runId === undefined ? "is" : "=", runId ?? null)
.returning("id") .returning("id")
.executeTakeFirst(); .executeTakeFirst();
return result ? await this.get(result.id) : undefined; 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()); }, row.updatedAt === null ? null : new Date(row.updatedAt).toISOString());
} }
async create(input: DatabaseConfigurationInput): Promise<WorkspaceDatabase> { async create(input: DatabaseConfigurationInput, creationId?: string): Promise<WorkspaceDatabase> {
try { try {
return await this.db.transaction().execute(async (trx) => { 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({ await trx.insertInto("workspaceDatabases").values({
id, id,
workspaceId: input.workspaceId, workspaceId: input.workspaceId,
@@ -1604,6 +1612,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
scope: CatalogSyncScope, scope: CatalogSyncScope,
tableIds: readonly string[], tableIds: readonly string[],
snapshot: ObservedSchemaSnapshot, snapshot: ObservedSchemaSnapshot,
syncRunId?: string,
): Promise<CatalogSyncCounts | undefined> { ): Promise<CatalogSyncCounts | undefined> {
return await this.db.transaction().execute(async (trx) => { return await this.db.transaction().execute(async (trx) => {
const database = await trx.selectFrom("workspaceDatabases").select("version") const database = await trx.selectFrom("workspaceDatabases").select("version")
@@ -1779,6 +1788,10 @@ export class KyselyCatalogRepository implements CatalogRepository {
schemaSyncedAt: now, schemaSyncedAt: now,
}).where("id", "=", databaseId).execute(); }).where("id", "=", databaseId).execute();
} }
if (syncRunId) {
await trx.updateTable("catalogSyncRuns").set({ phase: "memory_cleanup" })
.where("id", "=", syncRunId).where("databaseId", "=", databaseId).execute();
}
return { return {
tables: snapshot.tables.length, tables: snapshot.tables.length,
columns: scope === "tables" ? undefined : snapshot.columns.length, columns: scope === "tables" ? undefined : snapshot.columns.length,
@@ -1882,7 +1895,7 @@ export class KyselyCatalogRepository implements CatalogRepository {
async interruptActiveSyncRuns(): Promise<void> { async interruptActiveSyncRuns(): Promise<void> {
await this.db.updateTable("catalogSyncRuns").set({ await this.db.updateTable("catalogSyncRuns").set({
state: "interrupted", phase: "completed", errorCode: "worker_restarted", state: "interrupted", phase: sql`case when phase='memory_cleanup' then phase else 'completed' end`, errorCode: "worker_restarted",
errorMessage: "Synchronization was interrupted by a backend restart.", errorMessage: "Synchronization was interrupted by a backend restart.",
finishedAt: sql`now()`, updatedAt: sql`now()`, finishedAt: sql`now()`, updatedAt: sql`now()`,
leaseOwner: null, leaseExpiresAt: null, leaseOwner: null, leaseExpiresAt: null,
+46 -19
View File
@@ -58,6 +58,8 @@ export class CatalogSyncWorker {
private readonly introspector: CatalogSchemaIntrospector, private readonly introspector: CatalogSchemaIntrospector,
private readonly operations: CatalogOperationCoordinator, private readonly operations: CatalogOperationCoordinator,
private readonly timeoutMs: number, private readonly timeoutMs: number,
private readonly cleanupMemory: (database: WorkspaceDatabase, run: CatalogSyncRun) => Promise<number>
= async () => 0,
) {} ) {}
async initialize(): Promise<void> { async initialize(): Promise<void> {
@@ -67,6 +69,9 @@ export class CatalogSyncWorker {
} }
async start(database: WorkspaceDatabase, scope: CatalogSyncScope, tableIds: readonly string[]): Promise<CatalogSyncRun> { async start(database: WorkspaceDatabase, scope: CatalogSyncScope, tableIds: readonly string[]): Promise<CatalogSyncRun> {
if ((await this.repository.listSyncRuns(database.id, 100)).some(run => run.phase === "memory_cleanup")) {
throw new CatalogConflictError("Retry the pending Memory cleanup before starting another synchronization");
}
const uniqueTableIds = [...new Set(tableIds)]; const uniqueTableIds = [...new Set(tableIds)];
if (scope === "columns") { if (scope === "columns") {
const tables = await Promise.all(uniqueTableIds.map((tableId) => this.repository.getTable(database.id, tableId))); const tables = await Promise.all(uniqueTableIds.map((tableId) => this.repository.getTable(database.id, tableId)));
@@ -109,7 +114,7 @@ export class CatalogSyncWorker {
async cancel(runId: string): Promise<CatalogSyncRun | undefined> { async cancel(runId: string): Promise<CatalogSyncRun | undefined> {
const run = await this.repository.getSyncRun(runId); const run = await this.repository.getSyncRun(runId);
if (!run) return undefined; if (!run) return undefined;
if (run.state === "applying" || TERMINAL_STATES.has(run.state)) return run; if (run.phase === "memory_cleanup" || run.state === "applying" || TERMINAL_STATES.has(run.state)) return run;
await this.repository.requestSyncRunCancellation(runId); await this.repository.requestSyncRunCancellation(runId);
this.controllers.get(runId)?.abort(); this.controllers.get(runId)?.abort();
if (run.state === "queued" || run.state === "awaiting_confirmation") { if (run.state === "queued" || run.state === "awaiting_confirmation") {
@@ -138,6 +143,16 @@ export class CatalogSyncWorker {
} }
const database = await this.repository.get(previous.databaseId); const database = await this.repository.get(previous.databaseId);
if (!database) return undefined; if (!database) return undefined;
if (previous.phase === "memory_cleanup") {
const release = this.operations.reserve(database.id);
try {
const queued = await this.repository.updateSyncRun(runId, { state: "queued", cancelRequested: false,
errorCode: null, errorMessage: null, finishedAt: null, leaseOwner: null, leaseExpiresAt: null });
this.reservations.set(runId, release);
this.launch(runId);
return queued;
} catch (error) { release(); throw error; }
}
return await this.start(database, previous.scope, previous.tableIds); return await this.start(database, previous.scope, previous.tableIds);
} }
@@ -179,6 +194,10 @@ export class CatalogSyncWorker {
if (!database || database.version !== claimed.requestedDatabaseVersion) { if (!database || database.version !== claimed.requestedDatabaseVersion) {
throw new CatalogConflictError("Database binding changed before synchronization started"); throw new CatalogConflictError("Database binding changed before synchronization started");
} }
if (claimed.phase === "memory_cleanup") {
await this.finishMemoryCleanup(database, claimed);
return;
}
const progress: CatalogSchemaScanProgress = async (phase, counts) => { const progress: CatalogSchemaScanProgress = async (phase, counts) => {
await this.checkCancelled(runId); await this.checkCancelled(runId);
await this.repository.updateSyncRun(runId, { await this.repository.updateSyncRun(runId, {
@@ -230,36 +249,30 @@ export class CatalogSyncWorker {
claimed.scope, claimed.scope,
claimed.tableIds, claimed.tableIds,
snapshot, snapshot,
runId,
); );
if (!applied) throw new CatalogConflictError("Database binding changed before schema changes were applied"); if (!applied) throw new CatalogConflictError("Database binding changed before schema changes were applied");
await this.repository.updateSyncRun(runId, { const cleanupRun = await this.repository.updateSyncRun(runId, { counts: applied });
state: "succeeded", if (!cleanupRun) throw new Error("Synchronization run disappeared");
phase: "completed", await this.finishMemoryCleanup(database, cleanupRun);
counts: applied, /* Completion is recorded only after the durable Memory cleanup succeeds. */
finishedAt: new Date().toISOString(), return;
observedSnapshot: null,
plannedDiff: null,
confirmationToken: null,
heartbeatAt: new Date().toISOString(),
leaseOwner: null,
leaseExpiresAt: null,
});
await this.repository.appendSyncEvent(runId, "info", "succeeded", "Synchronization completed.", { ...applied });
this.release(runId);
} catch (error) { } catch (error) {
const current = await this.repository.getSyncRun(runId); const current = await this.repository.getSyncRun(runId);
const cancelled = !timedOut && (error instanceof SyncCancelledError || controller.signal.aborted || current?.cancelRequested); const cancelled = !timedOut && (error instanceof SyncCancelledError || controller.signal.aborted || current?.cancelRequested);
const failure = timedOut const failure = current?.phase === "memory_cleanup"
? { code: "memory_cleanup_pending", message: "Catalog synchronized. Memory cleanup is pending; retry this synchronization to complete it." }
: timedOut
? { code: "schema_sync_timed_out", message: "Schema synchronization timed out." } ? { code: "schema_sync_timed_out", message: "Schema synchronization timed out." }
: safeFailure(error); : safeFailure(error);
await this.repository.updateSyncRun(runId, { await this.repository.updateSyncRun(runId, {
state: cancelled ? "cancelled" : "failed", state: cancelled ? "cancelled" : "failed",
phase: "completed", phase: current?.phase === "memory_cleanup" ? "memory_cleanup" : "completed",
errorCode: cancelled ? null : failure.code, errorCode: cancelled ? null : failure.code,
errorMessage: cancelled ? null : failure.message, errorMessage: cancelled ? null : failure.message,
finishedAt: new Date().toISOString(), finishedAt: new Date().toISOString(),
observedSnapshot: null, observedSnapshot: current?.phase === "memory_cleanup" ? current.observedSnapshot : null,
plannedDiff: null, plannedDiff: current?.phase === "memory_cleanup" ? current.plannedDiff : null,
confirmationToken: null, confirmationToken: null,
leaseOwner: null, leaseOwner: null,
leaseExpiresAt: null, leaseExpiresAt: null,
@@ -278,6 +291,20 @@ export class CatalogSyncWorker {
} }
} }
private async finishMemoryCleanup(database: WorkspaceDatabase, run: CatalogSyncRun): Promise<void> {
if (!run.plannedDiff || run.phase !== "memory_cleanup") throw new Error("Missing committed cleanup context");
await this.repository.appendSyncEvent(run.id, "info", "memory_cleanup", "Removing Memory cards with deleted physical dependencies.");
const memoryDeleted = await this.cleanupMemory(database, run);
const counts = { ...run.counts, memoryDeleted };
await this.repository.updateSyncRun(run.id, {
state: "succeeded", phase: "completed", counts, finishedAt: new Date().toISOString(),
observedSnapshot: null, plannedDiff: null, confirmationToken: null,
heartbeatAt: new Date().toISOString(), leaseOwner: null, leaseExpiresAt: null,
});
await this.repository.appendSyncEvent(run.id, "info", "succeeded", "Synchronization completed.", counts);
this.release(run.id);
}
private assertCapability(scope: CatalogSyncScope, snapshot: ObservedSchemaSnapshot): void { private assertCapability(scope: CatalogSyncScope, snapshot: ObservedSchemaSnapshot): void {
const required = scope === "all" ? ["tables", "columns", "relationships"] as const : [scope] as const; const required = scope === "all" ? ["tables", "columns", "relationships"] as const : [scope] as const;
for (const name of required) { for (const name of required) {
+7 -2
View File
@@ -40,6 +40,7 @@ export interface WorkspaceDatabase {
metadataContentRevision: number; metadataContentRevision: number;
preprocessingStatus: CatalogPreprocessingStatus; preprocessingStatus: CatalogPreprocessingStatus;
preprocessingInputFingerprint?: string; preprocessingInputFingerprint?: string;
preprocessingRunId?: string;
preprocessedMetadataRevision?: number; preprocessedMetadataRevision?: number;
preprocessingStartedAt?: string; preprocessingStartedAt?: string;
preprocessingFinishedAt?: string; preprocessingFinishedAt?: string;
@@ -366,7 +367,7 @@ export type CatalogSyncState =
export type CatalogSyncPhase = export type CatalogSyncPhase =
| "queued" | "connecting" | "scanning_tables" | "scanning_columns" | "queued" | "connecting" | "scanning_tables" | "scanning_columns"
| "scanning_relationships" | "planning" | "awaiting_confirmation" | "scanning_relationships" | "planning" | "awaiting_confirmation"
| "applying" | "completed"; | "applying" | "memory_cleanup" | "completed";
export interface CatalogSchemaDiff { export interface CatalogSchemaDiff {
deletedTables: string[]; deletedTables: string[];
@@ -375,6 +376,7 @@ export interface CatalogSchemaDiff {
} }
export interface CatalogSyncCounts { export interface CatalogSyncCounts {
memoryDeleted?: number;
tables?: number; tables?: number;
columns?: number; columns?: number;
relationships?: number; relationships?: number;
@@ -452,16 +454,18 @@ export interface CatalogRepository {
beginPreprocessing( beginPreprocessing(
workspaceId: string, workspaceId: string,
inputFingerprint: string, inputFingerprint: string,
runId?: string,
): Promise<CatalogPreprocessingStartResult>; ): Promise<CatalogPreprocessingStartResult>;
finishPreprocessing( finishPreprocessing(
workspaceId: string, workspaceId: string,
metadataContentRevision: number, metadataContentRevision: number,
inputFingerprint: string, inputFingerprint: string,
outcome: { status: "succeeded" } | { status: "failed"; errorCode: string }, outcome: { status: "succeeded" } | { status: "failed"; errorCode: string },
runId?: string,
): Promise<WorkspaceDatabase | undefined>; ): Promise<WorkspaceDatabase | undefined>;
clearPreprocessing(workspaceId: string): Promise<CatalogPreprocessingClearResult>; clearPreprocessing(workspaceId: string): Promise<CatalogPreprocessingClearResult>;
getCatalogMetrics(databaseId?: string): Promise<CatalogMetrics | undefined>; 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>; update(id: string, expectedVersion: number, input: DatabaseConfigurationInput): Promise<WorkspaceDatabase | undefined>;
recordTest(id: string, expectedVersion: number, result: DatabaseTestResult): Promise<WorkspaceDatabase | undefined>; recordTest(id: string, expectedVersion: number, result: DatabaseTestResult): Promise<WorkspaceDatabase | undefined>;
touch(id: string, expectedVersion: number): Promise<WorkspaceDatabase | undefined>; touch(id: string, expectedVersion: number): Promise<WorkspaceDatabase | undefined>;
@@ -587,6 +591,7 @@ export interface CatalogRepository {
scope: CatalogSyncScope, scope: CatalogSyncScope,
tableIds: readonly string[], tableIds: readonly string[],
snapshot: ObservedSchemaSnapshot, snapshot: ObservedSchemaSnapshot,
syncRunId?: string,
): Promise<CatalogSyncCounts | undefined>; ): Promise<CatalogSyncCounts | undefined>;
createSyncRun( createSyncRun(
databaseId: string, databaseId: string,
+5
View File
@@ -30,8 +30,11 @@ export interface AppConfig {
dataRoot?: string; dataRoot?: string;
ollamaEnsureTimeoutMs: number; ollamaEnsureTimeoutMs: number;
piManagementTimeoutMs: number; piManagementTimeoutMs: number;
/** Host CLI platform projected into Docker; not the browser or container OS. */
hostPlatform?: string;
secretsFile?: string; secretsFile?: string;
installationConfigFile?: string; installationConfigFile?: string;
evidenceHostRegistryRoot?: string;
modelCatalogFile?: string; modelCatalogFile?: string;
sensitivityNer?: { sensitivityNer?: {
pythonExecutable: string; pythonExecutable: string;
@@ -474,8 +477,10 @@ export function loadConfig(
dataRoot: env.THT_DATA_ROOT, dataRoot: env.THT_DATA_ROOT,
ollamaEnsureTimeoutMs: Number(env.OLLAMA_ENSURE_TIMEOUT_MS ?? 60000), ollamaEnsureTimeoutMs: Number(env.OLLAMA_ENSURE_TIMEOUT_MS ?? 60000),
piManagementTimeoutMs: piManagementTimeout(env.PI_MANAGEMENT_TIMEOUT_MS), piManagementTimeoutMs: piManagementTimeout(env.PI_MANAGEMENT_TIMEOUT_MS),
hostPlatform: env.THT_HOST_PLATFORM,
secretsFile, secretsFile,
installationConfigFile, installationConfigFile,
evidenceHostRegistryRoot: env.THT_EVIDENCE_HOST_REGISTRY_ROOT || undefined,
modelCatalogFile, modelCatalogFile,
sensitivityNer, sensitivityNer,
piAuthFile, piAuthFile,
+18 -17
View File
@@ -41,15 +41,17 @@ const runtimeModelSchema = z.object({
supportsReasoningEffort: z.boolean(), supportsReasoningEffort: z.boolean(),
supportsStore: z.boolean(), supportsStore: z.boolean(),
maxTokensField: z.string().optional(), maxTokensField: z.string().optional(),
thinkingFormat: z.enum(["qwen", "qwen-chat-template"]).optional(),
}).strict().optional(), }).strict().optional(),
}).strict().optional(), }).strict().refine((session) => !session.compatibility?.thinkingFormat || session.reasoning, {
message: "thinkingFormat requires reasoning: true",
}).optional(),
metadataGeneration: z.object({ disableThinking: z.boolean() }).strict().optional(), metadataGeneration: z.object({ disableThinking: z.boolean() }).strict().optional(),
}).strict(); }).strict();
const catalogSchema = z.object({ const catalogSchema = z.object({
schemaVersion: z.literal(1), schemaVersion: z.literal(2),
defaultSession: canonicalId, defaultInteraction: canonicalId,
defaultMetadataGeneration: canonicalId.optional(),
embedding: z.object({ id: canonicalId, dimensions: z.number().int().positive() }).strict(), embedding: z.object({ id: canonicalId, dimensions: z.number().int().positive() }).strict(),
models: z.array(runtimeModelSchema).max(64), models: z.array(runtimeModelSchema).max(64),
}).strict(); }).strict();
@@ -57,8 +59,7 @@ const catalogSchema = z.object({
export type RuntimeModel = z.infer<typeof runtimeModelSchema>; export type RuntimeModel = z.infer<typeof runtimeModelSchema>;
export interface RuntimeModelCatalog { export interface RuntimeModelCatalog {
readonly defaultSession: string | null; readonly defaultInteraction: string | null;
readonly defaultMetadataGeneration: string | null;
readonly embedding: Readonly<{ id: string; dimensions: number }> | null; readonly embedding: Readonly<{ id: string; dimensions: number }> | null;
sessionModels(): readonly RuntimeModel[]; sessionModels(): readonly RuntimeModel[];
metadataModels(): readonly RuntimeModel[]; metadataModels(): readonly RuntimeModel[];
@@ -66,19 +67,21 @@ export interface RuntimeModelCatalog {
} }
class RestartLoadedRuntimeModelCatalog implements RuntimeModelCatalog { class RestartLoadedRuntimeModelCatalog implements RuntimeModelCatalog {
readonly defaultSession: string | null; readonly defaultInteraction: string | null;
readonly defaultMetadataGeneration: string | null;
readonly embedding: Readonly<{ id: string; dimensions: number }> | null; readonly embedding: Readonly<{ id: string; dimensions: number }> | null;
readonly #sessions: readonly RuntimeModel[]; readonly #sessions: readonly RuntimeModel[];
readonly #metadata: readonly RuntimeModel[]; readonly #metadata: readonly RuntimeModel[];
readonly #sessionIds: ReadonlySet<string>; readonly #sessionIds: ReadonlySet<string>;
constructor(catalog?: z.infer<typeof catalogSchema>) { constructor(catalog?: z.infer<typeof catalogSchema>) {
this.defaultSession = catalog?.defaultSession ?? null; this.defaultInteraction = catalog?.defaultInteraction ?? null;
this.defaultMetadataGeneration = catalog?.defaultMetadataGeneration ?? null;
this.embedding = catalog ? Object.freeze({ ...catalog.embedding }) : null; this.embedding = catalog ? Object.freeze({ ...catalog.embedding }) : null;
this.#sessions = Object.freeze((catalog?.models ?? []).filter((model) => model.session !== undefined)); // One operational list. Session-only installations can still run Core, but once Admin
this.#metadata = Object.freeze((catalog?.models ?? []).filter((model) => model.metadataGeneration !== undefined)); // LLM models are configured every selectable model must support both adapters.
const hasMetadata = catalog?.models.some((model) => model.metadataGeneration !== undefined);
this.#sessions = Object.freeze((catalog?.models ?? []).filter((model) =>
model.session !== undefined && (!hasMetadata || model.metadataGeneration !== undefined)));
this.#metadata = Object.freeze(this.#sessions.filter((model) => model.metadataGeneration !== undefined));
this.#sessionIds = new Set(this.#sessions.map((model) => model.id)); this.#sessionIds = new Set(this.#sessions.map((model) => model.id));
} }
@@ -129,11 +132,9 @@ export function loadRuntimeModelCatalog(file?: string): RuntimeModelCatalog {
if (ids.size !== parsed.data.models.length) throw new Error("runtime model catalog contains duplicate models"); if (ids.size !== parsed.data.models.length) throw new Error("runtime model catalog contains duplicate models");
const sessions = parsed.data.models.filter((model) => model.session !== undefined).map((model) => model.id); const sessions = parsed.data.models.filter((model) => model.session !== undefined).map((model) => model.id);
const metadata = parsed.data.models.filter((model) => model.metadataGeneration !== undefined).map((model) => model.id); const metadata = parsed.data.models.filter((model) => model.metadataGeneration !== undefined).map((model) => model.id);
if (!sessions.includes(parsed.data.defaultSession)) throw new Error("runtime model catalog session default is invalid"); if (!sessions.includes(parsed.data.defaultInteraction)
if ((metadata.length > 0) !== (parsed.data.defaultMetadataGeneration !== undefined) || (metadata.length > 0 && !metadata.includes(parsed.data.defaultInteraction))) {
|| (parsed.data.defaultMetadataGeneration !== undefined throw new Error("runtime model catalog interaction default is invalid");
&& !metadata.includes(parsed.data.defaultMetadataGeneration))) {
throw new Error("runtime model catalog metadata default is invalid");
} }
return new RestartLoadedRuntimeModelCatalog(parsed.data); return new RestartLoadedRuntimeModelCatalog(parsed.data);
} }
+135 -10
View File
@@ -16,12 +16,16 @@ import { loadSettings } from "./settings/settings-store.js";
import { ThtRunner, type SessionRow } from "./tht/tht-runner.js"; import { ThtRunner, type SessionRow } from "./tht/tht-runner.js";
import { WorkspaceRegistry } from "./workspaces/registry.js"; import { WorkspaceRegistry } from "./workspaces/registry.js";
import { WorkspaceSecretStore } from "./workspaces/secret-store.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 { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js"; import type { CatalogRepository } from "./catalog/types.js";
type OperatorAction = "maintenance-activate" | "maintenance-deactivate" | "maintenance-status" type OperatorAction = "maintenance-activate" | "maintenance-deactivate" | "maintenance-status"
| "session-inventory" | "workflow-doctor" | "workspace-integrity" | "session-inventory" | "workflow-doctor" | "workspace-integrity"
| "pi-test" | "effective-settings"; | "workspace-pull" | "workspace-test" | "pi-test" | "effective-settings";
const lifecyclePrincipal: PrincipalContext = { const lifecyclePrincipal: PrincipalContext = {
issuer: "tht-operator-command", issuer: "tht-operator-command",
@@ -88,17 +92,22 @@ async function workflowDiagnostics(config: AppConfig): Promise<{ ready: true; wo
if (revisions.length === 0) throw new Error("workflow diagnostics unavailable"); if (revisions.length === 0) throw new Error("workflow diagnostics unavailable");
return await withOperatorRunner(config, async (runner) => { return await withOperatorRunner(config, async (runner) => {
for (const revision of revisions) { for (const revision of revisions) {
const result = await runner.run(["doctor", "--json"], revision.snapshotPath); const runtime = await runner.acquireWorkspaceRuntime(revision.snapshotPath);
let payload: unknown;
try { try {
payload = JSON.parse(result.stdout); const result = await runner.run(["doctor", "--json"], runtime.path);
} catch { let payload: unknown;
throw new Error("workflow diagnostics failed"); try {
payload = JSON.parse(result.stdout);
} catch {
throw new Error("workflow diagnostics failed");
}
if (
result.code !== 0 || !payload || typeof payload !== "object"
|| (payload as { ok?: unknown }).ok !== true
) throw new Error("workflow diagnostics failed");
} finally {
runtime.release();
} }
if (
result.code !== 0 || !payload || typeof payload !== "object"
|| (payload as { ok?: unknown }).ok !== true
) throw new Error("workflow diagnostics failed");
} }
return { ready: true, workspaces: revisions.length }; return { ready: true, workspaces: revisions.length };
}); });
@@ -114,6 +123,119 @@ async function workspaceIntegrity(config: AppConfig): Promise<{
return { ready: true, ...integrity }; 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( export async function runOperatorAction(
action: OperatorAction, action: OperatorAction,
config: AppConfig, config: AppConfig,
@@ -127,6 +249,8 @@ export async function runOperatorAction(
if (action === "session-inventory") return await sessionInventory(config); if (action === "session-inventory") return await sessionInventory(config);
if (action === "workflow-doctor") return await workflowDiagnostics(config); if (action === "workflow-doctor") return await workflowDiagnostics(config);
if (action === "workspace-integrity") return await workspaceIntegrity(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); const modelCatalog = loadRuntimeModelCatalog(config.modelCatalogFile);
if (action === "effective-settings") { if (action === "effective-settings") {
return effectiveSettings(config, loadSettings(config), modelCatalog); return effectiveSettings(config, loadSettings(config), modelCatalog);
@@ -141,6 +265,7 @@ async function main(): Promise<void> {
if (!action || ![ if (!action || ![
"maintenance-activate", "maintenance-deactivate", "maintenance-status", "session-inventory", "maintenance-activate", "maintenance-deactivate", "maintenance-status", "session-inventory",
"workflow-doctor", "workspace-integrity", "pi-test", "effective-settings", "workflow-doctor", "workspace-integrity", "pi-test", "effective-settings",
"workspace-pull", "workspace-test",
].includes(action)) throw new Error("invalid operator action"); ].includes(action)) throw new Error("invalid operator action");
const result = await runOperatorAction(action, loadConfig(process.env)); const result = await runOperatorAction(action, loadConfig(process.env));
process.stdout.write(`${JSON.stringify(result)}\n`); process.stdout.write(`${JSON.stringify(result)}\n`);
+9
View File
@@ -11,6 +11,7 @@ import {
validateDeclarativePiConfig, validateDeclarativePiConfig,
} from "./managed-config.js"; } from "./managed-config.js";
import type { RuntimeModelCatalog } from "../models/runtime-model-catalog.js"; import type { RuntimeModelCatalog } from "../models/runtime-model-catalog.js";
import { secretValue } from "../config/secret-bundle.js";
export interface PiModel { export interface PiModel {
provider: string; provider: string;
@@ -64,6 +65,14 @@ export function createPiModelLister(cfg: AppConfig, opts: Opts = {}): ListModels
} }
const env = buildPiChildEnv({}); const env = buildPiChildEnv({});
// Pi's availability enumeration also needs the catalog-owned credentials for built-in
// providers. It must keep working after their obsolete Pi auth entries are removed.
for (const model of opts.modelCatalog?.sessionModels() ?? []) {
const name = model.authentication.mode === "secret_env" ? model.authentication.apiKeyEnv : undefined;
if (!name) continue;
const value = secretValue(cfg, name);
if (value) env[name] = value;
}
delete env.THT_DATA_ROOT; delete env.THT_DATA_ROOT;
if (cfg.dataRoot !== undefined) env.THT_DATA_ROOT = cfg.dataRoot; if (cfg.dataRoot !== undefined) env.THT_DATA_ROOT = cfg.dataRoot;
const child = spawnFn(cfg.piBin, ["--mode", "rpc"], { cwd: cfg.harnessDir, env }); const child = spawnFn(cfg.piBin, ["--mode", "rpc"], { cwd: cfg.harnessDir, env });
+13 -2
View File
@@ -138,7 +138,7 @@ export interface PiRuntimeAgentSnapshot {
* Bind a session Pi process to the exact managed auth/model bytes validated at spawn time. * Bind a session Pi process to the exact managed auth/model bytes validated at spawn time.
* Other agent resources remain live through symlinks, while session storage stays persistent. * Other agent resources remain live through symlinks, while session storage stays persistent.
*/ */
export function createPiRuntimeAgentSnapshot(): PiRuntimeAgentSnapshot { export function createPiRuntimeAgentSnapshot(options: { excludeAuthProvider?: string } = {}): PiRuntimeAgentSnapshot {
const sourceAgentDir = configuredPiAgentDir(); const sourceAgentDir = configuredPiAgentDir();
const auth = readPiAgentFile(sourceAgentDir, "auth.json", true); const auth = readPiAgentFile(sourceAgentDir, "auth.json", true);
const models = readPiAgentFile(sourceAgentDir, "models.json", true); const models = readPiAgentFile(sourceAgentDir, "models.json", true);
@@ -165,7 +165,18 @@ export function createPiRuntimeAgentSnapshot(): PiRuntimeAgentSnapshot {
); );
} }
if (auth !== undefined) { if (auth !== undefined) {
writeFileSync(join(snapshotDir, "auth.json"), auth, { flag: "wx", mode: 0o600 }); let effectiveAuth = auth;
if (options.excludeAuthProvider) {
const parsed = parsePiConfigJson(auth);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new PiManagedConfigError();
const provider = options.excludeAuthProvider.trim().toLowerCase();
effectiveAuth = JSON.stringify(Object.fromEntries(
Object.entries(parsed).filter(([key]) => key.trim().toLowerCase() !== provider),
));
}
// secret_env is authoritative for this provider. Keep the operator's auth file intact,
// but do not let an old Pi credential override the shared bundle inside this child.
writeFileSync(join(snapshotDir, "auth.json"), effectiveAuth, { flag: "wx", mode: 0o600 });
} }
if (models !== undefined) { if (models !== undefined) {
writeFileSync(join(snapshotDir, "models.json"), models, { flag: "wx", mode: 0o600 }); writeFileSync(join(snapshotDir, "models.json"), models, { flag: "wx", mode: 0o600 });
+15 -11
View File
@@ -36,6 +36,7 @@ export interface PiInstallationConfig {
} }
export interface PiStatus { export interface PiStatus {
hostPlatform: "linux" | "macos" | "windows";
version?: string; version?: string;
ready: boolean; ready: boolean;
credentials: PiCredentialStatus; credentials: PiCredentialStatus;
@@ -92,6 +93,9 @@ interface PiManagementDeps {
} }
export function createPiManagement(config: AppConfig, deps: PiManagementDeps): PiManagementService { export function createPiManagement(config: AppConfig, deps: PiManagementDeps): PiManagementService {
const platform = config.hostPlatform ?? process.platform;
const hostPlatform = platform === "darwin" ? "macos"
: platform === "windows" || platform === "win32" ? "windows" : "linux";
const now = deps.now ?? (() => new Date()); const now = deps.now ?? (() => new Date());
const diagnostics: string[] = []; const diagnostics: string[] = [];
const addDiagnostic = (message: string): void => { const addDiagnostic = (message: string): void => {
@@ -106,23 +110,23 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
}); });
const credentialStatus = deps.credentialStatus ?? ((provider: string | undefined) => { const credentialStatus = deps.credentialStatus ?? ((provider: string | undefined) => {
try { try {
const model = deps.modelCatalog.defaultSession const model = deps.modelCatalog.defaultInteraction
? deps.modelCatalog.sessionModels().find((entry) => entry.id === deps.modelCatalog.defaultSession) ? deps.modelCatalog.sessionModels().find((entry) => entry.id === deps.modelCatalog.defaultInteraction)
: undefined; : undefined;
const credentialName = model?.authentication.mode === "secret_env" const credentialName = model?.authentication.mode === "secret_env"
? model.authentication.apiKeyEnv ? model.authentication.apiKeyEnv
: undefined; : undefined;
const configuredApiKey = configuredPiProviderApiKey( const configuredApiKey = credentialName ? `$${credentialName}` : configuredPiProviderApiKey(
readConfiguredPiAgentFile("models.json", true), readConfiguredPiAgentFile("models.json", true),
provider, provider,
) ?? (credentialName ? `$${credentialName}` : undefined); );
return piProviderCredentialStatus({ return piProviderCredentialStatus({
provider, provider,
authProviders: loadPiAuthProviders(), authProviders: credentialName ? new Set() : loadPiAuthProviders(),
resolveCredentialValue: () => credentialName resolveCredentialValue: () => credentialName
? secretValue(config, credentialName) ? secretValue(config, credentialName)
: config.modelCatalogFile ? undefined : secretValue(config, "THT_MODEL_API_KEY"), : config.modelCatalogFile ? undefined : secretValue(config, "THT_MODEL_API_KEY"),
credentialFile: config.modelApiKeyFile, credentialFile: credentialName ? undefined : config.modelApiKeyFile,
configuredApiKey, configuredApiKey,
}); });
} catch { } catch {
@@ -151,9 +155,9 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
const installationConfig = (): PiInstallationConfig => { const installationConfig = (): PiInstallationConfig => {
const settings = readSettings(); const settings = readSettings();
const reasoning = config.defaults.thinking ?? settings.thinking; const reasoning = config.defaults.thinking ?? settings.thinking ?? "low";
const selected = deps.modelCatalog.defaultSession const selected = deps.modelCatalog.defaultInteraction
? splitCanonicalModelId(deps.modelCatalog.defaultSession) ? splitCanonicalModelId(deps.modelCatalog.defaultInteraction)
: undefined; : undefined;
return { return {
...(selected ? selected : {}), ...(selected ? selected : {}),
@@ -169,11 +173,11 @@ export function createPiManagement(config: AppConfig, deps: PiManagementDeps): P
try { try {
const currentVersion = await version(); const currentVersion = await version();
addDiagnostic("Pi version probe succeeded"); addDiagnostic("Pi version probe succeeded");
return { version: currentVersion, ready: true, credentials, config: current, checkedAt }; return { hostPlatform, version: currentVersion, ready: true, credentials, config: current, checkedAt };
} catch (error) { } catch (error) {
const message = stableMessage(error, "Pi runtime is unavailable"); const message = stableMessage(error, "Pi runtime is unavailable");
addDiagnostic(message); addDiagnostic(message);
return { ready: false, credentials, config: current, checkedAt, message }; return { hostPlatform, ready: false, credentials, config: current, checkedAt, message };
} }
}, },
+30 -19
View File
@@ -25,6 +25,7 @@ export interface SessionRuntime {
} }
export interface RuntimeOptions { export interface RuntimeOptions {
interactionLanguage?: string | null;
provider?: string; provider?: string;
model?: string; model?: string;
thinking?: string; thinking?: string;
@@ -48,6 +49,7 @@ export class PiProcessManager {
private spawnFn: ( private spawnFn: (
sessionId: string, author: string, provider: string | undefined, model: string | undefined, sessionId: string, author: string, provider: string | undefined, model: string | undefined,
principal?: PrincipalContext, runtimeConfigPath?: string, principal?: PrincipalContext, runtimeConfigPath?: string,
interactionLanguage?: string | null,
) => ChildProcessWithoutNullStreams; ) => ChildProcessWithoutNullStreams;
private loadAuthProviders: (agentDir: string) => ReadonlySet<string>; private loadAuthProviders: (agentDir: string) => ReadonlySet<string>;
private modelCatalog: RuntimeModelCatalog; private modelCatalog: RuntimeModelCatalog;
@@ -63,15 +65,15 @@ export class PiProcessManager {
) { ) {
this.modelCatalog = opts?.modelCatalog ?? loadRuntimeModelCatalog(cfg.modelCatalogFile); this.modelCatalog = opts?.modelCatalog ?? loadRuntimeModelCatalog(cfg.modelCatalogFile);
this.modelCatalogConfigured = cfg.modelCatalogFile !== undefined this.modelCatalogConfigured = cfg.modelCatalogFile !== undefined
|| this.modelCatalog.defaultSession !== null; || this.modelCatalog.defaultInteraction !== null;
this.loadAuthProviders = opts?.authProviders this.loadAuthProviders = opts?.authProviders
?? ((agentDir) => loadPiAuthProviders({ agentDir })); ?? ((agentDir) => loadPiAuthProviders({ agentDir }));
if (opts?.spawnFn) { if (opts?.spawnFn) {
this.spawnFn = (sessionId, author, provider, model, principal, runtimeConfigPath) => this.spawnFn = (sessionId, author, provider, model, principal, runtimeConfigPath, language) =>
this.spawnPi(opts.spawnFn!, sessionId, author, provider, model, principal, runtimeConfigPath); this.spawnPi(opts.spawnFn!, sessionId, author, provider, model, principal, runtimeConfigPath, language);
} else { } else {
this.spawnFn = (sessionId, author, provider, model, principal, runtimeConfigPath) => this.spawnFn = (sessionId, author, provider, model, principal, runtimeConfigPath, language) =>
this.spawnPi(nodeSpawn, sessionId, author, provider, model, principal, runtimeConfigPath); this.spawnPi(nodeSpawn, sessionId, author, provider, model, principal, runtimeConfigPath, language);
} }
} }
@@ -85,33 +87,35 @@ export class PiProcessManager {
private spawnPi( private spawnPi(
spawnFn: SpawnFn, sessionId: string, author: string, provider: string | undefined, spawnFn: SpawnFn, sessionId: string, author: string, provider: string | undefined,
model: string | undefined, principal?: PrincipalContext, runtimeConfigPath?: string, model: string | undefined, principal?: PrincipalContext, runtimeConfigPath?: string,
interactionLanguage?: string | null,
): ChildProcessWithoutNullStreams { ): ChildProcessWithoutNullStreams {
// This is the final shared boundary for createFor(), spawnFor(), and resume(). Validate // This is the final shared boundary for createFor(), spawnFor(), and resume(). Validate
// before auth-provider inspection, then make Pi consume the exact copied bytes rather than // before auth-provider inspection, then make Pi consume the exact copied bytes rather than
// reopening mutable mounted auth/models files after this check. // reopening mutable mounted auth/models files after this check.
const agent = createPiRuntimeAgentSnapshot(); const catalogModel = provider && model
? this.modelCatalog.sessionModels().find((entry) => entry.provider === provider && entry.model === model)
: undefined;
const credentialName = catalogModel?.authentication.mode === "secret_env"
? catalogModel.authentication.apiKeyEnv : undefined;
const agent = createPiRuntimeAgentSnapshot({ excludeAuthProvider: credentialName ? provider : undefined });
let child: ChildProcessWithoutNullStreams | undefined; let child: ChildProcessWithoutNullStreams | undefined;
try { try {
const catalogModel = provider && model const projectedApiKey = credentialName ? `$${credentialName}`
? this.modelCatalog.sessionModels() : configuredPiProviderApiKey(agent.models, provider);
.find((entry) => entry.provider === provider && entry.model === model)
: undefined;
const credentialName = catalogModel?.authentication.mode === "secret_env"
? catalogModel.authentication.apiKeyEnv
: undefined;
const projectedApiKey = configuredPiProviderApiKey(agent.models, provider)
?? (credentialName ? `$${credentialName}` : undefined);
const env = buildPiChildEnv({ const env = buildPiChildEnv({
provider, provider,
authProviders: this.loadAuthProviders(agent.agentDir), authProviders: credentialName ? new Set() : this.loadAuthProviders(agent.agentDir),
credentialValue: credentialName credentialValue: credentialName
? secretValue(this.cfg, credentialName) ? secretValue(this.cfg, credentialName)
: this.modelCatalogConfigured ? undefined : secretValue(this.cfg, "THT_MODEL_API_KEY"), : this.modelCatalogConfigured ? undefined : secretValue(this.cfg, "THT_MODEL_API_KEY"),
credentialFile: this.cfg.modelApiKeyFile, credentialFile: credentialName ? undefined : this.cfg.modelApiKeyFile,
configuredApiKey: projectedApiKey, configuredApiKey: projectedApiKey,
additions: { THT_SESSION: sessionId, THT_AUTHOR: author }, additions: { THT_SESSION: sessionId, THT_AUTHOR: author },
}); });
env.PI_CODING_AGENT_DIR = agent.agentDir; env.PI_CODING_AGENT_DIR = agent.agentDir;
// A launch hint only: the gate reads the authoritative manifest before each turn.
delete env.THT_INTERACTION_LANGUAGE;
if (interactionLanguage) env.THT_INTERACTION_LANGUAGE = interactionLanguage;
env.PI_CODING_AGENT_SESSION_DIR = agent.sessionDir; env.PI_CODING_AGENT_SESSION_DIR = agent.sessionDir;
clearPrincipalEnvironment(env); clearPrincipalEnvironment(env);
if (principal) Object.assign(env, principalEnvironment(principal)); if (principal) Object.assign(env, principalEnvironment(principal));
@@ -189,7 +193,9 @@ export class PiProcessManager {
const model = o.model ?? this.cfg.defaults.model; const model = o.model ?? this.cfg.defaults.model;
let child: ChildProcessWithoutNullStreams; let child: ChildProcessWithoutNullStreams;
try { try {
child = this.spawnFn(sessionId, author, provider, model, o.principal, o.runtimeConfig?.path); child = this.spawnFn(
sessionId, author, provider, model, o.principal, o.runtimeConfig?.path, o.interactionLanguage,
);
} catch (error) { } catch (error) {
o.runtimeConfig?.release(); o.runtimeConfig?.release();
throw error; throw error;
@@ -298,8 +304,13 @@ export class PiProcessManager {
} }
async resume(sessionId: string, tht: ThtRunner): Promise<SessionRuntime> { async resume(sessionId: string, tht: ThtRunner): Promise<SessionRuntime> {
const manifest = await tht.sessionShow(sessionId) as { provider?: string; model?: string; thinking?: string } | null; const manifest = await tht.sessionShow(sessionId) as {
provider?: string; model?: string; thinking?: string; interaction_language?: string | null;
} | null;
const language = manifest?.interaction_language
?? (await tht.ensureInteractionLanguage(sessionId)).interaction_language;
return this.spawnFor(sessionId, { return this.spawnFor(sessionId, {
interactionLanguage: language,
provider: manifest?.provider, provider: manifest?.provider,
model: manifest?.model, model: manifest?.model,
thinking: manifest?.thinking, thinking: manifest?.thinking,
+6 -5
View File
@@ -70,28 +70,29 @@ export function createPiProviderSmoke(
try { try {
const canonicalProvider = canonicalPiProvider(provider); const canonicalProvider = canonicalPiProvider(provider);
if (!canonicalProvider || timeoutMs <= 0) throw providerFailure(); if (!canonicalProvider || timeoutMs <= 0) throw providerFailure();
const configuredAuthProviders = authProviders(); const configuredAuthProviders = new Set(authProviders());
const configuredModels = options.readModelsStore const configuredModels = options.readModelsStore
? options.readModelsStore() ? options.readModelsStore()
: readConfiguredPiAgentFile("models.json", true); : readConfiguredPiAgentFile("models.json", true);
const catalog = options.modelCatalog ?? loadRuntimeModelCatalog(config.modelCatalogFile); const catalog = options.modelCatalog ?? loadRuntimeModelCatalog(config.modelCatalogFile);
const catalogConfigured = config.modelCatalogFile !== undefined const catalogConfigured = config.modelCatalogFile !== undefined
|| catalog.defaultSession !== null; || catalog.defaultInteraction !== null;
const catalogModel = catalog.sessionModels() const catalogModel = catalog.sessionModels()
.find((entry) => entry.provider === canonicalProvider && entry.model === model); .find((entry) => entry.provider === canonicalProvider && entry.model === model);
const upstreamModel = catalogModel?.upstreamModel ?? model; const upstreamModel = catalogModel?.upstreamModel ?? model;
const credentialName = catalogModel?.authentication.mode === "secret_env" const credentialName = catalogModel?.authentication.mode === "secret_env"
? catalogModel.authentication.apiKeyEnv ? catalogModel.authentication.apiKeyEnv
: undefined; : undefined;
const projectedApiKey = configuredPiProviderApiKey(configuredModels, canonicalProvider) if (credentialName) configuredAuthProviders.delete(canonicalProvider);
?? (credentialName ? `$${credentialName}` : undefined); const projectedApiKey = credentialName ? `$${credentialName}`
: configuredPiProviderApiKey(configuredModels, canonicalProvider);
const env = buildPiChildEnv({ const env = buildPiChildEnv({
provider: canonicalProvider, provider: canonicalProvider,
authProviders: configuredAuthProviders, authProviders: configuredAuthProviders,
credentialValue: credentialName credentialValue: credentialName
? secretValue(config, credentialName) ? secretValue(config, credentialName)
: catalogConfigured ? undefined : secretValue(config, "THT_MODEL_API_KEY"), : catalogConfigured ? undefined : secretValue(config, "THT_MODEL_API_KEY"),
credentialFile: config.modelApiKeyFile, credentialFile: credentialName ? undefined : config.modelApiKeyFile,
configuredApiKey: projectedApiKey, configuredApiKey: projectedApiKey,
}); });
clearPrincipalEnvironment(env); clearPrincipalEnvironment(env);
+1 -42
View File
@@ -1,60 +1,19 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod"; import { z } from "zod";
import { isPrincipalContext, requirePermission } from "../auth/authorization.js"; 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 { CatalogService, type CatalogSecretName } from "../catalog/service.js";
import { WorkspaceRegistryError } from "../workspaces/git-repository.js"; import { WorkspaceRegistryError } from "../workspaces/git-repository.js";
import { import {
CatalogConflictError, CatalogConflictError,
CatalogOperationInProgressError, CatalogOperationInProgressError,
CatalogUnavailableError, CatalogUnavailableError,
DATABASE_TRANSPORTS,
type CatalogRepository, type CatalogRepository,
type DatabaseConfigurationInput, type DatabaseConfigurationInput,
} from "../catalog/types.js"; } from "../catalog/types.js";
import type { CatalogOperationCoordinator } from "../catalog/operation-coordinator.js"; import type { CatalogOperationCoordinator } from "../catalog/operation-coordinator.js";
const idSchema = z.uuid(); 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 updateSchema = configSchema.extend({ version: z.number().int().positive() });
const secretNames = [ const secretNames = [
"password", "password",
+90
View File
@@ -0,0 +1,90 @@
import path from "node:path";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { requirePermission, isPrincipalContext } from "../auth/authorization.js";
import type { ThtRunner } from "../tht/tht-runner.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
import type { WorkspacePreprocessingService } from "../workspaces/preprocessing-service.js";
const params = z.object({ workspaceId: z.string().regex(/^[a-z][a-z0-9-]{2,62}$/),
evidenceId: z.string().regex(/^evidence:[a-z0-9]+(?:-[a-z0-9]+)*$/).optional() });
const query = z.object({
q: z.string().max(1000).optional(), kind: z.enum(["domain", "glossary", "enum", "example", "mapping", "normalization", "formula", "reference"]).optional(),
purpose: z.enum(["disambiguation", "rewriting", "schema_linking", "sql_generation"]).optional(),
status: z.enum(["new", "modified", "active", "removed", "review_required", "legacy", "invalid"]).optional(),
concept: z.string().max(300).optional(), table: z.string().max(300).optional(), column: z.string().max(300).optional(),
source: z.string().max(300).optional(), language: z.string().max(30).optional(),
sort: z.enum(["title", "id", "kind", "status"]).optional(), direction: z.enum(["asc", "desc"]).optional(),
page: z.coerce.number().int().positive().optional(), page_size: z.coerce.number().int().min(1).max(100).optional(),
}).strict();
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
export function evidenceRoutes(app: FastifyInstance, deps: {
runner: Pick<ThtRunner, "withPrincipal">; registry: Pick<WorkspaceRegistry, "list">;
registryRoot: string; hostRegistryRoot?: string;
service: Partial<Pick<WorkspacePreprocessingService, "consolidateEvidence" | "evidenceSources">>;
}) {
app.post("/workspaces/:workspaceId/evidence/sources", async (request, reply) => {
const principal = requirePermission(request, reply, "evidence.manage");
if (!isPrincipalContext(principal)) return reply;
try {
const { workspaceId } = params.parse(request.params);
const body = z.discriminatedUnion("action", [
z.object({ action: z.literal("refresh") }).strict(),
z.object({ action: z.literal("decide"), sourceId: z.string().regex(/^[a-f0-9]{64}$/),
revision: z.string().regex(/^[a-f0-9]{64}$/), decision: z.enum(["keep", "replace"]) }).strict(),
]).parse(request.body);
if (!(await deps.registry.list()).some(w => w.id === workspaceId)) return reply.code(404).send({ code: "workspace_invalid" });
if (!deps.service.evidenceSources) throw new Error("Evidence service unavailable");
return await deps.service.evidenceSources({ workspaceId, ...body, actor: principal.subject });
} catch (error) {
return reply.code(error instanceof z.ZodError ? 400 : 503).send({ code: "evidence_unavailable",
message: error instanceof z.ZodError ? "Invalid source request." : "Evidence source service is unavailable." });
}
});
app.get<{ Params: { workspaceId: string; evidenceId?: string } }>("/workspaces/:workspaceId/evidence", read);
app.get<{ Params: { workspaceId: string; evidenceId?: string } }>("/workspaces/:workspaceId/evidence/:evidenceId", read);
async function read(request: import("fastify").FastifyRequest, reply: import("fastify").FastifyReply) {
const principal = requirePermission(request, reply, "evidence.manage");
if (!isPrincipalContext(principal)) return reply;
try {
const { workspaceId, evidenceId } = params.parse(request.params);
const filters = query.parse(request.query);
if (!(await deps.registry.list()).some(w => w.id === workspaceId)) return reply.code(404).send({ code: "workspace_invalid" });
const root = path.join(deps.registryRoot, "repo", workspaceId);
const result = await deps.runner.withPrincipal(principal).runWithRuntimeSnapshot(
["evidence", "admin", "--workspace", workspaceId],
JSON.stringify({ root, query: { ...filters, ...(evidenceId ? { id: evidenceId } : {}) } }),
);
const payload = JSON.parse(result.stdout);
if (result.code !== 0) return reply.code(503).send(payload);
if (evidenceId && !payload.item) return reply.code(404).send({ code: "evidence_not_found", message: "Evidence was not found." });
const host = deps.hostRegistryRoot;
const hostPath = host && (path.isAbsolute(host) || path.win32.isAbsolute(host))
? (path.win32.isAbsolute(host) && !path.isAbsolute(host) ? path.win32 : path).join(host, "repo") : null;
const hostJoin = hostPath && path.win32.isAbsolute(hostPath) && !path.isAbsolute(hostPath) ? path.win32.join : path.join;
return { ...payload, location: { repository: hostPath, workspace: hostPath ? hostJoin(hostPath, workspaceId) : null,
runtime_workspace: root, host: "Installation host", command: `tht workspace evidence consolidate --workspace ${workspaceId}`,
git_commands: hostPath ? [
`git -C ${quote(hostPath)} status --short -- ${quote(workspaceId + "/evidence")}`,
`git -C ${quote(hostPath)} diff -- ${quote(workspaceId + "/evidence")}`,
`git -C ${quote(hostPath)} add -A -- ${quote(workspaceId + "/evidence")}`,
`git -C ${quote(hostPath)} commit --only -m 'Curate Evidence' -- ${quote(workspaceId + "/evidence")}`,
`git -C ${quote(hostPath)} push`,
] : [] } };
} catch (error) {
return reply.code(error instanceof z.ZodError ? 400 : 503).send({ code: "evidence_unavailable",
message: error instanceof z.ZodError ? "Evidence filters are invalid." : "Evidence archive is unavailable." });
}
}
app.post("/workspaces/:workspaceId/evidence/consolidate", async (request, reply) => {
const principal = requirePermission(request, reply, "evidence.manage");
if (!isPrincipalContext(principal)) return reply;
try {
const { workspaceId } = params.parse(request.params);
if (!(await deps.registry.list()).some(w => w.id === workspaceId)) return reply.code(404).send({ code: "workspace_invalid" });
if (!deps.service.consolidateEvidence) throw new Error("Evidence service unavailable");
return await deps.service.consolidateEvidence({ workspaceId });
} catch { return reply.code(503).send({ code: "evidence_unavailable", message: "Evidence consolidation is unavailable." }); }
});
}
+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" });
}
});
}
+94
View File
@@ -0,0 +1,94 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { isPrincipalContext, requirePermission } from "../auth/authorization.js";
import type { ThtRunner } from "../tht/tht-runner.js";
import type { WorkspaceRegistry } from "../workspaces/registry.js";
import type { SemanticRuntimeConfig } from "../workspaces/runtime-renderer.js";
const paramsSchema = z.object({
workspaceId: z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/),
cardId: z.string().regex(/^mem-[0-9a-f-]{36}$/).optional(),
});
const family = z.enum(["domain_clarification", "sql_rule", "solved_question", "explained_error"]);
const cardSchema = z.object({
family, subject: z.string().trim().min(1).max(1000),
detail: z.string().max(50000).default(""), scope: z.string().trim().min(1).max(10000),
rationale: z.string().max(10000).default(""), question: z.string().max(10000).default(""),
sql: z.string().max(100000).default(""),
concepts: z.array(z.string().trim().min(1).max(200)).max(100).default([]),
dependencies: z.array(z.object({
database: z.string().trim().min(1).max(200), schema_name: z.string().max(200).default(""),
table: z.string().max(200).default(""), column: z.string().max(200).default(""),
}).strict()).max(200).default([]),
links: z.array(z.object({
target_id: z.string().min(1).max(100), meaning: z.string().trim().min(1).max(1000),
}).strict()).max(200).default([]),
}).strict();
const querySchema = z.object({
q: z.string().max(1000).optional(), family: family.optional(),
concept: z.string().max(200).optional(), database: z.string().max(200).optional(),
table: z.string().max(200).optional(), column: z.string().max(200).optional(),
origin: z.enum(["manual", "workflow"]).optional(),
updated_after: z.iso.datetime({ offset: true }).optional(),
updated_before: z.iso.datetime({ offset: true }).optional(),
page: z.coerce.number().int().positive().optional(),
page_size: z.coerce.number().int().min(1).max(100).optional(),
sort: z.enum(["updated_at", "created_at", "subject", "family"]).optional(),
direction: z.enum(["asc", "desc"]).optional(),
}).strict();
export function memoryRoutes(app: FastifyInstance, deps: {
runner: Pick<ThtRunner, "withPrincipal">;
registry: Pick<WorkspaceRegistry, "list" | "read">;
runtime: SemanticRuntimeConfig;
}) {
const invoke = (action: string) => async (request: FastifyRequest, reply: FastifyReply) => {
const principal = requirePermission(request, reply, "memory.manage");
if (!isPrincipalContext(principal)) return reply;
try {
const { workspaceId, cardId } = paramsSchema.parse(request.params);
const input = action === "list" ? querySchema.parse(request.query)
: action === "create" || action === "update"
? { card: cardSchema.parse(request.body), ...(cardId ? { id: cardId } : {}) }
: cardId ? { id: cardId } : {};
// Registry identity is enough: administrative browsing must not require a DWH binding.
const workspaces = await deps.registry.list();
if (!workspaces.some(workspace => workspace.id === workspaceId)) {
return reply.code(404).send({ code: "workspace_invalid", message: "Workspace was not found." });
}
const { workspace } = await deps.registry.read(workspaceId);
const result = await deps.runner.withPrincipal(principal).runWithRuntimeSnapshot(
["memory", "admin", "--workspace", workspaceId],
JSON.stringify({ action, request: input, runtime: {
...deps.runtime, memoryLanguage: workspace.workspace.language,
} }),
);
let payload;
try { payload = JSON.parse(result.stdout); } catch {
return reply.code(503).send({ code: "memory_unavailable", message: "Memory archive is unavailable." });
}
if (result.code !== 0) {
const codes: Record<string, number> = {
memory_invalid: 400, memory_forbidden: 403, memory_not_found: 404,
memory_conflict: 409, memory_unavailable: 503,
};
const code = typeof payload?.code === "string" && payload.code in codes
? payload.code : "memory_unavailable";
return reply.code(codes[code]).send({ code, message: "Memory operation could not be completed." });
}
return reply.code(action === "create" ? 201 : 200).send(payload);
} catch (error) {
if (error instanceof z.ZodError) {
return reply.code(400).send({ code: "memory_invalid", message: "Memory request is invalid." });
}
return reply.code(503).send({ code: "memory_unavailable", message: "Memory archive is unavailable." });
}
};
app.get("/workspaces/:workspaceId/memory", invoke("list"));
app.post("/workspaces/:workspaceId/memory", invoke("create"));
app.get("/workspaces/:workspaceId/memory/pending", invoke("pending"));
app.get("/workspaces/:workspaceId/memory/:cardId", invoke("show"));
app.put("/workspaces/:workspaceId/memory/:cardId", invoke("update"));
app.delete("/workspaces/:workspaceId/memory/:cardId", invoke("delete"));
app.post("/workspaces/:workspaceId/memory/:cardId/retry", invoke("retry"));
}
+97 -23
View File
@@ -13,6 +13,7 @@ import type { MaintenanceBarrier } from "../runtime/maintenance-gate.js";
import { hasPermission, isPrincipalContext, requirePermission } from "../auth/authorization.js"; import { hasPermission, isPrincipalContext, requirePermission } from "../auth/authorization.js";
import { splitCanonicalModelId, type RuntimeModelCatalog } from "../models/runtime-model-catalog.js"; import { splitCanonicalModelId, type RuntimeModelCatalog } from "../models/runtime-model-catalog.js";
import type { CatalogRepository } from "../catalog/types.js"; import type { CatalogRepository } from "../catalog/types.js";
import { interactionLanguage } from "../tht/interaction-language.js";
const BOOTSTRAP_FAILURE_MESSAGE = const BOOTSTRAP_FAILURE_MESSAGE =
"Session startup failed. Check configuration and connectivity, then Resume the session."; "Session startup failed. Check configuration and connectivity, then Resume the session.";
@@ -150,13 +151,34 @@ export function sessionRoutes(
}); });
app.addHook("onResponse", async (req) => { admissionLeases.get(req)?.(); }); app.addHook("onResponse", async (req) => { admissionLeases.get(req)?.(); });
type SessionRevisionScan = {
revisions: Awaited<ReturnType<typeof d.workspaceRegistry.list>>;
retainedComplete: boolean;
};
let retainedSnapshotWarning: string | null = null;
/** Include retained historical descriptors so removed workspaces remain resumable. */ /** Include retained historical descriptors so removed workspaces remain resumable. */
const sessionRevisions = async () => { const sessionRevisions = async (): Promise<SessionRevisionScan> => {
const registry = d.workspaceRegistry as Partial<WorkspaceRegistry>; const registry = d.workspaceRegistry as Partial<WorkspaceRegistry>;
if (typeof registry.listRetainedSnapshots === "function") { if (typeof registry.listRetainedSnapshots === "function") {
return await registry.listRetainedSnapshots(); try {
const revisions = await registry.listRetainedSnapshots();
retainedSnapshotWarning = null;
return { revisions, retainedComplete: true };
} catch (error) {
// A legacy/corrupt historical snapshot must not make active sessions (and their SSE
// reviewer gates) unreachable. The registry still rejects that snapshot; this fallback
// exposes only descriptors from the verified active state and deliberately disables
// retention reconciliation because the resulting session view is incomplete.
const detail = error instanceof Error ? error.message : "unknown error";
if (retainedSnapshotWarning !== detail) {
console.warn("[sessions] retained snapshot discovery failed; using active snapshots:", detail);
retainedSnapshotWarning = detail;
}
return { revisions: await d.workspaceRegistry.list(), retainedComplete: false };
}
} }
return await d.workspaceRegistry.list(); return { revisions: await d.workspaceRegistry.list(), retainedComplete: true };
}; };
const isNotFound = (error: unknown) => const isNotFound = (error: unknown) =>
@@ -200,7 +222,7 @@ export function sessionRoutes(
}; };
let revisions: Awaited<ReturnType<typeof d.workspaceRegistry.list>>; let revisions: Awaited<ReturnType<typeof d.workspaceRegistry.list>>;
try { try {
revisions = await sessionRevisions(); ({ revisions } = await sessionRevisions());
} catch (registryError) { } catch (registryError) {
// Sessions created before revision pinning still live under the installation's legacy // Sessions created before revision pinning still live under the installation's legacy
// default config. Keep that compatibility path available when a fresh installation has // default config. Keep that compatibility path available when a fresh installation has
@@ -360,8 +382,17 @@ export function sessionRoutes(
app.post("/sessions", async (req, reply) => { app.post("/sessions", async (req, reply) => {
const b = req.body as { const b = req.body as {
question: string; name?: string; workspace?: string; workspaceId?: string; question: string; name?: string; workspace?: string; workspaceId?: string;
provider?: string; model?: string; thinking?: string; provider?: string; model?: string; thinking?: string; interactionLanguage?: unknown;
}; };
const language = interactionLanguage(b?.interactionLanguage);
if (!language) return reply.code(400).send({
code: "invalid_interaction_language",
error: "interactionLanguage must be a well-formed BCP-47 language tag",
});
if ((b.provider === undefined) !== (b.model === undefined)
|| (b.provider !== undefined && (typeof b.provider !== "string" || typeof b.model !== "string" || !b.provider || !b.model))) {
return reply.code(400).send({ error: "provider and model must be supplied together" });
}
const principal = getPrincipal(req); const principal = getPrincipal(req);
let s: Settings; let s: Settings;
try { s = await d.getSettings(principal); } catch { return storageFailure(reply); } try { s = await d.getSettings(principal); } catch { return storageFailure(reply); }
@@ -425,11 +456,9 @@ export function sessionRoutes(
} }
} }
const requestedCanonical = b.provider && b.model ? `${b.provider}/${b.model}` : undefined; const requestedCanonical = b.provider && b.model ? `${b.provider}/${b.model}` : undefined;
let selectedCanonical = requestedCanonical ?? d.modelCatalog.defaultSession; const selectedCanonical = requestedCanonical ?? d.modelCatalog.defaultInteraction;
let modelWarning: string | undefined; if (selectedCanonical && d.modelCatalog.defaultInteraction && !d.modelCatalog.hasSession(selectedCanonical)) {
if (selectedCanonical && d.modelCatalog.defaultSession && !d.modelCatalog.hasSession(selectedCanonical)) { return reply.code(503).send({ error: MODEL_UNAVAILABLE_MESSAGE, code: "model_unavailable" });
selectedCanonical = d.modelCatalog.defaultSession;
modelWarning = `Configured model ${requestedCanonical ?? "selection"} is unavailable; using ${selectedCanonical}.`;
} }
const selected = selectedCanonical ? splitCanonicalModelId(selectedCanonical) : undefined; const selected = selectedCanonical ? splitCanonicalModelId(selectedCanonical) : undefined;
const provider = selected?.provider ?? b.provider; const provider = selected?.provider ?? b.provider;
@@ -480,11 +509,15 @@ export function sessionRoutes(
// registry snapshot. The legacy fallback stays available for sessions created before // registry snapshot. The legacy fallback stays available for sessions created before
// the browser-local preference migration. // the browser-local preference migration.
let id: string; let id: string;
let sessionLanguage = language;
try { try {
({ id } = await runner.sessionNew({ const created = await runner.sessionNew({
question: b.question, name: b.name, workspaceConfigPath, question: b.question, name: b.name, workspaceConfigPath,
workspaceId, workspaceRevision, provider, model, thinking, workspaceId, workspaceRevision, provider, model, thinking,
})); interactionLanguage: language,
});
id = created.id;
sessionLanguage = created.interaction_language ?? language;
manifestPersisted = true; manifestPersisted = true;
if (revisionLease) { if (revisionLease) {
await revisionLease.markPersisted().catch((error: unknown) => { await revisionLease.markPersisted().catch((error: unknown) => {
@@ -497,6 +530,7 @@ export function sessionRoutes(
} catch { return storageFailure(reply); } } catch { return storageFailure(reply); }
const options = { const options = {
provider, model, thinking, provider, model, thinking,
interactionLanguage: sessionLanguage,
author: principal.displayName ?? principal.subject, author: principal.displayName ?? principal.subject,
principal, principal,
question: b.question, question: b.question,
@@ -533,7 +567,7 @@ export function sessionRoutes(
), ),
() => d.mgr.start(id, rt, runtimeOptions), () => d.mgr.start(id, rt, runtimeOptions),
); );
return { id, ...(modelWarning ? { warning: modelWarning } : {}) }; return { id };
} finally { } finally {
if (revisionLease && !manifestPersisted) { if (revisionLease && !manifestPersisted) {
await revisionLease.abort().catch((error: unknown) => { await revisionLease.abort().catch((error: unknown) => {
@@ -559,8 +593,8 @@ export function sessionRoutes(
? { ...principal, isAdmin: false } ? { ...principal, isAdmin: false }
: ownershipPrincipal(principal, "session.read_all"); : ownershipPrincipal(principal, "session.read_all");
const runner = runnerFor(scopedPrincipal); const runner = runnerFor(scopedPrincipal);
const revisions = await sessionRevisions(); const revisionScan = await sessionRevisions();
const lists = await Promise.all(revisions const lists = await Promise.all(revisionScan.revisions
.map((revision) => runner.sessionList(revision.snapshotPath) as Promise<SessionRow[]>)); .map((revision) => runner.sessionList(revision.snapshotPath) as Promise<SessionRow[]>));
const sessions = new Map<string, SessionRow>(); const sessions = new Map<string, SessionRow>();
for (const row of lists.flat()) { for (const row of lists.flat()) {
@@ -570,7 +604,8 @@ export function sessionRoutes(
// Only an administrator-visible complete list (or the single local principal) is safe // Only an administrator-visible complete list (or the single local principal) is safe
// input for retention. A remote per-user view can never discard another principal's pin. // input for retention. A remote per-user view can never discard another principal's pin.
const reconcileSnapshotRetention = (d.workspaceRegistry as Partial<WorkspaceRegistry>).reconcileSnapshotRetention; const reconcileSnapshotRetention = (d.workspaceRegistry as Partial<WorkspaceRegistry>).reconcileSnapshotRetention;
const hasCompleteRetentionView = (scope === "all" || principal.issuer === "local") const hasCompleteRetentionView = revisionScan.retainedComplete
&& (scope === "all" || principal.issuer === "local")
&& hasPermission(principal, "session.read_all"); && hasPermission(principal, "session.read_all");
if (hasCompleteRetentionView && typeof reconcileSnapshotRetention === "function") { if (hasCompleteRetentionView && typeof reconcileSnapshotRetention === "function") {
const retained = [...new Set(list const retained = [...new Set(list
@@ -604,6 +639,23 @@ export function sessionRoutes(
} catch (error) { return lifecycleFailure(reply, error); } } catch (error) { return lifecycleFailure(reply, error); }
const rt = d.mgr.get(id); const rt = d.mgr.get(id);
if (!rt) return reply.code(404).send({ error: "sessione non attiva" }); if (!rt) return reply.code(404).send({ error: "sessione non attiva" });
const pending = rt.bridge.pendingWidget?.() as any;
const response = (req.body as any)?.ui_response;
if (pending?.widget === "archive-repair" && response?.id === pending.id && !response.control) {
const choices = response.choices;
if (!Array.isArray(choices) || choices.length !== 1)
return reply.code(400).send({ error: "Select one archive repair choice" });
if (choices[0] !== "continue" && choices[0] !== "reject") {
const option = pending.repair?.options?.find((item: any) => item.id === choices[0]);
if (!option || !["memory", "evidence"].includes(option.archive))
return reply.code(400).send({ error: "Unknown archive repair choice" });
const permission = option.archive === "memory" ? "memory.manage" : "evidence.manage";
if (!principal.isAdmin || !hasPermission(principal, permission))
return reply.code(403).send({ error: "Archive corrections require an administrator" });
if (rt.ownerKey !== `${principal.issuer}\0${principal.subject}`)
return reply.code(409).send({ error: "Resume the session with your account before correcting an archive" });
}
}
if (!rt.bridge.respond((req.body as any).ui_response)) { if (!rt.bridge.respond((req.body as any).ui_response)) {
return reply.code(409).send({ error: "risposta non corrispondente al gate in attesa" }); return reply.code(409).send({ error: "risposta non corrispondente al gate in attesa" });
} }
@@ -623,6 +675,13 @@ export function sessionRoutes(
app.post("/sessions/:id/resume", async (req, reply) => { app.post("/sessions/:id/resume", async (req, reply) => {
const id = (req.params as any).id; const id = (req.params as any).id;
const principal = getPrincipal(req); const principal = getPrincipal(req);
if (Object.hasOwn(req.body ?? {}, "interactionLanguage")
|| Object.hasOwn(req.body ?? {}, "interaction_language")) {
return reply.code(400).send({
code: "interaction_language_pinned",
error: "Resume uses the session's persisted interaction language; overrides are not accepted",
});
}
return withSessionLifecycle(id, async () => { return withSessionLifecycle(id, async () => {
let settings: Settings; let settings: Settings;
let located: LocatedSession | undefined; let located: LocatedSession | undefined;
@@ -640,11 +699,19 @@ export function sessionRoutes(
const saved = manifest as { const saved = manifest as {
provider?: string; model?: string; thinking?: string; provider?: string; model?: string; thinking?: string;
workspace_id?: string; workspace_revision?: string; workspace_id?: string; workspace_revision?: string;
interaction_language?: string | null;
}; };
const savedCanonical = saved.provider && saved.model ? `${saved.provider}/${saved.model}` : ""; const requested = (req.body ?? {}) as { provider?: string; model?: string; thinking?: string };
if (d.modelCatalog.defaultSession && (!savedCanonical || !d.modelCatalog.hasSession(savedCanonical))) { if ((requested.provider === undefined) !== (requested.model === undefined)
|| (requested.provider !== undefined && (typeof requested.provider !== "string" || typeof requested.model !== "string" || !requested.provider || !requested.model))) {
return reply.code(400).send({ error: "provider and model must be supplied together" });
}
const selectedCanonical = requested.provider && requested.model
? `${requested.provider}/${requested.model}` : d.modelCatalog.defaultInteraction;
if (d.modelCatalog.defaultInteraction && (!selectedCanonical || !d.modelCatalog.hasSession(selectedCanonical))) {
return reply.code(503).send({ error: MODEL_UNAVAILABLE_MESSAGE, code: "model_unavailable" }); return reply.code(503).send({ error: MODEL_UNAVAILABLE_MESSAGE, code: "model_unavailable" });
} }
const selected = selectedCanonical ? splitCanonicalModelId(selectedCanonical) : saved;
let workspaceConfigPath: string; let workspaceConfigPath: string;
let workspaceDescriptor: WorkspaceDescriptor | undefined; let workspaceDescriptor: WorkspaceDescriptor | undefined;
try { try {
@@ -671,13 +738,19 @@ export function sessionRoutes(
}); });
} }
try { settings = await d.getSettings(principal); } catch { return storageFailure(reply); } try { settings = await d.getSettings(principal); } catch { return storageFailure(reply); }
let language = saved.interaction_language;
if (language == null) {
try {
language = (await runner.ensureInteractionLanguage(id, workspaceConfigPath)).interaction_language;
} catch { return reply.code(503).send({ error: RESUME_FAILURE_MESSAGE }); }
}
// This check belongs inside the per-session lock: a preceding cold Resume may have // This check belongs inside the per-session lock: a preceding cold Resume may have
// installed a running runtime while this request was waiting. // installed a running runtime while this request was waiting.
const existing = d.mgr.get(id); const existing = d.mgr.get(id);
if (existing) { if (existing) {
const state = existing.bridge.turnState(); const state = existing.bridge.turnState();
if (state === "running" || state === "waiting") { if (state === "running" || state === "waiting") {
return reply.code(200).send({ id, alreadyActive: true }); return reply.code(200).send({ id, alreadyActive: true, workspaceId: saved.workspace_id });
} }
} }
const ensure = await d.readiness.ensure( const ensure = await d.readiness.ensure(
@@ -688,8 +761,9 @@ export function sessionRoutes(
...(ensure.code ? { code: ensure.code } : {}), ...(ensure.code ? { code: ensure.code } : {}),
}); });
const options = { const options = {
provider: saved?.provider, provider: selected.provider,
model: saved?.model, interactionLanguage: language,
model: selected.model,
thinking: saved?.thinking ?? settings.thinking, thinking: saved?.thinking ?? settings.thinking,
author: principal.displayName ?? principal.subject, author: principal.displayName ?? principal.subject,
principal, principal,
@@ -711,7 +785,7 @@ export function sessionRoutes(
if (current) { if (current) {
const state = current.bridge.turnState(); const state = current.bridge.turnState();
if (state === "running" || state === "waiting") { if (state === "running" || state === "waiting") {
return reply.code(200).send({ id, alreadyActive: true }); return reply.code(200).send({ id, alreadyActive: true, workspaceId: saved.workspace_id });
} }
} }
@@ -752,7 +826,7 @@ export function sessionRoutes(
d.mgr.configure(rt, runtimeOptions), null, d.mgr.configure(rt, runtimeOptions), null,
() => d.mgr.start(id, rt, runtimeOptions), () => d.mgr.start(id, rt, runtimeOptions),
); );
return reply.code(200).send({ id, alreadyActive: false }); return reply.code(200).send({ id, alreadyActive: false, workspaceId: saved.workspace_id });
}); });
}); });
app.post("/sessions/:id/close", async (req, reply) => { app.post("/sessions/:id/close", async (req, reply) => {
+2 -2
View File
@@ -16,8 +16,8 @@ export function effectiveSettings(
modelCatalog?: RuntimeModelCatalog, modelCatalog?: RuntimeModelCatalog,
): Settings { ): Settings {
const workspaces = listWorkspaces(cfg.harnessDir); const workspaces = listWorkspaces(cfg.harnessDir);
const selected = modelCatalog?.defaultSession const selected = modelCatalog?.defaultInteraction
? splitCanonicalModelId(modelCatalog.defaultSession) ? splitCanonicalModelId(modelCatalog.defaultInteraction)
: undefined; : undefined;
return { return {
workspace: stored.workspace ?? workspaces[0]?.name, workspace: stored.workspace ?? workspaces[0]?.name,
@@ -10,6 +10,7 @@ import type { ThtRunner } from "../tht/tht-runner.js";
import type { WorkspacePreprocessingService } from "../workspaces/preprocessing-service.js"; import type { WorkspacePreprocessingService } from "../workspaces/preprocessing-service.js";
import type { PreprocessingJobState } from "../workspaces/preprocessing-state.js"; import type { PreprocessingJobState } from "../workspaces/preprocessing-state.js";
import type { WorkspaceRegistry } from "../workspaces/registry.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 workspaceIdSchema = z.string().regex(/^[a-z][a-z0-9-]{2,62}$/);
const ACTIVE_SYNC_STATES = new Set(["queued", "running", "awaiting_confirmation", "applying"]); 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) { 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) { if (error instanceof CatalogUnavailableError) {
return reply.code(503).send({ return reply.code(503).send({
code: "catalog_unavailable", code: "catalog_unavailable",
@@ -357,7 +361,8 @@ export function workspacePreprocessingRoutes(
try { try {
const workspaceId = workspaceIdFrom(request); const workspaceId = workspaceIdFrom(request);
const before = await readWorkspacePreprocessingStatus(workspaceId, deps); 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" }); return reply.code(409).send({ ...before, code: "preprocessing_blocked" });
} }
+10
View File
@@ -0,0 +1,10 @@
/** Validate/canonicalize the tag; available translation catalogs belong to the UI. */
export function interactionLanguage(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
try {
const [canonical] = Intl.getCanonicalLocales(value);
return canonical;
} catch {
return undefined;
}
}
+10 -1
View File
@@ -59,6 +59,7 @@ export interface SessionRow {
author: string | null; author: string | null;
workspace_id?: string | null; workspace_id?: string | null;
workspace_revision?: string | null; workspace_revision?: string | null;
interaction_language?: string | null;
archived?: boolean; archived?: boolean;
} }
@@ -482,6 +483,7 @@ export class ThtRunner {
async sessionNew(o: { async sessionNew(o: {
question: string; question: string;
interactionLanguage?: string;
provider?: string; provider?: string;
model?: string; model?: string;
thinking?: string; thinking?: string;
@@ -497,6 +499,7 @@ export class ThtRunner {
["--provider", o.provider], ["--provider", o.provider],
["--model", o.model], ["--model", o.model],
["--thinking", o.thinking], ["--thinking", o.thinking],
["--interaction-language", o.interactionLanguage],
["--name", o.name], ["--name", o.name],
["--workspace-id", o.workspaceId], ["--workspace-id", o.workspaceId],
["--workspace-revision", o.workspaceRevision], ["--workspace-revision", o.workspaceRevision],
@@ -504,7 +507,7 @@ export class ThtRunner {
if (v) a.push(f, v); if (v) a.push(f, v);
} }
a.push("--json"); a.push("--json");
return this.json<{ id: string }>(a, o.workspaceConfigPath ?? o.workspace); return this.json<{ id: string; interaction_language?: string }>(a, o.workspaceConfigPath ?? o.workspace);
} }
/** Build and persist the deterministic F1 retrieval pack for a new session. */ /** Build and persist the deterministic F1 retrieval pack for a new session. */
@@ -533,6 +536,12 @@ export class ThtRunner {
return this.json<unknown>(["session", "show", id, "--json"], workspace); return this.json<unknown>(["session", "show", id, "--json"], workspace);
} }
ensureInteractionLanguage(id: string, workspace?: string) {
return this.json<{ interaction_language: string }>(
["session", "ensure-interaction-language", id, "--json"], workspace,
);
}
sqlPreview(id: string, p: { limit?: number; offset?: number }, workspace?: string) { sqlPreview(id: string, p: { limit?: number; offset?: number }, workspace?: string) {
// No positional FILE: the harness resolves sql_final.sql from the session // No positional FILE: the harness resolves sql_final.sql from the session
// via _session_sql_file(cfg, session_id), which respects the workspace path. // via _session_sql_file(cfg, session_id), which respects the workspace path.
+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;
+20 -4
View File
@@ -9,6 +9,7 @@ import { WorkspaceSecretStore } from "./workspaces/secret-store.js";
import { WorkspacePreprocessingService, type WorkspaceOperationResult } from "./workspaces/preprocessing-service.js"; import { WorkspacePreprocessingService, type WorkspaceOperationResult } from "./workspaces/preprocessing-service.js";
import { createCatalogRepository } from "./catalog/repository.js"; import { createCatalogRepository } from "./catalog/repository.js";
import type { CatalogRepository } from "./catalog/types.js"; import type { CatalogRepository } from "./catalog/types.js";
import { guardedPreprocessingCommand } from "./workspaces/preprocessing-owner.js";
export interface WorkspaceMaintenanceIo { export interface WorkspaceMaintenanceIo {
stdin: string; stdin: string;
@@ -18,7 +19,7 @@ export interface WorkspaceMaintenanceIo {
writeStderr(value: string): void; writeStderr(value: string): void;
} }
type Command = "inspect" | "preprocess-run" | "preprocess-clear"; type Command = "inspect" | "preprocess-run" | "preprocess-clear" | "evidence-consolidate" | "evidence-refresh" | "evidence-decide";
function failureResult( function failureResult(
operation: string, operation: string,
@@ -65,6 +66,9 @@ function parseRequest(command: string, stdin: string): Record<string, unknown> {
inspect: ["schemaVersion", "workspaceId"], inspect: ["schemaVersion", "workspaceId"],
"preprocess-run": ["schemaVersion", "workspaceId"], "preprocess-run": ["schemaVersion", "workspaceId"],
"preprocess-clear": ["schemaVersion", "workspaceId"], "preprocess-clear": ["schemaVersion", "workspaceId"],
"evidence-consolidate": ["schemaVersion", "workspaceId"],
"evidence-refresh": ["schemaVersion", "workspaceId"],
"evidence-decide": ["schemaVersion", "workspaceId", "sourceId", "revision", "decision"],
}; };
const allowed = allowedByCommand[command]; const allowed = allowedByCommand[command];
if (!allowed) throw new Error("unknown command"); if (!allowed) throw new Error("unknown command");
@@ -81,6 +85,16 @@ function exitCodeFor(result: WorkspaceOperationResult): number {
async function dispatch(command: Command, service: WorkspacePreprocessingService, request: Record<string, unknown>): Promise<WorkspaceOperationResult> { async function dispatch(command: Command, service: WorkspacePreprocessingService, request: Record<string, unknown>): Promise<WorkspaceOperationResult> {
switch (command) { switch (command) {
case "evidence-refresh":
return await service.evidenceSources({ workspaceId: request.workspaceId as string, action: "refresh" });
case "evidence-decide":
if (typeof request.sourceId !== "string" || !/^[a-f0-9]{64}$/.test(request.sourceId)
|| typeof request.revision !== "string" || !/^[a-f0-9]{64}$/.test(request.revision)
|| (request.decision !== "keep" && request.decision !== "replace")) throw new Error("invalid request");
return await service.evidenceSources({ workspaceId: request.workspaceId as string, action: "decide",
sourceId: request.sourceId, revision: request.revision, decision: request.decision });
case "evidence-consolidate":
return await service.consolidateEvidence({ workspaceId: request.workspaceId as string });
case "inspect": case "inspect":
return await service.inspect({ workspaceId: request.workspaceId as string }); return await service.inspect({ workspaceId: request.workspaceId as string });
case "preprocess-run": case "preprocess-run":
@@ -127,7 +141,8 @@ export async function runWorkspaceMaintenanceCli(
|| message === "unexpected request field" || message === "unexpected request field"
|| message === "invalid workspace id"; || message === "invalid workspace id";
return command in { return command in {
inspect: true, "preprocess-run": true, "preprocess-clear": true, inspect: true, "preprocess-run": true, "preprocess-clear": true, "evidence-consolidate": true,
"evidence-refresh": true, "evidence-decide": true,
} ? (requestError ? 2 : 1) : 2; } ? (requestError ? 2 : 1) : 2;
} }
} }
@@ -224,7 +239,7 @@ export function createProductionWorkspacePreprocessingService(
active.releaseSecrets(); active.releaseSecrets();
} }
}, },
runChild: async ({ argv, configPath }) => { runChild: async ({ argv, configPath, guard }) => {
const configFd = openSync(configPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW); const configFd = openSync(configPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
try { try {
return await new Promise((resolve) => { return await new Promise((resolve) => {
@@ -240,7 +255,8 @@ export function createProductionWorkspacePreprocessingService(
"THT_CATALOG_MIGRATOR_USER", "THT_CATALOG_MIGRATOR_USER",
"THT_CATALOG_MIGRATOR_PASSWORD_FILE", "THT_CATALOG_MIGRATOR_PASSWORD_FILE",
]) delete childEnvironment[name]; ]) 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, cwd: config.harnessDir,
env: { ...childEnvironment, ...(config.dataRoot ? { THT_DATA_ROOT: config.dataRoot } : {}) }, env: { ...childEnvironment, ...(config.dataRoot ? { THT_DATA_ROOT: config.dataRoot } : {}) },
stdio: ["ignore", "pipe", "pipe", configFd], stdio: ["ignore", "pipe", "pipe", configFd],
+3 -3
View File
@@ -44,8 +44,8 @@ const catalogSchema = z.object({
}); });
}); });
function safeCatalogError(): Error { function safeCatalogError(cause?: unknown): Error {
return new Error("Workspace catalog is invalid"); return new Error("Workspace catalog is invalid", { cause });
} }
export function parseWorkspaceCatalogYaml(source: string): WorkspaceCatalog { export function parseWorkspaceCatalogYaml(source: string): WorkspaceCatalog {
@@ -57,7 +57,7 @@ export function parseWorkspaceCatalogYaml(source: string): WorkspaceCatalog {
return catalogSchema.parse(document.toJSON()) as WorkspaceCatalog; return catalogSchema.parse(document.toJSON()) as WorkspaceCatalog;
} catch (error) { } catch (error) {
if (error instanceof Error && error.message === "Workspace catalog is invalid") throw 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 };
}
@@ -22,6 +22,7 @@ export interface EvidencePreprocessingRequest {
evidence: EvidenceConfig; evidence: EvidenceConfig;
job: EvidenceJobState; job: EvidenceJobState;
dryRun?: boolean; dryRun?: boolean;
consolidate?: boolean;
httpPrivateHostAllowlist?: readonly string[]; httpPrivateHostAllowlist?: readonly string[];
} }
@@ -56,7 +57,7 @@ function isPrivateHost(hostname: string): boolean {
return hostname.endsWith(".internal"); return hostname.endsWith(".internal");
} }
function evidencePolicy( export function evidencePolicy(
evidence: EvidenceConfig, evidence: EvidenceConfig,
httpPrivateHostAllowlist?: readonly string[], httpPrivateHostAllowlist?: readonly string[],
): EvidencePreprocessingOutcome | undefined { ): EvidencePreprocessingOutcome | undefined {
@@ -95,13 +96,14 @@ function jobResult(job: EvidenceJobState): Pick<
}; };
} }
async function runEvidenceStage( export async function runEvidenceStage(
request: EvidencePreprocessingRequest, request: EvidencePreprocessingRequest,
deps: EvidencePreprocessingDependencies, deps: EvidencePreprocessingDependencies,
): Promise<EvidencePreprocessingOutcome> { ): Promise<EvidencePreprocessingOutcome> {
const payload = await deps.runStage([ const payload = await deps.runStage([
"preprocess", "preprocess",
"evidence", "evidence",
...(request.consolidate ? ["--consolidate"] : []),
...(request.dryRun ? ["--dry-run"] : []), ...(request.dryRun ? ["--dry-run"] : []),
...(request.job.childRuns.evidence ...(request.job.childRuns.evidence
? ["--resume", request.job.childRuns.evidence] ? ["--resume", request.job.childRuns.evidence]
+33
View File
@@ -3,6 +3,7 @@ import { lstatSync, mkdirSync } from "node:fs";
import { mkdir } from "node:fs/promises"; import { mkdir } from "node:fs/promises";
import { isAbsolute, join } from "node:path"; import { isAbsolute, join } from "node:path";
import { promisify, TextDecoder } from "node:util"; import { promisify, TextDecoder } from "node:util";
import { createHash } from "node:crypto";
import type { WorkspaceErrorCode, WorkspaceRegistryConfig } from "./types.js"; import type { WorkspaceErrorCode, WorkspaceRegistryConfig } from "./types.js";
const execFileAsync = promisify(execFile); const execFileAsync = promisify(execFile);
@@ -29,6 +30,13 @@ export interface EvidenceTreeObject {
posixPath: string; posixPath: string;
} }
export interface PreparedWorkspaceSource {
remote: string;
branch: string;
revision: string;
files: Record<string, string>;
}
export class WorkspaceRegistryError extends Error { export class WorkspaceRegistryError extends Error {
constructor(readonly code: WorkspaceErrorCode, message: string) { constructor(readonly code: WorkspaceErrorCode, message: string) {
super(message); super(message);
@@ -187,6 +195,31 @@ export class GitWorkspaceRepository {
return await this.status(); 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> { async pull(): Promise<GitStatus> {
await this.ensureLayout(); await this.ensureLayout();
if (isMissing(this.repoPath)) return await this.bootstrap(); 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] };
}
+131 -11
View File
@@ -3,6 +3,8 @@ import { renameSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import { import {
continueEvidencePreprocessing, continueEvidencePreprocessing,
evidencePolicy,
runEvidenceStage,
type EvidencePreprocessingDependencies, type EvidencePreprocessingDependencies,
type EvidencePreprocessingOutcome, type EvidencePreprocessingOutcome,
} from "./evidence/preprocessing.js"; } from "./evidence/preprocessing.js";
@@ -14,6 +16,7 @@ import {
import type { DeterministicRuntimeConfigLease } from "./runtime-config-lease.js"; import type { DeterministicRuntimeConfigLease } from "./runtime-config-lease.js";
import { buildCatalogMetadataSnapshot } from "../catalog/metadata-snapshot.js"; import { buildCatalogMetadataSnapshot } from "../catalog/metadata-snapshot.js";
import type { CatalogRepository } from "../catalog/types.js"; import type { CatalogRepository } from "../catalog/types.js";
import { acquirePreprocessingOwner, type PreprocessingChildGuard } from "./preprocessing-owner.js";
export interface WorkspaceOperationResult { export interface WorkspaceOperationResult {
schemaVersion: 1; schemaVersion: 1;
@@ -45,6 +48,7 @@ export interface WorkspaceOperationResult {
export interface ChildProcessRequest { export interface ChildProcessRequest {
argv: string[]; argv: string[];
configPath: string; configPath: string;
guard?: PreprocessingChildGuard;
} }
interface ActiveRuntime { interface ActiveRuntime {
@@ -77,6 +81,7 @@ export interface WorkspacePreprocessingServiceDeps {
} }
interface RunScope { interface RunScope {
owner: Awaited<ReturnType<typeof acquirePreprocessingOwner>>;
runtime: ActiveRuntime; runtime: ActiveRuntime;
state: PreprocessingStateStore; state: PreprocessingStateStore;
job: PreprocessingJobState; job: PreprocessingJobState;
@@ -108,6 +113,72 @@ function baseResult(
export class WorkspacePreprocessingService { export class WorkspacePreprocessingService {
constructor(private readonly deps: WorkspacePreprocessingServiceDeps) {} constructor(private readonly deps: WorkspacePreprocessingServiceDeps) {}
async evidenceSources(options: { workspaceId: string; action: "refresh" | "decide";
sourceId?: string; revision?: string; decision?: "keep" | "replace"; actor?: string }): Promise<WorkspaceOperationResult> {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
try {
if (options.action === "refresh") {
const refused = evidencePolicy(runtime.workspace.evidence, this.deps.httpPrivateHostAllowlist);
if (refused) return baseResult(runtime, "evidence refresh", "failed", refused.code);
}
const argv = ["evidence", "sources", options.action, "--json", "-c", "/dev/fd/3"];
if (options.action === "decide") {
if (!/^[a-f0-9]{64}$/.test(options.sourceId ?? "") || !/^[a-f0-9]{64}$/.test(options.revision ?? "")
|| !["keep", "replace"].includes(options.decision ?? "")) throw new Error("Invalid source decision");
const preflight = await this.deps.evidencePreflight(runtime.workspace);
if (!preflight.ok) return baseResult(runtime, "evidence sources", "failed", preflight.code);
argv.push("--source-id", options.sourceId!, "--revision", options.revision!, "--decision", options.decision!);
}
argv.push("--actor", options.actor ?? "installation operator");
const result = await this.deps.runChild({ argv, configPath: runtime.configLease.path });
const payload = JSON.parse(result.stdout);
if (result.exitCode !== 0 || payload.status !== "succeeded") throw new Error(
typeof payload.error === "string" ? payload.error.slice(0, 1500) : "Evidence source operation failed");
return baseResult(runtime, `evidence ${options.action}`, "succeeded", "ok", {
counts: this.numberRecord(payload.counts),
warnings: [options.action === "refresh" ? "Source comparisons are ready in Evidence management. Active content is unchanged."
: "Source decision activated locally. Commit and push the Evidence tree manually."],
});
} catch (error) {
return baseResult(runtime, `evidence ${options.action}`, "failed", "evidence_materialization_required", {
warnings: [error instanceof Error ? error.message : "Evidence source operation failed"],
});
}
}
async consolidateEvidence(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
const preflight = await this.deps.evidencePreflight(runtime.workspace);
if (!preflight.ok) return baseResult(runtime, "evidence consolidate", "failed", preflight.code);
// Evidence has its own durable archive/corpus jobs. Do not alter Catalog readiness
// or the full preprocessing job when publishing this one component.
try {
const outcome = await runEvidenceStage({ evidence: runtime.workspace.evidence,
consolidate: true, job: { runId: randomBytes(16).toString("hex"), completedStages: [], childRuns: {} },
}, {
runStage: async argv => {
const result = await this.deps.runChild({ argv, configPath: runtime.configLease.path });
const payload = JSON.parse(result.stdout);
if (result.exitCode !== 0 || payload.status !== "succeeded") {
return Promise.reject(new Error(typeof payload.error === "string" ? payload.error.slice(0, 1500) : "Evidence consolidation failed. Retry the command."));
}
return payload;
},
persistJob: () => undefined,
evidencePreflight: async () => preflight,
requireRunId: value => this.requireRunId(value),
numberRecord: value => this.numberRecord(value),
});
return baseResult(runtime, "evidence consolidate", "succeeded", "ok", {
...outcome, warnings: ["Evidence is active locally. Catalog and Schema readiness are unchanged. Commit and push the Evidence files manually."],
});
} catch (error) {
return baseResult(runtime, "evidence consolidate", "failed", "evidence_materialization_required", {
warnings: [error instanceof Error ? error.message : "Evidence consolidation failed. Retry the command."],
});
}
}
async inspect(options: { workspaceId: string }): Promise<WorkspaceOperationResult> { async inspect(options: { workspaceId: string }): Promise<WorkspaceOperationResult> {
try { try {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId); const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
@@ -137,13 +208,39 @@ export class WorkspacePreprocessingService {
const runtime = await this.deps.acquireActiveRuntime(options.workspaceId); const runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
return baseResult(runtime, "preprocess run", "failed", "catalog_not_ready"); 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> { 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 runtime = await this.deps.acquireActiveRuntime(options.workspaceId);
const repository = this.deps.catalogRepository; const repository = this.deps.catalogRepository;
if (!repository) return baseResult(runtime, "preprocess clear", "failed", "catalog_not_ready"); if (!repository) return baseResult(runtime, "preprocess clear", "failed", "catalog_not_ready");
owner.assertOwned();
const cleared = await repository.clearPreprocessing(runtime.workspaceId); const cleared = await repository.clearPreprocessing(runtime.workspaceId);
if (cleared.kind !== "cleared") { if (cleared.kind !== "cleared") {
return baseResult( return baseResult(
@@ -156,7 +253,9 @@ export class WorkspacePreprocessingService {
const result = await this.deps.runChild({ const result = await this.deps.runChild({
argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"], argv: ["preprocess", "clear", "--json", "-c", "/dev/fd/3"],
configPath: runtime.configLease.path, configPath: runtime.configLease.path,
guard: owner.guard,
}); });
owner.assertOwned();
if (result.exitCode !== 0) { if (result.exitCode !== 0) {
return baseResult(runtime, "preprocess clear", "failed", "preprocessing_clear_failed"); return baseResult(runtime, "preprocess clear", "failed", "preprocessing_clear_failed");
} }
@@ -166,11 +265,13 @@ export class WorkspacePreprocessingService {
}); });
} }
private async runFromCatalog(options: { workspaceId: string }): Promise<WorkspaceOperationResult> { private async runFromCatalog(options: { workspaceId: string }, owner: RunScope["owner"]): Promise<WorkspaceOperationResult> {
const scope = await this.startRun(options.workspaceId); const scope = await this.startRun(options.workspaceId, owner);
const repository = this.deps.catalogRepository!; const repository = this.deps.catalogRepository!;
const fingerprint = scope.runtime.configLease.inputFingerprint; 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") { if (started.kind !== "started") {
scope.job.status = "failed"; scope.job.status = "failed";
scope.state.writeJob(scope.job); scope.state.writeJob(scope.job);
@@ -192,19 +293,23 @@ export class WorkspacePreprocessingService {
scope.runtime.workspaceId, scope.runtime.workspaceId,
revision, revision,
); );
owner.assertOwned();
const snapshotPath = this.publishCatalogSnapshot( const snapshotPath = this.publishCatalogSnapshot(
scope.runtime.workspaceId, scope.runtime.workspaceId,
JSON.stringify(snapshot), JSON.stringify(snapshot),
); );
this.completeStages(scope, "catalog_snapshot"); this.completeStages(scope, "catalog_snapshot");
const semantic = await this.deps.semanticPreflight(scope.runtime.workspace); const semantic = await this.deps.semanticPreflight(scope.runtime.workspace);
owner.assertOwned();
if (!semantic.ok) { if (!semantic.ok) {
await repository.finishPreprocessing( await repository.finishPreprocessing(
scope.runtime.workspaceId, scope.runtime.workspaceId,
revision, revision,
fingerprint, fingerprint,
{ status: "failed", errorCode: semantic.code }, { status: "failed", errorCode: semantic.code },
scope.job.runId,
); );
owner.assertOwned();
scope.job.status = "failed"; scope.job.status = "failed";
scope.state.writeJob(scope.job); scope.state.writeJob(scope.job);
finished = true; finished = true;
@@ -212,7 +317,7 @@ export class WorkspacePreprocessingService {
} }
failureCode = "schema_index_failed"; failureCode = "schema_index_failed";
const payload = await this.runJsonStage(scope.runtime, [ const payload = await this.runJsonStage(scope, [
"preprocess", "preprocess",
"catalog", "catalog",
"--catalog-metadata", "--catalog-metadata",
@@ -233,12 +338,15 @@ export class WorkspacePreprocessingService {
this.evidenceDependencies(scope), this.evidenceDependencies(scope),
); );
if (!["succeeded", "unchanged"].includes(outcome.status)) { if (!["succeeded", "unchanged"].includes(outcome.status)) {
owner.assertOwned();
await repository.finishPreprocessing( await repository.finishPreprocessing(
scope.runtime.workspaceId, scope.runtime.workspaceId,
revision, revision,
fingerprint, fingerprint,
{ status: "failed", errorCode: outcome.code }, { status: "failed", errorCode: outcome.code },
scope.job.runId,
); );
owner.assertOwned();
scope.job.status = "failed"; scope.job.status = "failed";
scope.state.writeJob(scope.job); scope.state.writeJob(scope.job);
finished = true; finished = true;
@@ -251,29 +359,35 @@ export class WorkspacePreprocessingService {
revision, revision,
fingerprint, fingerprint,
{ status: "succeeded" }, { status: "succeeded" },
scope.job.runId,
); );
owner.assertOwned();
if (!completed) throw new Error("catalog preprocessing completion lost its lease"); if (!completed) throw new Error("catalog preprocessing completion lost its lease");
scope.job.status = "succeeded"; scope.job.status = "succeeded";
scope.state.writeJob(scope.job); scope.state.writeJob(scope.job);
finished = true; finished = true;
return this.evidenceResult(scope, outcome); return this.evidenceResult(scope, outcome);
} catch (error) { } catch (error) {
owner.assertOwned();
if (!finished) { if (!finished) {
await repository.finishPreprocessing( await repository.finishPreprocessing(
scope.runtime.workspaceId, scope.runtime.workspaceId,
revision, revision,
fingerprint, fingerprint,
{ status: "failed", errorCode: failureCode }, { status: "failed", errorCode: failureCode },
scope.job.runId,
); );
} }
owner.assertOwned();
scope.job.status = "failed"; scope.job.status = "failed";
scope.state.writeJob(scope.job); scope.state.writeJob(scope.job);
throw error; 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); const runtime = await this.deps.acquireActiveRuntime(workspaceId);
owner.assertOwned();
const state = this.state(runtime.workspaceId); const state = this.state(runtime.workspaceId);
const job = await state.beginJob({ const job = await state.beginJob({
operation: "preprocess run", operation: "preprocess run",
@@ -285,7 +399,10 @@ export class WorkspacePreprocessingService {
embeddingId: runtime.configLease.effectiveConfig.embedding.id, embeddingId: runtime.configLease.effectiveConfig.embedding.id,
embeddingDimensions: runtime.configLease.effectiveConfig.embedding.dimensions, 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 { private state(workspaceId: string): PreprocessingStateStore {
@@ -293,6 +410,7 @@ export class WorkspacePreprocessingService {
} }
private completeStages(scope: RunScope, ...stages: string[]): void { private completeStages(scope: RunScope, ...stages: string[]): void {
scope.owner.assertOwned();
for (const stage of stages) { for (const stage of stages) {
if (!scope.job.completedStages.includes(stage)) scope.job.completedStages.push(stage); if (!scope.job.completedStages.includes(stage)) scope.job.completedStages.push(stage);
} }
@@ -316,8 +434,8 @@ export class WorkspacePreprocessingService {
private evidenceDependencies(scope: RunScope): EvidencePreprocessingDependencies { private evidenceDependencies(scope: RunScope): EvidencePreprocessingDependencies {
return { return {
runStage: async (argv) => await this.runJsonStage(scope.runtime, argv), runStage: async (argv) => await this.runJsonStage(scope, argv),
persistJob: () => this.state(scope.runtime.workspaceId).writeJob(scope.job), persistJob: () => { scope.owner.assertOwned(); this.state(scope.runtime.workspaceId).writeJob(scope.job); },
evidencePreflight: async () => await this.deps.evidencePreflight(scope.runtime.workspace), evidencePreflight: async () => await this.deps.evidencePreflight(scope.runtime.workspace),
requireRunId: (value) => this.requireRunId(value), requireRunId: (value) => this.requireRunId(value),
numberRecord: (value) => this.numberRecord(value), numberRecord: (value) => this.numberRecord(value),
@@ -332,8 +450,10 @@ export class WorkspacePreprocessingService {
return baseResult(scope.runtime, "preprocess run", status, code, extra); return baseResult(scope.runtime, "preprocess run", status, code, extra);
} }
private async runJsonStage(runtime: ActiveRuntime, argv: string[]): Promise<Record<string, unknown>> { private async runJsonStage(scope: RunScope, argv: string[]): Promise<Record<string, unknown>> {
const result = await this.deps.runChild({ argv, configPath: runtime.configLease.path }); 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"); if (result.exitCode !== 0) throw new Error("workspace child failed");
return JSON.parse(result.stdout) as Record<string, unknown>; return JSON.parse(result.stdout) as Record<string, unknown>;
} }
+16 -3
View File
@@ -34,6 +34,7 @@ export interface SessionInventoryRow {
export interface WriterLockLease { export interface WriterLockLease {
holderPid: number; holderPid: number;
isHeld(): boolean;
release(): Promise<void>; release(): Promise<void>;
} }
@@ -66,6 +67,7 @@ export interface PreprocessingJobState {
status: "active" | "succeeded" | "blocked" | "failed"; status: "active" | "succeeded" | "blocked" | "failed";
candidateDigest?: string; candidateDigest?: string;
reviewDigest?: string; reviewDigest?: string;
ownerProtocol?: 1;
} }
export interface FkReviewRecord { export interface FkReviewRecord {
@@ -195,6 +197,14 @@ export class PreprocessingStateStore {
} }
writerLockPath(): string { return join(this.root, "writer.lock"); } 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"); } runtimeConfigDirectory(): string { return join(this.root, "runtime-config"); }
runtimeConfigManifestDirectory(): string { return join(this.root, "runtime-config-manifests"); } runtimeConfigManifestDirectory(): string { return join(this.root, "runtime-config-manifests"); }
jobsDirectory(): string { return join(this.root, "jobs"); } jobsDirectory(): string { return join(this.root, "jobs"); }
@@ -216,9 +226,9 @@ export class PreprocessingStateStore {
]) ensureDirectory(directory); ]) ensureDirectory(directory);
} }
async acquireWriterLock(): Promise<WriterLockLease> { async acquireWriterLock(kind: "writer" | "workers" = "writer"): Promise<WriterLockLease> {
this.ensureLayout(); this.ensureLayout();
const lockPath = this.writerLockPath(); const lockPath = kind === "writer" ? this.writerLockPath() : this.workerLockPath();
try { try {
const entry = lstatSync(lockPath); const entry = lstatSync(lockPath);
if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("invalid writer lock path"); if (!entry.isFile() || entry.isSymbolicLink()) throw new Error("invalid writer lock path");
@@ -257,11 +267,14 @@ export class PreprocessingStateStore {
let released = false; let released = false;
return { return {
holderPid: holder.pid ?? 0, holderPid: holder.pid ?? 0,
isHeld: () => !released && holder.exitCode === null && holder.signalCode === null,
release: async () => { release: async () => {
if (released) return; if (released) return;
released = true; 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(); 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, WorkspaceRepositoryLock,
normalizeRepositoryIdentity, normalizeRepositoryIdentity,
type GitStatus, type GitStatus,
type PreparedWorkspaceSource,
} from "./git-repository.js"; } from "./git-repository.js";
import { import {
parseWorkspaceYaml, 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> { async pull(): Promise<GitStatus> {
await this.repository.ensureLayout(); await this.repository.ensureLayout();
return await this.lock.run(async () => { return await this.lock.run(async () => {
@@ -497,7 +497,10 @@ export async function publishDeterministicRuntimeConfigLease(options: {
rendered.workspaceRevision, rendered.workspaceRevision,
renderedConfigObject, renderedConfigObject,
); );
const identitySuffix = inputFingerprintValue.slice(7, 23); // The Catalog input identity intentionally excludes representation-only changes.
// A lease also identifies its bytes, so a new renderer never collides with an
// immutable config produced by an earlier release for the same Catalog inputs.
const identitySuffix = sha256(inputFingerprintValue + "\n" + publishedConfig).slice(7, 23);
const preprocessingRoot = ensureTrustedDirectory(join( const preprocessingRoot = ensureTrustedDirectory(join(
options.dataRoot, options.dataRoot,
+2 -1
View File
@@ -1,4 +1,4 @@
import { basename, join } from "node:path"; import { basename, dirname, join } from "node:path";
import { stringify } from "yaml"; import { stringify } from "yaml";
import { buildInstallationContract } from "./contracts.js"; import { buildInstallationContract } from "./contracts.js";
import { validateWorkspaceDescriptor, type WorkspaceDescriptor } from "./schema.js"; import { validateWorkspaceDescriptor, type WorkspaceDescriptor } from "./schema.js";
@@ -179,6 +179,7 @@ function renderEvidence(
return { return {
evidence: { evidence: {
...(workspace.evidence.schema_version === 2 ? { schema_version: 2 } : {}), ...(workspace.evidence.schema_version === 2 ? { schema_version: 2 } : {}),
local_archive_root: join(dirname(dirname(context.revisionContentRoot)), "repo", context.workspaceId),
sources: [renderedSource], sources: [renderedSource],
}, },
vector: { vector: {
+16 -1
View File
@@ -11,7 +11,7 @@ import {
rmSync, rmSync,
writeFileSync, writeFileSync,
} from "node:fs"; } 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"; import { basename, join } from "node:path";
const STORE_ERROR = "Workspace secret store is unavailable."; const STORE_ERROR = "Workspace secret store is unavailable.";
@@ -122,6 +122,21 @@ export class WorkspaceSecretStore {
return this.readVault().entries[entryKey(workspaceId, requirementId)] !== undefined; 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 { generation(workspaceId: string): number {
assertIdentifier(workspaceId, "workspace identifier"); assertIdentifier(workspaceId, "workspace identifier");
const vault = this.readVault(); const vault = this.readVault();
@@ -0,0 +1,48 @@
import Fastify from "fastify";
import { expect, test, vi } from "vitest";
import { sessionRoutes } from "../src/routes/sessions.js";
import type { PrincipalContext } from "../src/auth/principal.js";
test.each([
[false, "m", 403], [false, "e", 403], [false, "reject", 204],
[true, "m", 204], [true, "e", 204], [true, "forged", 400],
] as const)("archive repair response enforces the responding principal (%s, %s)", async (admin, choice, status) => {
const app = Fastify();
const principal: PrincipalContext = { issuer: "test", subject: "reviewer", isAdmin: admin,
roles: admin ? ["admin"] : ["user"],
permissions: admin ? ["session.use", "memory.manage", "evidence.manage"] : ["session.use"] };
app.addHook("preHandler", async request => { request.principal = principal; });
const respond = vi.fn(() => true);
sessionRoutes(app, {
tht: {}, mgr: { get: () => ({ ownerKey: "test\0reviewer", bridge: {
respond, pendingWidget: () => ({ id: "gate", widget: "archive-repair", repair: { options: [
{ id: "m", archive: "memory" }, { id: "e", archive: "evidence" },
] } }),
} }) },
} as unknown as Parameters<typeof sessionRoutes>[1]);
try {
const result = await app.inject({ method: "POST", url: "/sessions/s/response",
payload: { ui_response: { id: "gate", choices: [choice] } } });
expect(result.statusCode).toBe(status);
expect(respond).toHaveBeenCalledTimes(status === 204 ? 1 : 0);
} finally { await app.close(); }
});
test("an administrator cannot attribute a repair to another runtime's principal", async () => {
const app = Fastify();
app.addHook("preHandler", async request => { request.principal = {
issuer: "test", subject: "second-admin", isAdmin: true, roles: ["admin"],
permissions: ["session.use", "memory.manage"],
}; });
const respond = vi.fn();
sessionRoutes(app, { tht: {}, mgr: { get: () => ({ ownerKey: "test\0first-admin", bridge: {
respond, pendingWidget: () => ({ id: "gate", widget: "archive-repair",
repair: { options: [{ id: "m", archive: "memory" }] } }),
} }) } } as unknown as Parameters<typeof sessionRoutes>[1]);
try {
const result = await app.inject({ method: "POST", url: "/sessions/s/response",
payload: { ui_response: { id: "gate", choices: ["m"] } } });
expect(result.statusCode).toBe(409);
expect(respond).not.toHaveBeenCalled();
} finally { await app.close(); }
});
+2
View File
@@ -188,6 +188,8 @@ test("roles collapse duplicates and admin contains all administrative permission
"workspace.manage", "workspace.manage",
"workspace.secrets.manage", "workspace.secrets.manage",
"database.manage", "database.manage",
"memory.manage",
"evidence.manage",
"pi.manage", "pi.manage",
"auth.diagnostics.read", "auth.diagnostics.read",
]); ]);
+1 -1
View File
@@ -130,7 +130,7 @@ test("local login sets a non-persistent opaque session cookie and exposes only a
roles: ["admin"], roles: ["admin"],
permissions: [ permissions: [
"session.use", "session.read_all", "session.manage_all", "settings.manage", "session.use", "session.read_all", "session.manage_all", "settings.manage",
"workspace.manage", "workspace.secrets.manage", "database.manage", "pi.manage", "auth.diagnostics.read", "workspace.manage", "workspace.secrets.manage", "database.manage", "memory.manage", "evidence.manage", "pi.manage", "auth.diagnostics.read",
], ],
isAdmin: true, isAdmin: true,
csrfToken: expect.stringMatching(/^[A-Za-z0-9_-]{43}$/), csrfToken: expect.stringMatching(/^[A-Za-z0-9_-]{43}$/),
+32 -6
View File
@@ -7,6 +7,8 @@ import { join } from "node:path";
import { expandLocalHome, localPrincipal, upstreamPrincipal } from "../src/auth/principal.js"; import { expandLocalHome, localPrincipal, upstreamPrincipal } from "../src/auth/principal.js";
import { buildApp } from "../src/app.js"; import { buildApp } from "../src/app.js";
import { loadConfig } from "../src/config.js"; import { loadConfig } from "../src/config.js";
import { rolesToPermissions } from "../src/auth/config.js";
import type { Permission, Role } from "../src/auth/types.js";
test("server smoke rejects retired trusted claims under OIDC authentication", () => { test("server smoke rejects retired trusted claims under OIDC authentication", () => {
const smoke = readFileSync("../scripts/unified-deployment-smoke.sh", "utf8"); const smoke = readFileSync("../scripts/unified-deployment-smoke.sh", "utf8");
@@ -32,7 +34,7 @@ test("local mode resolves a stable local principal", async () => {
roles: ["admin"], roles: ["admin"],
permissions: [ permissions: [
"session.use", "session.read_all", "session.manage_all", "settings.manage", "session.use", "session.read_all", "session.manage_all", "settings.manage",
"workspace.manage", "workspace.secrets.manage", "database.manage", "pi.manage", "auth.diagnostics.read", "workspace.manage", "workspace.secrets.manage", "database.manage", "memory.manage", "evidence.manage", "pi.manage", "auth.diagnostics.read",
], ],
isAdmin: true, isAdmin: true,
}); });
@@ -74,7 +76,7 @@ test("upstream mode accepts only normalized proxy principal headers", async () =
issuer: "portal", subject: "42", displayName: "Alice", roles: ["user", "admin"], issuer: "portal", subject: "42", displayName: "Alice", roles: ["user", "admin"],
permissions: [ permissions: [
"session.use", "session.read_all", "session.manage_all", "settings.manage", "session.use", "session.read_all", "session.manage_all", "settings.manage",
"workspace.manage", "workspace.secrets.manage", "database.manage", "pi.manage", "auth.diagnostics.read", "workspace.manage", "workspace.secrets.manage", "database.manage", "memory.manage", "evidence.manage", "pi.manage", "auth.diagnostics.read",
], ],
isAdmin: true, isAdmin: true,
}); });
@@ -206,15 +208,33 @@ test("the session boundary rejects tht maintenance headers outside exact loopbac
})).statusCode).toBe(503); })).statusCode).toBe(503);
}); });
test("the session boundary touches a valid cookie session through the bounded Task 7 store operation", async () => { test.each<{
name: string;
roles: Role[];
storedPermissions: Permission[];
}>([
{ name: "current user", roles: ["user"], storedPermissions: ["session.use"] },
{
name: "administrator signed in before archive permissions existed",
roles: ["admin"],
storedPermissions: rolesToPermissions(["admin"]).filter(
(permission) => permission !== "memory.manage" && permission !== "evidence.manage",
),
},
{
name: "user with obsolete administrative permissions",
roles: ["user"],
storedPermissions: ["session.use", "memory.manage", "evidence.manage"],
},
])("the session boundary derives current permissions and touches a valid cookie: $name", async ({ roles, storedPermissions }) => {
const sessions = { const sessions = {
resolve: vi.fn(async () => ({ resolve: vi.fn(async () => ({
version: 1, version: 1,
issuer: "local", issuer: "local",
subject: "user-1", subject: "user-1",
method: "local", method: "local",
roles: ["user"], roles,
permissions: ["session.use"], permissions: storedPermissions,
userAuthRevision: 1, userAuthRevision: 1,
authConfigRevision: "b".repeat(64), authConfigRevision: "b".repeat(64),
remembered: false, remembered: false,
@@ -249,7 +269,13 @@ test("the session boundary touches a valid cookie session through the bounded Ta
app.get("/private", async (request) => getPrincipal(request)); app.get("/private", async (request) => getPrincipal(request));
const token = "z".repeat(43); const token = "z".repeat(43);
expect((await app.inject({ method: "GET", url: "/private", headers: { cookie: `thothii_session=${token}` } })).statusCode).toBe(200); const response = await app.inject({ method: "GET", url: "/private", headers: { cookie: `thothii_session=${token}` } });
expect(response.statusCode).toBe(200);
expect(response.json()).toMatchObject({
roles,
permissions: rolesToPermissions(roles),
isAdmin: roles.includes("admin"),
});
expect(sessions.touch).toHaveBeenCalledWith(token); expect(sessions.touch).toHaveBeenCalledWith(token);
}); });
@@ -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 { spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto"; 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 { PostgreSqlContainer } from "@testcontainers/postgresql";
import { CamelCasePlugin, Kysely, PostgresDialect, sql } from "kysely"; import { CamelCasePlugin, Kysely, PostgresDialect, sql } from "kysely";
import { Pool } from "pg"; 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 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 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 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; 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 upLocalSensitivityAnalysis(db);
await upSensitivityReason(db); await upSensitivityReason(db);
await upCatalogPreprocessingState(db); await upCatalogPreprocessingState(db);
await upInstallationBindingImports(db);
await upPreprocessingRunIdentity(db);
await expect(db.selectFrom("sensitiveDataSuggestionRuns") await expect(db.selectFrom("sensitiveDataSuggestionRuns")
.select(["engine", "modelId", "policyVersion", "unknown"]) .select(["engine", "modelId", "policyVersion", "unknown"])
.where("id", "=", historicalSuggestionRunId) .where("id", "=", historicalSuggestionRunId)
@@ -124,8 +136,17 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
], ],
relationships: [], relationships: [],
}; };
expect(await repository.applySchemaSync(created.id, 1, "columns", [], fullColumnsSnapshot)) const memoryCleanupRun = await repository.createSyncRun(created.id, "columns", [], 1);
await repository.updateSyncRun(memoryCleanupRun.id, { state: "applying", phase: "applying" });
await expect(repository.applySchemaSync(created.id, 999, "columns", [], fullColumnsSnapshot, memoryCleanupRun.id))
.resolves.toBeUndefined();
expect((await repository.getSyncRun(memoryCleanupRun.id))?.phase).toBe("applying");
expect(await repository.applySchemaSync(created.id, 1, "columns", [], fullColumnsSnapshot, memoryCleanupRun.id))
.toMatchObject({ created: 4, deleted: 0 }); .toMatchObject({ created: 4, deleted: 0 });
expect((await repository.getSyncRun(memoryCleanupRun.id))?.phase).toBe("memory_cleanup");
await repository.interruptActiveSyncRuns();
expect(await repository.getSyncRun(memoryCleanupRun.id))
.toMatchObject({ state: "interrupted", phase: "memory_cleanup" });
expect((await repository.listColumns(created.id, patients.id)).map((column) => ({ expect((await repository.listColumns(created.id, patients.id)).map((column) => ({
name: column.name, name: column.name,
sensitive: column.sensitive, sensitive: column.sensitive,
@@ -233,6 +254,7 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
}); });
expect(await repository.listSyncRuns(created.id)).toEqual([ expect(await repository.listSyncRuns(created.id)).toEqual([
expect.objectContaining({ id: syncRun.id, tableIds: [patients.id] }), expect.objectContaining({ id: syncRun.id, tableIds: [patients.id] }),
expect.objectContaining({ id: memoryCleanupRun.id, phase: "memory_cleanup" }),
]); ]);
const lockedDatabase = await repository.create({ const lockedDatabase = await repository.create({
@@ -292,6 +314,16 @@ test.skipIf(!dockerAvailable)("PostgreSQL migration enforces one database per wo
preprocessingStatus: "succeeded", preprocessingStatus: "succeeded",
preprocessedMetadataRevision: beforePreprocessing.metadataContentRevision, 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({ await db.insertInto("catalogTables").values({
id: randomUUID(), id: randomUUID(),
databaseId: lockedDatabase.id, databaseId: lockedDatabase.id,
@@ -309,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.delete(created.id, 2)).toBe(true);
expect(await repository.list()).toEqual([]); expect(await repository.list()).toEqual([]);
expect(await repository.listTables(created.id)).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 { } finally {
await db.destroy(); await db.destroy();
await container.stop(); await container.stop();
+66 -2
View File
@@ -15,10 +15,34 @@ import {
import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js"; import { WorkspaceSecretStore } from "../src/workspaces/secret-store.js";
import type { WorkspaceRegistry, WorkspaceRevision } from "../src/workspaces/registry.js"; import type { WorkspaceRegistry, WorkspaceRevision } from "../src/workspaces/registry.js";
import type { WorkspaceDescriptor } from "../src/workspaces/schema.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[] = []; const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); 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 = { const workspace: WorkspaceDescriptor = {
workspace: { schema_version: 4, id: "psd-clinical", name: "Policlinico San Donato", language: "it" }, 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"] }, dwh: { engine: "postgres", database: "warehouse", schema: "datawarehouse", port: 5432, supported_transports: ["postgres_direct"] },
@@ -117,6 +141,7 @@ async function setup(env: Record<string, string> = {}) {
}); });
const introspector: CatalogSchemaIntrospector = { scan }; const introspector: CatalogSchemaIntrospector = { scan };
const operations = new CatalogOperationCoordinator(); const operations = new CatalogOperationCoordinator();
const cleanup = vi.fn(async () => ({ code: 0, stdout: JSON.stringify({ indexed: true, deleted: 0 }), stderr: "" }));
const registry = { const registry = {
list: vi.fn(async () => [revision]), list: vi.fn(async () => [revision]),
listCatalog: vi.fn(async () => [{ id: "psd-clinical", name: "Policlinico San Donato", configurationState: "ready", revision }]), listCatalog: vi.fn(async () => [{ id: "psd-clinical", name: "Policlinico San Donato", configurationState: "ready", revision }]),
@@ -124,7 +149,7 @@ async function setup(env: Record<string, string> = {}) {
readPinned: vi.fn(async () => ({ workspace, workspaceConfigPath: revision.snapshotPath })), readPinned: vi.fn(async () => ({ workspace, workspaceConfigPath: revision.snapshotPath })),
} as unknown as WorkspaceRegistry; } as unknown as WorkspaceRegistry;
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "/missing", NODE_ENV: "test", ...env }), { const app = buildApp(loadConfig({ THT_HARNESS_DIR: "/missing", NODE_ENV: "test", ...env }), {
thtRunner: {} as never, thtRunner: { withPrincipal: () => ({ runWithRuntimeSnapshot: cleanup }) } as never,
workspaceRegistry: registry, workspaceRegistry: registry,
workspaceSecretStore: new WorkspaceSecretStore({ root: secretRoot, runtimeRoot, installationId: "test" }), workspaceSecretStore: new WorkspaceSecretStore({ root: secretRoot, runtimeRoot, installationId: "test" }),
catalogRepository: repository, catalogRepository: repository,
@@ -133,7 +158,7 @@ async function setup(env: Record<string, string> = {}) {
workspaceDiagnoser: vi.fn(), workspaceDiagnoser: vi.fn(),
}); });
return { return {
app, repository, database: (await repository.get(created.id))!, scan, operations, app, repository, database: (await repository.get(created.id))!, scan, operations, cleanup,
setObserved(next: ObservedSchemaSnapshot) { observed = next; }, setObserved(next: ObservedSchemaSnapshot) { observed = next; },
}; };
} }
@@ -614,6 +639,45 @@ test("waits for confirmation and rescans before applying destructive changes", a
expect(scan).toHaveBeenCalledTimes(3); expect(scan).toHaveBeenCalledTimes(3);
}); });
test("retries committed Memory cleanup with the original removals without rescanning", async () => {
const { app, repository, database, scan, setObserved, cleanup } = await setup();
await seedCatalog(repository, database);
const observed = snapshot();
observed.tables = observed.tables.filter(t => t.name !== "visits");
observed.columns = observed.columns.filter(c => c.tableName !== "visits");
observed.relationships = [];
setObserved(observed);
cleanup.mockResolvedValueOnce({ code: 0, stdout: JSON.stringify({ indexed: false, deleted: 2 }), stderr: "" });
const started = await app.inject({ method: "POST", url: `/catalog/databases/${database.id}/sync-runs`,
payload: { version: database.version, scope: "all", tableIds: [] } });
const waiting = await waitFor(repository, started.json().id, "awaiting_confirmation");
expect(cleanup).not.toHaveBeenCalled();
await app.inject({ method: "POST", url: `/catalog/sync-runs/${waiting.id}/confirm`,
payload: { confirmationToken: waiting.confirmationToken } });
const failed = await waitFor(repository, waiting.id, "failed");
expect(failed).toMatchObject({ phase: "memory_cleanup", errorCode: "memory_cleanup_pending",
plannedDiff: { deletedTables: ["visits"] } });
expect((await repository.listTables(database.id)).map(t => t.name)).toEqual(["patients"]);
const callsBeforeRetry = scan.mock.calls.length;
const blocked = await app.inject({ method: "POST", url: `/catalog/databases/${database.id}/sync-runs`,
payload: { version: database.version, scope: "all", tableIds: [] } });
expect(blocked.statusCode).toBe(409);
// Simulate startup recovery and an unreachable DWH after schema application.
await repository.interruptActiveSyncRuns();
scan.mockRejectedValue(new Error("DWH unavailable"));
cleanup.mockResolvedValue({ code: 0, stdout: JSON.stringify({ indexed: true, deleted: 2 }), stderr: "" });
const retried = await app.inject({ method: "POST", url: `/catalog/sync-runs/${waiting.id}/retry` });
expect(retried.statusCode).toBe(202);
const completed = await waitFor(repository, waiting.id, "succeeded");
expect(completed.counts).toMatchObject({ memoryDeleted: 2 });
expect(scan.mock.calls.length).toBe(callsBeforeRetry);
expect(cleanup).toHaveBeenCalledTimes(2);
expect(cleanup.mock.calls[1]).toEqual(cleanup.mock.calls[0]);
const request = JSON.parse((cleanup.mock.calls[0] as unknown as string[])[1]!).request;
expect(request).toMatchObject({ sync_id: waiting.id, database: "warehouse",
schema_name: "datawarehouse", removed_tables: ["visits"] });
});
test("deletes every catalog table for multiple selected databases and cascades dependent metadata", async () => { test("deletes every catalog table for multiple selected databases and cascades dependent metadata", async () => {
const { app, repository, database } = await setup(); const { app, repository, database } = await setup();
const second = await repository.create({ const second = await repository.create({
@@ -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");
}
});
+2 -2
View File
@@ -36,7 +36,7 @@ test("loop F1: crea sessione → SSE riceve il widget → risponde → il modell
ollamaEnsure: async () => ({ ok: true }), ollamaEnsure: async () => ({ ok: true }),
searchPack: async () => {}, searchPack: async () => {},
sessionNew: async () => ({ id: "s1" }), sessionNew: async () => ({ id: "s1" }),
sessionShow: async (_id: string) => ({ id: "s1", provider: undefined, model: undefined, thinking: undefined }), sessionShow: async (_id: string) => ({ id: "s1", interaction_language: "en", provider: undefined, model: undefined, thinking: undefined }),
sessionList: async () => [], sessionList: async () => [],
} as any, } as any,
spawnFn: () => spawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => spawn("node", [FAKE, SCRIPT]) as any,
@@ -48,7 +48,7 @@ test("loop F1: crea sessione → SSE riceve il widget → risponde → il modell
const created = await fetch(`${base}/sessions`, { const created = await fetch(`${base}/sessions`, {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ workspace: "w", question: "q" }), body: JSON.stringify({ workspace: "w", question: "q", interactionLanguage: "en" }),
}); });
expect(created.status).toBe(200); expect(created.status).toBe(200);
+69
View File
@@ -0,0 +1,69 @@
import Fastify from "fastify";
import { afterEach, expect, test, vi } from "vitest";
import { evidenceRoutes } from "../src/routes/evidence.js";
import type { ThtRunner } from "../src/tht/tht-runner.js";
import type { PrincipalContext } from "../src/auth/principal.js";
const apps: ReturnType<typeof Fastify>[] = [];
afterEach(async () => { await Promise.all(apps.splice(0).map(app => app.close())); });
function setup(admin = true) {
const app = Fastify(); apps.push(app);
const principal: PrincipalContext = { issuer: "test", subject: "curator", roles: [admin ? "admin" : "user"],
permissions: admin ? ["evidence.manage"] : ["session.use"], isAdmin: admin };
app.addHook("preHandler", async request => { request.principal = principal; });
const run = vi.fn(async () => ({ code: 0, stdout: JSON.stringify({ items: [], total: 0 }), stderr: "" }));
const withPrincipal = vi.fn(() => ({ runWithRuntimeSnapshot: run }) as unknown as ThtRunner);
const consolidateEvidence = vi.fn();
const evidenceSources = vi.fn().mockResolvedValue({status: "succeeded"});
evidenceRoutes(app, { runner: { withPrincipal }, registryRoot: "/data/registry", hostRegistryRoot: "/srv/Thoth workspaces",
registry: { list: async () => [{ id: "sales", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/missing" }] },
service: { consolidateEvidence, evidenceSources } });
return { app, run, withPrincipal, principal, consolidateEvidence, evidenceSources };
}
test("browses complete local files with host paths, without a database runtime", async () => {
const { app, run, withPrincipal, principal } = setup();
const response = await app.inject("/workspaces/sales/evidence?kind=domain&concept=orders&page=2");
expect(response.statusCode).toBe(200);
expect(withPrincipal).toHaveBeenCalledWith(principal);
const [argv, snapshot] = run.mock.calls[0] as unknown as [string[], string];
expect(argv).toEqual(["evidence", "admin", "--workspace", "sales"]);
expect(JSON.parse(snapshot)).toEqual({ root: "/data/registry/repo/sales", query: { kind: "domain", concept: "orders", page: 2 } });
expect(response.json().location.workspace).toBe("/srv/Thoth workspaces/repo/sales");
expect(response.json().location.git_commands[0]).toContain("git -C '/srv/Thoth workspaces/repo'");
});
test("source actions require admin, bind the actor, and reject cross-workspace or arbitrary inputs", async () => {
const denied = setup(false);
expect((await denied.app.inject({method: "POST", url: "/workspaces/sales/evidence/sources", payload: {action: "refresh"}})).statusCode).toBe(403);
expect(denied.evidenceSources).not.toHaveBeenCalled();
const allowed = setup();
expect((await allowed.app.inject({method: "POST", url: "/workspaces/sales/evidence/sources", payload: {action: "refresh"}})).statusCode).toBe(200);
expect(allowed.evidenceSources).toHaveBeenCalledWith({workspaceId: "sales", action: "refresh", actor: "curator"});
const choice = {action: "decide", sourceId: "a".repeat(64), revision: "b".repeat(64), decision: "keep"};
expect((await allowed.app.inject({method: "POST", url: "/workspaces/sales/evidence/sources", payload: choice})).statusCode).toBe(200);
expect(allowed.evidenceSources).toHaveBeenLastCalledWith({...choice, workspaceId: "sales", actor: "curator"});
for (const payload of [{action: "refresh", url: "http://localhost"}, {...choice, actor: "forged"}, {...choice, revision: "../other"}]) {
expect((await allowed.app.inject({method: "POST", url: "/workspaces/sales/evidence/sources", payload})).statusCode).toBe(400);
}
expect((await allowed.app.inject({method: "POST", url: "/workspaces/other/evidence/sources", payload: choice})).statusCode).toBe(404);
expect(allowed.evidenceSources).toHaveBeenCalledTimes(2);
});
test.each(["/", "/evidence:rule", "/consolidate"])("refuses non-admin access %s", async suffix => {
const { app, run, consolidateEvidence } = setup(false);
const response = await app.inject({ method: suffix === "/consolidate" ? "POST" : "GET", url: `/workspaces/sales/evidence${suffix === "/" ? "" : suffix}` });
expect(response.statusCode).toBe(403); expect(run).not.toHaveBeenCalled(); expect(consolidateEvidence).not.toHaveBeenCalled();
});
test("rejects workspace escape, unknown workspace and unsupported filters", async () => {
const { app, run } = setup();
expect((await app.inject("/workspaces/foreign/evidence")).statusCode).toBe(404);
expect((await app.inject("/workspaces/sales/evidence?root=/private")).statusCode).toBe(400);
expect((await app.inject("/workspaces/sales/evidence?page_size=101")).statusCode).toBe(400);
expect(run).not.toHaveBeenCalled();
});
test("a missing unit is 404 and consolidation preserves the partial outcome", async () => {
const { app, consolidateEvidence } = setup();
expect((await app.inject("/workspaces/sales/evidence/evidence:missing")).statusCode).toBe(404);
consolidateEvidence.mockResolvedValue({ status: "failed", warnings: ["Saved; retry indexing."] });
const response = await app.inject({ method: "POST", url: "/workspaces/sales/evidence/consolidate" });
expect(response.json()).toEqual({ status: "failed", warnings: ["Saved; retry indexing."] });
});
+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"]);
});
+33 -1
View File
@@ -56,7 +56,7 @@ test("catalog listing translates upstream Pi IDs back to canonical model keys",
session: { reasoning: true, contextWindow: 32768, maxTokens: 8192 }, session: { reasoning: true, contextWindow: 32768, maxTokens: 8192 },
}; };
const modelCatalog: RuntimeModelCatalog = { const modelCatalog: RuntimeModelCatalog = {
defaultSession: model.id, defaultMetadataGeneration: null, embedding: null, defaultInteraction: model.id, embedding: null,
sessionModels: () => [model], metadataModels: () => [], hasSession: (id) => id === model.id, sessionModels: () => [model], metadataModels: () => [], hasSession: (id) => id === model.id,
}; };
try { try {
@@ -75,6 +75,38 @@ test("catalog listing translates upstream Pi IDs back to canonical model keys",
} }
}); });
test("catalog listing supplies the shared DeepSeek key without requiring Pi auth", async () => {
const script = scriptWith([{ provider: "deepseek", id: "deepseek-v4-pro", name: "DeepSeek V4 Pro" }]);
const secret = join(path.dirname(script), "thothii.secrets");
writeFileSync(secret, "DEEPSEEK_API_KEY=shared-key\nOPENAI_API_KEY=unrelated-key\n", { mode: 0o600 });
const model: RuntimeModel = {
id: "deepseek/deepseek-v4-pro", provider: "deepseek", model: "deepseek-v4-pro",
label: "DeepSeek V4 Pro", upstreamModel: "deepseek-v4-pro",
authentication: { mode: "secret_env", apiKeyEnv: "DEEPSEEK_API_KEY" },
sessionAdapter: { mode: "pi_builtin" }, session: { reasoning: false },
};
const modelCatalog: RuntimeModelCatalog = {
defaultInteraction: model.id, embedding: null,
sessionModels: () => [model], metadataModels: () => [], hasSession: (id) => id === model.id,
};
try {
const lister = createPiModelLister(loadConfig({ THT_SECRETS_FILE: secret }), {
...noManagedModels, modelCatalog, loadEnabledModels: enabled(model.id),
spawnFn: (_command, _args, options) => {
expect(options.env.DEEPSEEK_API_KEY).toBe("shared-key");
expect(options.env).not.toHaveProperty("OPENAI_API_KEY");
expect(options.env).not.toHaveProperty("THT_SECRETS_FILE");
return spawn("node", [FAKE, script], { env: options.env }) as any;
},
});
await expect(lister()).resolves.toEqual([{
provider: model.provider, id: model.model, name: model.label, reasoning: false,
}]);
} finally {
rmSync(path.dirname(script), { recursive: true, force: true });
}
});
test("createPiModelLister caches within ttl (spawns once for two calls)", async () => { test("createPiModelLister caches within ttl (spawns once for two calls)", async () => {
const script = scriptWith([{ provider: "zai", id: "glm-5.2", name: "GLM 5.2", reasoning: true }]); const script = scriptWith([{ provider: "zai", id: "glm-5.2", name: "GLM 5.2", reasoning: true }]);
try { try {
+81
View File
@@ -0,0 +1,81 @@
import Fastify from "fastify";
import { afterEach, expect, test, vi } from "vitest";
import { memoryRoutes } from "../src/routes/memory.js";
import { DEFAULT_SEMANTIC_RUNTIME } from "../src/workspaces/runtime-renderer.js";
import type { ThtRunner } from "../src/tht/tht-runner.js";
import type { PrincipalContext } from "../src/auth/principal.js";
const apps: ReturnType<typeof Fastify>[] = [];
afterEach(async () => { await Promise.all(apps.splice(0).map(app => app.close())); });
const id = "mem-11111111-1111-4111-8111-111111111111";
const input = { family: "domain_clarification", subject: "Order", scope: "Sales" };
function setup(admin = true) {
const app = Fastify(); apps.push(app);
const principal: PrincipalContext = { issuer: "test", subject: "operator", roles: [admin ? "admin" : "user"],
permissions: admin ? ["memory.manage"] : ["session.use"], isAdmin: admin };
app.addHook("preHandler", async request => { request.principal = principal; });
const run = vi.fn(async () => ({ code: 0, stdout: JSON.stringify({ items: [], total: 0 }), stderr: "" }));
const bound = { runWithRuntimeSnapshot: run } as unknown as ThtRunner;
const withPrincipal = vi.fn(() => bound);
memoryRoutes(app, { runner: { withPrincipal }, runtime: DEFAULT_SEMANTIC_RUNTIME,
registry: {
list: async () => [{ id: "sales", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: "/missing" }],
read: vi.fn().mockResolvedValue({ workspace: { workspace: { language: "it" } } }),
} });
return { app, run, withPrincipal, principal };
}
test("list binds principal and workspace without requiring a DWH runtime", async () => {
const { app, run, withPrincipal, principal } = setup();
const response = await app.inject("/workspaces/sales/memory?q=Order&page=2&column=id");
expect(response.statusCode).toBe(200);
expect(withPrincipal).toHaveBeenCalledWith(principal);
const [args, snapshot] = run.mock.calls[0] as unknown as [string[], string];
expect(args).toEqual(["memory", "admin", "--workspace", "sales"]);
expect(JSON.parse(snapshot)).toMatchObject({ action: "list", request: { q: "Order", page: 2, column: "id" } });
expect(JSON.parse(snapshot).runtime.memoryLanguage).toBe("it");
});
test.each([
["GET", ""], ["POST", ""], ["GET", "/pending"], ["GET", `/${id}`],
["PUT", `/${id}`], ["DELETE", `/${id}`], ["POST", `/${id}/retry`],
] as const)("non-admin cannot %s %s", async (method, suffix) => {
const { app, run } = setup(false);
const response = await app.inject({ method, url: `/workspaces/sales/memory${suffix}`,
...(method === "PUT" || method === "POST" && suffix === "" ? { payload: input } : {}) });
expect(response.statusCode).toBe(403); expect(run).not.toHaveBeenCalled();
});
test("unknown workspace and invalid input do not invoke the harness", async () => {
const { app, run } = setup();
expect((await app.inject("/workspaces/missing/memory")).statusCode).toBe(404);
expect((await app.inject("/workspaces/sales/memory?page_size=101")).statusCode).toBe(400);
expect((await app.inject({ method: "POST", url: "/workspaces/sales/memory",
payload: { ...input, workspace_id: "foreign" } })).statusCode).toBe(400);
expect(run).not.toHaveBeenCalled();
});
test("create preserves saved-but-unindexed outcome, update carries complete related changes", async () => {
const { app, run } = setup();
run.mockResolvedValue({ code: 0, stdout: JSON.stringify({ id, saved: true, indexed: false }), stderr: "" });
const result = await app.inject({ method: "POST", url: "/workspaces/sales/memory", payload: input });
expect(result.statusCode).toBe(201); expect(result.json()).toEqual({ id, saved: true, indexed: false });
await app.inject({ method: "PUT", url: `/workspaces/sales/memory/${id}`, payload: {
...input, links: [{ target_id: id, meaning: "Related" }], dependencies: [{ database: "dwh" }],
} });
const [, snapshot] = run.mock.calls[1] as unknown as [string[], string];
expect(JSON.parse(snapshot)).toMatchObject({ action: "update", request: { id, card: {
links: [{ target_id: id, meaning: "Related" }], dependencies: [{ database: "dwh" }],
} } });
});
test.each([["memory_not_found", 404], ["memory_conflict", 409], ["memory_unavailable", 503]])(
"maps %s without leaking stderr", async (code, status) => {
const { app, run } = setup();
run.mockResolvedValue({ code: 1, stdout: JSON.stringify({ code, message: "sensitive detail" }), stderr: "secret" });
const result = await app.inject("/workspaces/sales/memory");
expect(result.statusCode).toBe(status); expect(result.json().code).toBe(code);
expect(result.body).not.toMatch(/secret|sensitive/);
},
);
@@ -20,9 +20,8 @@ function runtimeCatalog(overrides: Record<string, unknown> = {}, secrets = "OPEN
const catalogFile = join(root, "catalog.json"); const catalogFile = join(root, "catalog.json");
const secretsFile = join(root, "thothii.secrets"); const secretsFile = join(root, "thothii.secrets");
const catalog = { const catalog = {
schemaVersion: 1, schemaVersion: 2,
defaultSession: "zai/glm-5.3", defaultInteraction: "zai/glm-5.3",
defaultMetadataGeneration: "zai/glm-5.3",
embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 }, embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 },
models: [ models: [
{ {
@@ -55,8 +54,8 @@ test("loads session default and safe metadata choices from the normalized runtim
const runtime = loadRuntimeModelCatalog(catalogFile); const runtime = loadRuntimeModelCatalog(catalogFile);
const metadata = loadMetadataGenerationModels({ catalogFile, secretsFile }); const metadata = loadMetadataGenerationModels({ catalogFile, secretsFile });
expect(runtime.defaultSession).toBe("zai/glm-5.3"); expect(runtime.defaultInteraction).toBe("zai/glm-5.3");
expect(runtime.hasSession("deepseek/deepseek-v4-pro")).toBe(true); expect(runtime.hasSession("deepseek/deepseek-v4-pro")).toBe(false);
expect(metadata.catalog()).toEqual({ expect(metadata.catalog()).toEqual({
models: [{ id: "zai/glm-5.3", label: "GLM 5.3" }], models: [{ id: "zai/glm-5.3", label: "GLM 5.3" }],
default: "zai/glm-5.3", default: "zai/glm-5.3",
@@ -69,14 +68,65 @@ test("loads session default and safe metadata choices from the normalized runtim
expect(() => metadata.resolve("zai/missing")).toThrow(MetadataGenerationModelUnavailableError); expect(() => metadata.resolve("zai/missing")).toThrow(MetadataGenerationModelUnavailableError);
}); });
test("DeepSeek uses one identity and bundle credential for native Pi and LiteLLM", () => {
const models = ["deepseek-v4-pro", "deepseek-v4-flash"].map((model) => ({
id: `deepseek/${model}`, provider: "deepseek", model, label: model, upstreamModel: model,
authentication: { mode: "secret_env", apiKeyEnv: "DEEPSEEK_API_KEY" },
sessionAdapter: { mode: "pi_builtin" }, metadataAdapter: { litellmProvider: "deepseek" },
session: { reasoning: false }, metadataGeneration: { disableThinking: false },
}));
const files = runtimeCatalog({ defaultInteraction: models[0].id, models }, "DEEPSEEK_API_KEY=shared-key\n");
const runtime = loadRuntimeModelCatalog(files.catalogFile);
const metadata = loadMetadataGenerationModels(files);
expect(runtime.sessionModels().map((model) => model.id)).toEqual(metadata.catalog().models.map((model) => model.id));
expect(metadata.catalog().default).toBe(runtime.defaultInteraction);
for (const model of models) {
expect(metadata.resolve(model.id)).toMatchObject({
id: model.id, provider: "deepseek", model: model.model,
apiKeyEnv: "DEEPSEEK_API_KEY", apiKey: "shared-key",
});
}
expect(() => metadata.resolve("deepseek-metadata/deepseek-v4-pro"))
.toThrow(MetadataGenerationModelUnavailableError);
});
test("returns empty catalogs when no runtime projection is configured", () => { test("returns empty catalogs when no runtime projection is configured", () => {
expect(loadRuntimeModelCatalog().defaultSession).toBeNull(); expect(loadRuntimeModelCatalog().defaultInteraction).toBeNull();
expect(loadMetadataGenerationModels({}).catalog()).toEqual({ models: [], default: null }); expect(loadMetadataGenerationModels({}).catalog()).toEqual({ models: [], default: null });
}); });
test.each([
["qwen-chat-template", true, true],
["qwen", true, true],
["qwen-typo", true, false],
["qwen-chat-template", false, false],
])("validates Qwen thinking format %s with reasoning=%s", (thinkingFormat, reasoning, valid) => {
const { catalogFile } = runtimeCatalog({
defaultInteraction: "local/qwen",
models: [{
id: "local/qwen", provider: "local", model: "qwen", label: "Qwen",
upstreamModel: "qwen", endpoint: { baseUrl: "http://localhost:8000/v1" },
authentication: { mode: "none" }, sessionAdapter: { mode: "openai_compatible" },
session: {
reasoning, contextWindow: 32768, maxTokens: 8192,
compatibility: {
supportsDeveloperRole: false, supportsReasoningEffort: false,
supportsStore: false, maxTokensField: "max_tokens", thinkingFormat,
},
},
}],
});
if (valid) {
expect(loadRuntimeModelCatalog(catalogFile).sessionModels()[0].session?.compatibility)
.toMatchObject({ thinkingFormat });
} else {
expect(() => loadRuntimeModelCatalog(catalogFile)).toThrow("runtime model catalog is invalid");
}
});
test("rejects a drifted default and an unprotected projection", () => { test("rejects a drifted default and an unprotected projection", () => {
const drifted = runtimeCatalog({ defaultSession: "zai/missing" }); const drifted = runtimeCatalog({ defaultInteraction: "zai/missing" });
expect(() => loadRuntimeModelCatalog(drifted.catalogFile)).toThrow("session default is invalid"); expect(() => loadRuntimeModelCatalog(drifted.catalogFile)).toThrow("interaction default is invalid");
const unprotected = runtimeCatalog(); const unprotected = runtimeCatalog();
chmodSync(unprotected.catalogFile, 0o666); chmodSync(unprotected.catalogFile, 0o666);
@@ -85,7 +135,7 @@ test("rejects a drifted default and an unprotected projection", () => {
test("rejects authentication semantics that cannot come from the installation catalog", () => { test("rejects authentication semantics that cannot come from the installation catalog", () => {
const invalid = runtimeCatalog({ const invalid = runtimeCatalog({
defaultMetadataGeneration: undefined, defaultInteraction: undefined,
models: [{ models: [{
id: "zai/glm-5.3", id: "zai/glm-5.3",
provider: "zai", provider: "zai",
@@ -112,3 +162,13 @@ test("splits canonical session identities without provider aliases", () => {
expect(splitCanonicalModelId("zai/glm-5.3")).toEqual({ provider: "zai", model: "glm-5.3" }); expect(splitCanonicalModelId("zai/glm-5.3")).toEqual({ provider: "zai", model: "glm-5.3" });
expect(() => splitCanonicalModelId("glm-5.3")).toThrow("model identity is invalid"); expect(() => splitCanonicalModelId("glm-5.3")).toThrow("model identity is invalid");
}); });
test("rejects a default supported by only one configured use", () => {
const { catalogFile } = runtimeCatalog({ defaultInteraction: "deepseek/deepseek-v4-pro" });
expect(() => loadRuntimeModelCatalog(catalogFile)).toThrow("interaction default is invalid");
});
test("requires regenerated runtime schema v2 rather than interpreting two legacy defaults", () => {
const { catalogFile } = runtimeCatalog({ schemaVersion: 1, defaultSession: "zai/glm-5.3" });
expect(() => loadRuntimeModelCatalog(catalogFile)).toThrow("runtime model catalog is invalid");
});
+32
View File
@@ -5,6 +5,8 @@ const fakes = vi.hoisted(() => ({
catalogRepository: { close: vi.fn(async () => {}) }, catalogRepository: { close: vi.fn(async () => {}) },
createCatalogRepository: vi.fn(), createCatalogRepository: vi.fn(),
runnerConfig: undefined as Record<string, unknown> | undefined, runnerConfig: undefined as Record<string, unknown> | undefined,
acquireWorkspaceRuntime: vi.fn(),
releaseWorkspaceRuntime: vi.fn(),
run: vi.fn(async () => ({ run: vi.fn(async () => ({
code: 0, code: 0,
stdout: JSON.stringify({ ok: true }), stdout: JSON.stringify({ ok: true }),
@@ -24,6 +26,8 @@ vi.mock("../src/tht/tht-runner.js", () => ({
run = fakes.run; run = fakes.run;
acquireWorkspaceRuntime = fakes.acquireWorkspaceRuntime;
withPrincipal() { withPrincipal() {
return this; return this;
} }
@@ -32,6 +36,10 @@ vi.mock("../src/tht/tht-runner.js", () => ({
vi.mock("../src/workspaces/registry.js", () => ({ vi.mock("../src/workspaces/registry.js", () => ({
WorkspaceRegistry: class { WorkspaceRegistry: class {
async pull() {
return { branch: "main", head: "a".repeat(40), ahead: 0, behind: 0, degraded: false };
}
async listRetainedSnapshots() { async listRetainedSnapshots() {
return [{ snapshotPath: "/data/workspace-registry/snapshots/revision/workspace.yaml" }]; return [{ snapshotPath: "/data/workspace-registry/snapshots/revision/workspace.yaml" }];
} }
@@ -67,6 +75,12 @@ beforeEach(() => {
fakes.createCatalogRepository.mockReset(); fakes.createCatalogRepository.mockReset();
fakes.createCatalogRepository.mockReturnValue(fakes.catalogRepository); fakes.createCatalogRepository.mockReturnValue(fakes.catalogRepository);
fakes.run.mockClear(); fakes.run.mockClear();
fakes.acquireWorkspaceRuntime.mockReset();
fakes.acquireWorkspaceRuntime.mockResolvedValue({
path: "/data/workspace-registry/snapshots/runtime/workspace.yaml",
release: fakes.releaseWorkspaceRuntime,
});
fakes.releaseWorkspaceRuntime.mockClear();
fakes.runnerConfig = undefined; fakes.runnerConfig = undefined;
}); });
@@ -78,5 +92,23 @@ test("workflow doctor gives schema-v4 runtime rendering a live Catalog repositor
expect(fakes.createCatalogRepository).toHaveBeenCalledWith(config.catalogDatabase); expect(fakes.createCatalogRepository).toHaveBeenCalledWith(config.catalogDatabase);
expect(fakes.runnerConfig?.catalogRepository).toBe(fakes.catalogRepository); expect(fakes.runnerConfig?.catalogRepository).toBe(fakes.catalogRepository);
expect(fakes.acquireWorkspaceRuntime).toHaveBeenCalledWith(
"/data/workspace-registry/snapshots/revision/workspace.yaml",
);
expect(fakes.run).toHaveBeenCalledWith(
["doctor", "--json"],
"/data/workspace-registry/snapshots/runtime/workspace.yaml",
);
expect(fakes.releaseWorkspaceRuntime).toHaveBeenCalledOnce();
expect(fakes.catalogRepository.close).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,
});
});
+54 -4
View File
@@ -1,4 +1,4 @@
import { mkdtempSync } from "node:fs"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { expect, test, vi } from "vitest"; import { expect, test, vi } from "vitest";
@@ -7,7 +7,34 @@ import {
createPiManagement, createPiManagement,
type PiExecFile, type PiExecFile,
} from "../src/pi/management.js"; } from "../src/pi/management.js";
import type { RuntimeModelCatalog } from "../src/models/runtime-model-catalog.js"; import type { RuntimeModel, RuntimeModelCatalog } from "../src/models/runtime-model-catalog.js";
test.each([false, true])("catalog credential status ignores legacy Pi auth, missing bundle key: %s", async (missingKey) => {
const root = mkdtempSync(join(tmpdir(), "tht-catalog-status-"));
writeFileSync(join(root, "auth.json"), JSON.stringify({ deepseek: { type: "api_key", key: "stale-key" } }), { mode: 0o600 });
const secret = join(root, "thothii.secrets");
writeFileSync(secret, missingKey ? "THT_MODEL_API_KEY=legacy-key\n" : "DEEPSEEK_API_KEY=shared-key\n", { mode: 0o600 });
vi.stubEnv("PI_CODING_AGENT_DIR", root);
const model: RuntimeModel = {
id: "deepseek/deepseek-v4-pro", provider: "deepseek", model: "deepseek-v4-pro",
label: "DeepSeek", upstreamModel: "deepseek-v4-pro",
authentication: { mode: "secret_env", apiKeyEnv: "DEEPSEEK_API_KEY" },
sessionAdapter: { mode: "pi_builtin" }, session: { reasoning: false },
};
try {
const service = createPiManagement(loadConfig({ THT_SECRETS_FILE: secret }), {
modelCatalog: {
defaultInteraction: model.id, embedding: null,
sessionModels: () => [model], metadataModels: () => [], hasSession: (id) => id === model.id,
},
execute: successfulExec([]), readSettings: () => ({ thinking: "medium" }),
});
expect((await service.status()).credentials).toBe(missingKey ? "missing" : "present");
} finally {
vi.unstubAllEnvs();
rmSync(root, { recursive: true, force: true });
}
});
function configFor(settingsFile = join(mkdtempSync(join(tmpdir(), "tht-pi-management-")), "settings.json")) { function configFor(settingsFile = join(mkdtempSync(join(tmpdir(), "tht-pi-management-")), "settings.json")) {
return loadConfig({ return loadConfig({
@@ -15,18 +42,29 @@ function configFor(settingsFile = join(mkdtempSync(join(tmpdir(), "tht-pi-manage
SETTINGS_FILE: settingsFile, SETTINGS_FILE: settingsFile,
PI_BIN: "/usr/local/bin/pi", PI_BIN: "/usr/local/bin/pi",
PI_MANAGEMENT_TIMEOUT_MS: "750", PI_MANAGEMENT_TIMEOUT_MS: "750",
THT_HOST_PLATFORM: "linux",
}); });
} }
const modelCatalog: RuntimeModelCatalog = { const modelCatalog: RuntimeModelCatalog = {
defaultSession: "zai/glm-5.2", defaultInteraction: "zai/glm-5.2",
defaultMetadataGeneration: null,
embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 }, embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 },
sessionModels: () => [], sessionModels: () => [],
metadataModels: () => [], metadataModels: () => [],
hasSession: (id) => id === "zai/glm-5.2", 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 { function successfulExec(calls: Array<{ command: string; args: string[]; timeout: number }>): PiExecFile {
return async (command, args, options) => { return async (command, args, options) => {
calls.push({ command, args, timeout: options.timeout }); calls.push({ command, args, timeout: options.timeout });
@@ -34,6 +72,16 @@ function successfulExec(calls: Array<{ command: string; args: string[]; timeout:
}; };
} }
test.each([
["linux", "linux"], ["darwin", "macos"], ["windows", "windows"],
])("reports installation host %s independently of the backend container OS", async (host, expected) => {
const service = createPiManagement(loadConfig({ THT_HOST_PLATFORM: host }), {
modelCatalog, execute: successfulExec([]), readSettings: () => ({ thinking: "medium" }),
credentialStatus: () => "missing",
});
expect((await service.status()).hostPlatform).toBe(expected);
});
// Catches a Pi executable that emits unexpected text or is invoked through a shell, which could // Catches a Pi executable that emits unexpected text or is invoked through a shell, which could
// turn a version display into a command-injection or information-disclosure surface. // turn a version display into a command-injection or information-disclosure surface.
test("status parses only a Pi version from a fixed execFile argument array", async () => { test("status parses only a Pi version from a fixed execFile argument array", async () => {
@@ -47,6 +95,7 @@ test("status parses only a Pi version from a fixed execFile argument array", asy
}); });
await expect(service.status()).resolves.toEqual({ await expect(service.status()).resolves.toEqual({
hostPlatform: "linux",
version: "0.80.3", version: "0.80.3",
ready: true, ready: true,
credentials: "missing", credentials: "missing",
@@ -78,6 +127,7 @@ test.each(["present", "missing"] as const)(
const status = await service.status(); const status = await service.status();
expect(status).toEqual({ expect(status).toEqual({
hostPlatform: "linux",
version: "0.80.3", version: "0.80.3",
ready: true, ready: true,
credentials, credentials,
+54 -16
View File
@@ -190,6 +190,29 @@ test("Pi receives the leased workspace runtime config and releases it on direct
expect(release).toHaveBeenCalledOnce(); expect(release).toHaveBeenCalledOnce();
}); });
test("Pi language launch hint comes from the session options and never ambient environment", () => {
const previous = process.env.THT_INTERACTION_LANGUAGE;
process.env.THT_INTERACTION_LANGUAGE = "it";
const environments: NodeJS.ProcessEnv[] = [];
const mgr = new PiProcessManager(loadConfig({}), {
spawnFn: (_command, _args, options) => {
environments.push(options.env);
return recordingChild() as any;
},
});
try {
mgr.createFor("explicit-language", { interactionLanguage: "en" });
mgr.teardown("explicit-language");
mgr.createFor("manifest-resolved-in-gate");
mgr.teardown("manifest-resolved-in-gate");
expect(environments[0].THT_INTERACTION_LANGUAGE).toBe("en");
expect(environments[1]).not.toHaveProperty("THT_INTERACTION_LANGUAGE");
} finally {
if (previous === undefined) delete process.env.THT_INTERACTION_LANGUAGE;
else process.env.THT_INTERACTION_LANGUAGE = previous;
}
});
test("a close-only child event releases its temporary Pi agent snapshot", () => { test("a close-only child event releases its temporary Pi agent snapshot", () => {
const child = recordingChild(); const child = recordingChild();
let snapshotDir: string | undefined; let snapshotDir: string | undefined;
@@ -642,27 +665,33 @@ test("session Pi spawn reads the single secret bundle and scrubs its path", asyn
} }
}); });
test("session Pi spawn resolves the selected catalog credential from the secret bundle", () => { test.each([false, true])("session Pi uses the catalog bundle despite stale Pi auth: %s", (missingKey) => {
const root = mkdtempSync(path.join(tmpdir(), "thothii-catalog-credential-")); const root = mkdtempSync(path.join(tmpdir(), "thothii-catalog-credential-"));
const agentDir = path.join(root, "agent"); const agentDir = path.join(root, "agent");
mkdirSync(agentDir, { mode: 0o700 }); mkdirSync(agentDir, { mode: 0o700 });
writeFileSync(path.join(agentDir, "auth.json"), "{}\n", { mode: 0o600 }); const originalAuth = JSON.stringify({
deepseek: { type: "api_key", key: "stale-key" },
anthropic: { type: "api_key", key: "unrelated-key" },
});
writeFileSync(path.join(agentDir, "auth.json"), originalAuth, { mode: 0o600 });
writeFileSync(path.join(agentDir, "models.json"), '{"providers":{}}\n', { mode: 0o600 }); writeFileSync(path.join(agentDir, "models.json"), '{"providers":{}}\n', { mode: 0o600 });
const secret = path.join(root, "thothii.secrets"); const secret = path.join(root, "thothii.secrets");
writeFileSync(secret, "ZAI_API_KEY=catalog-secret\nTHT_MODEL_API_KEY=legacy-secret\n", { mode: 0o600 }); writeFileSync(secret, missingKey ? "THT_MODEL_API_KEY=legacy-secret\n"
: "DEEPSEEK_API_KEY=catalog-secret\nTHT_MODEL_API_KEY=legacy-secret\n", { mode: 0o600 });
const legacyKey = path.join(root, "legacy-key");
writeFileSync(legacyKey, "legacy-file-key", { mode: 0o600 });
const model: RuntimeModel = { const model: RuntimeModel = {
id: "openai/test-model", id: "deepseek/deepseek-v4-pro",
provider: "openai", provider: "deepseek",
model: "test-model", model: "deepseek-v4-pro",
label: "Test model", label: "DeepSeek V4 Pro",
upstreamModel: "test-model", upstreamModel: "deepseek-v4-pro",
authentication: { mode: "secret_env", apiKeyEnv: "ZAI_API_KEY" }, authentication: { mode: "secret_env", apiKeyEnv: "DEEPSEEK_API_KEY" },
sessionAdapter: { mode: "pi_builtin" }, sessionAdapter: { mode: "pi_builtin" },
session: { reasoning: false }, session: { reasoning: false },
}; };
const modelCatalog: RuntimeModelCatalog = { const modelCatalog: RuntimeModelCatalog = {
defaultSession: model.id, defaultInteraction: model.id,
defaultMetadataGeneration: null,
embedding: null, embedding: null,
sessionModels: () => [model], sessionModels: () => [model],
metadataModels: () => [], metadataModels: () => [],
@@ -672,17 +701,26 @@ test("session Pi spawn resolves the selected catalog credential from the secret
const child = recordingChild(); const child = recordingChild();
child.stderr.resume = () => {}; child.stderr.resume = () => {};
vi.stubEnv("PI_CODING_AGENT_DIR", agentDir); vi.stubEnv("PI_CODING_AGENT_DIR", agentDir);
const mgr = new PiProcessManager(loadConfig({ THT_SECRETS_FILE: secret }), { const mgr = new PiProcessManager(loadConfig({ THT_SECRETS_FILE: secret, THT_MODEL_API_KEY_FILE: legacyKey }), {
modelCatalog, modelCatalog,
authProviders: () => new Set(), authProviders: () => new Set(["deepseek"]),
spawnFn: (...args: any[]) => { calls.push(args); return child as any; }, spawnFn: (...args: any[]) => { calls.push(args); return child as any; },
}); });
try { try {
mgr.createFor("catalog-credential", { provider: "openai", model: "test-model" }); const create = () => mgr.createFor("catalog-credential", { provider: model.provider, model: model.model });
expect(calls[0][2].env.ZAI_API_KEY).toBe("catalog-secret"); if (missingKey) {
expect(create).toThrow("model provider credential is unavailable");
expect(calls).toHaveLength(0);
return;
}
create();
expect(calls[0][2].env.DEEPSEEK_API_KEY).toBe("catalog-secret");
expect(calls[0][2].env).not.toHaveProperty("OPENAI_API_KEY"); expect(calls[0][2].env).not.toHaveProperty("OPENAI_API_KEY");
expect(calls[0][2].env).not.toHaveProperty("THT_MODEL_API_KEY"); expect(calls[0][2].env).not.toHaveProperty("THT_MODEL_API_KEY");
expect(JSON.parse(readFileSync(path.join(calls[0][2].env.PI_CODING_AGENT_DIR, "auth.json"), "utf8")))
.toEqual({ anthropic: { type: "api_key", key: "unrelated-key" } });
} finally { } finally {
expect(readFileSync(path.join(agentDir, "auth.json"), "utf8")).toBe(originalAuth);
mgr.teardown("catalog-credential"); mgr.teardown("catalog-credential");
vi.unstubAllEnvs(); vi.unstubAllEnvs();
rmSync(root, { recursive: true, force: true }); rmSync(root, { recursive: true, force: true });
@@ -750,7 +788,7 @@ test("set_model translates a canonical catalog key to its upstream Pi model ID",
session: { reasoning: false, contextWindow: 32768, maxTokens: 8192 }, session: { reasoning: false, contextWindow: 32768, maxTokens: 8192 },
}; };
const modelCatalog: RuntimeModelCatalog = { const modelCatalog: RuntimeModelCatalog = {
defaultSession: model.id, defaultMetadataGeneration: null, embedding: null, defaultInteraction: model.id, embedding: null,
sessionModels: () => [model], metadataModels: () => [], hasSession: (id) => id === model.id, sessionModels: () => [model], metadataModels: () => [], hasSession: (id) => id === model.id,
}; };
const mgr = new PiProcessManager(loadConfig({ PI_BIN: "/usr/local/bin/pi" }), { const mgr = new PiProcessManager(loadConfig({ PI_BIN: "/usr/local/bin/pi" }), {
+7 -4
View File
@@ -61,20 +61,22 @@ test("provider smoke resolves the selected catalog credential from the secret bu
session: { reasoning: false }, session: { reasoning: false },
}; };
const modelCatalog: RuntimeModelCatalog = { const modelCatalog: RuntimeModelCatalog = {
defaultSession: model.id, defaultInteraction: model.id,
defaultMetadataGeneration: null,
embedding: null, embedding: null,
sessionModels: () => [model], sessionModels: () => [model],
metadataModels: () => [], metadataModels: () => [],
hasSession: (id) => id === model.id, hasSession: (id) => id === model.id,
}; };
let spawnEnv: NodeJS.ProcessEnv | undefined; let spawnEnv: NodeJS.ProcessEnv | undefined;
const readAuthStore = vi.fn(() => JSON.stringify({ openai: { type: "api_key", key: "stale-key" } }));
const smoke = createPiProviderSmoke(loadConfig({ THT_SECRETS_FILE: secret }), { const smoke = createPiProviderSmoke(loadConfig({ THT_SECRETS_FILE: secret }), {
modelCatalog, modelCatalog,
authProviders: () => new Set(), authProviders: () => new Set(["openai"]),
readAuthStore,
readModelsStore: () => undefined, readModelsStore: () => undefined,
spawnFn: (_command, _args, options) => { spawnFn: (_command, _args, options) => {
spawnEnv = options.env; spawnEnv = options.env;
expect(existsSync(join(options.env.PI_CODING_AGENT_DIR!, "auth.json"))).toBe(false);
return successfulProviderChild(); return successfulProviderChild();
}, },
}); });
@@ -85,6 +87,7 @@ test("provider smoke resolves the selected catalog credential from the secret bu
expect(spawnEnv?.ZAI_API_KEY).toBe("catalog-secret"); expect(spawnEnv?.ZAI_API_KEY).toBe("catalog-secret");
expect(spawnEnv).not.toHaveProperty("OPENAI_API_KEY"); expect(spawnEnv).not.toHaveProperty("OPENAI_API_KEY");
expect(spawnEnv).not.toHaveProperty("THT_MODEL_API_KEY"); expect(spawnEnv).not.toHaveProperty("THT_MODEL_API_KEY");
expect(readAuthStore).not.toHaveBeenCalled();
} finally { } finally {
rmSync(root, { recursive: true, force: true }); rmSync(root, { recursive: true, force: true });
} }
@@ -306,7 +309,7 @@ test("provider smoke makes one configured request from an isolated no-capability
sessionAdapter: { mode: "pi_builtin" }, session: { reasoning: true }, sessionAdapter: { mode: "pi_builtin" }, session: { reasoning: true },
}; };
const smokeCatalog: RuntimeModelCatalog = { const smokeCatalog: RuntimeModelCatalog = {
defaultSession: smokeModel.id, defaultMetadataGeneration: null, embedding: null, defaultInteraction: smokeModel.id, embedding: null,
sessionModels: () => [smokeModel], metadataModels: () => [], sessionModels: () => [smokeModel], metadataModels: () => [],
hasSession: (id) => id === smokeModel.id, hasSession: (id) => id === smokeModel.id,
}; };
+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 }); }
});
+286 -54
View File
@@ -27,10 +27,9 @@ function operationalWorkspace(id = "default") {
} as const; } as const;
} }
function sessionCatalog(defaultSession = "zai/glm-5.2", available = [defaultSession]) { function sessionCatalog(defaultInteraction = "zai/glm-5.2", available = [defaultInteraction]) {
return { return {
defaultSession, defaultInteraction,
defaultMetadataGeneration: null,
embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 }, embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 },
sessionModels: () => [], sessionModels: () => [],
metadataModels: () => [], metadataModels: () => [],
@@ -54,7 +53,11 @@ const defaultWorkspaceRegistry = {
function buildApp(config: Parameters<typeof buildRealApp>[0], deps: Record<string, unknown> = {}) { function buildApp(config: Parameters<typeof buildRealApp>[0], deps: Record<string, unknown> = {}) {
const thtRunner = deps.thtRunner const thtRunner = deps.thtRunner
? { qdrantEnsure: async () => ({ ok: true }), ...(deps.thtRunner as object) } ? {
qdrantEnsure: async () => ({ ok: true }),
ensureInteractionLanguage: async () => ({ interaction_language: "en" }),
...(deps.thtRunner as object),
}
: undefined; : undefined;
return buildRealApp(config, { return buildRealApp(config, {
workspaceRuntimeSupport: () => true, workspaceRuntimeSupport: () => true,
@@ -89,6 +92,156 @@ const aliceHeaders = {
"x-thoth-is-admin": "0", "x-thoth-is-admin": "0",
}; };
test.each([undefined, null, "", "en--US", "en_US", "en\nIGNORE", "en<script>", 42])(
"new sessions reject invalid interaction language %s before persistence", async (interactionLanguage) => {
const app = mutApp({ sessionNew: async () => { throw new Error("must not create"); } });
try {
const response = await app.inject({
method: "POST", url: "/sessions", payload: { question: "Pazienti", interactionLanguage },
});
expect(response.statusCode).toBe(400);
expect(response.json()).toMatchObject({ code: "invalid_interaction_language" });
} finally { await app.close(); }
},
);
test.each([["en", "en"], ["fr-FR", "fr-FR"], ["FR-fr", "fr-FR"]])(
"new session forwards canonical interaction language %s without changing the question", async (language, canonical) => {
let created: any;
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {
sessionNew: async (options: any) => { created = options; return { id: "language" }; },
searchPack: async () => {},
},
readiness: { ensure: async () => ({ ok: true }) },
mgr: {
get: () => undefined, createFor: () => ({ bridge: { onClientEvent: () => {} } }),
configure: async () => {}, start: () => {},
},
getSettings: () => ({ workspace: "default" }),
});
try {
const response = await app.inject({
method: "POST", url: "/sessions", payload: { question: "Pazienti", interactionLanguage: language },
});
expect(response.statusCode).toBe(200);
expect(created).toMatchObject({ question: "Pazienti", interactionLanguage: canonical });
} finally { await app.close(); }
});
test("resume rejects browser interaction language overrides", async () => {
const app = mutApp({ sessionShow: async () => ({ status: "open", interaction_language: "it" }) });
try {
const response = await app.inject({
method: "POST", url: "/sessions/s1/resume", payload: { interactionLanguage: "en" },
});
expect(response.statusCode).toBe(400);
expect(response.json()).toMatchObject({ code: "interaction_language_pinned" });
} finally { await app.close(); }
});
test("new session starts Pi with the question language persisted by the harness", async () => {
let runtime: any;
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {
sessionNew: async () => ({ id: "english-question", interaction_language: "en" }),
searchPack: async () => {},
},
readiness: { ensure: async () => ({ ok: true }) },
mgr: {
get: () => undefined,
createFor: (_id: string, options: any) => {
runtime = options;
return { bridge: { onClientEvent: () => {} } };
},
configure: async () => {}, start: () => {},
},
getSettings: () => ({ workspace: "default" }),
});
try {
const response = await app.inject({ method: "POST", url: "/sessions", payload: {
question: "How many patients were admitted last year?", interactionLanguage: "it",
} });
expect(response.statusCode).toBe(200);
expect(runtime.interactionLanguage).toBe("en");
} finally { await app.close(); }
});
test("resume pins legacy interaction language using the resolved harness workspace", async () => {
let pinnedWorkspace: string | undefined;
let runtime: any;
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {
sessionShow: async () => ({ id: "legacy", status: "closed" }),
ensureInteractionLanguage: async (_id: string, workspace: string) => {
pinnedWorkspace = workspace;
return { interaction_language: "it" };
},
reopenSession: async () => {},
},
readiness: { ensure: async () => ({ ok: true }) },
mgr: {
get: () => undefined,
createFor: (_id: string, options: any) => {
runtime = options;
return { bridge: { onClientEvent: () => {} } };
},
configure: async () => {}, start: () => {},
},
getSettings: () => ({ workspace: "other-browser-workspace" }),
});
try {
const response = await app.inject({ method: "POST", url: "/sessions/legacy/resume" });
expect(response.statusCode).toBe(200);
expect(pinnedWorkspace).toContain("/default.yaml");
expect(runtime).toMatchObject({ interactionLanguage: "it", mode: "resume" });
} finally { await app.close(); }
});
test("resume retains persisted interaction language despite different browser settings", async () => {
let options: any;
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {
sessionShow: async () => ({ id: "saved", status: "closed", interaction_language: "it" }),
ensureInteractionLanguage: async () => { throw new Error("language is already pinned"); },
reopenSession: async () => {},
},
readiness: { ensure: async () => ({ ok: true }) },
mgr: {
get: () => undefined,
createFor: (_id: string, value: any) => {
options = value;
return { bridge: { onClientEvent: () => {} } };
},
configure: async () => {}, start: () => {},
},
getSettings: () => ({ workspace: "english-workspace", locale: "en" }),
});
try {
const response = await app.inject({ method: "POST", url: "/sessions/saved/resume" });
expect(response.statusCode).toBe(200);
expect(options.interactionLanguage).toBe("it");
} finally { await app.close(); }
});
test("resume cannot start Pi if legacy interaction language cannot be persisted", async () => {
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {
sessionShow: async () => ({ id: "legacy", status: "closed" }),
ensureInteractionLanguage: async () => { throw new Error("private storage details"); },
reopenSession: async () => { throw new Error("must not reopen"); },
},
readiness: { ensure: async () => ({ ok: true }) },
mgr: { createFor: () => { throw new Error("must not spawn"); } },
getSettings: () => ({ workspace: "default" }),
});
try {
const response = await app.inject({ method: "POST", url: "/sessions/legacy/resume" });
expect(response.statusCode).toBe(503);
expect(response.body).not.toContain("private storage details");
} finally { await app.close(); }
});
test("upstream requests without a principal fail before a Pi runtime can be created", async () => { test("upstream requests without a principal fail before a Pi runtime can be created", async () => {
let created = false; let created = false;
const app = buildApp(loadConfig({ AUTH_MODE: "upstream", THT_HARNESS_DIR: "../harness" }), { const app = buildApp(loadConfig({ AUTH_MODE: "upstream", THT_HARNESS_DIR: "../harness" }), {
@@ -96,7 +249,7 @@ test("upstream requests without a principal fail before a Pi runtime can be crea
thtRunner: {} as any, thtRunner: {} as any,
}); });
const response = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const response = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(response.statusCode).toBe(401); expect(response.statusCode).toBe(401);
expect(created).toBe(false); expect(created).toBe(false);
@@ -134,7 +287,7 @@ test("maintenance rejects new and resumed session admission without interrupting
}); });
const create = await app.inject({ const create = await app.inject({
method: "POST", url: "/sessions", headers: aliceHeaders, payload: { question: "q" }, method: "POST", url: "/sessions", headers: aliceHeaders, payload: { interactionLanguage: "en", question: "q" },
}); });
const resume = await app.inject({ method: "POST", url: "/sessions/open/resume", headers: aliceHeaders }); const resume = await app.inject({ method: "POST", url: "/sessions/open/resume", headers: aliceHeaders });
@@ -155,7 +308,7 @@ test("a durable maintenance marker initializes admission closed after backend re
AUTH_MODE: "upstream", THT_HARNESS_DIR: "../harness", THT_MAINTENANCE_FILE: marker, AUTH_MODE: "upstream", THT_HARNESS_DIR: "../harness", THT_MAINTENANCE_FILE: marker,
}), { thtRunner: {} as any }); }), { thtRunner: {} as any });
const response = await app.inject({ const response = await app.inject({
method: "POST", url: "/sessions", headers: aliceHeaders, payload: { question: "q" }, method: "POST", url: "/sessions", headers: aliceHeaders, payload: { interactionLanguage: "en", question: "q" },
}); });
expect(response.statusCode).toBe(503); expect(response.statusCode).toBe(503);
expect(response.json()).toMatchObject({ code: "maintenance" }); expect(response.json()).toMatchObject({ code: "maintenance" });
@@ -364,6 +517,65 @@ test("retention scans a removed workspace's retained snapshot", async () => {
expect(response.json()).toEqual([expect.objectContaining({ id: "resumable" })]); expect(response.json()).toEqual([expect.objectContaining({ id: "resumable" })]);
}); });
test("active sessions remain available when retained snapshot discovery is unreadable", async () => {
const activeSnapshot = "/registry/snapshots/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/active.yaml";
const retainedFailure = "invalid retained snapshot /registry/snapshots/secret/legacy.yaml";
const reconcileSnapshotRetention = vi.fn(async () => {});
const subscribed = vi.fn();
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
const manifest = {
id: "live-session", status: "open", archived: false,
workspace_id: "active", workspace_revision: "a".repeat(40),
};
const app = buildApp(loadConfig({ AUTH_MODE: "upstream", THT_HARNESS_DIR: "../harness" }), {
thtRunner: {
withPrincipal: () => ({
sessionList: async (snapshotPath: string) => {
expect(snapshotPath).toBe(activeSnapshot);
return [manifest];
},
sessionShow: async (id: string, snapshotPath?: string) => {
if (id === manifest.id && snapshotPath === activeSnapshot) return manifest;
throw new Error("session not found");
},
}),
} as any,
mgr: { get: () => undefined } as any,
hub: {
subscribe: (_id: string, _send: unknown, options: { close?: () => void }) => {
subscribed();
options.close?.();
return () => {};
},
} as any,
workspaceRegistry: {
listRetainedSnapshots: async () => { throw new Error(retainedFailure); },
list: async () => [{
id: "active", commit: "a".repeat(40), blob: "b".repeat(40), snapshotPath: activeSnapshot,
}],
reconcileSnapshotRetention,
} as any,
});
try {
const list = await app.inject({ method: "GET", url: "/sessions", headers: aliceHeaders });
const detail = await app.inject({ method: "GET", url: `/sessions/${manifest.id}`, headers: aliceHeaders });
const events = await app.inject({ method: "GET", url: `/sessions/${manifest.id}/events`, headers: aliceHeaders });
expect(list.statusCode).toBe(200);
expect(list.json()).toEqual([expect.objectContaining({ id: manifest.id, active: false })]);
expect(detail.statusCode).toBe(200);
expect(detail.json()).toMatchObject(manifest);
expect(events.statusCode).toBe(200);
expect(subscribed).toHaveBeenCalledOnce();
expect(reconcileSnapshotRetention).not.toHaveBeenCalled();
expect(list.body + detail.body + events.body).not.toContain(retainedFailure);
} finally {
warning.mockRestore();
await app.close();
}
});
test("the single local installation listing reconciles its resumable workspace pins", async () => { test("the single local installation listing reconciles its resumable workspace pins", async () => {
const retained = vi.fn(async () => {}); const retained = vi.fn(async () => {});
const retainedRevision = "d".repeat(40); const retainedRevision = "d".repeat(40);
@@ -434,7 +646,7 @@ test("new sessions are created through the authenticated principal, not a client
const response = await app.inject({ const response = await app.inject({
method: "POST", url: "/sessions", headers: aliceHeaders, method: "POST", url: "/sessions", headers: aliceHeaders,
payload: { question: "q", owner: "mallory" }, payload: { interactionLanguage: "en", question: "q", owner: "mallory" },
}); });
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
@@ -451,7 +663,7 @@ test("new sessions reject the client legacy workspace field unless local legacy
}); });
const response = await app.inject({ const response = await app.inject({
method: "POST", url: "/sessions", payload: { question: "q", workspace: "legacy" }, method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q", workspace: "legacy" },
}); });
expect(response.statusCode).toBe(409); expect(response.statusCode).toBe(409);
@@ -471,7 +683,7 @@ test("explicit local legacy mode permits the unpinned client workspace request",
}); });
const response = await app.inject({ const response = await app.inject({
method: "POST", url: "/sessions", payload: { question: "q", workspace: "legacy" }, method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q", workspace: "legacy" },
}); });
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
@@ -509,7 +721,7 @@ test("creates a session from the active immutable workspace revision", async ()
await app.inject({ await app.inject({
method: "POST", url: "/sessions", method: "POST", url: "/sessions",
payload: { question: "q", workspaceId: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "low" }, payload: { interactionLanguage: "en", question: "q", workspaceId: "psd-clinical", provider: "zai", model: "glm-5.2", thinking: "low" },
}); });
expect(sessionNew).toHaveBeenCalledWith(expect.objectContaining({ expect(sessionNew).toHaveBeenCalledWith(expect.objectContaining({
@@ -553,7 +765,7 @@ test("hands one Catalog-backed runtime to both retrieval and Pi", async () => {
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
url: "/sessions", url: "/sessions",
payload: { question: "Which users placed orders?", workspaceId: "default" }, payload: { interactionLanguage: "en", question: "Which users placed orders?", workspaceId: "default" },
}); });
expect(response.statusCode).toBe(200); expect(response.statusCode).toBe(200);
@@ -629,7 +841,7 @@ test("refuses core admission when the workspace preprocessing fingerprint is sta
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
url: "/sessions", url: "/sessions",
payload: { question: "q", workspaceId: "default" }, payload: { interactionLanguage: "en", question: "q", workspaceId: "default" },
}); });
expect(response.statusCode).toBe(409); expect(response.statusCode).toBe(409);
@@ -681,7 +893,7 @@ test("rejects an SSH-only Catalog binding before persisting or starting a sessio
} as any, } as any,
}); });
const response = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const response = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(response.statusCode).toBe(409); expect(response.statusCode).toBe(409);
expect(response.json()).toMatchObject({ code: "workspace_not_activatable" }); expect(response.json()).toMatchObject({ code: "workspace_not_activatable" });
@@ -721,7 +933,7 @@ test("hands a revision lease to retention only after the session manifest is dur
workspaceRegistry: { acquireSessionRevision } as any, workspaceRegistry: { acquireSessionRevision } as any,
}); });
const request = app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const request = app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
expect(markPersisted).not.toHaveBeenCalled(); expect(markPersisted).not.toHaveBeenCalled();
expect(abort).not.toHaveBeenCalled(); expect(abort).not.toHaveBeenCalled();
@@ -752,7 +964,7 @@ test("creates a session from the configured default workspace revision when work
workspaceRegistry: registry as any, workspaceRegistry: registry as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(registry.read).toHaveBeenCalledWith("psd-clinical"); expect(registry.read).toHaveBeenCalledWith("psd-clinical");
expect(sessionNew).toHaveBeenCalledWith(expect.objectContaining({ expect(sessionNew).toHaveBeenCalledWith(expect.objectContaining({
@@ -838,7 +1050,7 @@ test("session lifecycle locates a B session when installation default is A", asy
} as any, } as any,
}); });
expect((await app.inject({ method: "POST", url: "/sessions", payload: { expect((await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en",
question: "B question", workspaceId: "b-workspace", provider: "zai", model: "glm-5.2", thinking: "low", question: "B question", workspaceId: "b-workspace", provider: "zai", model: "glm-5.2", thinking: "low",
} })).statusCode).toBe(200); } })).statusCode).toBe(200);
expect((await app.inject({ method: "GET", url: "/sessions" })).json()).toEqual([ expect((await app.inject({ method: "GET", url: "/sessions" })).json()).toEqual([
@@ -850,7 +1062,7 @@ test("session lifecycle locates a B session when installation default is A", asy
active = undefined; active = undefined;
expect((await app.inject({ method: "POST", url: "/sessions/session-b/resume" })).json()) expect((await app.inject({ method: "POST", url: "/sessions/session-b/resume" })).json())
.toEqual({ id: "session-b", alreadyActive: false }); .toEqual({ id: "session-b", alreadyActive: false, workspaceId: "b-workspace" });
expect(calls).toContain(`new:${bPath}`); expect(calls).toContain(`new:${bPath}`);
expect(calls).toContain(`list:${bPath}`); expect(calls).toContain(`list:${bPath}`);
expect(calls).toContain(`show:${bPath}`); expect(calls).toContain(`show:${bPath}`);
@@ -881,7 +1093,7 @@ test("POST /sessions uses the catalog default with workspace/thinking settings a
], ],
spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any,
}); });
const created = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const created = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(created.json()).toEqual({ id: "s1" }); expect(created.json()).toEqual({ id: "s1" });
expect(sessionNewArg.workspaceConfigPath).toContain(`/snapshots/${"e".repeat(40)}/w.yaml`); expect(sessionNewArg.workspaceConfigPath).toContain(`/snapshots/${"e".repeat(40)}/w.yaml`);
expect(sessionNewArg.provider).toBe("zai"); expect(sessionNewArg.provider).toBe("zai");
@@ -942,11 +1154,11 @@ test("POST /sessions stops the user's previous open Pi runtime before creating a
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
expect((await app.inject({ method: "POST", url: "/sessions", payload: { question: "one" } })).statusCode) expect((await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "one" } })).statusCode)
.toBe(200); .toBe(200);
order.length = 0; order.length = 0;
const second = await app.inject({ method: "POST", url: "/sessions", payload: { question: "two" } }); const second = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "two" } });
expect(second.statusCode).toBe(200); expect(second.statusCode).toBe(200);
expect(second.json()).toEqual({ id: "s2" }); expect(second.json()).toEqual({ id: "s2" });
@@ -967,7 +1179,7 @@ test("POST /sessions refuses to create a session when the local DWH precheck fai
readiness: { ensure: async () => ({ ok: true }) } as any, readiness: { ensure: async () => ({ ok: true }) } as any,
getSettings: () => ({ workspace: "w" }) as any, getSettings: () => ({ workspace: "w" }) as any,
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.statusCode).toBe(503); expect(res.statusCode).toBe(503);
expect(res.json()).toMatchObject({ code: "dwh_unreachable" }); expect(res.json()).toMatchObject({ code: "dwh_unreachable" });
expect(pinged).toBe(1); expect(pinged).toBe(1);
@@ -988,7 +1200,7 @@ test("POST /sessions proceeds past a passing DWH precheck", async () => {
getSettings: () => ({ workspace: "w" }) as any, getSettings: () => ({ workspace: "w" }) as any,
spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any,
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
expect(pinged).toBe(1); expect(pinged).toBe(1);
expect(created).toBe(1); expect(created).toBe(1);
@@ -1007,7 +1219,7 @@ test("POST /sessions skips the DWH precheck when the flag is off (default)", asy
getSettings: () => ({ workspace: "w" }) as any, getSettings: () => ({ workspace: "w" }) as any,
spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any,
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(200);
expect(pinged).toBe(0); // probe never runs without the flag expect(pinged).toBe(0); // probe never runs without the flag
}); });
@@ -1041,7 +1253,7 @@ test("POST /sessions configura Pi con il thinking globale selezionato", async ()
], ],
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
expect(configured.thinking).toBe("high"); expect(configured.thinking).toBe("high");
@@ -1120,6 +1332,29 @@ test("POST /sessions/:id/resume uses the manifest's retained workspace revision"
); );
}); });
test.each([undefined, { provider: "local", model: "qwen" }])("resume uses the global model/default, not the historical manifest (%j)", async (payload) => {
const configure = vi.fn(async () => {});
const manifest = { status: "open", archived: false, provider: "retired", model: "old-model" };
const runtime = { bridge: { onClientEvent: () => {}, emitClientEvent: () => {} } };
let current: any;
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
mgr: {
get: () => current,
createFor: () => { current = runtime; return runtime; },
configure, start: () => {},
} as any,
thtRunner: { sessionShow: async () => manifest, reopenSession: async () => {} } as any,
readiness: { ensure: async () => ({ ok: true }) } as any,
runtimeModelCatalog: sessionCatalog("zai/glm-5.2", ["zai/glm-5.2", "local/qwen"]),
getSettings: () => ({ workspace: "psd", thinking: "medium" }) as any,
});
const response = await app.inject({ method: "POST", url: "/sessions/model-resume/resume", ...(payload ? { payload } : {}) });
expect(response.statusCode).toBe(200);
await new Promise((resolve) => setImmediate(resolve));
expect(configure).toHaveBeenCalledWith(expect.anything(), expect.objectContaining(payload ?? { provider: "zai", model: "glm-5.2" }));
expect(manifest).toMatchObject({ provider: "retired", model: "old-model" });
});
test("POST /sessions/:id/resume returns a sanitized error when its retained revision is unavailable", async () => { test("POST /sessions/:id/resume returns a sanitized error when its retained revision is unavailable", async () => {
const rawFailure = "cannot read /data/workspace-registry/snapshots/secret-revision"; const rawFailure = "cannot read /data/workspace-registry/snapshots/secret-revision";
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
@@ -1346,7 +1581,7 @@ test("resuming a different session stops the user's previous Pi runtime", async
readiness: { ensure: async () => ({ ok: true }) } as any, readiness: { ensure: async () => ({ ok: true }) } as any,
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
expect((await app.inject({ method: "POST", url: "/sessions", payload: { question: "one" } })).statusCode) expect((await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "one" } })).statusCode)
.toBe(200); .toBe(200);
const resumed = await app.inject({ method: "POST", url: "/sessions/s2/resume" }); const resumed = await app.inject({ method: "POST", url: "/sessions/s2/resume" });
@@ -1734,13 +1969,13 @@ test.each([
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "old" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "old" } });
if (lifecycle === "close") { if (lifecycle === "close") {
await app.inject({ method: "POST", url: "/sessions/s1/close" }); await app.inject({ method: "POST", url: "/sessions/s1/close" });
await app.inject({ method: "POST", url: "/sessions/s1/resume" }); await app.inject({ method: "POST", url: "/sessions/s1/resume" });
} else { } else {
await app.inject({ method: "DELETE", url: "/sessions/s1" }); await app.inject({ method: "DELETE", url: "/sessions/s1" });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "replacement" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "replacement" } });
} }
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
expect(current).toBe(replacement); expect(current).toBe(replacement);
@@ -1804,7 +2039,7 @@ test.each(["resolve", "reject"] as const)(
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "old" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "old" } });
await app.inject({ method: "DELETE", url: "/sessions/s1" }); await app.inject({ method: "DELETE", url: "/sessions/s1" });
published.length = 0; published.length = 0;
@@ -1996,7 +2231,7 @@ test("Close suppresses a bootstrap that settles while close persistence is pendi
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
const closeResponse = app.inject({ method: "POST", url: "/sessions/s1/close" }); const closeResponse = app.inject({ method: "POST", url: "/sessions/s1/close" });
await closeStarted; await closeStarted;
published.length = 0; published.length = 0;
@@ -2070,7 +2305,7 @@ test("bootstrap failure persists once and keeps Resume serialized behind that pe
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
oldConfigure.reject(new Error("configure failed")); oldConfigure.reject(new Error("configure failed"));
await failureStarted; await failureStarted;
const resumeResponse = app.inject({ method: "POST", url: "/sessions/s1/resume" }) const resumeResponse = app.inject({ method: "POST", url: "/sessions/s1/resume" })
@@ -2193,7 +2428,7 @@ test("a replaced runtime cannot publish or fail the newly resumed session", asyn
readiness: { ensure: async () => ({ ok: true }) } as any, readiness: { ensure: async () => ({ ok: true }) } as any,
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
oldBridge.setState("idle"); oldBridge.setState("idle");
@@ -2253,7 +2488,7 @@ test("a deleted runtime cannot repopulate or fail the forgotten session", async
readiness: { ensure: async () => ({ ok: true }) } as any, readiness: { ensure: async () => ({ ok: true }) } as any,
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
const response = await app.inject({ method: "DELETE", url: "/sessions/s1" }); const response = await app.inject({ method: "DELETE", url: "/sessions/s1" });
@@ -2298,7 +2533,7 @@ test("an unexpectedly exited runtime publishes its terminal sequence then releas
readiness: { ensure: async () => ({ ok: true }) } as any, readiness: { ensure: async () => ({ ok: true }) } as any,
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
published.length = 0; published.length = 0;
@@ -2349,7 +2584,7 @@ test("agent_end releases the Pi runtime after the session was finalized", async
readiness: { ensure: async () => ({ ok: true }) } as any, readiness: { ensure: async () => ({ ok: true }) } as any,
getSettings: () => ({ workspace: "local" }) as any, getSettings: () => ({ workspace: "local" }) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
bridge.emitClientEvent({ type: "system_event", event: "agent_end" }); bridge.emitClientEvent({ type: "system_event", event: "agent_end" });
@@ -2421,7 +2656,7 @@ test("POST /sessions/:id/response senza gate pendente risponde 409 (risposta sta
getSettings: () => ({ workspace: "w" }), getSettings: () => ({ workspace: "w" }),
spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any,
}); });
await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
// The fake Pi never emitted a ui_request: the bridge has no pending descriptor, so a // The fake Pi never emitted a ui_request: the bridge has no pending descriptor, so a
// response (stale UI, double submit) must be rejected instead of forwarded to Pi. // response (stale UI, double submit) must be rejected instead of forwarded to Pi.
const res = await app.inject({ method: "POST", url: "/sessions/s1/response", const res = await app.inject({ method: "POST", url: "/sessions/s1/response",
@@ -2562,7 +2797,7 @@ test("POST /sessions readiness failure returns one fixed public message without
getSettings: () => ({ workspace: "psd" }) as any, getSettings: () => ({ workspace: "psd" }) as any,
spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any,
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.statusCode).toBe(503); expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ expect(res.json()).toEqual({
error: "Session services are not ready. Check configuration and connectivity, then try again.", error: "Session services are not ready. Check configuration and connectivity, then try again.",
@@ -2583,7 +2818,7 @@ test.each(["semantic_index_incompatible", "workspace_not_activatable"] as const)
}); });
const response = await app.inject({ const response = await app.inject({
method: "POST", url: "/sessions", payload: { question: "q" }, method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" },
}); });
expect(response.statusCode).toBe(503); expect(response.statusCode).toBe(503);
@@ -2606,7 +2841,7 @@ test("POST /sessions returns storage 503 before creating a Pi runtime when sessi
mgr: { createFor: () => { piCreated = true; throw new Error("must not spawn"); } } as any, mgr: { createFor: () => { piCreated = true; throw new Error("must not spawn"); } } as any,
}); });
const response = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const response = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(response.statusCode).toBe(503); expect(response.statusCode).toBe(503);
expect(response.json()).toEqual({ error: "session storage is unavailable" }); expect(response.json()).toEqual({ error: "session storage is unavailable" });
@@ -2626,13 +2861,13 @@ test("POST /sessions proceeds when ollamaEnsure succeeds", async () => {
getSettings: () => ({ workspace: "psd" }) as any, getSettings: () => ({ workspace: "psd" }) as any,
spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any,
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.json()).toEqual({ id: "s1" }); expect(res.json()).toEqual({ id: "s1" });
expect(qdrantEnsure).toHaveBeenCalledWith(operationalWorkspace("psd"), 60, "self_heal"); expect(qdrantEnsure).toHaveBeenCalledWith(operationalWorkspace("psd"), 60, "self_heal");
expect(ensureWs).toContain(`/snapshots/${"e".repeat(40)}/psd.yaml`); expect(ensureWs).toContain(`/snapshots/${"e".repeat(40)}/psd.yaml`);
}); });
test("POST /sessions falls back from a stale requested model to the catalog default", async () => { test("POST /sessions rejects a stale requested model without silently using the default", async () => {
let created = 0; let created = 0;
let persisted: any; let persisted: any;
const runtime = { bridge: { onClientEvent: () => {} } }; const runtime = { bridge: { onClientEvent: () => {} } };
@@ -2659,16 +2894,13 @@ test("POST /sessions falls back from a stale requested model to the catalog defa
const res = await app.inject({ const res = await app.inject({
method: "POST", method: "POST",
url: "/sessions", url: "/sessions",
payload: { question: "q", provider: "deepseek", model: "deepseek-v4-pro" }, payload: { interactionLanguage: "en", question: "q", provider: "deepseek", model: "deepseek-v4-pro" },
}); });
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ expect(res.json()).toMatchObject({ code: "model_unavailable" });
id: "fallback", expect(persisted).toBeUndefined();
warning: "Configured model deepseek/deepseek-v4-pro is unavailable; using zai/glm-5.2.", expect(created).toBe(0);
});
expect(persisted).toMatchObject({ provider: "zai", model: "glm-5.2" });
expect(created).toBe(1);
}); });
test("POST /sessions marks a persisted session failed when runtime construction throws", async () => { test("POST /sessions marks a persisted session failed when runtime construction throws", async () => {
@@ -2697,7 +2929,7 @@ test("POST /sessions marks a persisted session failed when runtime construction
], ],
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.statusCode).toBe(503); expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ expect(res.json()).toEqual({
@@ -2790,7 +3022,7 @@ test.each([
try { try {
const response = flow === "new" const response = flow === "new"
? await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }) ? await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } })
: await app.inject({ method: "POST", url: `/sessions/${sessionId}/resume` }); : await app.inject({ method: "POST", url: `/sessions/${sessionId}/resume` });
const logs = consoleError.mock.calls.flat().map(String).join(" "); const logs = consoleError.mock.calls.flat().map(String).join(" ");
@@ -2896,7 +3128,7 @@ test("POST /sessions returns after bridge attachment but starts only after retri
getSettings: () => ({ workspace: "psd" }) as any, getSettings: () => ({ workspace: "psd" }) as any,
}); });
const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(res.json()).toEqual({ id: "s-early" }); expect(res.json()).toEqual({ id: "s-early" });
expect(bridgeAttached).toBe(true); expect(bridgeAttached).toBe(true);
expect(started).toBe(false); expect(started).toBe(false);
@@ -2943,7 +3175,7 @@ test("POST /sessions bootstrap failure emits only a fixed recovery message", asy
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
url: "/sessions", url: "/sessions",
payload: { question: "q" }, payload: { interactionLanguage: "en", question: "q" },
}); });
await new Promise((resolve) => setImmediate(resolve)); await new Promise((resolve) => setImmediate(resolve));
@@ -3039,7 +3271,7 @@ test.each([
})), })),
} as any, } as any,
}); });
const response = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const response = await app.inject({ method: "POST", url: "/sessions", payload: { interactionLanguage: "en", question: "q" } });
expect(response.statusCode).toBe(expectedStatus); expect(response.statusCode).toBe(expectedStatus);
expect(ensure).toHaveBeenCalledTimes(reachesReadiness ? 1 : 0); expect(ensure).toHaveBeenCalledTimes(reachesReadiness ? 1 : 0);
+2 -4
View File
@@ -160,8 +160,7 @@ test("GET /models returns session choices from the installation model catalog",
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {} as any, thtRunner: {} as any,
runtimeModelCatalog: { runtimeModelCatalog: {
defaultSession: "zai/glm-5.2", defaultInteraction: "zai/glm-5.2",
defaultMetadataGeneration: null,
embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 }, embedding: { id: "ollama/qwen3-embedding:0.6b", dimensions: 1024 },
sessionModels: () => [{ sessionModels: () => [{
id: "zai/glm-5.2", provider: "zai", model: "glm-5.2", label: "GLM 5.2", id: "zai/glm-5.2", provider: "zai", model: "glm-5.2", label: "GLM 5.2",
@@ -187,8 +186,7 @@ test("GET /models returns an empty list when the catalog has no session models",
const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), {
thtRunner: {} as any, thtRunner: {} as any,
runtimeModelCatalog: { runtimeModelCatalog: {
defaultSession: null, defaultInteraction: null,
defaultMetadataGeneration: null,
embedding: null, embedding: null,
sessionModels: () => [], sessionModels: () => [],
metadataModels: () => [], metadataModels: () => [],

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