Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
feat(config): enhance multi-instance support and Docker configurations
Dmitry Ng34a9cd2ee867
diff --git a/.env.example b/.env.exampleindex c0bb5952..1d8ff699 100644--- a/.env.example+++ b/.env.example@@ -1,5 +1,23 @@# PentAGI Environment Variables+## Core runtime+DEBUG=false++## DATA_DIR defaults to ./data (resolves to /opt/pentagi/data inside the image).+DATA_DIR=++## Optional namespace for instances sharing external resources — one PostgreSQL,+## one worker node, one Neo4j/Graphiti, one Langfuse (empty = standalone instance).+## Must match ^[a-z][a-z0-9_]{0,31}$; invalid value aborts startup.+## NOT derived from it, set per instance yourself: DATA_DIR (sharing it overwrites+## flow data), DOCKER_PORTS_BASE, listen ports, INSTALLATION_ID.+## See backend/docs/config.md -> "Multi-Instance Deployment (TENANT_ID)".+TENANT_ID=++## Base host port for per-flow sandbox port publishing (default 28000).+## Each instance owns [DOCKER_PORTS_BASE, DOCKER_PORTS_BASE+2000).+DOCKER_PORTS_BASE=+## For communication with PentAGI Cloud APIINSTALLATION_ID=LICENSE_KEY=@@ -164,6 +182,10 @@ SERVER_SSL_CRT=SERVER_SSL_KEY=SERVER_USE_SSL=true+## Go pprof HTTP listener (empty = disabled). Use host:port, e.g. :7777.+## Instances sharing a host network need distinct addresses.+PPROF_ADDR=+## OAuth googleOAUTH_GOOGLE_CLIENT_ID=OAUTH_GOOGLE_CLIENT_SECRET=diff --git a/backend/cmd/ftester/worker/executor.go b/backend/cmd/ftester/worker/executor.goindex feac6751..abcc4417 100644--- a/backend/cmd/ftester/worker/executor.go+++ b/backend/cmd/ftester/worker/executor.go@@ -183,6 +183,7 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Toote.subtaskID,containerID,containerLID,+ te.cfg.TenantPrefix(),te.dockerClient,te.proxies.GetTermLogProvider(),time.Duration(te.cfg.TerminalToolTimeout)*time.Second,@@ -196,6 +197,7 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Toote.subtaskID,containerID,containerLID,+ te.cfg.TenantPrefix(),te.dockerClient,te.proxies.GetTermLogProvider(),time.Duration(te.cfg.TerminalToolTimeout)*time.Second,@@ -319,6 +321,7 @@ func (te *toolExecutor) GetTool(ctx context.Context, funcName string) (tools.Toote.flowID,te.taskID,te.subtaskID,+ te.cfg.GroupID(te.flowID),te.graphitiClient,), nildiff --git a/backend/cmd/ftester/worker/tester.go b/backend/cmd/ftester/worker/tester.goindex c11865d6..b593efb7 100644--- a/backend/cmd/ftester/worker/tester.go+++ b/backend/cmd/ftester/worker/tester.go@@ -146,23 +146,28 @@ func (t *tester) initFlowProviderController() error {// Setup Langfuse observability to track the execution lifecycle// This is critical for debugging and monitoring flow performance// We use trace context to connect this execution with earlier/later runs+ traceMetadata := langfuse.Metadata{+ "flow_id": flow.ID,+ "user_id": flow.UserID,+ "user_email": user.Mail,+ "user_name": user.Name,+ "user_hash": user.Hash,+ "user_role": user.RoleName,+ "provider_name": flow.ModelProviderName,+ "provider_type": flow.ModelProviderType,+ }+ if t.cfg.HasTenant() {+ traceMetadata["tenant_id"] = t.cfg.TenantID+ }+ctx, observation := obs.Observer.NewObservation(t.ctx,langfuse.WithObservationTraceID(flow.TraceID.String),langfuse.WithObservationTraceContext(- langfuse.WithTraceName(fmt.Sprintf("%d flow worker", flow.ID)),- langfuse.WithTraceUserID(user.Mail),- langfuse.WithTraceTags([]string{"controller"}),- langfuse.WithTraceSessionID(fmt.Sprintf("flow-%d", flow.ID)),- langfuse.WithTraceMetadata(langfuse.Metadata{- "flow_id": flow.ID,- "user_id": flow.UserID,- "user_email": user.Mail,- "user_name": user.Name,- "user_hash": user.Hash,- "user_role": user.RoleName,- "provider_name": flow.ModelProviderName,- "provider_type": flow.ModelProviderType,- }),+ langfuse.WithTraceName(fmt.Sprintf("%s%d flow worker", t.cfg.TenantLabel(), flow.ID)),+ langfuse.WithTraceUserID(t.cfg.TenantUserID(user.Mail)),+ langfuse.WithTraceTags(t.cfg.TenantTags("controller")),+ langfuse.WithTraceSessionID(t.cfg.ScopedName(fmt.Sprintf("flow-%d", flow.ID))),+ langfuse.WithTraceMetadata(traceMetadata),),)diff --git a/backend/cmd/installer/processor/docker.go b/backend/cmd/installer/processor/docker.goindex 292b4660..895f0981 100644--- a/backend/cmd/installer/processor/docker.go+++ b/backend/cmd/installer/processor/docker.go@@ -8,6 +8,7 @@ import ("path/filepath""strings"+ "pentagi/pkg/docker""pentagi/pkg/tools"cerrdefs "github.com/containerd/errdefs"@@ -63,10 +64,19 @@ func (d *dockerOperationsImpl) removeWorkerContainers(ctx context.Context, statereturn fmt.Errorf("failed to list worker containers: %w", err)}+ // NOTE: docker returns names with a leading slash ("/pentagi-terminal-1"), so+ // this predicate has never matched anything and the sweep is effectively a+ // no-op today. It is left that way deliberately — "fixing" the slash would+ // silently turn a dormant no-op into force-removal of running containers,+ // which is a behavior change well beyond tenant isolation.+ //+ // The prefix is anchored on the tenant regardless, so that if the slash is+ // ever handled the sweep can only ever reach this instance's own containers.+ workerPrefix := d.tenantPrefix() + "pentagi-"var containers []container.Summaryfor _, c := range allContainers {for _, name := range c.Names {- if strings.HasPrefix(name, "pentagi-") {+ if strings.HasPrefix(name, workerPrefix) {containers = append(containers, c)break}@@ -325,8 +335,14 @@ func (d *dockerOperationsImpl) removeWorkerVolumes(ctx context.Context, state *oif err != nil {return err}+ // Anchor on this instance's own prefix. Because the tenant segment leads the+ // name ("acme-pentagi-terminal-1-data"), a default installation's sweep does+ // not match a tenant's volumes and vice versa — each purge reaches exactly+ // its own resources. With TENANT_ID unset this is the original predicate.+ workerPrefix := d.tenantPrefix() + tools.PrimaryTerminalNamePrefix+ workerSuffix := docker.WorkerVolumeNameSuffixfor _, v := range vols.Volumes {- if strings.HasPrefix(v.Name, tools.PrimaryTerminalNamePrefix) && strings.HasSuffix(v.Name, "-data") {+ if strings.HasPrefix(v.Name, workerPrefix) && strings.HasSuffix(v.Name, workerSuffix) {_ = cli.VolumeRemove(ctx, v.Name, true)}}@@ -409,6 +425,17 @@ func (d *dockerOperationsImpl) getWorkerDockerEnv() []string {return env}+// tenantPrefix returns this installation's tenant prefix ("acme-") or "" when+// TENANT_ID is unset. Every daemon-wide sweep must anchor on it so that a purge+// run for one instance cannot reach another instance's resources.+func (d *dockerOperationsImpl) tenantPrefix() string {+ envVar, exists := d.processor.state.GetVar("TENANT_ID")+ if !exists || envVar.Value == "" {+ return ""+ }+ return envVar.Value + "-"+}+func (d *dockerOperationsImpl) getWorkerImageName() string {envVar, exists := d.processor.state.GetVar("DOCKER_DEFAULT_IMAGE_FOR_PENTEST")if exists && envVar.Value != "" {diff --git a/backend/cmd/installer/wizard/controller/controller.go b/backend/cmd/installer/wizard/controller/controller.goindex f9d04b6c..1db0e088 100644--- a/backend/cmd/installer/wizard/controller/controller.go+++ b/backend/cmd/installer/wizard/controller/controller.go@@ -1977,7 +1977,9 @@ func (c *controller) ResetDockerConfig() *DockerConfig {// ServerSettingsConfig represents PentAGI server settings configurationtype ServerSettingsConfig struct {// direct form field mappings using loader.EnvVar+ TenantID loader.EnvVar // TENANT_IDLicenseKey loader.EnvVar // LICENSE_KEY+ PprofAddr loader.EnvVar // PPROF_ADDRListenIP loader.EnvVar // PENTAGI_LISTEN_IPListenPort loader.EnvVar // PENTAGI_LISTEN_PORTPublicURL loader.EnvVar // PUBLIC_URL@@ -1999,7 +2001,9 @@ type ServerSettingsConfig struct {// GetServerSettingsConfig returns current server settingsfunc (c *controller) GetServerSettingsConfig() *ServerSettingsConfig {vars, _ := c.GetVars([]string{+ "TENANT_ID","LICENSE_KEY",+ "PPROF_ADDR","PENTAGI_LISTEN_IP","PENTAGI_LISTEN_PORT","PUBLIC_URL",@@ -2016,6 +2020,7 @@ func (c *controller) GetServerSettingsConfig() *ServerSettingsConfig {defaults := map[string]string{"LICENSE_KEY": "",+ "PPROF_ADDR": "","PENTAGI_LISTEN_IP": "127.0.0.1","PENTAGI_LISTEN_PORT": "8443","PUBLIC_URL": "https://localhost:8443",@@ -2035,7 +2040,9 @@ func (c *controller) GetServerSettingsConfig() *ServerSettingsConfig {}cfg := &ServerSettingsConfig{+ TenantID: vars["TENANT_ID"],LicenseKey: vars["LICENSE_KEY"],+ PprofAddr: vars["PPROF_ADDR"],ListenIP: vars["PENTAGI_LISTEN_IP"],ListenPort: vars["PENTAGI_LISTEN_PORT"],PublicURL: vars["PUBLIC_URL"],@@ -2075,7 +2082,9 @@ func (c *controller) UpdateServerSettingsConfig(config *ServerSettingsConfig) er}updates := map[string]string{+ "TENANT_ID": config.TenantID.Value,"LICENSE_KEY": config.LicenseKey.Value,+ "PPROF_ADDR": config.PprofAddr.Value,"PENTAGI_LISTEN_IP": config.ListenIP.Value,"PENTAGI_LISTEN_PORT": config.ListenPort.Value,"PUBLIC_URL": config.PublicURL.Value,@@ -2100,7 +2109,9 @@ func (c *controller) UpdateServerSettingsConfig(config *ServerSettingsConfig) er// ResetServerSettingsConfig resets server settings to defaultsfunc (c *controller) ResetServerSettingsConfig() *ServerSettingsConfig {vars := []string{+ "TENANT_ID","LICENSE_KEY",+ "PPROF_ADDR","PENTAGI_LISTEN_IP","PENTAGI_LISTEN_PORT","PUBLIC_URL",@@ -2345,7 +2356,9 @@ func (c *controller) getVariableDescription(varName string) string {"DOCKER_TLS_VERIFY": locale.EnvDesc_DOCKER_TLS_VERIFY,"DOCKER_CERT_PATH": locale.EnvDesc_DOCKER_CERT_PATH,+ "TENANT_ID": locale.EnvDesc_TENANT_ID,"LICENSE_KEY": locale.EnvDesc_LICENSE_KEY,+ "PPROF_ADDR": locale.EnvDesc_PPROF_ADDR,"PENTAGI_LISTEN_IP": locale.EnvDesc_PENTAGI_LISTEN_IP,"PENTAGI_LISTEN_PORT": locale.EnvDesc_PENTAGI_LISTEN_PORT,"PUBLIC_URL": locale.EnvDesc_PUBLIC_URL,@@ -2572,7 +2585,9 @@ var criticalVariables = map[string]bool{"MAX_LIMITED_AGENT_TOOL_CALLS": true,"AGENT_PLANNING_STEP_ENABLED": true,+ "TENANT_ID": true,"LICENSE_KEY": true,+ "PPROF_ADDR": true,"PENTAGI_LISTEN_IP": true,"PENTAGI_LISTEN_PORT": true,"PUBLIC_URL": true,diff --git a/backend/cmd/installer/wizard/locale/locale.go b/backend/cmd/installer/wizard/locale/locale.goindex 75c87757..83363148 100644--- a/backend/cmd/installer/wizard/locale/locale.go+++ b/backend/cmd/installer/wizard/locale/locale.go@@ -1209,6 +1209,12 @@ const (ServerSettingsLicenseKey = "License Key"ServerSettingsLicenseKeyDesc = "PentAGI License Key in format of XXXX-XXXX-XXXX-XXXX"+ ServerSettingsTenantID = "Tenant ID"+ ServerSettingsTenantIDDesc = "Optional namespace for multi-instance deployment on one host (e.g., acme, team_alpha)"++ ServerSettingsPprofAddr = "pprof Listen Address"+ ServerSettingsPprofAddrDesc = "Optional Go pprof bind address; leave empty to disable (e.g., :7777, 127.0.0.1:7778)"+ServerSettingsHost = "Server Host (Listen IP)"ServerSettingsHostDesc = "Bind address used by Docker port mapping (e.g., 0.0.0.0 to expose on all interfaces)"@@ -1251,6 +1257,8 @@ const (// Hints for fields overviewServerSettingsLicenseKeyHint = "License Key"+ ServerSettingsTenantIDHint = "Tenant ID"+ ServerSettingsPprofAddrHint = "pprof Address"ServerSettingsHostHint = "Listen IP"ServerSettingsPortHint = "Listen Port"ServerSettingsPublicURLHint = "Public URL"@@ -1274,6 +1282,26 @@ SSL directory allows providing custom certificates. When set, server will use seServerSettingsLicenseKeyHelp = `PentAGI License Key in format of XXXX-XXXX-XXXX-XXXX. It's used to communicate with PentAGI Cloud API.`+ ServerSettingsTenantIDHelp = `Optional identifier that namespaces PostgreSQL schema, data directory, Docker objects, Graphiti group ids, auth cookies and telemetry when several PentAGI instances share one host and the same backing services.++Leave empty for a single-instance deployment (default). When set, the value must match ^[a-z][a-z0-9_]{0,31}$ — lowercase letter first, then lowercase letters, digits or underscores, max 32 characters. Hyphens are not allowed.++Examples:+• acme+• team_alpha+• staging01`++ ServerSettingsPprofAddrHelp = `Optional listen address for the Go pprof HTTP endpoint used for CPU/memory profiling.++Leave empty to keep pprof disabled (default, recommended for production). When set, the value must be a host:port pair such as :7777 or 127.0.0.1:7778.++Instances that share a host network namespace need distinct addresses — a port is not a string namespace and cannot be derived from TENANT_ID.++Examples:+• :7777+• 127.0.0.1:7778+• 0.0.0.0:7780`+ServerSettingsHostHelp = `Bind address for published port in docker-compose mapping.Examples:@@ -2333,7 +2361,9 @@ const (EnvDesc_DOCKER_TLS_VERIFY = "Docker TLS Verify"EnvDesc_DOCKER_CERT_PATH = "Docker Certificate Path"+ EnvDesc_TENANT_ID = "PentAGI Tenant ID"EnvDesc_LICENSE_KEY = "PentAGI License Key"+ EnvDesc_PPROF_ADDR = "PentAGI pprof Listen Address"EnvDesc_PENTAGI_LISTEN_IP = "PentAGI Server Host"EnvDesc_PENTAGI_LISTEN_PORT = "PentAGI Server Port"EnvDesc_PUBLIC_URL = "PentAGI Public URL"diff --git a/backend/cmd/installer/wizard/models/server_settings_form.go b/backend/cmd/installer/wizard/models/server_settings_form.goindex 38abb098..f595aa46 100644--- a/backend/cmd/installer/wizard/models/server_settings_form.go+++ b/backend/cmd/installer/wizard/models/server_settings_form.go@@ -2,6 +2,7 @@ package modelsimport ("fmt"+ "net""strconv""strings"@@ -11,6 +12,7 @@ import ("pentagi/cmd/installer/wizard/logger""pentagi/cmd/installer/wizard/styles""pentagi/cmd/installer/wizard/window"+ "pentagi/pkg/config"tea "github.com/charmbracelet/bubbletea""github.com/vxcontrol/cloud/sdk"@@ -43,6 +45,20 @@ func (m *ServerSettingsFormModel) BuildForm() tea.Cmd {true,))+ fields = append(fields, m.createTextField("pentagi_tenant_id",+ locale.ServerSettingsTenantID,+ locale.ServerSettingsTenantIDDesc,+ config.TenantID,+ false,+ ))++ fields = append(fields, m.createTextField("pentagi_pprof_addr",+ locale.ServerSettingsPprofAddr,+ locale.ServerSettingsPprofAddrDesc,+ config.PprofAddr,+ false,+ ))+// host and portfields = append(fields, m.createTextField("pentagi_server_host",locale.ServerSettingsHost,@@ -228,6 +244,24 @@ func (m *ServerSettingsFormModel) GetCurrentConfiguration() string {licenseStatus = m.GetStyles().Muted.Render(licenseStatus)sections = append(sections, fmt.Sprintf("• %s: %s", locale.ServerSettingsLicenseKeyHint, licenseStatus))+ if tenantID := cfg.TenantID.Value; tenantID != "" {+ tenantID = m.GetStyles().Info.Render(tenantID)+ sections = append(sections, fmt.Sprintf("• %s: %s", locale.ServerSettingsTenantIDHint, tenantID))+ } else {+ tenantID = locale.StatusNotConfigured+ tenantID = m.GetStyles().Muted.Render(tenantID)+ sections = append(sections, fmt.Sprintf("• %s: %s", locale.ServerSettingsTenantIDHint, tenantID))+ }++ if pprofAddr := cfg.PprofAddr.Value; pprofAddr != "" {+ pprofAddr = m.GetStyles().Info.Render(pprofAddr)+ sections = append(sections, fmt.Sprintf("• %s: %s", locale.ServerSettingsPprofAddrHint, pprofAddr))+ } else {+ pprofAddr = locale.StatusNotConfigured+ pprofAddr = m.GetStyles().Muted.Render(pprofAddr)+ sections = append(sections, fmt.Sprintf("• %s: %s", locale.ServerSettingsPprofAddrHint, pprofAddr))+ }+if listenIP := cfg.ListenIP.Value; listenIP != "" {listenIP = m.GetStyles().Info.Render(listenIP)sections = append(sections, fmt.Sprintf("• %s: %s", locale.ServerSettingsHostHint, listenIP))@@ -354,6 +388,10 @@ func (m *ServerSettingsFormModel) GetHelpContent() string {switch field.Key {case "pentagi_license_key":sections = append(sections, locale.ServerSettingsLicenseKeyHelp)+ case "pentagi_tenant_id":+ sections = append(sections, locale.ServerSettingsTenantIDHelp)+ case "pentagi_pprof_addr":+ sections = append(sections, locale.ServerSettingsPprofAddrHelp)case "pentagi_server_host":sections = append(sections, locale.ServerSettingsHostHelp)case "pentagi_server_port":@@ -391,7 +429,9 @@ func (m *ServerSettingsFormModel) HandleSave() error {fields := m.GetFormFields()newCfg := &controller.ServerSettingsConfig{+ TenantID: cfg.TenantID,LicenseKey: cfg.LicenseKey,+ PprofAddr: cfg.PprofAddr,ListenIP: cfg.ListenIP,ListenPort: cfg.ListenPort,CorsOrigins: cfg.CorsOrigins,@@ -419,6 +459,18 @@ func (m *ServerSettingsFormModel) HandleSave() error {}}newCfg.LicenseKey.Value = value+ case "pentagi_tenant_id":+ if err := (&config.Config{TenantID: value}).ValidateTenantID(); err != nil {+ return err+ }+ newCfg.TenantID.Value = value+ case "pentagi_pprof_addr":+ if value != "" {+ if _, _, err := net.SplitHostPort(value); err != nil {+ return fmt.Errorf("invalid pprof address: must be host:port (e.g., :7777 or 127.0.0.1:7778)")+ }+ }+ newCfg.PprofAddr.Value = valuecase "pentagi_server_host":newCfg.ListenIP.Value = valuecase "pentagi_server_port":diff --git a/backend/cmd/pentagi/main.go b/backend/cmd/pentagi/main.goindex 3ba824ab..cfd6a40f 100644--- a/backend/cmd/pentagi/main.go+++ b/backend/cmd/pentagi/main.go@@ -5,7 +5,6 @@ import ("database/sql""errors""fmt"- "log""net""os""os/signal"@@ -46,7 +45,10 @@ func main() {cfg, err := config.NewConfig()if err != nil {- log.Fatalf("Unable to load config: %v\n", err)+ // Fatal rather than Error: cfg is nil on failure, so continuing would+ // panic anyway, and an invalid TENANT_ID must never boot into a namespace+ // it did not intend to own.+ logrus.WithError(err).Fatal("Unable to load config")}// Configure logrus log level based on DEBUG env variable@@ -57,6 +59,17 @@ func main() {logrus.SetLevel(logrus.InfoLevel)}+ // Record the identity of this instance for the record: which tenant namespace+ // it owns and which data directory it writes to. Both are operator-supplied+ // and must differ between instances that share a host; having them in the+ // startup log makes an accidental overlap obvious after the fact.+ logrus.WithFields(logrus.Fields{+ "tenant_id": cfg.TenantID,+ "data_dir": cfg.DataDir,+ "schema": cfg.SchemaName(),+ "installation_id": cfg.InstallationID,+ }).Info("Instance identity")+// Telemetry is optional — degrade to a no-op observer on init failure so an// unreachable collector can't take the app down.lfclient, err := obs.NewLangfuseClient(ctx, cfg)@@ -81,15 +94,25 @@ func main() {obs.Observer.StartProcessMetricCollect(attribute.String("component", "server"))obs.Observer.StartGoRuntimeMetricCollect(attribute.String("component", "server"))+ // Create this tenant's schema and repoint DATABASE_URL at it before any+ // consumer reads the DSN. No-op when TENANT_ID is empty.+ if err := ensureTenantSchema(ctx, cfg); err != nil {+ logrus.WithError(err).Fatal("Tenant schema initialization failed")+ }+db, err := sql.Open("postgres", cfg.DatabaseURL)if err != nil {- log.Fatalf("Unable to open database: %v\n", err)+ logrus.WithError(err).Fatal("Unable to open database")}db.SetMaxOpenConns(cfg.DBMaxOpenConns)db.SetMaxIdleConns(cfg.DBMaxIdleConns)db.SetConnMaxLifetime(time.Hour)+ if err := verifySearchPath(ctx, db, cfg); err != nil {+ logrus.WithError(err).Fatal("Tenant schema verification failed")+ }+queries := database.New(db)// Pass the same *sql.DB to GORM so both sqlc and GORM share one connection@@ -97,19 +120,19 @@ func main() {// Postgres connections. Now together they consume at most DBMaxOpenConns.orm, err := database.NewGorm(db, cfg.Debug)if err != nil {- log.Fatalf("Unable to open database with gorm: %v\n", err)+ logrus.WithError(err).Fatal("Unable to open database with gorm")}// Create a shared pgxpool for all pgvector stores so that each executor// reuses pooled connections instead of opening a dedicated pgx.Connect.pgPoolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)if err != nil {- log.Fatalf("Failed to parse pgxpool config: %v\n", err)+ logrus.WithError(err).Fatal("Failed to parse pgxpool config")}pgPoolConfig.MaxConns = int32(cfg.DBVectorMaxConns)pgPool, err := pgxpool.NewWithConfig(ctx, pgPoolConfig)if err != nil {- log.Fatalf("Failed to create pgxpool: %v\n", err)+ logrus.WithError(err).Fatal("Failed to create pgxpool")}defer pgPool.Close()@@ -120,31 +143,40 @@ func main() {goose.SetBaseFS(migrations.EmbedMigrations)if err := goose.SetDialect("postgres"); err != nil {- log.Fatalf("Database dialect configuration failed: %v\n", err)+ logrus.WithError(err).Fatal("Database dialect configuration failed")}- if err := goose.Up(db, "sql"); err != nil {- log.Fatalf("Schema migration execution failed: %v\n", err)+ // Hold an advisory lock so simultaneous boots cannot execute the same+ // migration set concurrently; the initial migration uses bare CREATE TABLE,+ // so the loser would otherwise abort on "relation already exists".+ if err := runMigrations(ctx, db, cfg, func(db *sql.DB) error {+ return goose.Up(db, "sql")+ }); err != nil {+ // Fatal: continuing on a half-migrated schema and then serving traffic is+ // strictly worse than refusing to start.+ logrus.WithError(err).Fatal("Schema migration execution failed")}- log.Println("Database schema updated successfully")+ logrus.Info("Database schema updated successfully")- go profiling.Start()+ if cfg.PprofAddr != "" {+ go profiling.Start(cfg.PprofAddr)+ }client, err := docker.NewDockerClient(ctx, queries, cfg)if err != nil {- log.Fatalf("Docker runtime client initialization failed: %v", err)+ logrus.WithError(err).Fatal("Docker runtime client initialization failed")}providers, err := providers.NewProviderController(cfg, queries, client)if err != nil {- log.Fatalf("LLM provider controller initialization failed: %v", err)+ logrus.WithError(err).Fatal("LLM provider controller initialization failed")}subscriptions := subscriptions.NewSubscriptionsController()controller := controller.NewFlowController(queries, cfg, client, providers, subscriptions)if err := controller.LoadFlows(ctx); err != nil {- log.Fatalf("Active flows restoration failed: %v", err)+ logrus.WithError(err).Fatal("Active flows restoration failed")}r := router.NewRouter(queries, orm, cfg, providers, controller, subscriptions, client)diff --git a/backend/cmd/pentagi/tenant.go b/backend/cmd/pentagi/tenant.gonew file mode 100644index 00000000..d6314bd2--- /dev/null+++ b/backend/cmd/pentagi/tenant.go@@ -0,0 +1,221 @@+package main++import (+ "context"+ "database/sql"+ "errors"+ "fmt"+ "hash/crc32"+ "net/url"++ "pentagi/pkg/config"++ "github.com/lib/pq"+)++// requiredExtensions must live in a schema shared by every tenant. A PostgreSQL+// extension is a database-level object installed into exactly one schema: if+// tenant A created "vector" inside its own schema, tenant B's+// CREATE EXTENSION IF NOT EXISTS would be a silent no-op and its migrations+// would then fail with an opaque "type vector does not exist".+var requiredExtensions = []string{"vector", "pg_trgm"}++// sharedExtensionSchema is where extensions must live so that every tenant's+// search_path can reach them.+const sharedExtensionSchema = "public"++// ensureTenantSchema prepares this instance's PostgreSQL namespace and rewrites+// cfg.DatabaseURL so that every downstream consumer — sqlc, gorm, goose and the+// pgxpool backing the langchaingo vector store — resolves unqualified+// identifiers inside it.+//+// It is a strict no-op when TENANT_ID is empty: the DSN is left untouched and+// everything keeps resolving through the default "public" search path exactly+// as before.+func ensureTenantSchema(ctx context.Context, cfg *config.Config) error {+ if !cfg.HasTenant() {+ return nil+ }++ schema := cfg.SchemaName()++ // Short-lived bootstrap connection on the ORIGINAL DSN. Opening it before the+ // search_path rewrite means CREATE EXTENSION resolves against the default+ // path and lands in the shared schema rather than the tenant's.+ db, err := sql.Open("postgres", cfg.DatabaseURL)+ if err != nil {+ return fmt.Errorf("failed to open bootstrap database connection: %w", err)+ }+ defer db.Close()++ if err := db.PingContext(ctx); err != nil {+ return fmt.Errorf("failed to reach database for tenant bootstrap: %w", err)+ }++ // Serialize concurrent first boots so two instances cannot race on schema and+ // extension creation in the shared catalog.+ if err := withAdvisoryLock(ctx, db, "pentagi-tenant-bootstrap", func(conn *sql.Conn) error {+ // QuoteIdentifier is belt-and-braces: ValidateTenantID already restricts+ // the character set, but this keeps the statement safe if that ever relaxes.+ if _, err := conn.ExecContext(ctx,+ "CREATE SCHEMA IF NOT EXISTS "+pq.QuoteIdentifier(schema),+ ); err != nil {+ return fmt.Errorf("failed to create schema %q: %w", schema, err)+ }++ for _, ext := range requiredExtensions {+ if err := ensureSharedExtension(ctx, conn, ext); err != nil {+ return err+ }+ }++ return nil+ }); err != nil {+ return err+ }++ // Rewrite the DSN once; every consumer reads cfg.DatabaseURL afterwards.+ // Both lib/pq and pgx forward search_path as a libpq runtime parameter, so a+ // single URL change reaches every connection in every pool.+ rewritten, err := withSearchPath(cfg.DatabaseURL, schema+","+sharedExtensionSchema)+ if err != nil {+ return err+ }+ cfg.DatabaseURL = rewritten++ return nil+}++// ensureSharedExtension guarantees that ext exists and is reachable from every+// tenant's search_path. It checks before creating so that a database whose+// extensions were pre-installed by an administrator works without the+// application needing CREATE privileges.+func ensureSharedExtension(ctx context.Context, conn *sql.Conn, ext string) error {+ schema, err := extensionSchema(ctx, conn, ext)+ switch {+ case err != nil:+ return err++ case schema == "":+ // Not installed yet — create it explicitly in the shared schema.+ if _, err := conn.ExecContext(ctx, fmt.Sprintf(+ "CREATE EXTENSION IF NOT EXISTS %s SCHEMA %s",+ pq.QuoteIdentifier(ext), pq.QuoteIdentifier(sharedExtensionSchema),+ )); err != nil {+ return fmt.Errorf(+ "failed to create extension %q in schema %q (a privileged user must run "++ "CREATE EXTENSION %s SCHEMA %s once): %w",+ ext, sharedExtensionSchema, ext, sharedExtensionSchema, err,+ )+ }+ return nil++ case schema != sharedExtensionSchema:+ // Installed, but somewhere this tenant's search_path will not reach. Fail+ // with an actionable message rather than letting migrations die on a+ // confusing "type does not exist".+ return fmt.Errorf(+ "extension %q is installed in schema %q, but multi-tenant mode requires it in %q "++ "so every tenant can reach it; run: ALTER EXTENSION %s SET SCHEMA %s",+ ext, schema, sharedExtensionSchema, ext, sharedExtensionSchema,+ )++ default:+ return nil+ }+}++// extensionSchema returns the schema an extension is installed into, or "" when+// it is not installed.+func extensionSchema(ctx context.Context, conn *sql.Conn, ext string) (string, error) {+ var schema string+ err := conn.QueryRowContext(ctx, `+ SELECT n.nspname+ FROM pg_extension e+ JOIN pg_namespace n ON n.oid = e.extnamespace+ WHERE e.extname = $1`, ext).Scan(&schema)++ switch {+ case errors.Is(err, sql.ErrNoRows):+ return "", nil+ case err != nil:+ return "", fmt.Errorf("failed to resolve schema of extension %q: %w", ext, err)+ default:+ return schema, nil+ }+}++// verifySearchPath asserts that connections really do resolve into the expected+// schema. A typo in the DSN would otherwise route a tenant silently onto public,+// where every tenant would share one dataset — a quiet, catastrophic failure.+func verifySearchPath(ctx context.Context, db *sql.DB, cfg *config.Config) error {+ if !cfg.HasTenant() {+ return nil+ }++ var current sql.NullString+ if err := db.QueryRowContext(ctx, "SELECT current_schema()").Scan(¤t); err != nil {+ return fmt.Errorf("failed to resolve current schema: %w", err)+ }+ if current.String != cfg.SchemaName() {+ return fmt.Errorf(+ "search_path resolved to schema %q, expected %q — refusing to start so tenants "++ "do not silently share one dataset",+ current.String, cfg.SchemaName(),+ )+ }++ return nil+}++// runMigrations applies pending migrations while holding an advisory lock, so+// that two instances booting simultaneously cannot execute the same migration+// set concurrently. Without a tenant the lock is still taken, which also fixes+// the pre-existing race between two single-instance deployments sharing a+// database.+func runMigrations(ctx context.Context, db *sql.DB, cfg *config.Config, up func(*sql.DB) error) error {+ return withAdvisoryLock(ctx, db, "pentagi-migrations-"+cfg.SchemaName(), func(*sql.Conn) error {+ return up(db)+ })+}++// withAdvisoryLock runs fn while holding a PostgreSQL session-level advisory+// lock derived from key. The lock is taken on a dedicated connection because+// advisory locks are session-scoped and *sql.DB is a pool.+func withAdvisoryLock(ctx context.Context, db *sql.DB, key string, fn func(*sql.Conn) error) error {+ // crc32 into the signed 32-bit space keeps the key stable and collision-free+ // enough for the two distinct locks this application takes.+ lockID := int64(int32(crc32.ChecksumIEEE([]byte(key))))++ conn, err := db.Conn(ctx)+ if err != nil {+ return fmt.Errorf("failed to acquire database connection for advisory lock: %w", err)+ }+ defer conn.Close()++ if _, err := conn.ExecContext(ctx, "SELECT pg_advisory_lock($1)", lockID); err != nil {+ return fmt.Errorf("failed to acquire advisory lock %q: %w", key, err)+ }+ defer func() {+ // Best effort: closing the connection releases the lock regardless.+ _, _ = conn.ExecContext(context.WithoutCancel(ctx), "SELECT pg_advisory_unlock($1)", lockID)+ }()++ return fn(conn)+}++// withSearchPath returns dsn with the search_path runtime parameter set. It+// supports both URL-style DSNs (the shipped default) and libpq keyword strings.+func withSearchPath(dsn, searchPath string) (string, error) {+ u, err := url.Parse(dsn)+ if err != nil || u.Scheme == "" {+ // Not a URL — fall back to libpq keyword/value syntax.+ return fmt.Sprintf("%s search_path=%s", dsn, searchPath), nil+ }++ q := u.Query()+ q.Set("search_path", searchPath)+ u.RawQuery = q.Encode()++ return u.String(), nil+}diff --git a/backend/docs/config.md b/backend/docs/config.mdindex a8200f45..f2e8b808 100644--- a/backend/docs/config.md+++ b/backend/docs/config.md@@ -10,6 +10,7 @@ This document serves as a comprehensive guide to the configuration system in Pen- [Current Web Settings Coverage](#current-web-settings-coverage)- [Still Server-Managed](#still-server-managed)- [General Settings](#general-settings)+ - [Multi-Instance Deployment (`TENANT_ID`)](#multi-instance-deployment-tenant_id)- [Usage Details](#usage-details)- [Docker Settings](#docker-settings)- [Usage Details](#usage-details-1)@@ -140,9 +141,94 @@ These settings control basic application behavior and are foundational for the s| Debug | `DEBUG` | `false` | Enables debug mode with additional logging || DataDir | `DATA_DIR` | `./data` | Directory for storing persistent data || AskUser | `ASK_USER` | `false` | When enabled, requires explicit user confirmation for certain operations |+| TenantID | `TENANT_ID` | *(empty)* | Namespaces every externally-visible artifact this instance creates so several PentAGI instances can share one host and one set of backing services. Empty = single-instance behavior, unchanged. See [Multi-Instance Deployment](#multi-instance-deployment-tenant_id). |+| DockerPortsBase | `DOCKER_PORTS_BASE` | `0` (means `28000`) | First host port for per-flow sandbox port publishing; each instance owns `[base, base+2000)` || InstallationID | `INSTALLATION_ID` | *(none)* | Unique installation identifier for PentAGI Cloud API communication || LicenseKey | `LICENSE_KEY` | *(none)* | License key for PentAGI Cloud API authentication and feature activation |+### Multi-Instance Deployment (`TENANT_ID`)++`TENANT_ID` namespaces the artifacts a PentAGI instance creates in **shared external+services**, so that several independent installations can use one PostgreSQL server,+one worker node (Docker daemon), one Neo4j/Graphiti and one Langfuse without+colliding.++**Primary use case: several management instances, shared resources.** The typical+deployment puts each PentAGI management backend on its own server, while the heavy+shared resources — the worker node where sandbox containers run, and the database —+are common. `TENANT_ID` is what keeps those instances from writing over each other.++Running several management instances on **one** server is also possible (for example+behind an nginx reverse proxy), but that is not what the installer or the stock+`docker-compose.yml` are built for — see *Deployment topologies* below.++**When empty (the default) nothing changes.** Every helper degrades to an identity+function: container names stay `pentagi-terminal-<id>`, the database schema stays+`public`, Graphiti group ids stay `flow-<id>`, and the session cookie stays `auth`.+This is enforced in one place (`backend/pkg/config/tenant.go`) and covered by tests.++**Validation.** `TENANT_ID` must match `^[a-z][a-z0-9_]{0,31}$` — the intersection of+the constraints imposed by every consumer:++| Consumer | Constraint |+| --- | --- |+| Docker object name | `[a-zA-Z0-9][a-zA-Z0-9_.-]*` |+| PostgreSQL identifier | ≤ 63 bytes; unquoted-safe as `[a-z_][a-z0-9_]*` |+| Graphiti / Neo4j group id | parsed on a hyphen boundary, so no hyphens |++Hyphens are excluded deliberately: they separate the tenant from the rest of a group+id or object name. An invalid value **aborts startup** rather than being normalised,+because collapsing two distinct tenants onto one namespace is exactly the collision+tenancy exists to prevent.++#### What the application namespaces automatically++| Area | Effect |+| --- | --- |+| PostgreSQL | A schema named after the tenant is created on boot and `search_path` is set to `<tenant>,public`; the DSN is rewritten once so sqlc, GORM, goose and the pgvector pool all follow. Extensions (`vector`, `pg_trgm`) stay shared in `public`. |+| Worker containers | Sandbox container names become `<tenant>-pentagi-terminal-<flow>`; the per-flow volume and the container hostname derive from that name automatically. Both are labelled `pentagi.tenant`, so daemon-wide sweeps can filter by owner. |+| Host ports | Per-flow sandbox ports are allocated from `DOCKER_PORTS_BASE` (default `28000`), giving each instance the window `[base, base+2000)`. |+| Knowledge graph | Graphiti/Neo4j group ids become `<tenant>-flow-<id>`. The GraphQL API contract is unchanged — clients still send `flow-<id>` and the server rebuilds the namespaced key internally. |+| Auth | Cookie and JWT keys are derived from `COOKIE_SIGNING_SALT` **plus** the tenant, and the session cookie is renamed, so a session or API token minted by one instance is rejected by another. |+| Telemetry | OTel resources carry `service.instance.id` and, with a tenant set, `tenant_id`; Langfuse traces carry the native `environment` field plus a `tenant:<id>` tag and tenant-prefixed trace/session names. |++#### What stays the operator's responsibility++`TENANT_ID` does **not** rewrite infrastructure-level settings. The following must be+given distinct values per instance by whoever provisions it:++| Setting | Why it is not derived from `TENANT_ID` |+| --- | --- |+| `DATA_DIR` | The data directory is chosen by the operator. Flow file caches, the container `/work` bind mount, screenshots and `installation_id` all live under it, and two instances pointed at the same directory **will overwrite each other's flow data**. Give each instance its own path or its own volume. |+| `DOCKER_NETWORK` | Instances may legitimately share one Docker network; the application never renames it. Set it explicitly if you want separate networks. |+| Published ports | `PENTAGI_LISTEN_PORT`, `PGVECTOR_LISTEN_PORT`, `SCRAPER_LISTEN_PORT`, `PPROF_ADDR` and `DOCKER_PORTS_BASE` are host-level resources, not string namespaces. |+| `INSTALLATION_ID` | Unique per installation, or left empty to be generated once and cached in `DATA_DIR`. |+| Database privileges | The configured user needs `CREATE SCHEMA`, and on first boot `CREATE EXTENSION` — unless an administrator pre-installed `vector` and `pg_trgm` into `public`. |++The values actually in effect are written to the startup log under+`Instance identity` (`tenant_id`, `data_dir`, `schema`, `installation_id`), which is+the quickest way to confirm two instances are not sharing something they should not.++`DOCKER_INSIDE` is orthogonal to tenancy and may be enabled alongside it.++#### Deployment topologies++| Topology | Supported by |+| --- | --- |+| One instance per server, shared PostgreSQL and/or worker node | The installer and the stock `docker-compose.yml`, with `TENANT_ID` set per server. This is the intended setup. |+| Several instances on one server | Manual configuration only. The stock `docker-compose.yml` uses fixed `container_name` and network names, so copying it verbatim will not start a second stack. Adapt it to your network and infrastructure — for example, distinct container names behind a shared nginx — and give each instance its own `DATA_DIR` and ports. |++The installer provisions **one** instance per server; it does not manage several+side by side. Note that it does scope the sandbox resources it cleans up — worker+containers and volumes are matched by the tenant prefix — so a purge run for one+management instance will not remove another's sandboxes from a shared worker node.++**Upgrading an existing deployment.** Leave `TENANT_ID` empty. The instance keeps+using `public` and its current data directory; no migration is required. Setting+`TENANT_ID` on an existing installation points it at a **new, empty schema** — the+data in `public` is not migrated and will appear to be gone. Do not point an existing+`public` deployment at a `search_path` that lists another tenant's schema.+### Usage Details- **DatabaseURL**: This is a critical setting used throughout the application for all database connections. It is used to:diff --git a/backend/pkg/config/config.go b/backend/pkg/config/config.goindex bd2c0ec2..9f695afe 100644--- a/backend/pkg/config/config.go+++ b/backend/pkg/config/config.go@@ -23,6 +23,10 @@ type Config struct {DataDir string `env:"DATA_DIR" envDefault:"./data"`AskUser bool `env:"ASK_USER" envDefault:"false"`+ // TenantID namespaces every externally-visible artifact this instance creates+ // (PostgreSQL schema, docker object names, Graphiti group ids, telemetry identity)+ TenantID string `env:"TENANT_ID" envDefault:""`+// === PentAGI Cloud Service Integration ===InstallationID string `env:"INSTALLATION_ID"`LicenseKey string `env:"LICENSE_KEY"`@@ -34,6 +38,7 @@ type Config struct {DockerNetwork string `env:"DOCKER_NETWORK"`DockerPublicIP string `env:"DOCKER_PUBLIC_IP" envDefault:"0.0.0.0"`DockerWorkDir string `env:"DOCKER_WORK_DIR"`+ DockerPortsBase int `env:"DOCKER_PORTS_BASE" envDefault:"28000"`DockerDefaultImage string `env:"DOCKER_DEFAULT_IMAGE" envDefault:"debian:latest"`DockerDefaultImageForPentest string `env:"DOCKER_DEFAULT_IMAGE_FOR_PENTEST" envDefault:"vxcontrol/kali-linux"`TerminalToolTimeout int `env:"TERMINAL_TOOL_TIMEOUT" envDefault:"1200"`@@ -223,6 +228,9 @@ type Config struct {// === Observability: OpenTelemetry Collector ===TelemetryEndpoint string `env:"OTEL_HOST"`+ // PprofAddr is the pprof listener address. It is empty by default, which means pprof is disabled.+ PprofAddr string `env:"PPROF_ADDR" envDefault:""`+// === Observability: Langfuse LLM Analytics ===LangfuseBaseURL string `env:"LANGFUSE_BASE_URL"`LangfuseProjectID string `env:"LANGFUSE_PROJECT_ID"`@@ -274,6 +282,10 @@ func NewConfig() (*Config, error) {return nil, err}+ if err := config.ValidateTenantID(); err != nil {+ return nil, err+ }+ensureInstallationID(&config)ensureLicenseKey(&config)@@ -311,6 +323,30 @@ func ensureLicenseKey(config *Config) {}}+// WorkerPortsBase returns the base port for the worker container+func (c *Config) WorkerPortsBase() int {+ if c == nil {+ return 28000+ }+ return c.DockerPortsBase+}++// WorkerPublicIP returns the public IP for the worker container+func (c *Config) WorkerPublicIP() string {+ if c == nil || c.DockerPublicIP == "" {+ return "0.0.0.0"+ }+ return c.DockerPublicIP+}++// WorkerNetwork returns the network for the worker container+func (c *Config) WorkerNetwork() string {+ if c == nil {+ return ""+ }+ return c.DockerNetwork+}+// GetSecretPatterns returns a list of patterns for all secrets in the configfunc (c *Config) GetSecretPatterns() []patterns.Pattern {var result []patterns.Patterndiff --git a/backend/pkg/config/config_test.go b/backend/pkg/config/config_test.goindex 0fa7930b..972b0c06 100644--- a/backend/pkg/config/config_test.go+++ b/backend/pkg/config/config_test.go@@ -270,7 +270,7 @@ func clearConfigEnv(t *testing.T) {t.Helper()envVars := []string{- "DATABASE_URL", "DEBUG", "DATA_DIR", "ASK_USER", "INSTALLATION_ID", "LICENSE_KEY",+ "DATABASE_URL", "DEBUG", "DATA_DIR", "ASK_USER", "TENANT_ID", "INSTALLATION_ID", "LICENSE_KEY","DOCKER_INSIDE", "DOCKER_NET_ADMIN", "DOCKER_SOCKET", "DOCKER_NETWORK","DOCKER_PUBLIC_IP", "DOCKER_WORK_DIR", "DOCKER_DEFAULT_IMAGE", "DOCKER_DEFAULT_IMAGE_FOR_PENTEST", "TERMINAL_TOOL_TIMEOUT","SERVER_PORT", "SERVER_HOST", "SERVER_USE_SSL", "SERVER_SSL_KEY", "SERVER_SSL_CRT",diff --git a/backend/pkg/config/tenant.go b/backend/pkg/config/tenant.gonew file mode 100644index 00000000..3678a717--- /dev/null+++ b/backend/pkg/config/tenant.go@@ -0,0 +1,179 @@+package config++import (+ "fmt"+ "regexp"+ "strings"+)++// tenantIDRegex is the intersection of every constraint TENANT_ID must satisfy+// simultaneously:+//+// - Docker object name component: [a-zA-Z0-9][a-zA-Z0-9_.-]*+// - PostgreSQL identifier: <= 63 bytes, unquoted-safe as [a-z_][a-z0-9_]*+// - Filesystem path segment: no separators, no "." / ".."+// - Graphiti / Neo4j group id: parsed on a hyphen boundary, so no hyphens+//+// The hyphen is deliberately excluded: it is the separator used by group ids and+// docker object names, and admitting it would make those strings ambiguous to+// parse. 32 characters leaves ample headroom under PostgreSQL's 63-byte limit+// even once prefixes are applied.+var tenantIDRegex = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`)++// ValidateTenantID reports whether the configured TENANT_ID is usable. An empty+// tenant id is always valid and selects single-instance mode. Anything else must+// match tenantIDRegex; callers are expected to treat a non-nil result as fatal,+// because silently normalising an invalid value could collapse two distinct+// tenants onto one namespace — exactly the collision tenancy exists to prevent.+func (c *Config) ValidateTenantID() error {+ if c == nil || c.TenantID == "" {+ return nil+ }++ if !tenantIDRegex.MatchString(c.TenantID) {+ return fmt.Errorf(+ "invalid TENANT_ID %q: must match %s (lowercase letter first, then lowercase "++ "letters, digits or underscores, max 32 characters)",+ c.TenantID, tenantIDRegex.String(),+ )+ }++ return nil+}++// HasTenant reports whether this instance runs in multi-tenant mode.+func (c *Config) HasTenant() bool { return c != nil && c.TenantID != "" }++// TenantPrefix returns "<tenant>-", or "" when no tenant is configured. Prefer+// ScopedName when building a complete name; this exists for the call sites that+// must hand a prefix to another package.+func (c *Config) TenantPrefix() string {+ if c == nil || c.TenantID == "" {+ return ""+ }+ return c.TenantID + "-"+}++// ScopedName prefixes a docker object name, cookie name, or any other+// hyphen-separated identifier with this instance's tenant.+//+// ScopedName("pentagi-terminal-1") -> "pentagi-terminal-1" (no tenant)+// ScopedName("pentagi-terminal-1") -> "acme-pentagi-terminal-1" (tenant "acme")+//+// The prefix goes in front rather than in the middle so that tenant-owned+// objects fall outside existing "pentagi-*" prefix sweeps instead of inside+// them — see the installer's volume garbage collector.+func (c *Config) ScopedName(base string) string {+ if c == nil || c.TenantID == "" {+ return base+ }+ return c.TenantID + "-" + base+}++// GroupID builds the Graphiti / Neo4j group identifier for a flow.+//+// GroupID(42) -> "flow-42" (no tenant)+// GroupID(42) -> "acme-flow-42" (tenant "acme")+//+// ParseGroupID is the exact inverse; the two must always change together.+func (c *Config) GroupID(flowID int64) string {+ return c.TenantPrefix() + fmt.Sprintf("flow-%d", flowID)+}++// ParseGroupID is the inverse of GroupID. It strips this instance's tenant+// prefix and returns the flow id, rejecting group ids that belong to a different+// tenant so that one instance can never resolve another's knowledge-graph data.+//+// This must only be applied to strings that came back from Graphiti or Neo4j —+// never to a value supplied by an API client, which would let the client choose+// its own namespace.+func (c *Config) ParseGroupID(groupID string) (int64, error) {+ rest := groupID+ if c != nil && c.TenantID != "" {+ prefix := c.TenantID + "-"+ if !strings.HasPrefix(groupID, prefix) {+ return 0, fmt.Errorf("group id %q does not belong to tenant %q", groupID, c.TenantID)+ }+ rest = strings.TrimPrefix(groupID, prefix)+ }++ var flowID int64+ // Sscanf alone would accept trailing garbage ("flow-1x"), so verify the+ // round-trip instead of trusting the scan.+ if _, err := fmt.Sscanf(rest, "flow-%d", &flowID); err != nil {+ return 0, fmt.Errorf("invalid groupId format: %q (expected %q)", groupID, c.GroupID(0))+ }+ if c.GroupID(flowID) != groupID {+ return 0, fmt.Errorf("invalid groupId format: %q (expected %q)", groupID, c.GroupID(flowID))+ }++ return flowID, nil+}++// TenantUserID namespaces a telemetry "user" identity. Instances share the+// seeded [email protected] account, so without this every tenant's traces would+// collapse onto one Langfuse user. Returns the address unchanged in+// single-instance mode.+func (c *Config) TenantUserID(mail string) string {+ if c == nil || c.TenantID == "" {+ return mail+ }+ return c.TenantID + "/" + mail+}++// TenantTags appends a "tenant:<id>" tag so traces from several instances+// sharing one Langfuse project stay filterable. Returns exactly the base tags in+// single-instance mode, so the emitted payload is unchanged.+func (c *Config) TenantTags(base ...string) []string {+ if c == nil || c.TenantID == "" {+ return base+ }+ return append(append(make([]string, 0, len(base)+1), base...), "tenant:"+c.TenantID)+}++// TenantLabel returns a display prefix for human-facing telemetry names+// ("<tenant> " or ""), used for Langfuse trace names.+func (c *Config) TenantLabel() string {+ if c == nil || c.TenantID == "" {+ return ""+ }+ return c.TenantID + " "+}++// SchemaName returns the PostgreSQL schema this instance owns. Single-instance+// deployments keep using "public" so nothing about their layout changes.+func (c *Config) SchemaName() string {+ if c == nil || c.TenantID == "" {+ return "public"+ }+ return c.TenantID+}++// AuthSalt returns the effective salt for cookie and JWT key derivation. Mixing+// the tenant in makes one instance's session cookies and API tokens+// cryptographically invalid on another even when COOKIE_SIGNING_SALT is shared+// across instances — without it, identical salts plus identical user id+// sequences would let a session from one tenant authenticate against another.+func (c *Config) AuthSalt() string {+ if c == nil {+ return ""+ }+ if c.TenantID == "" {+ return c.CookieSigningSalt+ }+ return c.CookieSigningSalt + "|tenant|" + c.TenantID+}++// TenantLabels returns the docker object labels identifying this instance's+// resources. Returns nil when no tenant is configured, so labels stay absent and+// created objects are byte-identical to today.+func (c *Config) TenantLabels() map[string]string {+ if c == nil || c.TenantID == "" {+ return nil+ }+ return map[string]string{TenantLabelKey: c.TenantID}+}++// TenantLabelKey is the docker label carrying the owning tenant id. Sweeps over+// the daemon should filter on this rather than matching name prefixes.+const TenantLabelKey = "pentagi.tenant"diff --git a/backend/pkg/config/tenant_test.go b/backend/pkg/config/tenant_test.gonew file mode 100644index 00000000..94813e36--- /dev/null+++ b/backend/pkg/config/tenant_test.go@@ -0,0 +1,262 @@+package config++import (+ "strings"+ "testing"+)++// TestTenantHelpersAreNoOpWhenEmpty is the backward-compatibility contract: with+// TENANT_ID unset every helper must return exactly the value the codebase used+// before tenancy existed.+func TestTenantHelpersAreNoOpWhenEmpty(t *testing.T) {+ c := &Config{CookieSigningSalt: "salt"}++ if c.HasTenant() {+ t.Error("HasTenant() = true, want false for empty tenant id")+ }+ if got := c.TenantPrefix(); got != "" {+ t.Errorf("TenantPrefix() = %q, want %q", got, "")+ }+ if got := c.ScopedName("pentagi-terminal-1"); got != "pentagi-terminal-1" {+ t.Errorf("ScopedName() = %q, want %q", got, "pentagi-terminal-1")+ }+ if got := c.ScopedName("auth"); got != "auth" {+ t.Errorf("ScopedName(auth) = %q, want %q", got, "auth")+ }+ if got := c.GroupID(42); got != "flow-42" {+ t.Errorf("GroupID(42) = %q, want %q", got, "flow-42")+ }+ if got := c.TenantLabel(); got != "" {+ t.Errorf("TenantLabel() = %q, want %q", got, "")+ }+ if got := c.SchemaName(); got != "public" {+ t.Errorf("SchemaName() = %q, want %q", got, "public")+ }+ if got := c.AuthSalt(); got != "salt" {+ t.Errorf("AuthSalt() = %q, want %q (must equal CookieSigningSalt verbatim)", got, "salt")+ }+ if got := c.TenantLabels(); got != nil {+ t.Errorf("TenantLabels() = %v, want nil so docker objects stay unlabelled", got)+ }+}++func TestTenantHelpersWithTenant(t *testing.T) {+ c := &Config{TenantID: "acme", CookieSigningSalt: "salt"}++ if !c.HasTenant() {+ t.Error("HasTenant() = false, want true")+ }+ if got, want := c.TenantPrefix(), "acme-"; got != want {+ t.Errorf("TenantPrefix() = %q, want %q", got, want)+ }+ if got, want := c.ScopedName("pentagi-terminal-1"), "acme-pentagi-terminal-1"; got != want {+ t.Errorf("ScopedName() = %q, want %q", got, want)+ }+ if got, want := c.GroupID(42), "acme-flow-42"; got != want {+ t.Errorf("GroupID(42) = %q, want %q", got, want)+ }+ if got, want := c.TenantLabel(), "acme "; got != want {+ t.Errorf("TenantLabel() = %q, want %q", got, want)+ }+ if got, want := c.SchemaName(), "acme"; got != want {+ t.Errorf("SchemaName() = %q, want %q", got, want)+ }+ if got := c.AuthSalt(); got == "salt" {+ t.Error("AuthSalt() must differ from the raw salt when a tenant is configured")+ }+ if got := c.TenantLabels(); got[TenantLabelKey] != "acme" {+ t.Errorf("TenantLabels()[%s] = %q, want %q", TenantLabelKey, got[TenantLabelKey], "acme")+ }+}++// TestScopedNameEscapesInstallerVolumeSweep pins the property that motivated+// putting the tenant prefix in front rather than in the middle: the installer's+// garbage collector force-removes volumes matching+// HasPrefix("pentagi-terminal-") && HasSuffix("-data"), and a tenant's volumes+// must fall outside that filter.+func TestScopedNameEscapesInstallerVolumeSweep(t *testing.T) {+ tenant := &Config{TenantID: "acme"}+ def := &Config{}++ tenantVolume := tenant.ScopedName("pentagi-terminal-1") + "-data"+ defaultVolume := def.ScopedName("pentagi-terminal-1") + "-data"++ sweepMatches := func(name string) bool {+ return strings.HasPrefix(name, "pentagi-terminal-") && strings.HasSuffix(name, "-data")+ }++ if sweepMatches(tenantVolume) {+ t.Errorf("tenant volume %q matches the installer sweep; it would be destroyed by another tenant's purge", tenantVolume)+ }+ if !sweepMatches(defaultVolume) {+ t.Errorf("default volume %q no longer matches the installer sweep; single-instance cleanup would break", defaultVolume)+ }+}++func TestParseGroupIDRoundTrip(t *testing.T) {+ for _, tenantID := range []string{"", "acme"} {+ c := &Config{TenantID: tenantID}+ for _, flowID := range []int64{0, 1, 42, 9999999999} {+ gid := c.GroupID(flowID)+ got, err := c.ParseGroupID(gid)+ if err != nil {+ t.Errorf("tenant %q: ParseGroupID(%q) returned error: %v", tenantID, gid, err)+ continue+ }+ if got != flowID {+ t.Errorf("tenant %q: ParseGroupID(%q) = %d, want %d", tenantID, gid, got, flowID)+ }+ }+ }+}++func TestParseGroupIDRejectsForeignTenant(t *testing.T) {+ c := &Config{TenantID: "acme"}++ for _, gid := range []string{"flow-1", "other-flow-1", "acme2-flow-1", ""} {+ if _, err := c.ParseGroupID(gid); err == nil {+ t.Errorf("ParseGroupID(%q) succeeded; want rejection for tenant %q", gid, c.TenantID)+ }+ }+}++func TestParseGroupIDRejectsMalformed(t *testing.T) {+ c := &Config{}++ for _, gid := range []string{"flow-", "flow-abc", "flow-1x", "notflow-1", "1", ""} {+ if _, err := c.ParseGroupID(gid); err == nil {+ t.Errorf("ParseGroupID(%q) succeeded; want rejection", gid)+ }+ }+}++func TestValidateTenantID(t *testing.T) {+ valid := []string{+ "", // single-instance mode+ "a", // minimum+ "acme",+ "acme2",+ "a_b_c",+ "tenant_01",+ strings.Repeat("a", 32), // maximum length+ }+ for _, id := range valid {+ c := &Config{TenantID: id}+ if err := c.ValidateTenantID(); err != nil {+ t.Errorf("ValidateTenantID(%q) = %v, want nil", id, err)+ }+ }++ invalid := []string{+ "Acme", // uppercase breaks unquoted postgres identifiers+ "1acme", // must start with a letter (docker + postgres)+ "_acme", // must start with a letter+ "acme-prod", // hyphen is the group-id / docker-name separator+ "acme.prod", // dot is not valid in a postgres identifier+ "acme prod", // whitespace+ "../etc", // path traversal+ "acme/prod", // path separator+ "acme;DROP SCHEMA", // sql metacharacters+ strings.Repeat("a", 33), // over the length limit+ }+ for _, id := range invalid {+ c := &Config{TenantID: id}+ if err := c.ValidateTenantID(); err == nil {+ t.Errorf("ValidateTenantID(%q) = nil, want error", id)+ }+ }+}++// TestTenantIDFitsPostgresIdentifierLimit guards the derivation in SchemaName+// against PostgreSQL's 63-byte identifier cap.+func TestTenantIDFitsPostgresIdentifierLimit(t *testing.T) {+ c := &Config{TenantID: strings.Repeat("a", 32)}+ if err := c.ValidateTenantID(); err != nil {+ t.Fatalf("max-length tenant id rejected: %v", err)+ }+ if got := len(c.SchemaName()); got > 63 {+ t.Errorf("SchemaName() is %d bytes, exceeds the PostgreSQL 63-byte identifier limit", got)+ }+}++// TestBackwardCompatibilityContract is the guard for the single hard requirement+// of the tenancy work: with TENANT_ID unset, every externally-visible name,+// path, identifier and key must be exactly what it was before tenancy existed.+//+// The literals on the right-hand side are the historical values, written out+// explicitly rather than computed, so that a future refactor of the helpers+// cannot silently move them.+func TestBackwardCompatibilityContract(t *testing.T) {+ c := &Config{+ DataDir: "./data",+ DockerNetwork: "pentagi-network",+ CookieSigningSalt: "salt",+ InstallationID: "3f2504e0-4f89-11d3-9a0c-0305e82c3301",+ }+ if err := c.ValidateTenantID(); err != nil {+ t.Fatalf("empty TENANT_ID must be valid, got %v", err)+ }++ cases := []struct {+ what string+ got string+ want string+ }{+ {"docker container name", c.ScopedName("pentagi-terminal-1"), "pentagi-terminal-1"},+ {"docker volume name", c.ScopedName("pentagi-terminal-1") + "-data", "pentagi-terminal-1-data"},+ {"docker network", c.DockerNetwork, "pentagi-network"},+ {"session cookie name", c.ScopedName("auth"), "auth"},+ {"oauth state cookie", c.TenantPrefix() + "state", "state"},+ {"oauth nonce cookie", c.TenantPrefix() + "nonce", "nonce"},+ {"graphiti group id", c.GroupID(1), "flow-1"},+ {"graphiti group id (large)", c.GroupID(9999999999), "flow-9999999999"},+ {"postgres schema", c.SchemaName(), "public"},+ {"cookie/jwt salt", c.AuthSalt(), "salt"},+ // Left verbatim, not even filepath.Clean'ed: applyTenantScoping returns+ // before touching it, so an upgraded deployment sees the identical string.+ {"data dir", c.DataDir, "./data"},+ {"langfuse trace prefix", c.TenantLabel(), ""},+ {"installation id", c.InstallationID, "3f2504e0-4f89-11d3-9a0c-0305e82c3301"},+ }+ for _, tc := range cases {+ if tc.got != tc.want {+ t.Errorf("%s = %q, want %q (backward compatibility broken)", tc.what, tc.got, tc.want)+ }+ }++ if c.TenantLabels() != nil {+ t.Error("docker objects must carry no labels when TENANT_ID is unset")+ }+ if c.HasTenant() {+ t.Error("HasTenant() must be false when TENANT_ID is unset")+ }+}++// TestTenantIsolationIsMutual checks the property that actually matters at+// runtime: two instances with different tenant ids must not produce a single+// colliding name for the same flow id.+func TestTenantIsolationIsMutual(t *testing.T) {+ alpha := &Config{TenantID: "alpha", CookieSigningSalt: "shared"}+ beta := &Config{TenantID: "beta", CookieSigningSalt: "shared"}+ plain := &Config{CookieSigningSalt: "shared"}++ const flowID = 1+ for _, probe := range []struct {+ what string+ fn func(*Config) string+ }{+ {"container name", func(c *Config) string { return c.ScopedName("pentagi-terminal-1") }},+ {"group id", func(c *Config) string { return c.GroupID(flowID) }},+ {"schema", func(c *Config) string { return c.SchemaName() }},+ {"cookie name", func(c *Config) string { return c.ScopedName("auth") }},+ {"auth salt", func(c *Config) string { return c.AuthSalt() }},+ } {+ a, b, p := probe.fn(alpha), probe.fn(beta), probe.fn(plain)+ if a == b {+ t.Errorf("%s collides between tenants: both %q", probe.what, a)+ }+ if a == p || b == p {+ t.Errorf("%s collides with the untenanted instance: %q / %q / %q", probe.what, a, b, p)+ }+ }+}diff --git a/backend/pkg/controller/assistant.go b/backend/pkg/controller/assistant.goindex d2d3cdab..bb4811c9 100644--- a/backend/pkg/controller/assistant.go+++ b/backend/pkg/controller/assistant.go@@ -137,12 +137,12 @@ func NewAssistantWorker(ctx context.Context, awc newAssistantWorkerCtx) (Assistactx, observation := obs.Observer.NewObservation(ctx,langfuse.WithObservationTraceContext(- langfuse.WithTraceName(fmt.Sprintf("%d flow %d assistant worker", awc.flowID, assistant.ID)),- langfuse.WithTraceUserID(user.Mail),- langfuse.WithTraceTags([]string{"controller", "assistant"}),+ langfuse.WithTraceName(fmt.Sprintf("%s%d flow %d assistant worker", awc.cfg.TenantLabel(), awc.flowID, assistant.ID)),+ langfuse.WithTraceUserID(tenantUserID(awc.cfg, user.Mail)),+ langfuse.WithTraceTags(tenantTags(awc.cfg, "controller", "assistant")),langfuse.WithTraceInput(awc.input),- langfuse.WithTraceSessionID(fmt.Sprintf("assistant-%d-flow-%d", assistant.ID, awc.flowID)),- langfuse.WithTraceMetadata(langfuse.Metadata{+ langfuse.WithTraceSessionID(awc.cfg.ScopedName(fmt.Sprintf("assistant-%d-flow-%d", assistant.ID, awc.flowID))),+ langfuse.WithTraceMetadata(tenantMeta(awc.cfg, langfuse.Metadata{"assistant_id": assistant.ID,"flow_id": awc.flowID,"user_id": awc.userID,@@ -152,7 +152,7 @@ func NewAssistantWorker(ctx context.Context, awc newAssistantWorkerCtx) (Assista"user_role": user.RoleName,"provider_name": awc.prvname.String(),"provider_type": awc.prvtype.String(),- }),+ })),),)assistantSpan := observation.Span(langfuse.WithSpanName("prepare assistant worker"))@@ -305,11 +305,11 @@ func LoadAssistantWorker(ctx, observation := obs.Observer.NewObservation(ctx,langfuse.WithObservationTraceContext(- langfuse.WithTraceName(fmt.Sprintf("%d flow %d assistant worker", awc.flowID, assistant.ID)),- langfuse.WithTraceUserID(user.Mail),- langfuse.WithTraceTags([]string{"controller", "assistant"}),- langfuse.WithTraceSessionID(fmt.Sprintf("assistant-%d-flow-%d", assistant.ID, awc.flowID)),- langfuse.WithTraceMetadata(langfuse.Metadata{+ langfuse.WithTraceName(fmt.Sprintf("%s%d flow %d assistant worker", awc.cfg.TenantLabel(), awc.flowID, assistant.ID)),+ langfuse.WithTraceUserID(tenantUserID(awc.cfg, user.Mail)),+ langfuse.WithTraceTags(tenantTags(awc.cfg, "controller", "assistant")),+ langfuse.WithTraceSessionID(awc.cfg.ScopedName(fmt.Sprintf("assistant-%d-flow-%d", assistant.ID, awc.flowID))),+ langfuse.WithTraceMetadata(tenantMeta(awc.cfg, langfuse.Metadata{"assistant_id": assistant.ID,"flow_id": awc.flowID,"user_id": awc.userID,@@ -319,7 +319,7 @@ func LoadAssistantWorker("user_role": user.RoleName,"provider_name": assistant.ModelProviderName,"provider_type": assistant.ModelProviderType,- }),+ })),),)assistantSpan := observation.Span(langfuse.WithSpanName("prepare assistant worker"))diff --git a/backend/pkg/controller/context.go b/backend/pkg/controller/context.goindex b098eab8..a34f2603 100644--- a/backend/pkg/controller/context.go+++ b/backend/pkg/controller/context.go@@ -5,6 +5,7 @@ import ("errors""fmt"+ "pentagi/pkg/config""pentagi/pkg/database""pentagi/pkg/graph/subscriptions""pentagi/pkg/observability/langfuse"@@ -58,3 +59,35 @@ func wrapErrorEndSpan(ctx context.Context, span langfuse.Span, msg string, err e)return err}++// tenantMeta adds a tenant_id key to trace metadata when a tenant is configured.+// The key is absent otherwise, so the emitted payload is byte-identical to what+// a single-instance deployment sends today.+func tenantMeta(cfg *config.Config, md langfuse.Metadata) langfuse.Metadata {+ if cfg == nil || !cfg.HasTenant() {+ return md+ }++ if md == nil {+ md = make(langfuse.Metadata)+ }++ md["tenant_id"] = cfg.TenantID++ return md+}++// tenantUserID namespaces the Langfuse "user" dimension. Instances share the+// seeded [email protected] account, so without this every tenant's traces would+// collapse onto one Langfuse user. Returns the address unchanged in+// single-instance mode.+func tenantUserID(cfg *config.Config, mail string) string {+ return cfg.TenantUserID(mail)+}++// tenantTags appends a "tenant:<id>" tag so traces from several instances+// sharing one Langfuse project stay filterable. Returns exactly the base tags in+// single-instance mode, so the emitted payload is unchanged.+func tenantTags(cfg *config.Config, base ...string) []string {+ return cfg.TenantTags(base...)+}diff --git a/backend/pkg/controller/flow.go b/backend/pkg/controller/flow.goindex 7b0d684f..735ed350 100644--- a/backend/pkg/controller/flow.go+++ b/backend/pkg/controller/flow.go@@ -55,6 +55,7 @@ type FlowWorker interface {type flowWorker struct {tc TaskControllerwg *sync.WaitGroup+ cfg *config.Configaws map[int64]AssistantWorkerawsMX *sync.Mutexctx context.Context@@ -66,7 +67,6 @@ type flowWorker struct {taskCCH chan struct{}input chan flowInputflowCtx *FlowContext- dataDir stringdocker docker.DockerClientlogger *logrus.Entry}@@ -179,12 +179,12 @@ func NewFlowWorker(ctx, observation := obs.Observer.NewObservation(ctx,langfuse.WithObservationTraceContext(- langfuse.WithTraceName(fmt.Sprintf("%d flow worker", flow.ID)),- langfuse.WithTraceUserID(user.Mail),- langfuse.WithTraceTags([]string{"controller", "flow"}),+ langfuse.WithTraceName(fmt.Sprintf("%s%d flow worker", fwc.cfg.TenantLabel(), flow.ID)),+ langfuse.WithTraceUserID(tenantUserID(fwc.cfg, user.Mail)),+ langfuse.WithTraceTags(tenantTags(fwc.cfg, "controller", "flow")),langfuse.WithTraceInput(fwc.input),- langfuse.WithTraceSessionID(fmt.Sprintf("flow-%d", flow.ID)),- langfuse.WithTraceMetadata(langfuse.Metadata{+ langfuse.WithTraceSessionID(fwc.cfg.ScopedName(fmt.Sprintf("flow-%d", flow.ID))),+ langfuse.WithTraceMetadata(tenantMeta(fwc.cfg, langfuse.Metadata{"flow_id": flow.ID,"user_id": fwc.userID,"user_email": user.Mail,@@ -193,7 +193,7 @@ func NewFlowWorker("user_role": user.RoleName,"provider_name": fwc.prvname.String(),"provider_type": fwc.prvtype.String(),- }),+ })),),)flowSpan := observation.Span(langfuse.WithSpanName("prepare flow worker"))@@ -272,6 +272,7 @@ func NewFlowWorker(wg: &sync.WaitGroup{},aws: make(map[int64]AssistantWorker),awsMX: &sync.Mutex{},+ cfg: fwc.cfg,ctx: ctx,cancel: cancel,taskMX: &sync.Mutex{},@@ -280,7 +281,6 @@ func NewFlowWorker(taskCCH: make(chan struct{}),input: make(chan flowInput),flowCtx: flowCtx,- dataDir: fwc.cfg.DataDir,docker: fwc.docker,logger: logrus.WithFields(logrus.Fields{"flow_id": flow.ID,@@ -351,11 +351,11 @@ func LoadFlowWorker(ctx context.Context, flow database.Flow, fwc flowWorkerCtx)ctx, observation := obs.Observer.NewObservation(ctx,langfuse.WithObservationTraceID(flow.TraceID.String),langfuse.WithObservationTraceContext(- langfuse.WithTraceName(fmt.Sprintf("%d flow worker", flow.ID)),- langfuse.WithTraceUserID(user.Mail),- langfuse.WithTraceTags([]string{"controller", "flow"}),- langfuse.WithTraceSessionID(fmt.Sprintf("flow-%d", flow.ID)),- langfuse.WithTraceMetadata(langfuse.Metadata{+ langfuse.WithTraceName(fmt.Sprintf("%s%d flow worker", fwc.cfg.TenantLabel(), flow.ID)),+ langfuse.WithTraceUserID(tenantUserID(fwc.cfg, user.Mail)),+ langfuse.WithTraceTags(tenantTags(fwc.cfg, "controller", "flow")),+ langfuse.WithTraceSessionID(fwc.cfg.ScopedName(fmt.Sprintf("flow-%d", flow.ID))),+ langfuse.WithTraceMetadata(tenantMeta(fwc.cfg, langfuse.Metadata{"flow_id": flow.ID,"user_id": flow.UserID,"user_email": user.Mail,@@ -364,7 +364,7 @@ func LoadFlowWorker(ctx context.Context, flow database.Flow, fwc flowWorkerCtx)"user_role": user.RoleName,"provider_name": flow.ModelProviderName,"provider_type": flow.ModelProviderType,- }),+ })),),)flowSpan := observation.Span(langfuse.WithSpanName("prepare flow worker"))@@ -432,6 +432,7 @@ func LoadFlowWorker(ctx context.Context, flow database.Flow, fwc flowWorkerCtx)wg: &sync.WaitGroup{},aws: make(map[int64]AssistantWorker),awsMX: &sync.Mutex{},+ cfg: fwc.cfg,ctx: ctx,cancel: cancel,taskMX: &sync.Mutex{},@@ -440,7 +441,6 @@ func LoadFlowWorker(ctx context.Context, flow database.Flow, fwc flowWorkerCtx)taskCCH: make(chan struct{}),input: make(chan flowInput),flowCtx: flowCtx,- dataDir: fwc.cfg.DataDir,docker: fwc.docker,logger: logrus.WithFields(logrus.Fields{"flow_id": flow.ID,@@ -696,8 +696,8 @@ func (fw *flowWorker) copyResourcesToFS(dbResources []database.UserResource) ([]})}- storeDir := resources.ResourcesDir(fw.dataDir)- return flowfiles.CopyResourcesToFlow(fw.dataDir, storeDir, uint64(fw.flowCtx.FlowID), refs, false)+ storeDir := resources.ResourcesDir(fw.cfg.DataDir)+ return flowfiles.CopyResourcesToFlow(fw.cfg.DataDir, storeDir, uint64(fw.flowCtx.FlowID), refs, false)}// pushResourcesToContainer pushes newly added resource files into the running primary container.@@ -706,13 +706,13 @@ func (fw *flowWorker) pushResourcesToContainer(ctx context.Context, addedPaths [if fw.docker == nil {return}- containerName := tools.PrimaryTerminalName(fw.flowCtx.FlowID)+ containerName := tools.PrimaryTerminalName(fw.cfg.TenantPrefix(), fw.flowCtx.FlowID)running, _ := fw.docker.IsContainerRunning(ctx, containerName)if !running {return}- resourcesDir := flowfiles.FlowResourcesDir(fw.dataDir, uint64(fw.flowCtx.FlowID))+ resourcesDir := flowfiles.FlowResourcesDir(fw.cfg.DataDir, uint64(fw.flowCtx.FlowID))for _, relPath := range addedPaths {fsRelPath := relPath[len(flowfiles.ResourcesDirName)+1:]absPath := resourcesDir + "/" + fsRelPath@@ -744,7 +744,7 @@ func (fw *flowWorker) publishResourceFileEvents(ctx context.Context, addedPathsreturn}- resourcesDir := flowfiles.FlowResourcesDir(fw.dataDir, uint64(fw.flowCtx.FlowID))+ resourcesDir := flowfiles.FlowResourcesDir(fw.cfg.DataDir, uint64(fw.flowCtx.FlowID))pub := fw.flowCtx.Publisherfor _, relPath := range addedPaths {fsRelPath := relPath[len(flowfiles.ResourcesDirName)+1:]diff --git a/backend/pkg/docker/client.go b/backend/pkg/docker/client.goindex 972b9eda..43f6d12b 100644--- a/backend/pkg/docker/client.go+++ b/backend/pkg/docker/client.go@@ -30,9 +30,11 @@ import ("golang.org/x/sync/errgroup")-const WorkFolderPathInContainer = "/work"--const BaseContainerPortsNumber = 28000+const (+ WorkFolderPathInContainer = "/work"+ WorkerVolumeNameSuffix = "-data"+ BaseContainerPortsNumber = 28000+)const (defaultImage = "debian:latest"@@ -53,16 +55,18 @@ const ()type dockerClient struct {- db database.Querier- logger *logrus.Logger- dataDir string- hostDir string- client *client.Client- inside bool- defImage string- socket string- network string- publicIP string+ db database.Querier+ logger *logrus.Logger+ dataDir string+ hostDir string+ client *client.Client+ inside bool+ defImage string+ socket string+ network string+ publicIP string+ portsBase int+ labels map[string]string}type DockerClient interface {@@ -82,11 +86,16 @@ type DockerClient interface {GetDefaultImage() string}-func GetPrimaryContainerPorts(flowID int64) []int {+// GetPrimaryContainerPorts returns the host ports for a flow relative to+// portsBase. A portsBase of 0 falls back to BaseContainerPortsNumber.+func GetPrimaryContainerPorts(portsBase int, flowID int64) []int {+ if portsBase <= 0 || portsBase > (65535-limitContainerPortsNumber) {+ portsBase = BaseContainerPortsNumber+ }ports := make([]int, containerPortsNumber)- for i := 0; i < containerPortsNumber; i++ {+ for i := range containerPortsNumber {delta := (int(flowID)*containerPortsNumber + i) % limitContainerPortsNumber- ports[i] = BaseContainerPortsNumber + delta+ ports[i] = portsBase + delta}return ports}@@ -124,12 +133,6 @@ func NewDockerClient(ctx context.Context, db database.Querier, cfg *config.ConfidefImage = defaultImage}- // TODO: if this process running in a docker container, we need to use the host machine's data directory- // maybe there need to resolve the data directory path from volume list- // or maybe need to sync files from container to host machine- // or disable passing data directory to the container- // or create temporary volume for each container-dataDir, err := filepath.Abs(cfg.DataDir)if err != nil {return nil, fmt.Errorf("failed to get absolute path: %w", err)@@ -160,16 +163,18 @@ func NewDockerClient(ctx context.Context, db database.Querier, cfg *config.Confi}).Debug("Docker client initialized")return &dockerClient{- db: db,- client: cli,- dataDir: dataDir,- hostDir: hostDir,- logger: logger,- inside: inside,- defImage: defImage,- socket: socket,- network: netName,- publicIP: publicIP,+ db: db,+ client: cli,+ dataDir: dataDir,+ hostDir: hostDir,+ logger: logger,+ inside: inside,+ defImage: defImage,+ socket: socket,+ network: netName,+ publicIP: publicIP,+ portsBase: cfg.DockerPortsBase,+ labels: cfg.TenantLabels(),}, nil}@@ -262,6 +267,16 @@ func (dc *dockerClient) RunContainer(config.Hostname = fmt.Sprintf("%08x", crc32.ChecksumIEEE([]byte(containerName)))config.WorkingDir = WorkFolderPathInContainer+ // Tag the container with its owning tenant so daemon-wide sweeps can filter on+ // ownership rather than matching name prefixes. Absent when no tenant is+ // configured, keeping the created container byte-identical to before.+ for k, v := range dc.labels {+ if config.Labels == nil {+ config.Labels = make(map[string]string, len(dc.labels))+ }+ config.Labels[k] = v+ }+if hostConfig == nil {hostConfig = &container.HostConfig{}}@@ -275,8 +290,9 @@ func (dc *dockerClient) RunContainer(if hostDir == "" {volumeName, err := dc.client.VolumeCreate(ctx, volume.CreateOptions{- Name: fmt.Sprintf("%s-data", containerName),+ Name: fmt.Sprintf("%s%s", containerName, WorkerVolumeNameSuffix),Driver: "local",+ Labels: dc.labels,})if err != nil {return database.Container{}, fmt.Errorf("failed to create volume: %w", err)@@ -333,7 +349,7 @@ func (dc *dockerClient) RunContainer(if config.ExposedPorts == nil {config.ExposedPorts = nat.PortSet{}}- for _, port := range GetPrimaryContainerPorts(flowID) {+ for _, port := range GetPrimaryContainerPorts(dc.portsBase, flowID) {natPort := nat.Port(fmt.Sprintf("%d/tcp", port))hostConfig.PortBindings[natPort] = []nat.PortBinding{{diff --git a/backend/pkg/graph/schema.resolvers.go b/backend/pkg/graph/schema.resolvers.goindex 9eb0d6cf..c37a64f9 100644--- a/backend/pkg/graph/schema.resolvers.go+++ b/backend/pkg/graph/schema.resolvers.go@@ -788,7 +788,7 @@ func (r *mutationResolver) CreateAPIToken(ctx context.Context, input model.Creatclaims := auth.MakeAPITokenClaims(tokenID, user.Hash, uint64(uid), uint64(user.RoleID), uint64(input.TTL))- tokenString, err := auth.MakeAPIToken(r.Config.CookieSigningSalt, claims)+ tokenString, err := auth.MakeAPIToken(r.Config.AuthSalt(), claims)if err != nil {return nil, fmt.Errorf("failed to create token: %w", err)}diff --git a/backend/pkg/observability/langfuse/observer.go b/backend/pkg/observability/langfuse/observer.goindex f54eb955..bfd6d3e4 100644--- a/backend/pkg/observability/langfuse/observer.go+++ b/backend/pkg/observability/langfuse/observer.go@@ -35,18 +35,19 @@ type enqueue interface {}type observer struct {- mx *sync.Mutex- wg *sync.WaitGroup- ctx context.Context- cancel context.CancelFunc- client *Client- project string- release string- interval time.Duration- timeout time.Duration- queueSize int- queue chan *api.IngestionEvent- flusher chan chan error+ mx *sync.Mutex+ wg *sync.WaitGroup+ ctx context.Context+ cancel context.CancelFunc+ client *Client+ project string+ release string+ environment string+ interval time.Duration+ timeout time.Duration+ queueSize int+ queue chan *api.IngestionEvent+ flusher chan chan error}func NewObserver(client *Client, opts ...ObserverOption) Observer {@@ -287,18 +288,19 @@ func (o *observer) putTraceInfo(obsCtx ObservationContext) {Timestamp: getCurrentTimeString(),Type: api.IngestionEventZeroType(ingestionCreateTrace).Ptr(),Body: &api.TraceBody{- ID: getStringRef(obsCtx.TraceID),- Timestamp: obsCtx.TraceCtx.Timestamp,- Name: obsCtx.TraceCtx.Name,- UserID: obsCtx.TraceCtx.UserID,- Input: obsCtx.TraceCtx.Input,- Output: obsCtx.TraceCtx.Output,- SessionID: obsCtx.TraceCtx.SessionID,- Release: getStringRef(o.release),- Version: obsCtx.TraceCtx.Version,- Metadata: obsCtx.TraceCtx.Metadata,- Tags: obsCtx.TraceCtx.Tags,- Public: obsCtx.TraceCtx.Public,+ ID: getStringRef(obsCtx.TraceID),+ Timestamp: obsCtx.TraceCtx.Timestamp,+ Name: obsCtx.TraceCtx.Name,+ UserID: obsCtx.TraceCtx.UserID,+ Input: obsCtx.TraceCtx.Input,+ Output: obsCtx.TraceCtx.Output,+ SessionID: obsCtx.TraceCtx.SessionID,+ Release: getStringRef(o.release),+ Version: obsCtx.TraceCtx.Version,+ Metadata: obsCtx.TraceCtx.Metadata,+ Tags: obsCtx.TraceCtx.Tags,+ Public: obsCtx.TraceCtx.Public,+ Environment: getStringRef(o.environment),},}}diff --git a/backend/pkg/observability/langfuse/options.go b/backend/pkg/observability/langfuse/options.goindex 8284d5af..f29affb5 100644--- a/backend/pkg/observability/langfuse/options.go+++ b/backend/pkg/observability/langfuse/options.go@@ -16,6 +16,12 @@ func WithRelease(release string) ObserverOption {}}+func WithEnvironment(environment string) ObserverOption {+ return func(o *observer) {+ o.environment = environment+ }+}+func WithSendInterval(interval time.Duration) ObserverOption {return func(o *observer) {o.interval = intervaldiff --git a/backend/pkg/observability/lfclient.go b/backend/pkg/observability/lfclient.goindex e4d2ce28..8bd3f41a 100644--- a/backend/pkg/observability/lfclient.go+++ b/backend/pkg/observability/lfclient.go@@ -102,6 +102,7 @@ func NewLangfuseClient(ctx context.Context, cfg *config.Config) (LangfuseClient,langfuse.WithQueueSize(DefaultQueueSize),langfuse.WithProject(cfg.LangfuseProjectID),langfuse.WithRelease(version.GetBinaryVersion()),+ langfuse.WithEnvironment(cfg.TenantID),)return &langfuseClient{diff --git a/backend/pkg/observability/otelclient.go b/backend/pkg/observability/otelclient.goindex 5c737f24..6a42c9b7 100644--- a/backend/pkg/observability/otelclient.go+++ b/backend/pkg/observability/otelclient.go@@ -138,7 +138,7 @@ func NewTelemetryClient(ctx context.Context, cfg *config.Config) (TelemetryCliensdklog.WithExportInterval(DefaultLogInterval),sdklog.WithExportTimeout(DefaultLogTimeout),)),- sdklog.WithResource(newResource()),+ sdklog.WithResource(newResource(resourceAttrs(cfg)...)),)meterProvider := sdkmetric.NewMeterProvider(@@ -147,7 +147,7 @@ func NewTelemetryClient(ctx context.Context, cfg *config.Config) (TelemetryCliensdkmetric.WithInterval(DefaultMetricInterval),sdkmetric.WithTimeout(DefaultMetricTimeout),)),- sdkmetric.WithResource(newResource()),+ sdkmetric.WithResource(newResource(resourceAttrs(cfg)...)),)tracerProvider := sdktrace.NewTracerProvider(@@ -156,7 +156,7 @@ func NewTelemetryClient(ctx context.Context, cfg *config.Config) (TelemetryCliensdktrace.WithBatchTimeout(DefaultTraceInterval),sdktrace.WithExportTimeout(DefaultTraceTimeout),)),- sdktrace.WithResource(newResource()),+ sdktrace.WithResource(newResource(resourceAttrs(cfg)...)),)return &telemetryClient{@@ -167,12 +167,33 @@ func NewTelemetryClient(ctx context.Context, cfg *config.Config) (TelemetryClien}, nil}-func newResource(opts ...attribute.KeyValue) *resource.Resource {+func resourceAttrs(cfg *config.Config) []attribute.KeyValue {var env = "production"if version.IsDevelopMode() {env = "development"}+ if cfg == nil {+ return []attribute.KeyValue{+ attribute.String("environment", env),+ }+ }++ attrs := []attribute.KeyValue{+ semconv.ServiceInstanceID(cfg.InstallationID),+ }++ if !cfg.HasTenant() {+ return append(attrs, attribute.String("environment", env))+ }++ return append(attrs,+ attribute.String("environment", cfg.TenantID),+ attribute.String("tenant_id", cfg.TenantID),+ )+}++func newResource(opts ...attribute.KeyValue) *resource.Resource {service := version.GetBinaryName()verRev := strings.Split(version.GetBinaryVersion(), "-")version := strings.TrimPrefix(verRev[0], "v")@@ -180,7 +201,6 @@ func newResource(opts ...attribute.KeyValue) *resource.Resource {opts = append(opts,semconv.ServiceName(service),semconv.ServiceVersion(version),- attribute.String("environment", env),)return resource.NewWithAttributes(diff --git a/backend/pkg/observability/profiling/profiling.go b/backend/pkg/observability/profiling/profiling.goindex f5ce630c..d9eab9b7 100644--- a/backend/pkg/observability/profiling/profiling.go+++ b/backend/pkg/observability/profiling/profiling.go@@ -7,9 +7,16 @@ import ("github.com/sirupsen/logrus")-const profilerAddress = ":7777"+// DefaultProfilerAddress is the historical listen address, used when Start is+// called with an empty address.+const DefaultProfilerAddress = ":7777"++func Start(addr string) {+ profilerAddress := addr+ if profilerAddress == "" {+ profilerAddress = DefaultProfilerAddress+ }-func Start() {router := http.NewServeMux()router.HandleFunc("/profiler/", pprof.Index)router.HandleFunc("/profiler/profile", pprof.Profile)diff --git a/backend/pkg/providers/helpers.go b/backend/pkg/providers/helpers.goindex 1445e575..3e126a16 100644--- a/backend/pkg/providers/helpers.go+++ b/backend/pkg/providers/helpers.go@@ -861,13 +861,13 @@ func (fp *flowProvider) subtasksToMarkdown(subtasks []tools.SubtaskInfo) string}func (fp *flowProvider) getContainerPortsDescription() string {- ports := docker.GetPrimaryContainerPorts(fp.flowID)+ ports := docker.GetPrimaryContainerPorts(fp.cfg.WorkerPortsBase(), fp.flowID)var buffer strings.Builderbuffer.WriteString("**OOB Attack Infrastructure:**\n\n")// Host network mode: container has direct access to host network interfaces- if fp.dockerNetwork == "host" {+ if fp.cfg.WorkerNetwork() == "host" {buffer.WriteString("This container uses **host network mode** with direct access to host network interfaces.\n\n")buffer.WriteString("**MANDATORY PORTS - YOU MUST USE ONLY THESE:**\n\n")@@ -883,14 +883,14 @@ func (fp *flowProvider) getContainerPortsDescription() string {buffer.WriteString("- All host network interfaces are accessible for binding\n\n")buffer.WriteString("**Usage for OOB Attacks:**\n")- if fp.publicIP == "0.0.0.0" {+ if fp.cfg.WorkerPublicIP() == "0.0.0.0" {buffer.WriteString("To determine the public IP for callbacks:\n")buffer.WriteString("1. Discover your public IP: `curl -s https://api.ipify.org` or `curl -s ipinfo.io/ip`\n")buffer.WriteString("2. Use discovered IP in exploit payloads for callbacks\n")buffer.WriteString("3. Listen on allocated ports (shown above) to receive connections\n\n")buffer.WriteString("**Important:** Check Task.Input - user may have specified the public IP to use.\n")} else {- buffer.WriteString(fmt.Sprintf("Your external IP is: **%s**\n\n", fp.publicIP))+ buffer.WriteString(fmt.Sprintf("Your external IP is: **%s**\n\n", fp.cfg.WorkerPublicIP()))buffer.WriteString("Use this IP in exploit payloads requiring callbacks (DNS exfiltration, reverse shells, XXE OOB, SSRF verification, etc.)\n")buffer.WriteString("Listen on the allocated ports above to receive incoming connections.\n")}@@ -899,7 +899,7 @@ func (fp *flowProvider) getContainerPortsDescription() string {buffer.WriteString("**MANDATORY FORWARDED PORTS - YOU MUST USE ONLY THESE:**\n\n")for _, port := range ports {- buffer.WriteString(fmt.Sprintf("- Port %d/tcp (container) → %s:%d (external)\n", port, fp.publicIP, port))+ buffer.WriteString(fmt.Sprintf("- Port %d/tcp (container) → %s:%d (external)\n", port, fp.cfg.WorkerPublicIP(), port))}buffer.WriteString("\n**Port Usage Rules:**\n")@@ -910,14 +910,14 @@ func (fp *flowProvider) getContainerPortsDescription() string {buffer.WriteString("**Usage for OOB Attacks:**\n")- if fp.publicIP == "0.0.0.0" {+ if fp.cfg.WorkerPublicIP() == "0.0.0.0" {buffer.WriteString("The bind IP is 0.0.0.0 (all interfaces). To receive external callbacks:\n")buffer.WriteString("1. Discover your public IP: `curl -s https://api.ipify.org` or `curl -s ipinfo.io/ip`\n")buffer.WriteString("2. Use discovered IP in exploit payloads for callbacks\n")buffer.WriteString("3. Listen on container ports (shown above) to receive connections\n\n")buffer.WriteString("**Important:** Check Task.Input - user may have specified the public IP to use.\n")} else {- buffer.WriteString(fmt.Sprintf("Your external IP is: %s\n", fp.publicIP))+ buffer.WriteString(fmt.Sprintf("Your external IP is: %s\n", fp.cfg.WorkerPublicIP()))buffer.WriteString("Use this IP in exploit payloads requiring callbacks (DNS exfiltration, reverse shells, XXE OOB, SSRF verification, etc.)\n")buffer.WriteString("Listen on the container ports above to receive incoming connections.\n")}diff --git a/backend/pkg/providers/helpers_test.go b/backend/pkg/providers/helpers_test.goindex b5d3bb25..2b483487 100644--- a/backend/pkg/providers/helpers_test.go+++ b/backend/pkg/providers/helpers_test.go@@ -11,6 +11,7 @@ import ("testing""pentagi/pkg/cast"+ "pentagi/pkg/config""github.com/stretchr/testify/assert""github.com/vxcontrol/langchaingo/llms"@@ -201,7 +202,7 @@ func cloneChain(chain []llms.MessageContent) []llms.MessageContent {func newFlowProvider() *flowProvider {return &flowProvider{mx: &sync.RWMutex{},- dataDir: "testdata",+ cfg: &config.Config{DataDir: "testdata"},summarizerCache: newSummarizerCache(),callCounter: &atomic.Int64{},maxGACallsLimit: maxGeneralAgentChainIterations,diff --git a/backend/pkg/providers/performer.go b/backend/pkg/providers/performer.goindex 2ed993cf..c1c990aa 100644--- a/backend/pkg/providers/performer.go+++ b/backend/pkg/providers/performer.go@@ -83,7 +83,7 @@ func (fp *flowProvider) performAgentChain(return fmt.Errorf("failed to get execution context: %w", err)}- groupID := fmt.Sprintf("flow-%d", fp.flowID)+ groupID := fp.cfg.GroupID(fp.flowID)toolTypeMapping := tools.GetToolTypeMapping()var maxCallsLimit intdiff --git a/backend/pkg/providers/provider.go b/backend/pkg/providers/provider.goindex b1aab2ad..019faada 100644--- a/backend/pkg/providers/provider.go+++ b/backend/pkg/providers/provider.go@@ -9,6 +9,7 @@ import ("sync/atomic""pentagi/pkg/cast"+ "pentagi/pkg/config""pentagi/pkg/csum""pentagi/pkg/database""pentagi/pkg/docker"@@ -131,13 +132,12 @@ type flowProvider struct {db database.Queriermx *sync.RWMutex+ cfg *config.Config+embedder embeddings.EmbeddergraphitiClient *graphiti.Client- flowID int64- dataDir string- publicIP string- dockerNetwork string+ flowID int64callCounter *atomic.Int64@@ -229,10 +229,10 @@ func (fp *flowProvider) Title() string {// userFilesListing returns the compact XML listing of user files in uploads/ and resources/// for injection into agent system prompts. Returns empty string if no files are present.func (fp *flowProvider) userFilesListing() string {- if fp.dataDir == "" {+ if fp.cfg == nil || fp.cfg.DataDir == "" {return ""}- return flowfiles.FileListingForPrompt(fp.dataDir, uint64(fp.flowID))+ return flowfiles.FileListingForPrompt(fp.cfg.DataDir, uint64(fp.flowID))}func (fp *flowProvider) SetTitle(title string) {diff --git a/backend/pkg/providers/providers.go b/backend/pkg/providers/providers.goindex b5d78463..f6a11387 100644--- a/backend/pkg/providers/providers.go+++ b/backend/pkg/providers/providers.go@@ -140,15 +140,11 @@ type providerController struct {db database.Queriercfg *config.Configdocker docker.DockerClient- publicIP string- dockerNetwork stringembedder embeddings.EmbeddergraphitiClient *graphiti.ClientstartCallNumber *atomic.Int64- defaultDockerImageForPentest string-summarizerAgent csum.SummarizersummarizerAssistant csum.Summarizer@@ -256,15 +252,11 @@ func NewProviderController(db: db,cfg: cfg,docker: docker,- publicIP: cfg.DockerPublicIP,- dockerNetwork: cfg.DockerNetwork,embedder: embedder,graphitiClient: graphitiClient,startCallNumber: newAtomicInt64(0), // 0 means to make it random- defaultDockerImageForPentest: cfg.DockerDefaultImageForPentest,-summarizerAgent: summarizerAgent,summarizerAssistant: summarizerAssistant,@@ -311,7 +303,7 @@ func (pc *providerController) NewFlowProvider(imageTmpl, err := prompter.RenderTemplate(templates.PromptTypeImageChooser, map[string]any{"DefaultImage": pc.docker.GetDefaultImage(),- "DefaultImageForPentest": pc.defaultDockerImageForPentest,+ "DefaultImageForPentest": pc.cfg.DockerDefaultImageForPentest,"Input": input,})if err != nil {@@ -361,12 +353,10 @@ func (pc *providerController) NewFlowProvider(fp := &flowProvider{db: pc.db,mx: &sync.RWMutex{},+ cfg: pc.cfg,embedder: pc.embedder,graphitiClient: pc.graphitiClient,flowID: flowID,- dataDir: pc.cfg.DataDir,- publicIP: pc.publicIP,- dockerNetwork: pc.dockerNetwork,callCounter: newAtomicInt64(pc.startCallNumber.Add(deltaCallCounter)),image: image,title: title,@@ -413,12 +403,10 @@ func (pc *providerController) LoadFlowProvider(fp := &flowProvider{db: pc.db,mx: &sync.RWMutex{},+ cfg: pc.cfg,embedder: pc.embedder,graphitiClient: pc.graphitiClient,flowID: flowID,- dataDir: pc.cfg.DataDir,- publicIP: pc.publicIP,- dockerNetwork: pc.dockerNetwork,callCounter: newAtomicInt64(pc.startCallNumber.Add(deltaCallCounter)),image: image,title: title,@@ -510,12 +498,10 @@ func (pc *providerController) NewAssistantProvider(fp: flowProvider{db: pc.db,mx: &sync.RWMutex{},+ cfg: pc.cfg,embedder: pc.embedder,graphitiClient: pc.graphitiClient,flowID: flowID,- dataDir: pc.cfg.DataDir,- publicIP: pc.publicIP,- dockerNetwork: pc.dockerNetwork,callCounter: newAtomicInt64(pc.startCallNumber.Add(deltaCallCounter)),image: image,title: title,@@ -565,12 +551,10 @@ func (pc *providerController) LoadAssistantProvider(fp: flowProvider{db: pc.db,mx: &sync.RWMutex{},+ cfg: pc.cfg,embedder: pc.embedder,graphitiClient: pc.graphitiClient,flowID: flowID,- dataDir: pc.cfg.DataDir,- publicIP: pc.publicIP,- dockerNetwork: pc.dockerNetwork,callCounter: newAtomicInt64(pc.startCallNumber.Add(deltaCallCounter)),image: image,title: title,diff --git a/backend/pkg/server/router.go b/backend/pkg/server/router.goindex e698966d..d2449207 100644--- a/backend/pkg/server/router.go+++ b/backend/pkg/server/router.go@@ -98,7 +98,7 @@ func NewRouter(tokenCache := auth.NewTokenCache(orm)userCache := auth.NewUserCache(orm)- authMiddleware := auth.NewAuthMiddleware(baseURL, cfg.CookieSigningSalt, tokenCache, userCache)+ authMiddleware := auth.NewAuthMiddleware(baseURL, cfg.AuthSalt(), tokenCache, userCache)oauthClients := make(map[string]oauth.OAuthClient)oauthLoginCallbackURL := "/auth/login-callback"@@ -172,6 +172,7 @@ func NewRouter(BaseURL: baseURL,LoginCallbackURL: oauthLoginCallbackURL,SessionTimeout: 4 * 60 * 60, // 4 hours+ CookiePrefix: cfg.TenantPrefix(),},orm,oauthClients,@@ -181,7 +182,7 @@ func NewRouter(providerService := services.NewProviderService(providers)settingsService := services.NewSettingsService(cfg)flowService := services.NewFlowService(orm, providers, controller, subscriptions)- flowFileService := services.NewFlowFileService(orm, cfg.DataDir, dockerClient, subscriptions)+ flowFileService := services.NewFlowFileService(orm, cfg.DataDir, cfg.TenantPrefix(), dockerClient, subscriptions)resourceService := services.NewResourceService(orm, cfg.DataDir, subscriptions)taskService := services.NewTaskService(orm)subtaskService := services.NewSubtaskService(orm)@@ -197,7 +198,7 @@ func NewRouter(screenshotService := services.NewScreenshotService(orm, cfg.DataDir)promptService := services.NewPromptService(orm)analyticsService := services.NewAnalyticsService(orm)- tokenService := services.NewTokenService(orm, cfg.CookieSigningSalt, tokenCache, subscriptions)+ tokenService := services.NewTokenService(orm, cfg.AuthSalt(), tokenCache, subscriptions)knowledgeService := services.NewKnowledgeService(orm, knowledgeStore)anonymizerService := services.NewAnonymizerService(textReplacer)graphqlService := services.NewGraphqlService(@@ -238,8 +239,13 @@ func NewRouter(router.Use(gin.Recovery())router.Use(logger.WithGinLogger("pentagi-api"))- cookieStore := cookie.NewStore(auth.MakeCookieStoreKey(cfg.CookieSigningSalt)...)- router.Use(sessions.Sessions("auth", cookieStore))+ // AuthSalt mixes TENANT_ID into the key derivation so a session minted by one+ // instance is cryptographically invalid on another even when COOKIE_SIGNING_SALT+ // is shared. ScopedName separates the cookie itself, because cookies are scoped+ // by host and NOT by port — two instances on one host would otherwise overwrite+ // each other's sessions. Both are identity operations when TENANT_ID is empty.+ cookieStore := cookie.NewStore(auth.MakeCookieStoreKey(cfg.AuthSalt())...)+ router.Use(sessions.Sessions(cfg.ScopedName("auth"), cookieStore))api := router.Group(baseURL)api.Use(noCacheMiddleware())diff --git a/backend/pkg/server/services/auth.go b/backend/pkg/server/services/auth.goindex 558af8cb..3f91aa98 100644--- a/backend/pkg/server/services/auth.go+++ b/backend/pkg/server/services/auth.go@@ -42,6 +42,22 @@ type AuthServiceConfig struct {BaseURL stringLoginCallbackURL stringSessionTimeout int // in seconds++ // CookiePrefix namespaces the OAuth CSRF cookies for this instance. Cookies+ // are scoped by host and not by port, so two instances on one host would+ // otherwise clobber each other's in-flight OAuth handshakes. Empty in+ // single-instance mode, which keeps the cookie names exactly "state"/"nonce".+ CookiePrefix string+}++// stateCookieName returns the tenant-scoped name of the OAuth CSRF state cookie.+func (s *AuthService) stateCookieName() string {+ return s.cfg.CookiePrefix + authStateCookieName+}++// nonceCookieName returns the tenant-scoped name of the OIDC nonce cookie.+func (s *AuthService) nonceCookieName() string {+ return s.cfg.CookiePrefix + authNonceCookieName}type AuthService struct {@@ -296,8 +312,8 @@ func (s *AuthService) AuthAuthorize(c *gin.Context) {}maxAge := int(authStateRequestTTL / time.Second)- s.setCallbackCookie(c.Writer, c.Request, authStateCookieName, state, maxAge, sameSiteMode)- s.setCallbackCookie(c.Writer, c.Request, authNonceCookieName, nonce, maxAge, sameSiteMode)+ s.setCallbackCookie(c.Writer, c.Request, s.stateCookieName(), state, maxAge, sameSiteMode)+ s.setCallbackCookie(c.Writer, c.Request, s.nonceCookieName(), nonce, maxAge, sameSiteMode)authOpts := []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("nonce", nonce),@@ -328,7 +344,7 @@ func (s *AuthService) AuthLoginGetCallback(c *gin.Context) {return}- state, err := c.Request.Cookie(authStateCookieName)+ state, err := c.Request.Cookie(s.stateCookieName())if err != nil {logger.FromContext(c).WithError(err).Errorf("error getting state from cookie")response.Error(c, response.ErrAuthInvalidAuthorizationState, err)@@ -383,7 +399,7 @@ func (s *AuthService) AuthLoginPostCallback(c *gin.Context) {return}- state, err := c.Request.Cookie(authStateCookieName)+ state, err := c.Request.Cookie(s.stateCookieName())if err != nil {logger.FromContext(c).WithError(err).Errorf("error getting state from cookie")response.Error(c, response.ErrAuthInvalidAuthorizationState, err)@@ -476,7 +492,7 @@ func (s *AuthService) authLoginCallback(c *gin.Context, stateData map[string]strreturn}- nonce, err := c.Request.Cookie(authNonceCookieName)+ nonce, err := c.Request.Cookie(s.nonceCookieName())if err != nil {logger.FromContext(c).WithError(err).Errorf("error getting nonce from cookie")response.Error(c, response.ErrAuthInvalidAuthorizationNonce, err)@@ -618,8 +634,8 @@ func (s *AuthService) authLoginCallback(c *gin.Context, stateData map[string]strif stateData["provider"] == "google" {sameSiteMode = http.SameSiteNoneMode}- s.setCallbackCookie(c.Writer, c.Request, authStateCookieName, "", 0, sameSiteMode)- s.setCallbackCookie(c.Writer, c.Request, authNonceCookieName, "", 0, sameSiteMode)+ s.setCallbackCookie(c.Writer, c.Request, s.stateCookieName(), "", 0, sameSiteMode)+ s.setCallbackCookie(c.Writer, c.Request, s.nonceCookieName(), "", 0, sameSiteMode)logger.FromContext(c).WithFields(logrus.Fields{diff --git a/backend/pkg/server/services/flow_files.go b/backend/pkg/server/services/flow_files.goindex 59baaa59..c6d5ba4a 100644--- a/backend/pkg/server/services/flow_files.go+++ b/backend/pkg/server/services/flow_files.go@@ -55,6 +55,7 @@ type pendingUpload struct {// - container sync → {dataDir}/flow-{id}-data/container/ (pulled from container, never sent back)type FlowFileService struct {dataDir string+ tenantPrefix stringdb *gorm.DBdockerClient docker.DockerClientss subscriptions.SubscriptionsController@@ -63,11 +64,13 @@ type FlowFileService struct {func NewFlowFileService(db *gorm.DB,dataDir string,+ tenantPrefix string,dockerClient docker.DockerClient,ss subscriptions.SubscriptionsController,) *FlowFileService {return &FlowFileService{dataDir: dataDir,+ tenantPrefix: tenantPrefix,db: db,dockerClient: dockerClient,ss: ss,@@ -723,7 +726,7 @@ func (s *FlowFileService) PullFlowFiles(c *gin.Context) {return}- containerName := primaryContainerName(flowID)+ containerName := primaryContainerName(s.tenantPrefix, flowID)running, err := s.dockerClient.IsContainerRunning(c.Request.Context(), containerName)if err != nil {logger.FromContext(c).WithError(err).WithFields(map[string]any{@@ -957,7 +960,7 @@ func (s *FlowFileService) GetFlowContainerFiles(c *gin.Context) {containerPaths = []string{docker.WorkFolderPathInContainer}}- containerName := primaryContainerName(flowID)+ containerName := primaryContainerName(s.tenantPrefix, flowID)running, err := s.dockerClient.IsContainerRunning(c.Request.Context(), containerName)if err != nil {logger.FromContext(c).WithError(err).WithFields(map[string]any{@@ -1234,7 +1237,7 @@ func (s *FlowFileService) copyLocalFilesToPrimaryWork(ctx context.Context, flowIreturn nil}- containerName := primaryContainerName(flowID)+ containerName := primaryContainerName(s.tenantPrefix, flowID)running, err := s.dockerClient.IsContainerRunning(ctx, containerName)if err != nil || !running {return nil@@ -1313,7 +1316,7 @@ func (s *FlowFileService) deleteUploadsFromContainer(ctx context.Context, flowIDreturn nil}- containerName := primaryContainerName(flowID)+ containerName := primaryContainerName(s.tenantPrefix, flowID)running, err := s.dockerClient.IsContainerRunning(ctx, containerName)if err != nil {return nil // container absent or unavailable — cache deletion will be synced on next start@@ -1521,8 +1524,12 @@ func sortFlowFiles(files []models.FlowFile) {}// primaryContainerName returns the Docker container name for a flow's primary terminal.-func primaryContainerName(flowID uint64) string {- return fmt.Sprintf("%s%d", tools.PrimaryTerminalNamePrefix, flowID)+//+// Delegates to tools.PrimaryTerminalName so there is exactly one definition of+// this name; the two used to be independent implementations that had to be kept+// in sync by hand.+func primaryContainerName(tenantPrefix string, flowID uint64) string {+ return tools.PrimaryTerminalName(tenantPrefix, int64(flowID))}// AddResourcesToFlow copies user-owned resources into the flow resources directory.diff --git a/backend/pkg/server/services/flow_files_partial_test.go b/backend/pkg/server/services/flow_files_partial_test.goindex 8578438f..b185b2df 100644--- a/backend/pkg/server/services/flow_files_partial_test.go+++ b/backend/pkg/server/services/flow_files_partial_test.go@@ -39,7 +39,7 @@ func listContainerFiles(t *testing.T, fake *fakeDockerClient, query string) (*int.Helper()db := setupFlowFileServiceTestDB(t)seedFlow(t, db, 1, 1)- svc := NewFlowFileService(db, t.TempDir(), fake, nil)+ svc := NewFlowFileService(db, t.TempDir(), "", fake, nil)c, w := newFlowFileTestContext(http.MethodGet, "/flows/1/files/container?"+query, nil,[]string{"flow_files.view", "containers.view"}, 1, 1)svc.GetFlowContainerFiles(c)@@ -149,7 +149,7 @@ func TestGetFlowContainerFiles_TooManyPathsRejected(t *testing.T) {// One over the cap → 400 before any docker call.db := setupFlowFileServiceTestDB(t)seedFlow(t, db, 1, 1)- svc := NewFlowFileService(db, t.TempDir(), &fakeDockerClient{running: true}, nil)+ svc := NewFlowFileService(db, t.TempDir(), "", &fakeDockerClient{running: true}, nil)c, w := newFlowFileTestContext(http.MethodGet,"/flows/1/files/container?"+buildQuery(maxContainerListPaths+1), nil,[]string{"flow_files.view", "containers.view"}, 1, 1)diff --git a/backend/pkg/server/services/flow_files_test.go b/backend/pkg/server/services/flow_files_test.goindex 6044d2b9..d317090d 100644--- a/backend/pkg/server/services/flow_files_test.go+++ b/backend/pkg/server/services/flow_files_test.go@@ -109,7 +109,7 @@ func TestSanitizeContainerCachePath(t *testing.T) {// ── directory helpers ─────────────────────────────────────────────────────────func TestFlowFileService_Dirs(t *testing.T) {- svc := NewFlowFileService(nil, "/data", nil, nil)+ svc := NewFlowFileService(nil, "/data", "", nil, nil)assert.Equal(t, "/data/flow-42-data", svc.flowDataDir(42))assert.Equal(t, "/data/flow-42-data/uploads", svc.flowUploadsDir(42))assert.Equal(t, "/data/flow-42-data/container", svc.flowContainerDir(42))@@ -124,7 +124,7 @@ func TestMaxUploadFileSize(t *testing.T) {// ── resolveCachedPath ─────────────────────────────────────────────────────────func TestResolveCachedPath(t *testing.T) {- svc := NewFlowFileService(nil, "/data", nil, nil)+ svc := NewFlowFileService(nil, "/data", "", nil, nil)tests := []struct {name string@@ -222,7 +222,7 @@ func TestListDirEntriesRecursive_PreservesNestedPaths(t *testing.T) {func TestFlowFileService_ListFlowFiles_BothSources(t *testing.T) {dataDir := t.TempDir()- svc := NewFlowFileService(nil, dataDir, nil, nil)+ svc := NewFlowFileService(nil, dataDir, "", nil, nil)uploadsDir := filepath.Join(dataDir, "flow-7-data", "uploads")containerDir := filepath.Join(dataDir, "flow-7-data", "container")@@ -251,7 +251,7 @@ func TestFlowFileService_ListFlowFiles_BothSources(t *testing.T) {}func TestFlowFileService_ListFlowFiles_EmptyDirs(t *testing.T) {- svc := NewFlowFileService(nil, t.TempDir(), nil, nil)+ svc := NewFlowFileService(nil, t.TempDir(), "", nil, nil)files, err := svc.listFlowFiles(999)require.NoError(t, err)assert.Empty(t, files)@@ -496,7 +496,7 @@ func TestZipDirectory_ExcludesSymlinks(t *testing.T) {// ── primaryContainerName ─────────────────────────────────────────────────────func TestPrimaryContainerName(t *testing.T) {- assert.Equal(t, "pentagi-terminal-42", primaryContainerName(42))+ assert.Equal(t, "pentagi-terminal-42", primaryContainerName("", 42))}// ── sorting ───────────────────────────────────────────────────────────────────@@ -1211,7 +1211,7 @@ func TestFlowFileService_GetFlowFilesScenarios(t *testing.T) {db := setupFlowFileServiceTestDB(t)dataDir := t.TempDir()ss := &flowFileCaptureSubscriptions{}- svc := NewFlowFileService(db, dataDir, nil, ss)+ svc := NewFlowFileService(db, dataDir, "", nil, ss)if tt.seedFlow != nil {seedFlow(t, db, tt.seedFlow.id, tt.seedFlow.userID)@@ -1377,7 +1377,7 @@ func TestFlowFileService_UploadFlowFilesScenarios(t *testing.T) {dataDir := t.TempDir()ss := &flowFileCaptureSubscriptions{}fakeDocker := &fakeDockerClient{running: tt.dockerRunning}- svc := NewFlowFileService(db, dataDir, fakeDocker, ss)+ svc := NewFlowFileService(db, dataDir, "", fakeDocker, ss)if tt.flowOwner != 0 {seedFlow(t, db, tt.flowID, tt.flowOwner)@@ -1570,7 +1570,7 @@ func TestFlowFileService_UploadFlowFilesPathTraversalSecurity(t *testing.T) {db := setupFlowFileServiceTestDB(t)dataDir := t.TempDir()ss := &flowFileCaptureSubscriptions{}- svc := NewFlowFileService(db, dataDir, nil, ss)+ svc := NewFlowFileService(db, dataDir, "", nil, ss)seedFlow(t, db, 1, 1)body, contentType := flowFileMultipartBody(t,@@ -2077,7 +2077,7 @@ func TestFlowFileService_DeleteFlowFileScenarios(t *testing.T) {execCreateErr: tt.execCreateErr,execInspectCode: tt.execInspectCode,}- svc := NewFlowFileService(db, dataDir, fakeDocker, ss)+ svc := NewFlowFileService(db, dataDir, "", fakeDocker, ss)if tt.seedFlow {owner := tt.flowOwner@@ -2477,7 +2477,7 @@ func TestFlowFileService_DownloadFlowFileScenarios(t *testing.T) {t.Run(tt.name, func(t *testing.T) {db := setupFlowFileServiceTestDB(t)dataDir := t.TempDir()- svc := NewFlowFileService(db, dataDir, nil, nil)+ svc := NewFlowFileService(db, dataDir, "", nil, nil)if tt.flowOwner != 0 {seedFlow(t, db, tt.flowID, tt.flowOwner)@@ -2937,7 +2937,7 @@ func TestFlowFileService_PullFlowFilesScenarios(t *testing.T) {if !tt.dockerNil {dockerClient = fakeDocker}- svc := NewFlowFileService(db, dataDir, dockerClient, ss)+ svc := NewFlowFileService(db, dataDir, "", dockerClient, ss)seedFlow(t, db, tt.flowID, tt.flowOwner)@@ -3389,7 +3389,7 @@ func TestFlowFileService_GetFlowContainerFilesScenarios(t *testing.T) {if !tt.dockerNil {dockerClient = fakeDocker}- svc := NewFlowFileService(db, dataDir, dockerClient, nil)+ svc := NewFlowFileService(db, dataDir, "", dockerClient, nil)if tt.flowOwner != 0 {seedFlow(t, db, tt.flowID, tt.flowOwner)@@ -3583,7 +3583,7 @@ func TestFlowFileService_AddResourcesToFlowScenarios(t *testing.T) {db := setupFlowFileServiceTestDB(t)dataDir := t.TempDir()ss := &flowFileCaptureSubscriptions{}- svc := NewFlowFileService(db, dataDir, nil, ss)+ svc := NewFlowFileService(db, dataDir, "", nil, ss)require.NoError(t, resources.EnsureResourcesDir(dataDir))if tt.flowOwner != 0 {@@ -4127,7 +4127,7 @@ func TestFlowFileService_AddResourceFromFlowScenarios(t *testing.T) {db := setupFlowFileServiceTestDB(t)dataDir := t.TempDir()ss := &flowFileCaptureSubscriptions{}- svc := NewFlowFileService(db, dataDir, nil, ss)+ svc := NewFlowFileService(db, dataDir, "", nil, ss)require.NoError(t, resources.EnsureResourcesDir(dataDir))if tt.flowOwner != 0 {diff --git a/backend/pkg/tools/graphiti_search.go b/backend/pkg/tools/graphiti_search.goindex fb9a8eaf..eef81adb 100644--- a/backend/pkg/tools/graphiti_search.go+++ b/backend/pkg/tools/graphiti_search.go@@ -118,6 +118,7 @@ type graphitiSearchTool struct {flowID int64taskID *int64subtaskID *int64+ groupID stringgraphitiClient GraphitiSearcher}@@ -125,12 +126,14 @@ type graphitiSearchTool struct {func NewGraphitiSearchTool(flowID int64,taskID, subtaskID *int64,+ groupID string,graphitiClient GraphitiSearcher,) Tool {return &graphitiSearchTool{flowID: flowID,taskID: taskID,subtaskID: subtaskID,+ groupID: groupID,graphitiClient: graphitiClient,}}@@ -168,8 +171,6 @@ func (t *graphitiSearchTool) Handle(ctx context.Context, name string, args json.return "", fmt.Errorf("search_type parameter is required")}- groupID := fmt.Sprintf("flow-%d", t.flowID)-ctx, observation := obs.Observer.NewObservation(ctx)retrieverTitle, ok := graphitiRetrieverTitles[searchArgs.SearchType.String()]@@ -179,12 +180,12 @@ func (t *graphitiSearchTool) Handle(ctx context.Context, name string, args json.retriever := observation.Retriever(langfuse.WithRetrieverName(retrieverTitle),- langfuse.WithRetrieverInput(searchArgs.retrieverInput(groupID)),+ langfuse.WithRetrieverInput(searchArgs.retrieverInput(t.groupID)),langfuse.WithRetrieverMetadata(langfuse.Metadata{"tool_name": name,"engine": "graphiti","search_type": searchArgs.SearchType,- "group_id": groupID,+ "group_id": t.groupID,"query": searchArgs.Query,}),)@@ -203,19 +204,19 @@ func (t *graphitiSearchTool) Handle(ctx context.Context, name string, args json.)switch searchArgs.SearchType {case "temporal_window":- result, err = t.handleTemporalWindowSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleTemporalWindowSearch(ctx, t.groupID, searchArgs, observationObject)case "entity_relationships":- result, err = t.handleEntityRelationshipsSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleEntityRelationshipsSearch(ctx, t.groupID, searchArgs, observationObject)case "diverse_results":- result, err = t.handleDiverseResultsSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleDiverseResultsSearch(ctx, t.groupID, searchArgs, observationObject)case "episode_context":- result, err = t.handleEpisodeContextSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleEpisodeContextSearch(ctx, t.groupID, searchArgs, observationObject)case "successful_tools":- result, err = t.handleSuccessfulToolsSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleSuccessfulToolsSearch(ctx, t.groupID, searchArgs, observationObject)case "recent_context":- result, err = t.handleRecentContextSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleRecentContextSearch(ctx, t.groupID, searchArgs, observationObject)case "entity_by_label":- result, err = t.handleEntityByLabelSearch(ctx, groupID, searchArgs, observationObject)+ result, err = t.handleEntityByLabelSearch(ctx, t.groupID, searchArgs, observationObject)default:err = fmt.Errorf("unknown search_type: %s", searchArgs.SearchType)}diff --git a/backend/pkg/tools/graphiti_search_test.go b/backend/pkg/tools/graphiti_search_test.goindex 5ac93e3e..5b82f395 100644--- a/backend/pkg/tools/graphiti_search_test.go+++ b/backend/pkg/tools/graphiti_search_test.go@@ -13,6 +13,8 @@ import ("pentagi/pkg/graphiti")+const testGroupID = "test-group"+// stubGraphitiSearcher is a minimal GraphitiSearcher test double: every method// returns whatever error/response was configured for it, so tests can exercise// the Handle() error-classification logic without a real Graphiti/Neo4j backend.@@ -98,7 +100,7 @@ func fakeStatusError(statusCode int, body string) error {}func TestGraphitiSearchTool_Handle_ServerError5xx_DegradesGracefullyWithBody(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true,err: fakeStatusError(502, "<html><body>502 Bad Gateway</body></html>"),})@@ -119,7 +121,7 @@ func TestGraphitiSearchTool_Handle_ServerError5xx_DegradesGracefullyWithBody(t *func TestGraphitiSearchTool_Handle_ServerError5xx_BodyTruncatedAt512Bytes(t *testing.T) {hugeBody := strings.Repeat("x", 2000)- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true,err: fakeStatusError(500, hugeBody),})@@ -140,7 +142,7 @@ func TestGraphitiSearchTool_Handle_ServerError5xx_BodyTruncatedAt512Bytes(t *tesfunc TestGraphitiSearchTool_Handle_ClientError4xx_StaysHardWithTruncatedBody(t *testing.T) {hugeBody := strings.Repeat("y", 2000)- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true,err: fakeStatusError(400, hugeBody),})@@ -160,7 +162,7 @@ func TestGraphitiSearchTool_Handle_ClientError4xx_StaysHardWithTruncatedBody(t *}func TestGraphitiSearchTool_Handle_NetworkFailure_DegradesGracefully(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true, err: fakeNetError()})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true, err: fakeNetError()})args := []byte(`{"search_type":"recent_context","query":"test query","message":"m"}`)result, err := tool.Handle(t.Context(), GraphitiSearchToolName, args)@@ -174,7 +176,7 @@ func TestGraphitiSearchTool_Handle_NetworkFailure_DegradesGracefully(t *testing.}func TestGraphitiSearchTool_Handle_ValidationError_StaysHard(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})// Invalid search_type never reaches the graphiti client - it is rejected by// Handle() itself, so this must remain a hard failure regardless of the@@ -188,7 +190,7 @@ func TestGraphitiSearchTool_Handle_ValidationError_StaysHard(t *testing.T) {}func TestGraphitiSearchTool_Handle_EntityByLabel_MissingNodeLabels_GivesActionableError(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})args := []byte(`{"search_type":"entity_by_label","query":"test query","message":"m"}`)_, err := tool.Handle(t.Context(), GraphitiSearchToolName, args)@@ -205,7 +207,7 @@ func TestGraphitiSearchTool_Handle_EntityByLabel_MissingNodeLabels_GivesActionab}func TestGraphitiSearchTool_Handle_EntityByLabel_WithNodeLabels_Succeeds(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})args := []byte(`{"search_type":"entity_by_label","query":"test query","node_labels":["Vulnerability"],"message":"m"}`)_, err := tool.Handle(t.Context(), GraphitiSearchToolName, args)@@ -216,7 +218,7 @@ func TestGraphitiSearchTool_Handle_EntityByLabel_WithNodeLabels_Succeeds(t *test}func TestGraphitiSearchTool_Handle_EntityRelationships_MissingCenterNodeUUID_StaysHard(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})args := []byte(`{"search_type":"entity_relationships","query":"test query","message":"m"}`)_, err := tool.Handle(t.Context(), GraphitiSearchToolName, args)@@ -227,7 +229,7 @@ func TestGraphitiSearchTool_Handle_EntityRelationships_MissingCenterNodeUUID_Sta}func TestGraphitiSearchTool_Handle_EntityRelationships_MalformedCenterNodeUUID_GivesActionableError(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})// Simulates a diagnostic string, truncated ID, or otherwise non-UUID value// ending up in center_node_uuid (e.g. a hallucinated or mangled value) -@@ -247,7 +249,7 @@ func TestGraphitiSearchTool_Handle_EntityRelationships_MalformedCenterNodeUUID_G}func TestGraphitiSearchTool_Handle_EntityRelationships_ValidCenterNodeUUID_Succeeds(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})args := []byte(`{"search_type":"entity_relationships","query":"test query","center_node_uuid":"f7b95dfc-ee58-4a8b-8d85-582cf117b4df","message":"m"}`)_, err := tool.Handle(t.Context(), GraphitiSearchToolName, args)@@ -285,7 +287,7 @@ func TestParseGraphitiTime(t *testing.T) {}func TestGraphitiSearchTool_Handle_TemporalWindow_MissingTimezone_Succeeds(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})// Reproduces the exact production near-miss: an LLM omitted the trailing// 'Z'/offset on an otherwise well-formed timestamp.@@ -298,7 +300,7 @@ func TestGraphitiSearchTool_Handle_TemporalWindow_MissingTimezone_Succeeds(t *te}func TestGraphitiSearchTool_Handle_TemporalWindow_GarbageTime_StaysHard(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})args := []byte(`{"search_type":"temporal_window","query":"test query","time_start":"not-a-date","time_end":"2026-07-25T11:53:34Z","message":"m"}`)_, err := tool.Handle(t.Context(), GraphitiSearchToolName, args)@@ -309,7 +311,7 @@ func TestGraphitiSearchTool_Handle_TemporalWindow_GarbageTime_StaysHard(t *testi}func TestGraphitiSearchTool_Handle_InvalidRecencyWindow_StaysHard(t *testing.T) {- tool := NewGraphitiSearchTool(1, nil, nil, &stubGraphitiSearcher{enabled: true})+ tool := NewGraphitiSearchTool(1, nil, nil, testGroupID, &stubGraphitiSearcher{enabled: true})// Argument-validation errors (not network errors) must still be treated as// hard failures so the tool-call arg-fixer can actually help here.diff --git a/backend/pkg/tools/terminal.go b/backend/pkg/tools/terminal.goindex 503feb4a..2e187344 100644--- a/backend/pkg/tools/terminal.go+++ b/backend/pkg/tools/terminal.go@@ -47,6 +47,7 @@ type terminal struct {subtaskID *int64containerID int64containerLID string+ tenantPrefix stringdockerClient docker.DockerClienttlp TermLogProviderdefaultExecTimeout time.Duration@@ -56,6 +57,7 @@ func NewTerminalTool(flowID int64,taskID, subtaskID *int64,containerID int64, containerLID string,+ tenantPrefix string,dockerClient docker.DockerClient,tlp TermLogProvider,defaultExecTimeout time.Duration,@@ -66,6 +68,7 @@ func NewTerminalTool(subtaskID: subtaskID,containerID: containerID,containerLID: containerLID,+ tenantPrefix: tenantPrefix,dockerClient: dockerClient,tlp: tlp,defaultExecTimeout: defaultExecTimeout,@@ -190,7 +193,7 @@ func (t *terminal) ExecCommand(detach bool,timeout time.Duration,) (string, error) {- containerName := PrimaryTerminalName(t.flowID)+ containerName := PrimaryTerminalName(t.tenantPrefix, t.flowID)cmd := []string{"sh",@@ -358,7 +361,7 @@ func (t *terminal) ReadFile(ctx context.Context, flowID int64, path string) (str// content only as an intermediate step (e.g. EditFile, before reapplying a// diff and writing back) don't echo a spurious "cat" transcript entry.func (t *terminal) readFileFromContainer(ctx context.Context, flowID int64, path string) (string, error) {- containerName := PrimaryTerminalName(flowID)+ containerName := PrimaryTerminalName(t.tenantPrefix, flowID)isRunning, err := t.dockerClient.IsContainerRunning(ctx, t.containerLID)if err != nil {@@ -445,7 +448,7 @@ func (t *terminal) WriteFile(ctx context.Context, flowID int64, content string,// overwriting it. It performs no terminal-log writes; WriteFile and EditFile// each log their own, differently-worded, success message.func (t *terminal) writeFileToContainer(ctx context.Context, flowID int64, path, content string) error {- containerName := PrimaryTerminalName(flowID)+ containerName := PrimaryTerminalName(t.tenantPrefix, flowID)isRunning, err := t.dockerClient.IsContainerRunning(ctx, t.containerLID)if err != nil {@@ -527,8 +530,19 @@ func (t *terminal) EditFile(ctx context.Context, flowID int64, path, diffText streturn successMsg, nil}-func PrimaryTerminalName(flowID int64) string {- return fmt.Sprintf("%s%d", PrimaryTerminalNamePrefix, flowID)+// PrimaryTerminalName returns the docker container name for a flow's primary+// terminal, namespaced by the configured tenant.+//+// "pentagi-terminal-1" (single instance)+// "acme-pentagi-terminal-1" (TENANT_ID=acme)+//+// The tenant goes in FRONT of the well-known prefix on purpose: the installer's+// volume garbage collector force-removes anything matching+// HasPrefix("pentagi-terminal-") && HasSuffix("-data"), so a leading tenant+// segment keeps one tenant's objects outside another tenant's sweep. A tenant+// segment placed after the prefix would stay inside it and be destroyed.+func PrimaryTerminalName(tenantPrefix string, flowID int64) string {+ return fmt.Sprintf("%s%s%d", tenantPrefix, PrimaryTerminalNamePrefix, flowID)}func (t *terminal) IsAvailable() bool {diff --git a/backend/pkg/tools/terminal_test.go b/backend/pkg/tools/terminal_test.goindex fe71570c..364970b2 100644--- a/backend/pkg/tools/terminal_test.go+++ b/backend/pkg/tools/terminal_test.go@@ -550,7 +550,7 @@ func TestPrimaryTerminalName(t *testing.T) {t.Run(fmt.Sprintf("flowID=%d", tt.flowID), func(t *testing.T) {t.Parallel()- if got := PrimaryTerminalName(tt.flowID); got != tt.want {+ if got := PrimaryTerminalName("", tt.flowID); got != tt.want {t.Errorf("PrimaryTerminalName(%d) = %q, want %q", tt.flowID, got, tt.want)}})diff --git a/backend/pkg/tools/tools.go b/backend/pkg/tools/tools.goindex ea2c6183..70bc2d32 100644--- a/backend/pkg/tools/tools.go+++ b/backend/pkg/tools/tools.go@@ -486,7 +486,8 @@ func (fte *flowToolsExecutor) Prepare(ctx context.Context) error {fte.primaryID = cnt.IDfte.primaryLID = cnt.LocalID.Stringif err := fte.syncMissingFiles(ctx); err != nil {- return fmt.Errorf("failed to sync missing files to container '%s': %w", PrimaryTerminalName(fte.flowID), err)+ containerName := PrimaryTerminalName(fte.cfg.TenantPrefix(), fte.flowID)+ return fmt.Errorf("failed to sync missing files to container '%s': %w", containerName, err)}return nildefault:@@ -514,7 +515,7 @@ func (fte *flowToolsExecutor) Prepare(ctx context.Context) error {capAdd = append(capAdd, "NET_ADMIN")}- containerName := PrimaryTerminalName(fte.flowID)+ containerName := PrimaryTerminalName(fte.cfg.TenantPrefix(), fte.flowID)cnt, err := fte.docker.RunContainer(ctx,containerName,@@ -646,7 +647,7 @@ func (fte *flowToolsExecutor) findMissingInContainer(ctx context.Context, entriecmd = append(cmd, e.containerPath)}- containerName := PrimaryTerminalName(fte.flowID)+ containerName := PrimaryTerminalName(fte.cfg.TenantPrefix(), fte.flowID)createResp, err := fte.docker.ContainerExecCreate(ctx, containerName, container.ExecOptions{Cmd: cmd,AttachStdout: true,@@ -700,7 +701,7 @@ func (fte *flowToolsExecutor) copyEntriesToContainer(ctx context.Context, entrieerrCh <- flowfiles.WriteFilesTar(pw, convertSyncEntriesToTarEntries(entries))}()- containerName := PrimaryTerminalName(fte.flowID)+ containerName := PrimaryTerminalName(fte.cfg.TenantPrefix(), fte.flowID)copyErr := fte.docker.CopyToContainer(ctx, containerName, docker.WorkFolderPathInContainer, pr,container.CopyToContainerOptions{AllowOverwriteDirWithFile: true})pr.Close()@@ -755,7 +756,7 @@ func (fte *flowToolsExecutor) Release(ctx context.Context) error {// TODO: here better to get flow containers list and purge all of themif err := fte.docker.RemoveContainer(ctx, fte.primaryLID, fte.primaryID); err != nil {- containerName := PrimaryTerminalName(fte.flowID)+ containerName := PrimaryTerminalName(fte.cfg.TenantPrefix(), fte.flowID)return fmt.Errorf("failed to purge container '%s': %w", containerName, err)}@@ -841,6 +842,7 @@ func (fte *flowToolsExecutor) GetAssistantExecutor(cfg AssistantExecutorConfig)fte.flowID, nil, nil,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1090,6 +1092,7 @@ func (fte *flowToolsExecutor) GetInstallerExecutor(cfg InstallerExecutorConfig)cfg.SubtaskID,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1196,6 +1199,7 @@ func (fte *flowToolsExecutor) GetCoderExecutor(cfg CoderExecutorConfig) (Contextcfg.SubtaskID,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1273,6 +1277,7 @@ func (fte *flowToolsExecutor) GetCoderExecutor(cfg CoderExecutorConfig) (Contextfte.flowID,cfg.TaskID,cfg.SubtaskID,+ fte.cfg.GroupID(fte.flowID),fte.graphitiClient,)if graphitiSearch.IsAvailable() {@@ -1319,6 +1324,7 @@ func (fte *flowToolsExecutor) GetPentesterExecutor(cfg PentesterExecutorConfig)cfg.SubtaskID,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1398,6 +1404,7 @@ func (fte *flowToolsExecutor) GetPentesterExecutor(cfg PentesterExecutorConfig)fte.flowID,cfg.TaskID,cfg.SubtaskID,+ fte.cfg.GroupID(fte.flowID),fte.graphitiClient,)if graphitiSearch.IsAvailable() {@@ -1510,6 +1517,7 @@ func (fte *flowToolsExecutor) GetGeneratorExecutor(cfg GeneratorExecutorConfig)nil,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1578,6 +1586,7 @@ func (fte *flowToolsExecutor) GetRefinerExecutor(cfg RefinerExecutorConfig) (Connil,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1642,6 +1651,7 @@ func (fte *flowToolsExecutor) GetMemoristExecutor(cfg MemoristExecutorConfig) (Ccfg.SubtaskID,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1687,6 +1697,7 @@ func (fte *flowToolsExecutor) GetMemoristExecutor(cfg MemoristExecutorConfig) (Cfte.flowID,cfg.TaskID,cfg.SubtaskID,+ fte.cfg.GroupID(fte.flowID),fte.graphitiClient,)if graphitiSearch.IsAvailable() {@@ -1713,6 +1724,7 @@ func (fte *flowToolsExecutor) GetEnricherExecutor(cfg EnricherExecutorConfig) (Ccfg.SubtaskID,container.ID,container.LocalID.String,+ fte.cfg.TenantPrefix(),fte.docker,fte.tlp,time.Duration(fte.cfg.TerminalToolTimeout)*time.Second,@@ -1758,6 +1770,7 @@ func (fte *flowToolsExecutor) GetEnricherExecutor(cfg EnricherExecutorConfig) (Cfte.flowID,cfg.TaskID,cfg.SubtaskID,+ fte.cfg.GroupID(fte.flowID),fte.graphitiClient,)if graphitiSearch.IsAvailable() {diff --git a/docker-compose.yml b/docker-compose.ymlindex 790d219e..5f72976d 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -36,12 +36,16 @@ services:condition: service_healthyenvironment:- DEBUG=${DEBUG:-false}+ - DATA_DIR=${DATA_DIR:-}- DOCKER_GID=998- CORS_ORIGINS=${CORS_ORIGINS:-}- COOKIE_SIGNING_SALT=${COOKIE_SIGNING_SALT:-}- INSTALLATION_ID=${INSTALLATION_ID:-}- LICENSE_KEY=${LICENSE_KEY:-}- ASK_USER=${ASK_USER:-false}+ - TENANT_ID=${TENANT_ID:-}+ - PPROF_ADDR=${PPROF_ADDR:-}+ - DOCKER_PORTS_BASE=${DOCKER_PORTS_BASE:-}- OPEN_AI_KEY=${OPEN_AI_KEY:-}- OPEN_AI_SERVER_URL=${OPEN_AI_SERVER_URL:-}- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}