diff --git a/monkeyai/README.md b/monkeyai/README.md index 1d0b8ca3..9a9992eb 100644 --- a/monkeyai/README.md +++ b/monkeyai/README.md @@ -54,6 +54,8 @@ MIGRATE_IMAGE=registry.example.com/team/monkeyai-migrate:v1.0.0 \ docker compose up --no-build ``` +当前迁移已收敛为完整初始化版本 `000001`,需连接全新的 PostgreSQL 数据库或数据目录。不能复用已执行旧版迁移的数据目录,也不能通过 `force 1` 完成升级;需要保留旧数据时应另行制定迁移方案。验证要求见 [数据库迁移说明](backend/migrations/README.md)。 + 迁移 SQL 已打包在 Migrate 镜像中。远程部署无需同步 `backend/migrations` 目录,但必须为 `MIGRATE_IMAGE` 指定与 Backend 相同发布版本的已推送镜像。 停止服务: @@ -66,7 +68,7 @@ PostgreSQL 数据保存在 `./data/postgres`,执行 `docker compose down` 不 ## 资源管理与 RustFS -Connector 已直接保存连接与认证配置,支持同一用户在同一连接下持有多份凭证。设计见 [连接与多凭证认证设计](design/connector-auth-design.md),现有数据库升级见 [迁移与接入说明](design/connector-migration.md)。 +Connector 已直接保存连接与认证配置,支持同一用户在同一连接下持有多份凭证。设计见 [连接与多凭证认证设计](design/connector-auth-design.md),初始化部署与客户端接入见 [迁移与接入说明](design/connector-migration.md)。 技能、规则、专家和 MCP 连接使用 PostgreSQL 持久化;技能 ZIP 和连接图标字节保存在私有 RustFS Bucket。后台和工作 Agent 均经后端鉴权下载,不直接接触对象存储凭据;技能包在返回前校验大小与 SHA-256,发现损坏时拒绝下发。技能编辑会重建 ZIP 并计算 SHA-256,保留包内附件。 @@ -102,7 +104,7 @@ Agent 按资源类型读取 `/api/v1/settings`、`/api/v1/models`、`/api/v1/rul 计费后台使用 `/api/admin/v1/billing/*`。管理员可以设置分组/个人周期额度、独立保存价格和计费方式、查看账户余额与冻结额、调整当期积分,并查询流水、退款和待处理交易。组织授权分组与单一计费归属分组分开维护。 -- 首次升级先执行 `000002_billing_create_transactions` 增量迁移;保留历史账户和流水。已有交易后 down 迁移主动拒绝,回滚应关闭新调用扣费并保留交易恢复能力。 +- 计费账户、交易与流水已纳入 `000001` 初始化结构;down 会删除业务数据,仅供可丢弃测试库验证。 - 默认关闭实际扣费,仅记录调用。检查价格、额度和模型上限后,在费用设置中开启。旧计费设置写接口返回冲突提示,统一通过计费接口写入。 - 模型需要配置有效的 `context_window_tokens` 和 `max_output_tokens`。代理以管理员确认的模型上下文上界预留、强制输出限制,使用真实 usage 结算;目前仅支持单结果同步调用,不支持 `n > 1`、`best_of > 1` 或后台异步生成。上下文上界错误、缺失用量或实际费用超出预留都会转待核查,不能按估值扣款。 - 模型调用沿用 `/v1/chat/completions`、`/v1/responses`、`/v1/messages`;MCP 使用 `POST /mcp/connectors/{id}/credentials/{credential_id}`,免认证使用 `POST /mcp/connectors/{id}`;全局调用密钥认证用户,地址确定授权资源,密钥作用域为 `mcp:invoke`。集中认证工具成功收费;独立认证、免认证和明确失败不收费。入口采用无状态 Streamable HTTP,支持握手、通知、工具列表和调用,返回 JSON;上游 JSON/SSE 均可解析。OAuth 调用前自动刷新,每次上游会话结束后清理。详见 [MCP 接入说明](backend/api/README.md#mcp-代理)。 @@ -128,7 +130,7 @@ Agent 按资源类型读取 `/api/v1/settings`、`/api/v1/models`、`/api/v1/rul 部署配置支持 `BAIZHIYUN_BASE_URL`、`BAIZHIYUN_APP_ID`、`MONKEYAI_WALLET_CERT_DIR`;未填写 URL 时仍兼容 `BAIZHIYUN_ENV=dev/prod`,目录包含上述三个文件;后台保存的配置优先。存在未完成远程交易时禁止切换服务 URL 或应用 ID,同一应用允许更新证书。证书配置成功仅表示本地校验通过,真实钱包连接和账户权限仍需联调确认。 -升级时迁移 `000008` 自动将已有环境配置和交易快照转换为对应 URL。已有自定义 URL 配置或交易记录时禁止回退该迁移,避免旧版本把交易发送到错误的服务。 +初始化结构直接使用 `wallet_billing_records.base_url` 保存交易服务地址,钱包设置同样使用 `base_url`。 容器部署时通过单独 Compose override 或现有部署系统向后端传入上述变量,将真实证书目录只读挂载到 `MONKEYAI_WALLET_CERT_DIR`。证书和私钥不进入镜像。新增私有 SDK 依赖,构建机需要私有模块读取权限;Docker 构建支持 BuildKit 的 `netrc` secret(`--secret id=netrc,src=<已有认证文件>`),不得将凭据写入 Dockerfile 或构建参数。 diff --git a/monkeyai/backend/README.md b/monkeyai/backend/README.md index 2fdf886f..c5986743 100644 --- a/monkeyai/backend/README.md +++ b/monkeyai/backend/README.md @@ -111,7 +111,8 @@ migrations/<唯一版本>__*.sql - 路由使用 `chi/v5` 组织版本、调用方和中间件,处理器保持标准 `http.Handler` 接口。 - HTTP DTO 不直接充当业务对象。 - 测试与对应 Go 源码放在同一目录;暂不创建独立测试树。 -- 迁移文件使用 `migrate create -ext sql -dir migrations -seq _` 生成,采用默认六位递增序号。合并前必须检查序号未被其他分支占用;如有冲突,重新生成序号。已经发布的迁移不可改写。 +- 本次重新部署将原 1–13 版收敛为完整初始化版本 `000001`,仅用于全新数据库;不能直接升级旧库或通过 `force 1` 切换。详见 [迁移说明](migrations/README.md)。 +- 后续迁移文件使用 `migrate create -ext sql -dir migrations -seq _` 生成,采用默认六位递增序号。合并前必须检查序号未被其他分支占用;如有冲突,重新生成序号。已经发布的迁移不可改写。 - 不创建 `pkg`、`utils` 或 `common`;出现明确复用对象后再决定归属。 ## Go 编码原则 @@ -153,7 +154,7 @@ export MONKEYAI_S3_SECRET_KEY='测试访问密钥密码' go test ./... -count=1 ``` -集成测试创建独立随机 schema,测试结束后删除该 schema,不重置其他 schema;必须使用测试数据库和测试 Bucket。测试包括版本 1 的 up/down/up、版本 2 的计费升级、版本 3 的旧系统分组升级与授权和额度保留、虚拟团队根节点及分组操作、Cookie 管理员身份与 Agent Bearer 身份、权限差异、独立资源目录 ETag、技能字节上传/重建/下载、专家委托、撤权、真实 MCP HTTP 协议、用户目录隔离及本地 OAuth state/PKCE 回调防重放。测试可能留下不可变技能对象,仅位于测试 Bucket。 +集成测试创建独立随机 schema,测试结束后删除该 schema,不重置其他 schema;必须使用测试数据库和测试 Bucket。测试包括版本 1 的完整初始化及带业务数据的 down/up、计费账户与不可变流水、连接多凭证约束、虚拟团队根节点及分组操作、Cookie 管理员身份与 Agent Bearer 身份、权限差异、独立资源目录 ETag、技能字节上传/重建/下载、专家委托、撤权、真实 MCP HTTP 协议、用户目录隔离及本地 OAuth state/PKCE 回调防重放。测试可能留下不可变技能对象,仅位于测试 Bucket。 业务标识统一由后端通过 Go 标准库 `uuid.New()` 生成。MCP 连接模板的内部 `identifier` 不接受客户端指定,管理端与 Agent API 均不返回该字段或 `provider_identifier`,调用方使用资源 `id` 关联。保存 `authentication` 设置时,新 OAuth 连接省略 `id`,后端生成并通过保存响应返回,后续编辑和删除使用返回的 `id`。管理员额度调整提交当前账户返回的 `version`;后端在事务中检查账本版本,相同版本和内容的重试不会重复记账,版本过期或已用于不同调整时须刷新账户再确认。 diff --git a/monkeyai/backend/internal/app/resources_test.go b/monkeyai/backend/internal/app/resources_test.go index e16cf554..e85ad04c 100644 --- a/monkeyai/backend/internal/app/resources_test.go +++ b/monkeyai/backend/internal/app/resources_test.go @@ -245,6 +245,11 @@ CREATE CONSTRAINT TRIGGER reject_test_tag AFTER INSERT ON tags DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`); err != nil { t.Fatal(err) } + t.Cleanup(func() { + if _, err := pool.Exec(ctx, `DROP TRIGGER reject_test_tag ON tags; DROP FUNCTION reject_test_tag()`); err != nil { + t.Error(err) + } + }) if code, _, _ := call("POST", "/api/admin/v1/tags", resource.Object{"name": "提交失败测试"}, "", ""); code != 500 { t.Fatalf("提交失败应返回 500: %d", code) } @@ -539,7 +544,7 @@ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`) allGroup := must("POST", "/api/admin/v1/groups", resource.Object{"name": "资源测试组", "parent_id": nil}, "", "") must("PUT", "/api/admin/v1/groups/"+allGroup.String("id")+"/members", resource.Object{"member_ids": users}, "", "") must("POST", "/api/admin/v1/rules", resource.Object{"name": "强制规则", "content": "强制", "grants": []resource.Object{{"group_id": allGroup.String("id"), "usage_requirement": "required"}}}, "", "") - t.Run("个人 MCP 工具下发与历史数据修复", func(t *testing.T) { + t.Run("个人 MCP 工具下发与重新发现", func(t *testing.T) { provider := resource.Object{"name": "自定义 MCP", "url": upstream.URL, "authorization_mode": "none"} connector := must("POST", "/api/v1/connectors", resource.Object{"name": "自定义连接", "url": provider["url"], "authorization_mode": provider["authorization_mode"], "authorization_method": provider["authorization_method"], "oauth_config": provider["oauth_config"], "oauth_client_secret": provider["oauth_client_secret"]}, "a", "") path := "/api/v1/connectors/" + connector.String("id") @@ -579,22 +584,14 @@ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`) t.Fatal(err) } before := must("GET", "/api/v1/connectors", nil, "a", "") - for _, direction := range []string{"up", "down", "up"} { - migration, err := os.ReadFile("../../migrations/000010_mcp_enable_personal_tools." + direction + ".sql") - if err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, string(migration)); err != nil { - t.Fatal(err) - } - verify() - var enabled bool - if err := pool.QueryRow(ctx, `SELECT bool_or(enabled) FROM mcp_tools WHERE connector_id=$1 OR (connector_id=$2 AND name IN ('removed','stale'))`, conn.String("id"), connector.String("id")).Scan(&enabled); err != nil || enabled { - t.Fatalf("数据修复启用了系统工具或失效个人工具:%v", err) - } + must("POST", ownerPath+"/test", nil, "a", "") + verify() + var enabled bool + if err := pool.QueryRow(ctx, `SELECT bool_or(enabled) FROM mcp_tools WHERE connector_id=$1 OR (connector_id=$2 AND name IN ('removed','stale'))`, conn.String("id"), connector.String("id")).Scan(&enabled); err != nil || enabled { + t.Fatalf("重新发现启用了系统工具或失效个人工具:%v", err) } if after := must("GET", "/api/v1/connectors", nil, "a", ""); after.String("version") == before.String("version") { - t.Fatal("个人工具修复后资源目录版本未更新") + t.Fatal("重新发现后资源目录版本未更新") } must("PATCH", "/api/admin/v1/connectors/"+conn.String("id")+"/tools/"+tool.String("id"), resource.Object{"enabled": true, "credits_per_call": "0"}, "", "") }) @@ -1189,7 +1186,7 @@ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`) must("GET", "/api/v1/experts/"+expert.String("id")+"/manifest", nil, "a", "") }) - t.Run("专家移除模型依赖及存量迁移", func(t *testing.T) { + t.Run("专家不依赖模型", func(t *testing.T) { must := func(method, path string, body any, token, revision string) resource.Object { t.Helper() code, out, _ := call(method, path, body, token, revision) @@ -1202,16 +1199,6 @@ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`) } return out } - apply := func(direction string) { - t.Helper() - data, err := os.ReadFile("../../migrations/000013_expert_remove_default_model." + direction + ".sql") - if err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(ctx, string(data)); err != nil { - t.Fatal(err) - } - } model := must("POST", "/api/admin/v1/models", resource.Object{"model_id": "expert-independent", "display_name": "专家独立模型", "protocol": "openai_chat_completions", "base_url": upstream.URL, "api_key": "test", "advanced_config": resource.Object{"context_window_tokens": 1000, "max_output_tokens": 100}, "credit_multiplier": 1, "authorization": resource.Object{"all_users": true}}, "", "") rule := must("POST", "/api/admin/v1/rules", resource.Object{"name": "专家模型移除规则", "content": "保留关联规则", "grants": grantA}, "", "") var saved []resource.Object @@ -1225,29 +1212,19 @@ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`) saved = append(saved, must("PUT", paths[i], input, tokens[i], `"1"`)) } - apply("down") var bindings int - if err := pool.QueryRow(ctx, `SELECT count(*) FROM experts WHERE default_model_id IS NOT NULL`).Scan(&bindings); err != nil || bindings != 0 { - t.Fatalf("回滚应仅恢复空字段: %d %v", bindings, err) - } - for _, expert := range saved { - if _, err := pool.Exec(ctx, `UPDATE experts SET default_model_id=$2 WHERE id=$1`, expert.String("id"), model.String("id")); err != nil { - t.Fatal(err) - } - } - apply("up") if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='experts' AND column_name='default_model_id'`).Scan(&bindings); err != nil || bindings != 0 { - t.Fatalf("升级未删除默认模型字段: %d %v", bindings, err) + t.Fatalf("初始化不应包含默认模型字段: %d %v", bindings, err) } versions := make([]string, len(saved)) for i, expert := range saved { current := must("GET", paths[i], nil, tokens[i], "") if resource.Hash(current) != resource.Hash(expert) { - t.Fatalf("迁移改变了专家数据或关联: %v", current) + t.Fatalf("读取的专家数据或关联与保存结果不一致: %v", current) } manifest := must("GET", "/api/v1/experts/"+expert.String("id")+"/manifest", nil, "a", "") if !manifest.Bool("available") || len(manifest["rules"].([]any)) != 1 { - t.Fatalf("升级后专家或规则不可用: %v", manifest) + t.Fatalf("专家或规则不可用: %v", manifest) } versions[i] = manifest.String("version") } @@ -1278,17 +1255,18 @@ DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_test_tag();`) } }) - // 多凭证迁移拒绝有损回滚;测试库显式重建验证全量初始化。 - down, err := os.ReadFile("../../migrations/000012_mcp_connector_credentials.down.sql") + // 在已有业务数据的测试库验证完整回滚,再重新初始化。 + down, err := os.ReadFile("../../migrations/000001_initial_create_schema.down.sql") if err != nil { t.Fatal(err) } - if _, err = pool.Exec(ctx, string(down)); err == nil { - t.Fatal("多凭证迁移允许有损回滚") - } - if _, err = root.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE; CREATE SCHEMA "+schema); err != nil { + if _, err = pool.Exec(ctx, string(down)); err != nil { t.Fatal(err) } + var remaining int + if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM pg_class WHERE relnamespace=current_schema()::regnamespace)+(SELECT count(*) FROM pg_proc WHERE pronamespace=current_schema()::regnamespace)`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("回滚后仍有数据库对象: %d %v", remaining, err) + } for _, path := range migrations { up, err := os.ReadFile(path) if err != nil { diff --git a/monkeyai/backend/internal/billing/connection_test.go b/monkeyai/backend/internal/billing/connection_test.go index d66a4854..9f56fd1f 100644 --- a/monkeyai/backend/internal/billing/connection_test.go +++ b/monkeyai/backend/internal/billing/connection_test.go @@ -326,7 +326,7 @@ func TestWalletCustomURLs(t *testing.T) { } } -func TestWalletURLMigration(t *testing.T) { +func TestWalletURLPersistence(t *testing.T) { for _, env := range []string{"dev", "prod"} { t.Run(env, func(t *testing.T) { s, user, model := fixture(t) @@ -349,28 +349,13 @@ func TestWalletURLMigration(t *testing.T) { if _, err := s.pool.Exec(t.Context(), `UPDATE settings SET value=jsonb_set(value,'{wallet}',$1::jsonb) WHERE key='billing'`, raw); err != nil { t.Fatal(err) } - for _, direction := range []string{"down", "up"} { - migration, err := os.ReadFile("../../migrations/000008_billing_wallet_urls." + direction + ".sql") - if err != nil { - t.Fatal(err) - } - if _, err = s.pool.Exec(t.Context(), string(migration)); err != nil { - t.Fatal(err) - } - if direction == "down" { - var stored string - if err := s.pool.QueryRow(t.Context(), `SELECT value#>>'{wallet,environment}' FROM settings WHERE key='billing'`).Scan(&stored); err != nil || stored != env { - t.Fatal("未恢复旧环境配置", err) - } - } - } wallet, err := s.wallet(t.Context(), s.pool) if err != nil || !wallet.ready() || wallet.config != cfg { - t.Fatal("旧配置迁移后未正确恢复", err) + t.Fatal("钱包地址配置未正确保存", err) } var baseURL string if err := s.pool.QueryRow(t.Context(), `SELECT base_url FROM wallet_billing_records`).Scan(&baseURL); err != nil || baseURL != cfg.BaseURL { - t.Fatal("原交易地址未正确迁移", err) + t.Fatal("交易未保存服务地址", err) } call := walletAdmin(t, s, user) call("PATCH", "/billing/settings/wallet", map[string]any{"revision": 1, "base_url": cfg.BaseURL, "app_id": cfg.AppID}, 200) diff --git a/monkeyai/backend/internal/billing/service_test.go b/monkeyai/backend/internal/billing/service_test.go index 43812062..7cdeddf0 100644 --- a/monkeyai/backend/internal/billing/service_test.go +++ b/monkeyai/backend/internal/billing/service_test.go @@ -478,68 +478,6 @@ func TestMissingUsageKeepsReservation(t *testing.T) { } } -func TestLegacyQuotaMigration(t *testing.T) { - dsn := os.Getenv("MONKEYAI_TEST_DATABASE_URL") - if dsn == "" { - t.Skip("需要 PostgreSQL") - } - ctx := t.Context() - root, err := pgxpool.New(ctx, dsn) - if err != nil { - t.Fatal(err) - } - schema := "test_legacy_billing_" + strings.ReplaceAll(resource.ID(), "-", "") - if _, err = root.Exec(ctx, "CREATE SCHEMA "+schema); err != nil { - t.Fatal(err) - } - cfg, err := pgxpool.ParseConfig(dsn) - if err != nil { - t.Fatal(err) - } - cfg.ConnConfig.RuntimeParams["search_path"] = schema - pool, err := pgxpool.NewWithConfig(ctx, cfg) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - pool.Close() - _, _ = root.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE") - root.Close() - }) - apply := func(path string) { - t.Helper() - raw, err := os.ReadFile(path) - if err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, string(raw)); err != nil { - t.Fatal(err) - } - } - apply("../../migrations/000001_initial_create_schema.up.sql") - id := resource.ID() - if _, err = pool.Exec(ctx, `INSERT INTO users(id,name,email,role) VALUES($1,'旧用户','legacy@example.com','admin')`, id); err != nil { - t.Fatal(err) - } - raw, _ := json.Marshal(map[string]any{"root_credits": 222, "quota_overrides": map[string]string{id: "33", "member-01": "44"}, "remote_billing_api_key": "legacy-secret"}) - if _, err = pool.Exec(ctx, `INSERT INTO settings(key,value,updated_by_user_id) VALUES('billing',$1,$2)`, raw, id); err != nil { - t.Fatal(err) - } - apply("../../migrations/000002_billing_create_transactions.up.sql") - var credits string - var issues int - if err = pool.QueryRow(ctx, `SELECT credits_per_cycle::text FROM billing_quotas WHERE user_id=$1`, id).Scan(&credits); err != nil || amountText(credits) != amountText("33") { - t.Fatal(credits, err) - } - if err = pool.QueryRow(ctx, `SELECT count(*) FROM billing_migration_issues`).Scan(&issues); err != nil || issues != 1 { - t.Fatal(issues, err) - } - var secret bool - if err = pool.QueryRow(ctx, `SELECT value ? 'remote_billing_api_key' FROM settings WHERE key='billing'`).Scan(&secret); err != nil || secret { - t.Fatal("旧密钥未移除", err) - } -} - func TestQuotaChangePreservesUnopenedAccount(t *testing.T) { s, user, _ := fixture(t) ctx := t.Context() diff --git a/monkeyai/backend/internal/group/service_test.go b/monkeyai/backend/internal/group/service_test.go index 18642d46..28bb1f01 100644 --- a/monkeyai/backend/internal/group/service_test.go +++ b/monkeyai/backend/internal/group/service_test.go @@ -99,7 +99,6 @@ func TestGroups(t *testing.T) { if err != nil || len(groups) != 0 { t.Fatalf("初始化不应创建分组: %v, %v", groups, err) } - testLegacyGroups(t, pool, actor, member) rootID := resource.ID() create := func(name string, parent any) Group { t.Helper() @@ -243,108 +242,3 @@ func TestGroups(t *testing.T) { } } } - -func testLegacyGroups(t *testing.T, pool *pgxpool.Pool, actor, member string) { - t.Helper() - ctx := t.Context() - upgrade, err := os.ReadFile(filepath.Join("..", "..", "migrations", "000003_group_virtual_root.up.sql")) - if err != nil { - t.Fatal(err) - } - // 新库执行增量迁移也不能初始化分组。 - if _, err = pool.Exec(ctx, string(upgrade)); err != nil { - t.Fatal(err) - } - groups, err := NewService(pool).List(ctx) - if err != nil || len(groups) != 0 { - t.Fatalf("新库迁移创建了分组: %v %v", groups, err) - } - root, admin := "00000000-0000-0000-0000-000000000001", "00000000-0000-0000-0000-000000000002" - custom, nested, item := resource.ID(), resource.ID(), resource.ID() - if _, err = pool.Exec(ctx, `INSERT INTO groups(id,parent_id,name) VALUES($1,NULL,'旧团队'),($2,$1,'管理员'),($3,$1,'旧业务组'),($4,$2,'旧管理员子组')`, root, admin, custom, nested); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `CREATE UNIQUE INDEX groups_one_active_root_key ON groups ((true)) WHERE parent_id IS NULL AND deleted_at IS NULL`); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `INSERT INTO group_users(group_id,user_id,assigned_by_user_id) VALUES($1,$2,$3)`, nested, member, actor); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,group_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$4),('rule',$1,$3,'read_write','required',$4)`, item, root, admin, actor); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `INSERT INTO resource_access_grants(resource_type,resource_id,user_id,access_level,usage_requirement,granted_by_user_id) VALUES('rule',$1,$2,'read_only','optional',$3)`, item, member, actor); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `INSERT INTO settings(key,value,updated_by_user_id) VALUES('billing','{}',$1)`, actor); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id) VALUES('group',$1,222,$3),('group',$2,77,$3)`, root, admin, actor); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `UPDATE users SET billing_group_id=$1 WHERE id=$2`, root, member); err != nil { - t.Fatal(err) - } - var account string - if err = pool.QueryRow(ctx, `INSERT INTO credit_accounts(user_id,balance,quota,group_id,period_start_at,period_end_at,last_refreshed_at) VALUES($1,42,222,$2,now(),now()+interval '1 month',now()) RETURNING id`, member, root).Scan(&account); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `INSERT INTO credit_ledger_entries(account_id,user_id,entry_type,category,item_name,credit_delta,balance_after,occurred_at,group_id,sequence) VALUES($1,$2,'grant','other','旧周期额度',42,42,now(),$3,1)`, account, member, root); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, string(upgrade)); err != nil { - t.Fatal(err) - } - groups, err = NewService(pool).List(ctx) - if err != nil || len(groups) != 2 { - t.Fatalf("旧库升级后的分组: %v %v", groups, err) - } - var rootCredits, adminCredits, childCredits, balance, legacy string - var billingGroup, accountGroup, ledgerGroup *string - if err = pool.QueryRow(ctx, `SELECT (SELECT value->>'root_credits' FROM settings WHERE key='billing'),(SELECT credits_per_cycle::text FROM billing_quotas WHERE user_id=$1),(SELECT credits_per_cycle::text FROM billing_quotas WHERE group_id=$2),(SELECT billing_group_id::text FROM users WHERE id=$3)`, actor, nested, member).Scan(&rootCredits, &adminCredits, &childCredits, &billingGroup); err != nil { - t.Fatal(err) - } - if rootCredits != "222.000000" || adminCredits != "77.000000" || childCredits != "77.000000" || billingGroup != nil { - t.Fatalf("旧额度迁移错误: %s %s %s %v", rootCredits, adminCredits, childCredits, billingGroup) - } - if err = pool.QueryRow(ctx, `SELECT a.balance::text,a.group_id::text,e.group_id::text,e.metadata->>'legacy_group_id' FROM credit_accounts a JOIN credit_ledger_entries e ON e.account_id=a.id WHERE a.id=$1`, account).Scan(&balance, &accountGroup, &ledgerGroup, &legacy); err != nil { - t.Fatal(err) - } - if balance != "42.000000" || accountGroup != nil || ledgerGroup != nil || legacy != root { - t.Fatalf("旧账户流水迁移错误: %s %v %v %s", balance, accountGroup, ledgerGroup, legacy) - } - if _, err = pool.Exec(ctx, `UPDATE credit_ledger_entries SET balance_after=0 WHERE account_id=$1`, account); err == nil { - t.Fatal("迁移后流水防修改触发器未恢复") - } - for _, group := range groups { - if group.ParentID != nil || group.ID == root || group.ID == admin { - t.Fatalf("旧系统分组未移除或子分组未提升: %+v", group) - } - } - var count int - if err = pool.QueryRow(ctx, `SELECT count(*) FROM resource_access_grants WHERE resource_id=$1 AND user_id IN ($2,$3) AND access_level='read_write' AND usage_requirement='required'`, item, actor, member).Scan(&count); err != nil { - t.Fatal(err) - } - if count != 2 { - t.Fatalf("旧授权展开或合并错误: %d", count) - } - if err = pool.QueryRow(ctx, `SELECT count(*) FROM group_users WHERE group_id=$1 AND user_id=$2 AND removed_at IS NULL`, nested, member).Scan(&count); err != nil || count != 1 { - t.Fatalf("自定义组成员关系丢失: %d %v", count, err) - } - if _, err = pool.Exec(ctx, string(upgrade)); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `DELETE FROM resource_access_grants WHERE resource_id=$1`, item); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `DELETE FROM group_users WHERE group_id=$1`, nested); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `DELETE FROM billing_quotas WHERE group_id IN ($1,$2)`, custom, nested); err != nil { - t.Fatal(err) - } - if _, err = pool.Exec(ctx, `DELETE FROM groups WHERE id IN ($1,$2)`, custom, nested); err != nil { - t.Fatal(err) - } - -} diff --git a/monkeyai/backend/internal/mcp/agent_test.go b/monkeyai/backend/internal/mcp/agent_test.go index 1fcb9962..b495e871 100644 --- a/monkeyai/backend/internal/mcp/agent_test.go +++ b/monkeyai/backend/internal/mcp/agent_test.go @@ -42,8 +42,7 @@ type fixture struct { users map[string]string } -func setup(t *testing.T) *fixture { return setupAt(t, 0) } -func setupAt(t *testing.T, last int) *fixture { +func setup(t *testing.T) *fixture { t.Helper() dsn := os.Getenv("MONKEYAI_TEST_DATABASE_URL") if dsn == "" { @@ -70,10 +69,7 @@ func setupAt(t *testing.T, last int) *fixture { } t.Cleanup(pool.Close) files, _ := filepath.Glob("../../migrations/*.up.sql") - for i, path := range files { - if last > 0 && i >= last { - break - } + for _, path := range files { b, err := os.ReadFile(path) if err != nil { t.Fatal(err) @@ -311,66 +307,26 @@ func TestOAuthMultipleCredentials(t *testing.T) { } } -func TestCredentialMigration(t *testing.T) { - f := setupAt(t, 11) - p, c1, c2, cred, tool, expert, auth := resource.ID(), resource.ID(), resource.ID(), resource.ID(), resource.ID(), resource.ID(), resource.ID() - f.sql(`INSERT INTO connector_providers(id,identifier,owner_user_id,name,url,authorization_mode,authorization_method,enabled,icon_s3_key) VALUES($1,'legacy',$2,'旧模板','https://template.example','independent','http_header',false,'shared/icon.png')`, p, f.users["owner"]) +func TestCredentialConstraints(t *testing.T) { + f := setup(t) + c1, c2 := resource.ID(), resource.ID() for _, id := range []string{c1, c2} { - f.sql(`INSERT INTO connectors(id,provider_id,owner_user_id,name,url,authorization_mode,authorization_method) VALUES($1,$2,$3,($1::uuid)::text,'https://instance.example','independent','http_header')`, id, p, f.users["owner"]) + f.sql(`INSERT INTO connectors(id,owner_user_id,name,url,authorization_mode,authorization_method) VALUES($1,$2,($1::uuid)::text,'https://connector.example','independent','http_header')`, id, f.users["owner"]) } - f.sql(`INSERT INTO connector_credentials(id,connector_id,user_id,method,http_headers,config_revision) VALUES($1,$2,$3,'http_header','{"X-Key":"preserved"}',1)`, cred, c1, f.users["owner"]) - f.sql(`INSERT INTO mcp_tools(id,connector_id,credential_id,name,config_revision,enabled) VALUES($1,$2,$3,'legacy',1,true)`, tool, c1, cred) - f.sql(`INSERT INTO experts(id,name,description,prompt,owner_user_id,created_by_user_id) VALUES($1,'旧专家','','测试',$2,$2)`, expert, f.users["owner"]) - f.sql(`INSERT INTO expert_connector_providers(expert_id,provider_id,required,tool_allowlist) VALUES($1,$2,false,'{legacy}')`, expert, p) - f.sql(`INSERT INTO connector_oauth_requests(id,connector_id,user_id,centralized,config_revision,state_hash,verifier,redirect_uri,expires_at) VALUES($1,$2,$3,false,1,'state','verifier','http://localhost',now()+interval '1 minute')`, auth, c1, f.users["owner"]) - report, err := os.ReadFile("../../tools/connectorcheck.sql") - if err != nil { - t.Fatal(err) + cred := resource.ID() + f.sql(`INSERT INTO connector_credentials(id,connector_id,user_id,name,http_headers,config_revision) VALUES($1,$2,$3,'同名凭证','{"X-Key":"first"}',1)`, cred, c1, f.users["owner"]) + f.sql(`INSERT INTO connector_credentials(connector_id,user_id,name,http_headers,config_revision) VALUES($1,$2,'同名凭证','{"X-Key":"second"}',1)`, c1, f.users["owner"]) + f.sql(`INSERT INTO mcp_tools(connector_id,credential_id,name,config_revision) VALUES($1,$2,'tool',1)`, c1, cred) + if _, err := f.pool.Exec(t.Context(), `INSERT INTO mcp_tools(connector_id,credential_id,name,config_revision) VALUES($1,$2,'tool',1)`, c2, cred); err == nil { + t.Fatal("工具允许引用其他连接的凭证") } - if _, err = f.pool.Exec(t.Context(), string(report)); err != nil { - t.Fatalf("只读预检查失败: %v", err) - } - up, err := os.ReadFile("../../migrations/000012_mcp_connector_credentials.up.sql") - if err != nil { - t.Fatal(err) - } - if _, err = f.pool.Exec(t.Context(), string(up)); err == nil || !strings.Contains(err.Error(), "ambiguous_connector") { - t.Fatalf("多候选迁移应停止: %v", err) - } - var count int - if err = f.pool.QueryRow(t.Context(), `SELECT count(*) FROM connector_providers WHERE id=$1`, p).Scan(&count); err != nil || count != 1 { - t.Fatal("失败迁移修改了原数据") - } - conn, err := f.pool.Acquire(t.Context()) - if err != nil { - t.Fatal(err) - } - defer conn.Release() - mapping, _ := json.Marshal(resource.Object{expert: resource.Object{p: c1}}) - if _, err = conn.Exec(t.Context(), `SELECT set_config('monkeyai.connector_mappings',$1,false)`, string(mapping)); err != nil { - t.Fatal(err) - } - if _, err = conn.Exec(t.Context(), string(up)); err != nil { - t.Fatal(err) - } - var target, icon, address, status string - var enabled, required bool - if err = f.pool.QueryRow(t.Context(), `SELECT x.connector_id::text,x.required,c.icon_s3_key,c.url,c.enabled FROM expert_connectors x JOIN connectors c ON c.id=x.connector_id WHERE expert_id=$1`, expert).Scan(&target, &required, &icon, &address, &enabled); err != nil { - t.Fatal(err) - } - if target != c1 || required || icon != "shared/icon.png" || address != "https://instance.example" || enabled { - t.Fatal("映射、实例配置或旧停用状态未保留") - } - if err = f.pool.QueryRow(t.Context(), `SELECT status FROM connector_oauth_requests WHERE id=$1`, auth).Scan(&status); err != nil || status != "failed" { - t.Fatal("旧授权事务仍可写入") - } - if err = f.pool.QueryRow(t.Context(), `SELECT count(*) FROM mcp_tools WHERE id=$1 AND credential_id=$2 AND deleted_at IS NULL`, tool, cred).Scan(&count); err != nil || count != 1 { - t.Fatal("迁移丢失有效工具历史") - } - f.sql(`INSERT INTO connector_credentials(connector_id,user_id,name,http_headers,config_revision) VALUES($1,$2,'新增','{"X-Key":"second"}',1)`, c1, f.users["owner"]) - if err = f.pool.QueryRow(t.Context(), `SELECT count(*) FROM connector_credentials WHERE connector_id=$1 AND user_id=$2`, c1, f.users["owner"]).Scan(&count); err != nil || count != 2 { - t.Fatal("迁移后仍限制单凭证") + f.sql(`UPDATE connectors SET authorization_mode='centralized' WHERE id=$1`, c2) + f.sql(`INSERT INTO connector_credentials(connector_id,name,config_revision) VALUES($1,'集中凭证',1)`, c2) + if _, err := f.pool.Exec(t.Context(), `INSERT INTO connector_credentials(connector_id,name,config_revision) VALUES($1,'第二份集中凭证',1)`, c2); err == nil { + t.Fatal("连接允许多份有效集中凭证") } + f.sql(`UPDATE connector_credentials SET revoked_at=now() WHERE connector_id=$1`, c2) + f.sql(`INSERT INTO connector_credentials(connector_id,name,config_revision) VALUES($1,'新集中凭证',1)`, c2) } func TestRefreshRevocation(t *testing.T) { diff --git a/monkeyai/backend/migrations/000001_initial_create_schema.down.sql b/monkeyai/backend/migrations/000001_initial_create_schema.down.sql index 2f53bf98..82fc17b6 100644 --- a/monkeyai/backend/migrations/000001_initial_create_schema.down.sql +++ b/monkeyai/backend/migrations/000001_initial_create_schema.down.sql @@ -6,8 +6,15 @@ DROP TABLE oauth_authorization_codes; DROP TABLE oauth_login_states; DROP TABLE oauth_authorization_requests; DROP TABLE browser_sessions; +DROP TABLE email_code_deliveries; +DROP TABLE email_codes; DROP TABLE audits; DROP TABLE credit_ledger_entries; +DROP FUNCTION billing_immutable_ledger(); +DROP TABLE billing_migration_issues; +DROP TABLE wallet_billing_records; +DROP TABLE wallet_user_bindings; +DROP TABLE billing_transactions; DROP TABLE credit_accounts; DROP TABLE billing_quotas; DROP TABLE mcp_tool_calls; @@ -15,7 +22,7 @@ DROP TABLE model_calls; DROP TABLE sessions; DROP TABLE expert_skills; DROP TABLE expert_rules; -DROP TABLE expert_connector_providers; +DROP TABLE expert_connectors; DROP TABLE resource_tags; DROP TABLE resource_access_grants; DROP TABLE experts; @@ -23,13 +30,13 @@ DROP TABLE connector_oauth_requests; DROP TABLE mcp_tools; DROP TABLE connector_credentials; DROP TABLE connectors; -DROP TABLE connector_providers; DROP TABLE rules; DROP TABLE skills; DROP TABLE tags; DROP TABLE models; DROP TABLE settings; DROP TABLE group_users; +ALTER TABLE users DROP CONSTRAINT users_billing_group_id_fkey; DROP TABLE groups; DROP TABLE user_identities; DROP TABLE users; diff --git a/monkeyai/backend/migrations/000001_initial_create_schema.up.sql b/monkeyai/backend/migrations/000001_initial_create_schema.up.sql index 240e2790..78c8f1ae 100644 --- a/monkeyai/backend/migrations/000001_initial_create_schema.up.sql +++ b/monkeyai/backend/migrations/000001_initial_create_schema.up.sql @@ -14,6 +14,7 @@ CREATE TABLE users ( created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, + billing_group_id uuid, CONSTRAINT users_role_check CHECK (role IN ('admin', 'user')), CONSTRAINT users_status_check CHECK (status IN ('active', 'disabled')), CONSTRAINT users_disabled_at_check CHECK ( @@ -43,7 +44,7 @@ CREATE TABLE user_identities ( updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, CONSTRAINT user_identities_provider_check CHECK ( - provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc') + provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc', 'baizhiyun') ) ); @@ -70,6 +71,9 @@ CREATE INDEX groups_parent_idx ON groups (parent_id) WHERE deleted_at IS NULL; +ALTER TABLE users ADD CONSTRAINT users_billing_group_id_fkey + FOREIGN KEY (billing_group_id) REFERENCES groups (id); + CREATE TABLE group_users ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), group_id uuid NOT NULL REFERENCES groups (id), @@ -95,6 +99,7 @@ CREATE TABLE settings ( updated_by_user_id uuid NOT NULL REFERENCES users (id), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + revision bigint NOT NULL DEFAULT 1, CONSTRAINT settings_key_check CHECK ( key IN ('branding', 'authentication', 'email', 'billing') ), @@ -192,33 +197,8 @@ CREATE INDEX rules_owner_idx ON rules (owner_user_id) WHERE deleted_at IS NULL; -CREATE TABLE connector_providers ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - identifier text NOT NULL, - ownership_type text NOT NULL DEFAULT 'system' CHECK (ownership_type IN ('system','user')), - owner_user_id uuid NOT NULL REFERENCES users(id), - name text NOT NULL, - description text NOT NULL DEFAULT '', - icon_s3_key text NOT NULL DEFAULT '', - url text NOT NULL, - authorization_mode text NOT NULL CHECK (authorization_mode IN ('none','centralized','independent')), - authorization_method text CHECK (authorization_method IN ('http_header','oauth')), - header_schema jsonb NOT NULL DEFAULT '{}'::jsonb, - oauth_config jsonb NOT NULL DEFAULT '{}'::jsonb, - oauth_client_secret text NOT NULL DEFAULT '', - enabled boolean NOT NULL DEFAULT true, - revision bigint NOT NULL DEFAULT 1, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - deleted_at timestamptz, - CHECK ((authorization_mode = 'none' AND authorization_method IS NULL) OR - (authorization_mode <> 'none' AND authorization_method IS NOT NULL)) -); -CREATE UNIQUE INDEX connector_providers_identifier_key ON connector_providers(lower(btrim(identifier))) WHERE deleted_at IS NULL; - CREATE TABLE connectors ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - provider_id uuid NOT NULL REFERENCES connector_providers(id), ownership_type text NOT NULL DEFAULT 'system' CHECK (ownership_type IN ('system','user')), owner_user_id uuid NOT NULL REFERENCES users(id), name text NOT NULL, @@ -237,6 +217,7 @@ CREATE TABLE connectors ( created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, + icon_s3_key text NOT NULL DEFAULT '', CHECK ((authorization_mode = 'none' AND authorization_method IS NULL) OR (authorization_mode <> 'none' AND authorization_method IS NOT NULL)) ); @@ -244,18 +225,25 @@ CREATE TABLE connector_credentials ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), connector_id uuid NOT NULL REFERENCES connectors(id), user_id uuid REFERENCES users(id), - method text NOT NULL CHECK (method IN ('oauth','http_header')), http_headers jsonb NOT NULL DEFAULT '{}'::jsonb, oauth_access_token text NOT NULL DEFAULT '', oauth_refresh_token text NOT NULL DEFAULT '', oauth_expires_at timestamptz, - status text NOT NULL DEFAULT 'authorized' CHECK (status IN ('authorized','expired','revoked','error')), config_revision bigint NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), revoked_at timestamptz, - UNIQUE NULLS NOT DISTINCT (connector_id,user_id) + name text NOT NULL DEFAULT '原有凭证' CHECK (char_length(btrim(name)) BETWEEN 1 AND 128), + revision bigint NOT NULL DEFAULT 1, + connection_status text NOT NULL DEFAULT 'unknown' CHECK (connection_status IN ('unknown','connected','error')), + last_checked_at timestamptz, + last_error text, + CONSTRAINT connector_credentials_id_connector_key UNIQUE (id, connector_id) ); +CREATE INDEX connector_credentials_user_idx ON connector_credentials(connector_id, user_id); +CREATE UNIQUE INDEX connector_credentials_centralized_idx ON connector_credentials(connector_id) + WHERE user_id IS NULL AND revoked_at IS NULL; + CREATE TABLE mcp_tools ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), connector_id uuid NOT NULL REFERENCES connectors(id), @@ -269,13 +257,14 @@ CREATE TABLE mcp_tools ( discovered_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, - UNIQUE NULLS NOT DISTINCT (connector_id,credential_id,name) + UNIQUE NULLS NOT DISTINCT (connector_id,credential_id,name), + CONSTRAINT mcp_tools_credential_connector_fkey + FOREIGN KEY (credential_id, connector_id) REFERENCES connector_credentials(id, connector_id) ); CREATE TABLE connector_oauth_requests ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), connector_id uuid NOT NULL REFERENCES connectors(id), user_id uuid NOT NULL REFERENCES users(id), - centralized boolean NOT NULL, config_revision bigint NOT NULL, state_hash text NOT NULL UNIQUE, verifier text NOT NULL, @@ -283,21 +272,28 @@ CREATE TABLE connector_oauth_requests ( expires_at timestamptz NOT NULL, consumed_at timestamptz, status text NOT NULL DEFAULT 'pending', - created_at timestamptz NOT NULL DEFAULT now() + created_at timestamptz NOT NULL DEFAULT now(), + credential_id uuid REFERENCES connector_credentials(id), + credential_revision bigint, + name text NOT NULL DEFAULT '原有凭证', + CONSTRAINT connector_oauth_requests_status_check CHECK (status IN ('pending','processing','succeeded','failed','expired')) ); +CREATE INDEX connector_oauth_requests_expires_idx ON connector_oauth_requests(expires_at); + CREATE TABLE experts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text NOT NULL, description text NOT NULL, prompt text NOT NULL, - default_model_id uuid REFERENCES models(id), enabled boolean NOT NULL DEFAULT true, created_by_user_id uuid NOT NULL REFERENCES users (id), revision bigint NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - deleted_at timestamptz + deleted_at timestamptz, + ownership_type text NOT NULL DEFAULT 'system' CHECK (ownership_type IN ('system', 'user')), + owner_user_id uuid NOT NULL REFERENCES users(id) ); CREATE INDEX experts_enabled_idx @@ -315,11 +311,12 @@ CREATE TABLE resource_access_grants ( granted_by_user_id uuid NOT NULL REFERENCES users (id), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + all_users boolean NOT NULL DEFAULT false, CONSTRAINT resource_access_grants_resource_type_check CHECK ( resource_type IN ('model', 'skill', 'rule', 'connector', 'expert') ), CONSTRAINT resource_access_grants_subject_check CHECK ( - (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer = 1 + (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer + all_users::integer = 1 ), CONSTRAINT resource_access_grants_access_level_check CHECK ( access_level IN ('read_only', 'read_write') @@ -346,6 +343,10 @@ CREATE INDEX resource_access_grants_group_idx ON resource_access_grants (group_id, resource_type) WHERE group_id IS NOT NULL; +CREATE UNIQUE INDEX resource_access_grants_all_users_key + ON resource_access_grants (resource_type, resource_id) + WHERE all_users; + CREATE TABLE resource_tags ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), resource_type text NOT NULL, @@ -361,15 +362,15 @@ CREATE TABLE resource_tags ( CREATE INDEX resource_tags_tag_idx ON resource_tags (tag_id); -CREATE TABLE expert_connector_providers ( +CREATE TABLE expert_connectors ( expert_id uuid NOT NULL REFERENCES experts(id), - provider_id uuid NOT NULL REFERENCES connector_providers(id), + connector_id uuid NOT NULL REFERENCES connectors(id), required boolean NOT NULL DEFAULT true, tool_allowlist text[] NOT NULL DEFAULT '{}', tool_denylist text[] NOT NULL DEFAULT '{}', - PRIMARY KEY (expert_id,provider_id) + PRIMARY KEY (expert_id, connector_id) ); -CREATE INDEX expert_connector_providers_provider_idx ON expert_connector_providers(provider_id); +CREATE INDEX expert_connectors_connector_idx ON expert_connectors(connector_id); CREATE TABLE expert_rules ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), @@ -436,7 +437,7 @@ CREATE INDEX sessions_expert_idx CREATE TABLE model_calls ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - session_id uuid NOT NULL REFERENCES sessions (id), + session_id uuid REFERENCES sessions (id), user_id uuid NOT NULL REFERENCES users (id), model_id uuid NOT NULL REFERENCES models (id), request_id text, @@ -479,7 +480,7 @@ CREATE INDEX model_calls_user_started_idx CREATE TABLE mcp_tool_calls ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - session_id uuid NOT NULL REFERENCES sessions (id), + session_id uuid REFERENCES sessions (id), user_id uuid NOT NULL REFERENCES users (id), connector_id uuid NOT NULL REFERENCES connectors (id), tool_id uuid NOT NULL REFERENCES mcp_tools (id), @@ -541,16 +542,58 @@ CREATE UNIQUE INDEX billing_quotas_user_active_key CREATE TABLE credit_accounts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users (id) UNIQUE, + user_id uuid NOT NULL REFERENCES users (id), balance numeric(24, 6) NOT NULL DEFAULT 0, period_start_at timestamptz NOT NULL, period_end_at timestamptz NOT NULL, last_refreshed_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT credit_accounts_period_check CHECK (period_end_at > period_start_at) + frozen numeric(24,6) NOT NULL DEFAULT 0, + quota numeric(24,6) NOT NULL DEFAULT 0, + group_id uuid REFERENCES groups(id), + sequence bigint NOT NULL DEFAULT 0, + CONSTRAINT credit_accounts_period_check CHECK (period_end_at > period_start_at), + CONSTRAINT credit_accounts_amount_check CHECK (balance >= 0 AND frozen >= 0 AND frozen <= balance) ); +CREATE UNIQUE INDEX credit_accounts_user_period_key ON credit_accounts(user_id,period_start_at); + +CREATE TABLE billing_transactions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + user_id uuid NOT NULL REFERENCES users(id), + account_id uuid NOT NULL REFERENCES credit_accounts(id), + session_id uuid REFERENCES sessions(id), + category text NOT NULL CHECK(category IN ('model','tool')), + resource_id uuid NOT NULL, + connector_id uuid REFERENCES connectors(id), + item_name text NOT NULL, + user_name text NOT NULL, + user_email text NOT NULL, + group_id uuid REFERENCES groups(id), + mode text NOT NULL CHECK(mode IN ('local','remote')), + status text NOT NULL CHECK(status IN ('created','reserved','running','settling','settled','released','rejected','unknown')), + reserve numeric(24,6) NOT NULL CHECK(reserve >= 0), + amount numeric(24,6), + raw_amount numeric(24,6), + pricing jsonb NOT NULL CHECK(jsonb_typeof(pricing)='object'), + usage jsonb NOT NULL DEFAULT '{}', + result text, + error_code text NOT NULL DEFAULT '', + idempotency_key text, + request_hash text NOT NULL DEFAULT '', + request_id text NOT NULL DEFAULT '', + attempts integer NOT NULL DEFAULT 0, + next_retry_at timestamptz, + started_at timestamptz NOT NULL DEFAULT now(), + completed_at timestamptz, + updated_at timestamptz NOT NULL DEFAULT now(), + CHECK(amount IS NULL OR amount >= 0) +); +CREATE UNIQUE INDEX billing_transactions_idempotency_key ON billing_transactions(user_id,category,idempotency_key) WHERE idempotency_key IS NOT NULL; +CREATE INDEX billing_transactions_status_idx ON billing_transactions(status,next_retry_at); +CREATE INDEX billing_transactions_user_time_idx ON billing_transactions(user_id,started_at DESC,id DESC); + CREATE TABLE credit_ledger_entries ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES credit_accounts (id), @@ -572,6 +615,14 @@ CREATE TABLE credit_ledger_entries ( metadata jsonb NOT NULL DEFAULT '{}'::jsonb, occurred_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), + transaction_id uuid REFERENCES billing_transactions(id), + event_key text, + sequence bigint, + user_name text, + user_email text, + group_id uuid REFERENCES groups(id), + mode text NOT NULL DEFAULT 'local', + reverses_id uuid REFERENCES credit_ledger_entries(id), CONSTRAINT credit_ledger_entries_entry_type_check CHECK ( entry_type IN ('charge', 'grant', 'refund', 'reset', 'adjustment') ), @@ -611,6 +662,43 @@ CREATE INDEX credit_ledger_entries_source_idx ON credit_ledger_entries (source_type, source_id) WHERE source_type IS NOT NULL AND source_id IS NOT NULL; +CREATE UNIQUE INDEX credit_ledger_entries_event_key ON credit_ledger_entries(event_key) WHERE event_key IS NOT NULL; +CREATE UNIQUE INDEX credit_ledger_entries_sequence_key ON credit_ledger_entries(account_id,sequence); +CREATE INDEX credit_ledger_entries_time_idx ON credit_ledger_entries(occurred_at DESC,id DESC); +CREATE TABLE wallet_user_bindings ( + user_id uuid PRIMARY KEY REFERENCES users(id), + external_user_id text NOT NULL UNIQUE, + verified_at timestamptz NOT NULL, + updated_by_user_id uuid NOT NULL REFERENCES users(id) +); +CREATE TABLE wallet_billing_records ( + biz_id text PRIMARY KEY, + transaction_id uuid NOT NULL UNIQUE REFERENCES billing_transactions(id), + external_user_id text NOT NULL, + team_slug text NOT NULL DEFAULT '', + base_url text NOT NULL, + app_id integer NOT NULL, + status text NOT NULL CHECK(status IN ('pending','reserved','confirming','confirmed','rejected','unknown')), + frozen_amount_quota bigint NOT NULL CHECK(frozen_amount_quota >= 0), + actual_amount_quota bigint, + confirmation_status text, + error_code text NOT NULL DEFAULT '', + trace_id text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + confirmed_at timestamptz +); +CREATE TABLE billing_migration_issues ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + subject text NOT NULL, + value jsonb NOT NULL, + reason text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE FUNCTION billing_immutable_ledger() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION '计费流水不可修改或删除,请使用冲正'; END $$; +CREATE TRIGGER credit_ledger_immutable BEFORE UPDATE OR DELETE ON credit_ledger_entries FOR EACH ROW EXECUTE FUNCTION billing_immutable_ledger(); + CREATE TABLE audits ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), actor_type text NOT NULL, @@ -628,11 +716,13 @@ CREATE TABLE audits ( error_message text, occurred_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), + request_id text, CONSTRAINT audits_actor_type_check CHECK (actor_type IN ('user', 'system')), CONSTRAINT audits_result_check CHECK (result IN ('success', 'failed')), CONSTRAINT audits_request_params_check CHECK (jsonb_typeof(request_params) = 'object') ); +CREATE INDEX audits_request_idx ON audits (request_id) WHERE request_id IS NOT NULL; CREATE INDEX audits_occurred_idx ON audits (occurred_at DESC); CREATE INDEX audits_actor_occurred_idx ON audits (actor_user_id, occurred_at DESC); CREATE INDEX audits_category_occurred_idx ON audits (category, occurred_at DESC); @@ -646,8 +736,27 @@ CREATE UNIQUE INDEX rules_system_name_key ON rules(lower(btrim(name))) WHERE own CREATE UNIQUE INDEX rules_user_name_key ON rules(owner_user_id,lower(btrim(name))) WHERE ownership_type='user' AND deleted_at IS NULL; CREATE UNIQUE INDEX connectors_system_name_key ON connectors(lower(btrim(name))) WHERE ownership_type='system' AND deleted_at IS NULL; CREATE UNIQUE INDEX connectors_user_name_key ON connectors(owner_user_id,lower(btrim(name))) WHERE ownership_type='user' AND deleted_at IS NULL; -CREATE UNIQUE INDEX experts_name_key ON experts(lower(btrim(name))) WHERE deleted_at IS NULL; +CREATE UNIQUE INDEX experts_system_name_key ON experts(lower(btrim(name))) + WHERE ownership_type = 'system' AND deleted_at IS NULL; +CREATE UNIQUE INDEX experts_user_name_key ON experts(owner_user_id, lower(btrim(name))) + WHERE ownership_type = 'user' AND deleted_at IS NULL; +CREATE TABLE email_codes ( + email text NOT NULL, + purpose text NOT NULL CHECK (purpose IN ('login', 'register', 'reset')), + code_hash text NOT NULL, + expires_at timestamptz NOT NULL, + attempts integer NOT NULL DEFAULT 0, + ready boolean NOT NULL DEFAULT false, + PRIMARY KEY (email, purpose) +); +CREATE TABLE email_code_deliveries ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + email text NOT NULL, + ip_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX email_code_deliveries_created_idx ON email_code_deliveries (created_at); CREATE TABLE browser_sessions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), @@ -659,7 +768,7 @@ CREATE TABLE browser_sessions ( created_at timestamptz NOT NULL DEFAULT now(), revoked_at timestamptz, CONSTRAINT browser_sessions_authentication_method_check CHECK ( - authentication_method IN ('password', 'oauth') + authentication_method IN ('password', 'oauth', 'email_code') ), CONSTRAINT browser_sessions_expiry_check CHECK (expires_at > created_at) ); @@ -730,9 +839,6 @@ CREATE INDEX oauth_tokens_user_idx ON oauth_tokens (user_id, client_id) WHERE revoked_at IS NULL; - - - CREATE TABLE api_keys ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), user_id uuid NOT NULL REFERENCES users (id), @@ -760,5 +866,10 @@ CREATE INDEX api_keys_expiry_idx ON api_keys (expires_at) WHERE revoked_at IS NULL; +CREATE INDEX model_calls_started_idx ON model_calls (started_at); +CREATE INDEX model_calls_completed_idx ON model_calls (completed_at) WHERE completed_at IS NOT NULL; +CREATE INDEX mcp_tool_calls_completed_idx ON mcp_tool_calls (completed_at) WHERE completed_at IS NOT NULL; +CREATE INDEX sessions_started_idx ON sessions (started_at DESC,id DESC) WHERE deleted_at IS NULL; +CREATE INDEX sessions_last_active_idx ON sessions (last_active_at) WHERE deleted_at IS NULL; COMMIT; diff --git a/monkeyai/backend/migrations/000002_billing_create_transactions.down.sql b/monkeyai/backend/migrations/000002_billing_create_transactions.down.sql deleted file mode 100644 index ecce456c..00000000 --- a/monkeyai/backend/migrations/000002_billing_create_transactions.down.sql +++ /dev/null @@ -1,15 +0,0 @@ -BEGIN; -DO $$ BEGIN IF EXISTS(SELECT 1 FROM billing_transactions) OR EXISTS(SELECT 1 FROM credit_accounts GROUP BY user_id HAVING count(*)>1) THEN RAISE EXCEPTION '已有计费交易或周期历史,不允许破坏性回滚'; END IF; END $$; -DROP TRIGGER credit_ledger_immutable ON credit_ledger_entries; -DROP FUNCTION billing_immutable_ledger(); -DROP TABLE wallet_billing_records; -DROP TABLE wallet_user_bindings; -DROP TABLE billing_migration_issues; -ALTER TABLE credit_ledger_entries DROP COLUMN transaction_id,DROP COLUMN event_key,DROP COLUMN sequence,DROP COLUMN user_name,DROP COLUMN user_email,DROP COLUMN group_id,DROP COLUMN mode,DROP COLUMN reverses_id; -DROP TABLE billing_transactions; -DROP INDEX credit_accounts_user_period_key; -ALTER TABLE credit_accounts DROP CONSTRAINT credit_accounts_amount_check,DROP COLUMN frozen,DROP COLUMN quota,DROP COLUMN group_id,DROP COLUMN sequence; -ALTER TABLE credit_accounts ADD CONSTRAINT credit_accounts_user_id_key UNIQUE(user_id); -ALTER TABLE users DROP COLUMN billing_group_id; -ALTER TABLE settings DROP COLUMN revision; -COMMIT; diff --git a/monkeyai/backend/migrations/000002_billing_create_transactions.up.sql b/monkeyai/backend/migrations/000002_billing_create_transactions.up.sql deleted file mode 100644 index 58cdecae..00000000 --- a/monkeyai/backend/migrations/000002_billing_create_transactions.up.sql +++ /dev/null @@ -1,114 +0,0 @@ -BEGIN; -ALTER TABLE settings ADD COLUMN revision bigint NOT NULL DEFAULT 1; -ALTER TABLE users ADD COLUMN billing_group_id uuid REFERENCES groups(id); -ALTER TABLE credit_accounts DROP CONSTRAINT credit_accounts_user_id_key; -ALTER TABLE credit_accounts ADD COLUMN frozen numeric(24,6) NOT NULL DEFAULT 0; -ALTER TABLE credit_accounts ADD COLUMN quota numeric(24,6) NOT NULL DEFAULT 0; -ALTER TABLE credit_accounts ADD COLUMN group_id uuid REFERENCES groups(id); -ALTER TABLE credit_accounts ADD COLUMN sequence bigint NOT NULL DEFAULT 0; -UPDATE credit_accounts a SET quota=GREATEST(balance,0),sequence=(SELECT count(*) FROM credit_ledger_entries e WHERE e.account_id=a.id); -ALTER TABLE credit_accounts ADD CONSTRAINT credit_accounts_amount_check CHECK(balance >= 0 AND frozen >= 0 AND frozen <= balance) NOT VALID; -CREATE UNIQUE INDEX credit_accounts_user_period_key ON credit_accounts(user_id,period_start_at); -ALTER TABLE model_calls ALTER COLUMN session_id DROP NOT NULL; -ALTER TABLE mcp_tool_calls ALTER COLUMN session_id DROP NOT NULL; -CREATE TABLE billing_transactions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id), - account_id uuid NOT NULL REFERENCES credit_accounts(id), - session_id uuid REFERENCES sessions(id), - category text NOT NULL CHECK(category IN ('model','tool')), - resource_id uuid NOT NULL, - connector_id uuid REFERENCES connectors(id), - item_name text NOT NULL, - user_name text NOT NULL, - user_email text NOT NULL, - group_id uuid REFERENCES groups(id), - mode text NOT NULL CHECK(mode IN ('local','remote')), - status text NOT NULL CHECK(status IN ('created','reserved','running','settling','settled','released','rejected','unknown')), - reserve numeric(24,6) NOT NULL CHECK(reserve >= 0), - amount numeric(24,6), - raw_amount numeric(24,6), - pricing jsonb NOT NULL CHECK(jsonb_typeof(pricing)='object'), - usage jsonb NOT NULL DEFAULT '{}', - result text, - error_code text NOT NULL DEFAULT '', - idempotency_key text, - request_hash text NOT NULL DEFAULT '', - request_id text NOT NULL DEFAULT '', - attempts integer NOT NULL DEFAULT 0, - next_retry_at timestamptz, - started_at timestamptz NOT NULL DEFAULT now(), - completed_at timestamptz, - updated_at timestamptz NOT NULL DEFAULT now(), - CHECK(amount IS NULL OR amount >= 0) -); -CREATE UNIQUE INDEX billing_transactions_idempotency_key ON billing_transactions(user_id,category,idempotency_key) WHERE idempotency_key IS NOT NULL; -CREATE INDEX billing_transactions_status_idx ON billing_transactions(status,next_retry_at); -CREATE INDEX billing_transactions_user_time_idx ON billing_transactions(user_id,started_at DESC,id DESC); -ALTER TABLE credit_ledger_entries ADD COLUMN transaction_id uuid REFERENCES billing_transactions(id); -ALTER TABLE credit_ledger_entries ADD COLUMN event_key text; -ALTER TABLE credit_ledger_entries ADD COLUMN sequence bigint; -ALTER TABLE credit_ledger_entries ADD COLUMN user_name text; -ALTER TABLE credit_ledger_entries ADD COLUMN user_email text; -ALTER TABLE credit_ledger_entries ADD COLUMN group_id uuid REFERENCES groups(id); -ALTER TABLE credit_ledger_entries ADD COLUMN mode text NOT NULL DEFAULT 'local'; -ALTER TABLE credit_ledger_entries ADD COLUMN reverses_id uuid REFERENCES credit_ledger_entries(id); -WITH numbered AS (SELECT id,row_number() OVER(PARTITION BY account_id ORDER BY created_at,id) AS n FROM credit_ledger_entries) UPDATE credit_ledger_entries e SET sequence=n.n FROM numbered n WHERE n.id=e.id; -UPDATE credit_ledger_entries e SET user_name=u.name,user_email=u.email FROM users u WHERE u.id=e.user_id; -CREATE UNIQUE INDEX credit_ledger_entries_event_key ON credit_ledger_entries(event_key) WHERE event_key IS NOT NULL; -CREATE UNIQUE INDEX credit_ledger_entries_sequence_key ON credit_ledger_entries(account_id,sequence); -CREATE INDEX credit_ledger_entries_time_idx ON credit_ledger_entries(occurred_at DESC,id DESC); -CREATE TABLE wallet_user_bindings ( - user_id uuid PRIMARY KEY REFERENCES users(id), - external_user_id text NOT NULL UNIQUE, - verified_at timestamptz NOT NULL, - updated_by_user_id uuid NOT NULL REFERENCES users(id) -); -CREATE TABLE wallet_billing_records ( - biz_id text PRIMARY KEY, - transaction_id uuid NOT NULL UNIQUE REFERENCES billing_transactions(id), - external_user_id text NOT NULL, - team_slug text NOT NULL DEFAULT '', - environment text NOT NULL, - app_id integer NOT NULL, - status text NOT NULL CHECK(status IN ('pending','reserved','confirming','confirmed','rejected','unknown')), - frozen_amount_quota bigint NOT NULL CHECK(frozen_amount_quota >= 0), - actual_amount_quota bigint, - confirmation_status text, - error_code text NOT NULL DEFAULT '', - trace_id text NOT NULL DEFAULT '', - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - confirmed_at timestamptz -); -CREATE TABLE billing_migration_issues ( - id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, - subject text NOT NULL, - value jsonb NOT NULL, - reason text NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() -); -INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id) -SELECT 'group','00000000-0000-0000-0000-000000000001',CASE WHEN (s.value->>'root_credits') ~ '^\d+(\.\d{1,6})?$' THEN (s.value->>'root_credits')::numeric ELSE 15000 END,s.updated_by_user_id -FROM settings s WHERE s.key='billing' AND EXISTS(SELECT 1 FROM groups WHERE id='00000000-0000-0000-0000-000000000001') AND NOT EXISTS(SELECT 1 FROM billing_quotas WHERE group_id='00000000-0000-0000-0000-000000000001' AND deleted_at IS NULL); -CREATE TEMP TABLE billing_legacy_quotas ON COMMIT DROP AS -SELECT e.key,e.value,s.updated_by_user_id, - CASE WHEN g.id IS NOT NULL AND u.id IS NULL THEN 'group' WHEN u.id IS NOT NULL AND g.id IS NULL THEN 'user' END subject_type, - g.id group_id,u.id user_id, - CASE WHEN (e.value #>> '{}') ~ '^\d{1,12}(\.\d{1,6})?$' THEN (e.value #>> '{}')::numeric END credits -FROM settings s -CROSS JOIN LATERAL jsonb_each(CASE WHEN jsonb_typeof(s.value->'quota_overrides')='object' THEN s.value->'quota_overrides' ELSE '{}' END) e -LEFT JOIN groups g ON g.id::text=lower(e.key) AND g.deleted_at IS NULL -LEFT JOIN users u ON u.id::text=lower(e.key) AND u.deleted_at IS NULL -WHERE s.key='billing'; -INSERT INTO billing_migration_issues(subject,value,reason) -SELECT l.key,l.value,CASE WHEN l.subject_type IS NULL THEN '旧额度对象不能匹配唯一真实用户或分组' WHEN l.credits IS NULL THEN '旧额度金额无效' ELSE '额度表已存在配置,保留原配置并记录差异' END -FROM billing_legacy_quotas l WHERE l.subject_type IS NULL OR l.credits IS NULL OR EXISTS(SELECT 1 FROM billing_quotas q WHERE q.deleted_at IS NULL AND (q.group_id=l.group_id OR q.user_id=l.user_id) AND q.credits_per_cycle<>l.credits); -INSERT INTO billing_quotas(subject_type,group_id,user_id,credits_per_cycle,updated_by_user_id) -SELECT l.subject_type,l.group_id,l.user_id,l.credits,l.updated_by_user_id FROM billing_legacy_quotas l -WHERE l.subject_type IS NOT NULL AND l.credits IS NOT NULL AND NOT EXISTS(SELECT 1 FROM billing_quotas q WHERE q.deleted_at IS NULL AND (q.group_id=l.group_id OR q.user_id=l.user_id)); - -UPDATE settings SET value=value-'quota_overrides'-'remote_billing_api_key'-'remote_billing_base_url',revision=revision+1 WHERE key='billing'; -CREATE FUNCTION billing_immutable_ledger() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION '计费流水不可修改或删除,请使用冲正'; END $$; -CREATE TRIGGER credit_ledger_immutable BEFORE UPDATE OR DELETE ON credit_ledger_entries FOR EACH ROW EXECUTE FUNCTION billing_immutable_ledger(); -COMMIT; diff --git a/monkeyai/backend/migrations/000003_group_virtual_root.down.sql b/monkeyai/backend/migrations/000003_group_virtual_root.down.sql deleted file mode 100644 index e390c136..00000000 --- a/monkeyai/backend/migrations/000003_group_virtual_root.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DO $$ -BEGIN - RAISE EXCEPTION '旧系统分组授权已转换为用户授权,无法无损回滚;请恢复升级前的数据库备份'; -END $$; diff --git a/monkeyai/backend/migrations/000003_group_virtual_root.up.sql b/monkeyai/backend/migrations/000003_group_virtual_root.up.sql deleted file mode 100644 index 5b631532..00000000 --- a/monkeyai/backend/migrations/000003_group_virtual_root.up.sql +++ /dev/null @@ -1,89 +0,0 @@ -BEGIN; - -LOCK TABLE groups, group_users, resource_access_grants, users, settings, billing_quotas, credit_accounts, billing_transactions, credit_ledger_entries IN SHARE ROW EXCLUSIVE MODE; - -DROP INDEX IF EXISTS groups_one_active_root_key; - --- 将旧系统组的有效授权保留为当前成员的直接授权,不再按角色自动扩展。 -WITH RECURSIVE descendants(root_id, id) AS ( - SELECT id, id FROM groups - WHERE id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002') - AND deleted_at IS NULL - UNION - SELECT d.root_id, g.id FROM groups g - JOIN descendants d ON g.parent_id = d.id - WHERE g.deleted_at IS NULL -), members(group_id, user_id) AS ( - SELECT g.id, u.id FROM groups g CROSS JOIN users u - WHERE g.id = '00000000-0000-0000-0000-000000000001' - AND g.deleted_at IS NULL AND u.deleted_at IS NULL - UNION - SELECT g.id, u.id FROM groups g CROSS JOIN users u - WHERE g.id = '00000000-0000-0000-0000-000000000002' - AND g.deleted_at IS NULL AND u.deleted_at IS NULL AND u.role = 'admin' - UNION - SELECT d.root_id, gu.user_id FROM descendants d - JOIN group_users gu ON gu.group_id = d.id AND gu.removed_at IS NULL - JOIN users u ON u.id = gu.user_id AND u.deleted_at IS NULL -) -INSERT INTO resource_access_grants ( - resource_type, resource_id, user_id, access_level, - usage_requirement, granted_by_user_id, created_at -) -SELECT g.resource_type, g.resource_id, m.user_id, - CASE WHEN bool_or(g.access_level = 'read_write') THEN 'read_write' ELSE 'read_only' END, - CASE WHEN bool_or(g.usage_requirement = 'required') THEN 'required' ELSE 'optional' END, - min(g.granted_by_user_id::text)::uuid, min(g.created_at) -FROM resource_access_grants g -JOIN members m ON m.group_id = g.group_id -GROUP BY g.resource_type, g.resource_id, m.user_id -ON CONFLICT (resource_type, resource_id, user_id) WHERE user_id IS NOT NULL -DO UPDATE SET - access_level = CASE WHEN resource_access_grants.access_level = 'read_write' OR EXCLUDED.access_level = 'read_write' THEN 'read_write' ELSE 'read_only' END, - usage_requirement = CASE WHEN resource_access_grants.usage_requirement = 'required' OR EXCLUDED.usage_requirement = 'required' THEN 'required' ELSE 'optional' END, - updated_at = now(); - --- 团队额度改存计费设置;管理员组的既有额度转为当前成员或直属子组的显式额度。 -UPDATE settings s SET value=jsonb_set(s.value,'{root_credits}',to_jsonb(q.credits_per_cycle::text)), revision=revision+1 -FROM billing_quotas q -WHERE s.key='billing' AND q.group_id='00000000-0000-0000-0000-000000000001' AND q.deleted_at IS NULL; - -INSERT INTO billing_quotas(subject_type,user_id,credits_per_cycle,updated_by_user_id) -SELECT 'user',u.id,q.credits_per_cycle,q.updated_by_user_id FROM users u CROSS JOIN billing_quotas q -WHERE q.group_id='00000000-0000-0000-0000-000000000002' AND q.deleted_at IS NULL - AND u.deleted_at IS NULL - AND (u.billing_group_id=q.group_id OR (u.billing_group_id IS NULL AND u.role='admin')) -ON CONFLICT (user_id) WHERE subject_type='user' AND deleted_at IS NULL DO NOTHING; - -INSERT INTO billing_quotas(subject_type,group_id,credits_per_cycle,updated_by_user_id) -SELECT 'group',g.id,q.credits_per_cycle,q.updated_by_user_id FROM groups g JOIN billing_quotas q ON q.group_id=g.parent_id -WHERE q.group_id='00000000-0000-0000-0000-000000000002' AND q.deleted_at IS NULL AND g.deleted_at IS NULL -ON CONFLICT (group_id) WHERE subject_type='group' AND deleted_at IS NULL DO NOTHING; - -UPDATE users SET billing_group_id=NULL -WHERE billing_group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002'); -UPDATE credit_accounts SET group_id=NULL -WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002'); -UPDATE billing_transactions SET group_id=NULL -WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002'); --- 仅迁移分组引用,流水金额、顺序、余额及业务标识保持不变。 -ALTER TABLE credit_ledger_entries DISABLE TRIGGER credit_ledger_immutable; -UPDATE credit_ledger_entries SET metadata=metadata || jsonb_build_object('legacy_group_id',group_id),group_id=NULL -WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002'); -ALTER TABLE credit_ledger_entries ENABLE TRIGGER credit_ledger_immutable; -DELETE FROM billing_quotas -WHERE group_id IN ('00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002'); - -UPDATE groups SET parent_id = NULL, updated_at = now() -WHERE parent_id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002'); - -DELETE FROM group_users -WHERE group_id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002'); - -DELETE FROM resource_access_grants -WHERE group_id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002'); - -DELETE FROM groups -WHERE id IN ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000002'); - -COMMIT; diff --git a/monkeyai/backend/migrations/000004_stats_add_indexes.down.sql b/monkeyai/backend/migrations/000004_stats_add_indexes.down.sql deleted file mode 100644 index de1a6e71..00000000 --- a/monkeyai/backend/migrations/000004_stats_add_indexes.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; -DROP INDEX sessions_last_active_idx; -DROP INDEX sessions_started_idx; -DROP INDEX mcp_tool_calls_completed_idx; -DROP INDEX model_calls_completed_idx; -DROP INDEX model_calls_started_idx; -COMMIT; diff --git a/monkeyai/backend/migrations/000004_stats_add_indexes.up.sql b/monkeyai/backend/migrations/000004_stats_add_indexes.up.sql deleted file mode 100644 index 1b5333aa..00000000 --- a/monkeyai/backend/migrations/000004_stats_add_indexes.up.sql +++ /dev/null @@ -1,7 +0,0 @@ -BEGIN; -CREATE INDEX model_calls_started_idx ON model_calls (started_at); -CREATE INDEX model_calls_completed_idx ON model_calls (completed_at) WHERE completed_at IS NOT NULL; -CREATE INDEX mcp_tool_calls_completed_idx ON mcp_tool_calls (completed_at) WHERE completed_at IS NOT NULL; -CREATE INDEX sessions_started_idx ON sessions (started_at DESC,id DESC) WHERE deleted_at IS NULL; -CREATE INDEX sessions_last_active_idx ON sessions (last_active_at) WHERE deleted_at IS NULL; -COMMIT; diff --git a/monkeyai/backend/migrations/000005_audit_request.down.sql b/monkeyai/backend/migrations/000005_audit_request.down.sql deleted file mode 100644 index 9f359fbc..00000000 --- a/monkeyai/backend/migrations/000005_audit_request.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX audits_request_idx; -ALTER TABLE audits DROP COLUMN request_id; diff --git a/monkeyai/backend/migrations/000005_audit_request.up.sql b/monkeyai/backend/migrations/000005_audit_request.up.sql deleted file mode 100644 index f7d629da..00000000 --- a/monkeyai/backend/migrations/000005_audit_request.up.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE audits ADD COLUMN request_id text; -CREATE INDEX audits_request_idx ON audits (request_id) WHERE request_id IS NOT NULL; diff --git a/monkeyai/backend/migrations/000006_identity_email_auth.down.sql b/monkeyai/backend/migrations/000006_identity_email_auth.down.sql deleted file mode 100644 index 792ffee3..00000000 --- a/monkeyai/backend/migrations/000006_identity_email_auth.down.sql +++ /dev/null @@ -1,5 +0,0 @@ -DELETE FROM browser_sessions WHERE authentication_method = 'email_code'; -ALTER TABLE browser_sessions DROP CONSTRAINT browser_sessions_authentication_method_check; -ALTER TABLE browser_sessions ADD CONSTRAINT browser_sessions_authentication_method_check CHECK (authentication_method IN ('password', 'oauth')); -DROP TABLE email_code_deliveries; -DROP TABLE email_codes; diff --git a/monkeyai/backend/migrations/000006_identity_email_auth.up.sql b/monkeyai/backend/migrations/000006_identity_email_auth.up.sql deleted file mode 100644 index 48de69e6..00000000 --- a/monkeyai/backend/migrations/000006_identity_email_auth.up.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE email_codes ( - email text NOT NULL, - purpose text NOT NULL CHECK (purpose IN ('login', 'register', 'reset')), - code_hash text NOT NULL, - expires_at timestamptz NOT NULL, - attempts integer NOT NULL DEFAULT 0, - ready boolean NOT NULL DEFAULT false, - PRIMARY KEY (email, purpose) -); -CREATE TABLE email_code_deliveries ( - id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, - email text NOT NULL, - ip_hash text NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX email_code_deliveries_created_idx ON email_code_deliveries (created_at); -ALTER TABLE browser_sessions DROP CONSTRAINT browser_sessions_authentication_method_check; -ALTER TABLE browser_sessions ADD CONSTRAINT browser_sessions_authentication_method_check CHECK (authentication_method IN ('password', 'oauth', 'email_code')); diff --git a/monkeyai/backend/migrations/000007_resource_all_users_grant.down.sql b/monkeyai/backend/migrations/000007_resource_all_users_grant.down.sql deleted file mode 100644 index dfb23766..00000000 --- a/monkeyai/backend/migrations/000007_resource_all_users_grant.down.sql +++ /dev/null @@ -1,21 +0,0 @@ -BEGIN; - --- 降级前须显式撤销全员授权,避免静默丢失访问范围。 -DO $$ -BEGIN - IF EXISTS (SELECT 1 FROM resource_access_grants WHERE all_users) THEN - RAISE EXCEPTION '请先撤销全员授权,再回滚迁移'; - END IF; -END -$$; - -DROP INDEX resource_access_grants_all_users_key; - -ALTER TABLE resource_access_grants - DROP CONSTRAINT resource_access_grants_subject_check, - DROP COLUMN all_users, - ADD CONSTRAINT resource_access_grants_subject_check CHECK ( - (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer = 1 - ); - -COMMIT; diff --git a/monkeyai/backend/migrations/000007_resource_all_users_grant.up.sql b/monkeyai/backend/migrations/000007_resource_all_users_grant.up.sql deleted file mode 100644 index 5c92f7d2..00000000 --- a/monkeyai/backend/migrations/000007_resource_all_users_grant.up.sql +++ /dev/null @@ -1,14 +0,0 @@ -BEGIN; - -ALTER TABLE resource_access_grants - ADD COLUMN all_users boolean NOT NULL DEFAULT false, - DROP CONSTRAINT resource_access_grants_subject_check, - ADD CONSTRAINT resource_access_grants_subject_check CHECK ( - (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer + all_users::integer = 1 - ); - -CREATE UNIQUE INDEX resource_access_grants_all_users_key - ON resource_access_grants (resource_type, resource_id) - WHERE all_users; - -COMMIT; diff --git a/monkeyai/backend/migrations/000008_billing_wallet_urls.down.sql b/monkeyai/backend/migrations/000008_billing_wallet_urls.down.sql deleted file mode 100644 index 2f55d71d..00000000 --- a/monkeyai/backend/migrations/000008_billing_wallet_urls.down.sql +++ /dev/null @@ -1,27 +0,0 @@ -DO $$ -BEGIN - IF EXISTS ( - SELECT 1 FROM wallet_billing_records - WHERE base_url NOT IN ('https://baizhiyun.vip', 'https://baizhi.cloud') - ) OR EXISTS ( - SELECT 1 FROM settings WHERE key = 'billing' - AND value#>>'{wallet,base_url}' NOT IN ('https://baizhiyun.vip', 'https://baizhi.cloud') - ) THEN - RAISE EXCEPTION '旧版本不支持自定义百智云 URL,无法回退当前连接配置或交易记录'; - END IF; -END $$; - -UPDATE settings -SET value = jsonb_set(value, '{wallet}', ((value->'wallet') - 'base_url') || jsonb_build_object( - 'environment', CASE value#>>'{wallet,base_url}' - WHEN 'https://baizhiyun.vip' THEN 'dev' - WHEN 'https://baizhi.cloud' THEN 'prod' END -)) -WHERE key = 'billing' AND value#>>'{wallet,base_url}' IS NOT NULL; - -UPDATE wallet_billing_records -SET base_url = CASE base_url - WHEN 'https://baizhiyun.vip' THEN 'dev' - WHEN 'https://baizhi.cloud' THEN 'prod' END; - -ALTER TABLE wallet_billing_records RENAME COLUMN base_url TO environment; diff --git a/monkeyai/backend/migrations/000008_billing_wallet_urls.up.sql b/monkeyai/backend/migrations/000008_billing_wallet_urls.up.sql deleted file mode 100644 index 96362186..00000000 --- a/monkeyai/backend/migrations/000008_billing_wallet_urls.up.sql +++ /dev/null @@ -1,15 +0,0 @@ -ALTER TABLE wallet_billing_records RENAME COLUMN environment TO base_url; - -UPDATE wallet_billing_records -SET base_url = CASE base_url - WHEN 'dev' THEN 'https://baizhiyun.vip' - WHEN 'prod' THEN 'https://baizhi.cloud' - ELSE base_url END; - -UPDATE settings -SET value = jsonb_set(value, '{wallet}', ((value->'wallet') - 'environment') || jsonb_build_object( - 'base_url', CASE value#>>'{wallet,environment}' - WHEN 'dev' THEN 'https://baizhiyun.vip' - WHEN 'prod' THEN 'https://baizhi.cloud' END -)) -WHERE key = 'billing' AND value#>>'{wallet,environment}' IN ('dev', 'prod'); diff --git a/monkeyai/backend/migrations/000009_identity_baizhiyun_provider.down.sql b/monkeyai/backend/migrations/000009_identity_baizhiyun_provider.down.sql deleted file mode 100644 index e7d910ac..00000000 --- a/monkeyai/backend/migrations/000009_identity_baizhiyun_provider.down.sql +++ /dev/null @@ -1,18 +0,0 @@ -BEGIN; - -DO $$ -BEGIN - IF EXISTS (SELECT 1 FROM user_identities WHERE provider = 'baizhiyun') - OR EXISTS (SELECT 1 FROM settings WHERE key = 'authentication' - AND value @> '{"oauth_connections":[{"provider":"baizhiyun"}]}') THEN - RAISE EXCEPTION '存在百智云登录配置或身份,不能回滚'; - END IF; -END $$; - -ALTER TABLE user_identities - DROP CONSTRAINT user_identities_provider_check, - ADD CONSTRAINT user_identities_provider_check CHECK ( - provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc') - ); - -COMMIT; diff --git a/monkeyai/backend/migrations/000009_identity_baizhiyun_provider.up.sql b/monkeyai/backend/migrations/000009_identity_baizhiyun_provider.up.sql deleted file mode 100644 index 52c3c2a4..00000000 --- a/monkeyai/backend/migrations/000009_identity_baizhiyun_provider.up.sql +++ /dev/null @@ -1,9 +0,0 @@ -BEGIN; - -ALTER TABLE user_identities - DROP CONSTRAINT user_identities_provider_check, - ADD CONSTRAINT user_identities_provider_check CHECK ( - provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc', 'baizhiyun') - ); - -COMMIT; diff --git a/monkeyai/backend/migrations/000010_mcp_enable_personal_tools.down.sql b/monkeyai/backend/migrations/000010_mcp_enable_personal_tools.down.sql deleted file mode 100644 index 33c9d412..00000000 --- a/monkeyai/backend/migrations/000010_mcp_enable_personal_tools.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- 数据修复保留已启用的个人工具,回滚不重新禁用用户可用的工具。 -SELECT 1; diff --git a/monkeyai/backend/migrations/000010_mcp_enable_personal_tools.up.sql b/monkeyai/backend/migrations/000010_mcp_enable_personal_tools.up.sql deleted file mode 100644 index 831d5ac0..00000000 --- a/monkeyai/backend/migrations/000010_mcp_enable_personal_tools.up.sql +++ /dev/null @@ -1,10 +0,0 @@ -UPDATE mcp_tools t -SET enabled = true, - updated_at = now() -FROM connectors c -WHERE c.id = t.connector_id - AND c.ownership_type = 'user' - AND c.deleted_at IS NULL - AND t.config_revision = c.config_revision - AND t.deleted_at IS NULL - AND NOT t.enabled; diff --git a/monkeyai/backend/migrations/000011_expert_personal_ownership.down.sql b/monkeyai/backend/migrations/000011_expert_personal_ownership.down.sql deleted file mode 100644 index a16b42e0..00000000 --- a/monkeyai/backend/migrations/000011_expert_personal_ownership.down.sql +++ /dev/null @@ -1,11 +0,0 @@ -DO $$ -BEGIN - IF EXISTS (SELECT 1 FROM experts WHERE ownership_type = 'user' AND deleted_at IS NULL) THEN - RAISE EXCEPTION '存在未删除的个人专家,不能回退专家归属迁移'; - END IF; -END $$; - -DROP INDEX experts_user_name_key; -DROP INDEX experts_system_name_key; -CREATE UNIQUE INDEX experts_name_key ON experts(lower(btrim(name))) WHERE deleted_at IS NULL; -ALTER TABLE experts DROP COLUMN owner_user_id, DROP COLUMN ownership_type; diff --git a/monkeyai/backend/migrations/000011_expert_personal_ownership.up.sql b/monkeyai/backend/migrations/000011_expert_personal_ownership.up.sql deleted file mode 100644 index 74aacab6..00000000 --- a/monkeyai/backend/migrations/000011_expert_personal_ownership.up.sql +++ /dev/null @@ -1,13 +0,0 @@ -ALTER TABLE experts - ADD COLUMN ownership_type text NOT NULL DEFAULT 'system' - CHECK (ownership_type IN ('system', 'user')), - ADD COLUMN owner_user_id uuid REFERENCES users(id); - -UPDATE experts SET owner_user_id = created_by_user_id; -ALTER TABLE experts ALTER COLUMN owner_user_id SET NOT NULL; - -DROP INDEX experts_name_key; -CREATE UNIQUE INDEX experts_system_name_key ON experts(lower(btrim(name))) - WHERE ownership_type = 'system' AND deleted_at IS NULL; -CREATE UNIQUE INDEX experts_user_name_key ON experts(owner_user_id, lower(btrim(name))) - WHERE ownership_type = 'user' AND deleted_at IS NULL; diff --git a/monkeyai/backend/migrations/000012_mcp_connector_credentials.down.sql b/monkeyai/backend/migrations/000012_mcp_connector_credentials.down.sql deleted file mode 100644 index 311ce8a9..00000000 --- a/monkeyai/backend/migrations/000012_mcp_connector_credentials.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DO $$ BEGIN - RAISE EXCEPTION '多凭证结构不能无损恢复为单凭证;请恢复完整备份或另行完成数据归并,禁止静默删除凭证。'; -END $$; diff --git a/monkeyai/backend/migrations/000012_mcp_connector_credentials.up.sql b/monkeyai/backend/migrations/000012_mcp_connector_credentials.up.sql deleted file mode 100644 index f9c45c11..00000000 --- a/monkeyai/backend/migrations/000012_mcp_connector_credentials.up.sql +++ /dev/null @@ -1,116 +0,0 @@ -BEGIN; - -CREATE TABLE expert_connectors ( - expert_id uuid NOT NULL REFERENCES experts(id), - connector_id uuid NOT NULL REFERENCES connectors(id), - required boolean NOT NULL DEFAULT true, - tool_allowlist text[] NOT NULL DEFAULT '{}', - tool_denylist text[] NOT NULL DEFAULT '{}', - PRIMARY KEY (expert_id, connector_id) -); -CREATE INDEX expert_connectors_connector_idx ON expert_connectors(connector_id); - --- 多候选依赖通过连接参数 monkeyai.connector_mappings 显式指定:{"专家ID":{"模板ID":"连接ID"}}。 -DO $$ -DECLARE - link record; - selected uuid; - candidates uuid[]; - mappings jsonb := COALESCE(NULLIF(current_setting('monkeyai.connector_mappings', true), ''), '{}')::jsonb; - issues jsonb := '[]'::jsonb; -BEGIN - FOR link IN - SELECT x.*, e.ownership_type, e.owner_user_id - FROM expert_connector_providers x JOIN experts e ON e.id = x.expert_id - WHERE e.deleted_at IS NULL - LOOP - WITH RECURSIVE user_groups AS ( - SELECT g.id, g.parent_id FROM groups g JOIN group_users gu ON gu.group_id = g.id - WHERE gu.user_id = link.owner_user_id AND gu.removed_at IS NULL AND g.deleted_at IS NULL - UNION - SELECT p.id, p.parent_id FROM groups p JOIN user_groups child ON child.parent_id = p.id - WHERE p.deleted_at IS NULL - ) - SELECT array_agg(c.id ORDER BY c.id) INTO candidates - FROM connectors c - WHERE c.provider_id = link.provider_id AND c.deleted_at IS NULL AND c.enabled - AND (link.ownership_type = 'system' AND c.ownership_type = 'system' - OR link.ownership_type = 'user' AND EXISTS ( - SELECT 1 FROM users u WHERE u.id = link.owner_user_id AND u.status = 'active' AND u.deleted_at IS NULL - ) AND (c.ownership_type = 'user' AND c.owner_user_id = link.owner_user_id - OR EXISTS (SELECT 1 FROM resource_access_grants g - WHERE g.resource_type = 'connector' AND g.resource_id = c.id - AND (g.all_users OR g.user_id = link.owner_user_id OR g.group_id IN (SELECT id FROM user_groups)))) - AND (c.ownership_type = 'user' - OR NOT EXISTS (SELECT 1 FROM settings WHERE key = 'billing' AND value->>'charging_mode' = 'remote') - OR EXISTS (SELECT 1 FROM user_identities i WHERE i.user_id = link.owner_user_id - AND i.provider = 'baizhiyun' AND i.deleted_at IS NULL))); - selected := (mappings -> link.expert_id::text ->> link.provider_id::text)::uuid; - IF selected IS NULL AND cardinality(candidates) = 1 THEN - selected := candidates[1]; - END IF; - IF selected IS NULL OR NOT COALESCE(selected = ANY(candidates), false) THEN - issues := issues || jsonb_build_array(jsonb_build_object( - 'expert_id', link.expert_id, 'provider_id', link.provider_id, - 'candidates', COALESCE(to_jsonb(candidates), '[]'::jsonb), - 'reason', CASE WHEN selected IS NOT NULL THEN 'invalid_mapping' WHEN COALESCE(cardinality(candidates),0) = 0 THEN 'missing_connector' ELSE 'ambiguous_connector' END)); - ELSE - INSERT INTO expert_connectors(expert_id, connector_id, required, tool_allowlist, tool_denylist) - VALUES(link.expert_id, selected, link.required, link.tool_allowlist, link.tool_denylist); - END IF; - END LOOP; - IF jsonb_array_length(issues) > 0 THEN - RAISE EXCEPTION '专家连接映射不完整,请设置 monkeyai.connector_mappings;未修改原数据。% ', issues; - END IF; -END $$; - -ALTER TABLE connectors ADD COLUMN icon_s3_key text NOT NULL DEFAULT ''; -UPDATE connectors c SET icon_s3_key = p.icon_s3_key, - enabled = c.enabled AND p.enabled AND p.deleted_at IS NULL -FROM connector_providers p WHERE c.provider_id = p.id; - -ALTER TABLE connector_credentials - DROP CONSTRAINT connector_credentials_connector_id_user_id_key, - ADD COLUMN name text NOT NULL DEFAULT '原有凭证' CHECK (char_length(btrim(name)) BETWEEN 1 AND 128), - ADD COLUMN revision bigint NOT NULL DEFAULT 1, - ADD COLUMN connection_status text NOT NULL DEFAULT 'unknown' CHECK (connection_status IN ('unknown','connected','error')), - ADD COLUMN last_checked_at timestamptz, - ADD COLUMN last_error text; -UPDATE connector_credentials SET revoked_at = COALESCE(revoked_at, now()) WHERE status = 'revoked'; -UPDATE connector_credentials SET http_headers = '{}', oauth_access_token = '', oauth_refresh_token = '', - oauth_expires_at = now(), revision = revision + 1 -WHERE status = 'error' OR (status = 'expired' AND oauth_refresh_token = ''); -UPDATE connector_credentials cc SET revoked_at = COALESCE(cc.revoked_at, now()) -FROM connectors c WHERE c.id = cc.connector_id AND (c.authorization_mode = 'none' - OR (c.authorization_mode = 'centralized' AND cc.user_id IS NOT NULL) - OR (c.authorization_mode = 'independent' AND cc.user_id IS NULL) - OR cc.method IS DISTINCT FROM c.authorization_method); -UPDATE connector_credentials cc SET http_headers = '{}' FROM connectors c -WHERE c.id = cc.connector_id AND c.authorization_method IS DISTINCT FROM 'http_header'; -UPDATE connector_credentials cc SET oauth_access_token = '', oauth_refresh_token = '', oauth_expires_at = NULL -FROM connectors c WHERE c.id = cc.connector_id AND c.authorization_method IS DISTINCT FROM 'oauth'; -ALTER TABLE connector_credentials DROP COLUMN method, DROP COLUMN status; -CREATE INDEX connector_credentials_user_idx ON connector_credentials(connector_id, user_id); -CREATE UNIQUE INDEX connector_credentials_centralized_idx ON connector_credentials(connector_id) - WHERE user_id IS NULL AND revoked_at IS NULL; -ALTER TABLE connector_credentials ADD CONSTRAINT connector_credentials_id_connector_key UNIQUE(id, connector_id); -ALTER TABLE mcp_tools ADD CONSTRAINT mcp_tools_credential_connector_fkey - FOREIGN KEY (credential_id, connector_id) REFERENCES connector_credentials(id, connector_id); -UPDATE mcp_tools t SET deleted_at = COALESCE(t.deleted_at, now()) -FROM connector_credentials cc WHERE t.credential_id = cc.id - AND (cc.revoked_at IS NOT NULL OR (cc.http_headers = '{}' AND cc.oauth_access_token = '' AND cc.oauth_refresh_token = '')); - -ALTER TABLE connector_oauth_requests - ADD COLUMN credential_id uuid REFERENCES connector_credentials(id), - ADD COLUMN credential_revision bigint, - ADD COLUMN name text NOT NULL DEFAULT '原有凭证', - DROP COLUMN centralized; -UPDATE connector_oauth_requests SET status = CASE WHEN status = 'authorized' THEN 'succeeded' ELSE 'failed' END; -ALTER TABLE connector_oauth_requests ADD CONSTRAINT connector_oauth_requests_status_check - CHECK (status IN ('pending','processing','succeeded','failed','expired')); -CREATE INDEX connector_oauth_requests_expires_idx ON connector_oauth_requests(expires_at); - -DROP TABLE expert_connector_providers; -ALTER TABLE connectors DROP COLUMN provider_id; -DROP TABLE connector_providers; -COMMIT; diff --git a/monkeyai/backend/migrations/000013_expert_remove_default_model.down.sql b/monkeyai/backend/migrations/000013_expert_remove_default_model.down.sql deleted file mode 100644 index fa7b4604..00000000 --- a/monkeyai/backend/migrations/000013_expert_remove_default_model.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- 只恢复字段结构,已删除的默认模型绑定无法恢复。 -ALTER TABLE experts ADD COLUMN default_model_id uuid REFERENCES models(id); diff --git a/monkeyai/backend/migrations/000013_expert_remove_default_model.up.sql b/monkeyai/backend/migrations/000013_expert_remove_default_model.up.sql deleted file mode 100644 index bc90aa55..00000000 --- a/monkeyai/backend/migrations/000013_expert_remove_default_model.up.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE experts DROP COLUMN default_model_id; diff --git a/monkeyai/backend/migrations/README.md b/monkeyai/backend/migrations/README.md index 22688426..8cc0b003 100644 --- a/monkeyai/backend/migrations/README.md +++ b/monkeyai/backend/migrations/README.md @@ -1,27 +1,25 @@ # 数据库迁移 -- `000001_initial_create_schema`:完整初始结构,包含身份、OAuth、调用密钥、模型、资源、计费及审计;不预置任何分组。 -- `000002_billing_create_transactions`:计费账户、额度与流水。 -- `000003_group_virtual_root`:将旧部署的系统分组转换为虚拟团队根节点的结构。新库同样执行此版本,不会创建分组。 +本次按重新部署要求,将原 `000001` 至 `000013` 的最终结构收敛到一版初始化迁移: -- `000004_stats_add_indexes`:为统计查询补充调用与会话的时间索引,仅增索引,可独立回滚。 +- `000001_initial_create_schema.up.sql`:完整创建身份与邮箱认证、OAuth、调用密钥、分组、设置、模型、资源、连接与多凭证、专家、计费、统计索引及审计结构。 +- `000001_initial_create_schema.down.sql`:按依赖逆序删除本版本的表、序列和计费流水保护函数,仅用于可丢弃测试数据库。 -运行 `migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up`。成功后应为 `version=13, dirty=false`,再次执行为 `no change`。已有数据库执行增量升级,无需清库或 `force`。 +必须使用全新的 PostgreSQL 数据库或数据目录。重建容器但复用旧数据目录不构成全新初始化。此版本替换了旧迁移历史,不支持在已执行旧版迁移的数据库上直接升级,也不能通过 `force 1` 代替数据迁移;需保留旧数据时应另行制定迁移方案。本次代码收敛不操作现有部署数据。 -团队根节点仅用于界面展示,名称读取 `settings` 中 `branding` 的 `workspace_name`,不写入 `groups`。`parent_id IS NULL` 的记录均为团队根节点的直属子分组;成员关系通过 `group_users` 显式维护,不根据用户角色自动建组或分配。 +从 `backend` 目录执行: -版本 3 升级会移除旧版固定 ID 的根组和管理员组,将它们的子分组提升到团队下,保留自定义分组、成员账号和自定义组的成员关系。旧系统组的资源授权转换为升级时有效成员的直接用户授权,保留强制规则和读写权限;后续新用户或角色变化不会自动获得这些授权。用户原有的直接授权和其他分组授权会保留。 +```sh +migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up +migrate -path migrations -database "$MONKEYAI_DATABASE_URL" version +``` -升级前应备份数据库。系统分组及其授权转换无法无损还原,因此版本 3 的 down 脚本明确拒绝回滚,需要恢复升级前备份。版本 1 的 down 脚本仅供可丢弃测试数据库验证。 +成功后 `schema_migrations` 应为 `version=1, dirty=false`,再次 `up` 返回 `no change`。可丢弃测试库执行 `down -all` 后再 `up`,应能完整重建。 -后续 schema 变更追加迁移版本。字符串统一使用 `text`,候选值使用 `CHECK`。 +初始化不预置用户、分组或业务设置。首次管理员由后端按部署环境变量创建,RustFS Bucket 由后端启动流程检查并按需创建。团队根节点仅用于界面展示,名称读取 `settings.branding.workspace_name`;顶层分组使用 `parent_id IS NULL`,成员关系通过 `group_users` 显式维护。 -团队额度存入计费设置,旧管理员组额度转为当前相关用户及直属子分组的显式额度。旧系统组计费归属置空,历史账户金额保持不变,流水的旧分组 ID 留在 metadata 中。 +连接直接保存配置,专家直接关联连接;同一用户可以为同一连接创建多份凭证,每个连接最多保留一份未撤销的集中凭证。工具的组合外键防止跨连接引用凭证。计费账户从初始化起校验余额与冻结金额,流水触发器禁止修改和删除。 -- `000005_audit_request`:增加审计请求关联字段和索引,保留历史记录;升级服务前先执行迁移。 +`migrations` 仍是结构定义的唯一来源。修改后在 `backend` 运行 `make generate` 更新 sqlc schema 与生成文件,再运行 `make check`;数据库集成测试验证有业务数据时的 `down → up`。迁移文件名和 up/down 配对由 `go test ./migrations` 检查。 -- `000010_mcp_enable_personal_tools`:启用已有个人 MCP 中当前配置版本下未删除的工具,修复服务端发现工具但客户端目录为空的问题。系统工具配置保持原值。此迁移仅修复数据,down 保留修复结果,不重新禁用个人工具;部署本次 MCP 修复时需升级至版本 10。 - -- `000011_expert_personal_ownership`:为专家增加归属与所有者,历史专家保持系统归属,个人专家按所有者约束名称唯一。部署个人专家共享功能前升级至版本 11;存在未删除的个人专家时拒绝回滚,避免将个人数据转换为系统资源。 - -- `000013_expert_remove_default_model`:删除系统和个人专家的 `default_model_id` 及模型外键,保留专家本身与规则、技能、连接关系。升级服务前先执行迁移至版本 13。down 只恢复可空字段与外键,原模型绑定不能恢复。 +本次单版重置是重新部署的特定安排。后续正式发布后的 schema 变更正常追加六位递增迁移版本,已发布迁移不再改写。字符串统一使用 `text`,候选值使用 `CHECK`。 diff --git a/monkeyai/backend/migrations/migrations_test.go b/monkeyai/backend/migrations/migrations_test.go index 62a1d7bf..699a4ebc 100644 --- a/monkeyai/backend/migrations/migrations_test.go +++ b/monkeyai/backend/migrations/migrations_test.go @@ -51,8 +51,8 @@ func TestMigrations(t *testing.T) { } } - if versions["000001"] != "initial_create_schema" || versions["000002"] != "billing_create_transactions" || versions["000003"] != "group_virtual_root" { - t.Error("必须保留初始化迁移及计费增量迁移") + if versions["000001"] != "initial_create_schema" { + t.Error("必须保留完整初始化迁移") } for key, directions := range pairs { if !directions["up"] || !directions["down"] { diff --git a/monkeyai/backend/schema/schema.sql b/monkeyai/backend/schema/schema.sql index 77b24fa8..0c222df5 100644 --- a/monkeyai/backend/schema/schema.sql +++ b/monkeyai/backend/schema/schema.sql @@ -14,6 +14,7 @@ CREATE TABLE users ( created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, + billing_group_id uuid, CONSTRAINT users_role_check CHECK (role IN ('admin', 'user')), CONSTRAINT users_status_check CHECK (status IN ('active', 'disabled')), CONSTRAINT users_disabled_at_check CHECK ( @@ -35,7 +36,7 @@ CREATE TABLE user_identities ( updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, CONSTRAINT user_identities_provider_check CHECK ( - provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc') + provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc', 'baizhiyun') ) ); @@ -50,6 +51,9 @@ CREATE TABLE groups ( CONSTRAINT groups_not_own_parent_check CHECK (parent_id IS DISTINCT FROM id) ); +ALTER TABLE users ADD CONSTRAINT users_billing_group_id_fkey + FOREIGN KEY (billing_group_id) REFERENCES groups (id); + CREATE TABLE group_users ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), group_id uuid NOT NULL REFERENCES groups (id), @@ -67,6 +71,7 @@ CREATE TABLE settings ( updated_by_user_id uuid NOT NULL REFERENCES users (id), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + revision bigint NOT NULL DEFAULT 1, CONSTRAINT settings_key_check CHECK ( key IN ('branding', 'authentication', 'email', 'billing') ), @@ -140,32 +145,8 @@ CREATE TABLE rules ( CONSTRAINT rules_ownership_type_check CHECK (ownership_type IN ('system', 'user')) ); -CREATE TABLE connector_providers ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - identifier text NOT NULL, - ownership_type text NOT NULL DEFAULT 'system' CHECK (ownership_type IN ('system','user')), - owner_user_id uuid NOT NULL REFERENCES users(id), - name text NOT NULL, - description text NOT NULL DEFAULT '', - icon_s3_key text NOT NULL DEFAULT '', - url text NOT NULL, - authorization_mode text NOT NULL CHECK (authorization_mode IN ('none','centralized','independent')), - authorization_method text CHECK (authorization_method IN ('http_header','oauth')), - header_schema jsonb NOT NULL DEFAULT '{}'::jsonb, - oauth_config jsonb NOT NULL DEFAULT '{}'::jsonb, - oauth_client_secret text NOT NULL DEFAULT '', - enabled boolean NOT NULL DEFAULT true, - revision bigint NOT NULL DEFAULT 1, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - deleted_at timestamptz, - CHECK ((authorization_mode = 'none' AND authorization_method IS NULL) OR - (authorization_mode <> 'none' AND authorization_method IS NOT NULL)) -); - CREATE TABLE connectors ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - provider_id uuid NOT NULL REFERENCES connector_providers(id), ownership_type text NOT NULL DEFAULT 'system' CHECK (ownership_type IN ('system','user')), owner_user_id uuid NOT NULL REFERENCES users(id), name text NOT NULL, @@ -184,6 +165,7 @@ CREATE TABLE connectors ( created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, + icon_s3_key text NOT NULL DEFAULT '', CHECK ((authorization_mode = 'none' AND authorization_method IS NULL) OR (authorization_mode <> 'none' AND authorization_method IS NOT NULL)) ); @@ -192,17 +174,20 @@ CREATE TABLE connector_credentials ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), connector_id uuid NOT NULL REFERENCES connectors(id), user_id uuid REFERENCES users(id), - method text NOT NULL CHECK (method IN ('oauth','http_header')), http_headers jsonb NOT NULL DEFAULT '{}'::jsonb, oauth_access_token text NOT NULL DEFAULT '', oauth_refresh_token text NOT NULL DEFAULT '', oauth_expires_at timestamptz, - status text NOT NULL DEFAULT 'authorized' CHECK (status IN ('authorized','expired','revoked','error')), config_revision bigint NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), revoked_at timestamptz, - UNIQUE NULLS NOT DISTINCT (connector_id,user_id) + name text NOT NULL DEFAULT '原有凭证' CHECK (char_length(btrim(name)) BETWEEN 1 AND 128), + revision bigint NOT NULL DEFAULT 1, + connection_status text NOT NULL DEFAULT 'unknown' CHECK (connection_status IN ('unknown','connected','error')), + last_checked_at timestamptz, + last_error text, + CONSTRAINT connector_credentials_id_connector_key UNIQUE (id, connector_id) ); CREATE TABLE mcp_tools ( @@ -218,14 +203,15 @@ CREATE TABLE mcp_tools ( discovered_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), deleted_at timestamptz, - UNIQUE NULLS NOT DISTINCT (connector_id,credential_id,name) + UNIQUE NULLS NOT DISTINCT (connector_id,credential_id,name), + CONSTRAINT mcp_tools_credential_connector_fkey + FOREIGN KEY (credential_id, connector_id) REFERENCES connector_credentials(id, connector_id) ); CREATE TABLE connector_oauth_requests ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), connector_id uuid NOT NULL REFERENCES connectors(id), user_id uuid NOT NULL REFERENCES users(id), - centralized boolean NOT NULL, config_revision bigint NOT NULL, state_hash text NOT NULL UNIQUE, verifier text NOT NULL, @@ -233,7 +219,11 @@ CREATE TABLE connector_oauth_requests ( expires_at timestamptz NOT NULL, consumed_at timestamptz, status text NOT NULL DEFAULT 'pending', - created_at timestamptz NOT NULL DEFAULT now() + created_at timestamptz NOT NULL DEFAULT now(), + credential_id uuid REFERENCES connector_credentials(id), + credential_revision bigint, + name text NOT NULL DEFAULT '原有凭证', + CONSTRAINT connector_oauth_requests_status_check CHECK (status IN ('pending','processing','succeeded','failed','expired')) ); CREATE TABLE experts ( @@ -241,13 +231,14 @@ CREATE TABLE experts ( name text NOT NULL, description text NOT NULL, prompt text NOT NULL, - default_model_id uuid REFERENCES models(id), enabled boolean NOT NULL DEFAULT true, created_by_user_id uuid NOT NULL REFERENCES users (id), revision bigint NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - deleted_at timestamptz + deleted_at timestamptz, + ownership_type text NOT NULL DEFAULT 'system' CHECK (ownership_type IN ('system', 'user')), + owner_user_id uuid NOT NULL REFERENCES users(id) ); CREATE TABLE resource_access_grants ( @@ -261,11 +252,12 @@ CREATE TABLE resource_access_grants ( granted_by_user_id uuid NOT NULL REFERENCES users (id), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), + all_users boolean NOT NULL DEFAULT false, CONSTRAINT resource_access_grants_resource_type_check CHECK ( resource_type IN ('model', 'skill', 'rule', 'connector', 'expert') ), CONSTRAINT resource_access_grants_subject_check CHECK ( - (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer = 1 + (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer + all_users::integer = 1 ), CONSTRAINT resource_access_grants_access_level_check CHECK ( access_level IN ('read_only', 'read_write') @@ -289,13 +281,13 @@ CREATE TABLE resource_tags ( CONSTRAINT resource_tags_resource_key UNIQUE (resource_type, resource_id, tag_id) ); -CREATE TABLE expert_connector_providers ( +CREATE TABLE expert_connectors ( expert_id uuid NOT NULL REFERENCES experts(id), - provider_id uuid NOT NULL REFERENCES connector_providers(id), + connector_id uuid NOT NULL REFERENCES connectors(id), required boolean NOT NULL DEFAULT true, tool_allowlist text[] NOT NULL DEFAULT '{}', tool_denylist text[] NOT NULL DEFAULT '{}', - PRIMARY KEY (expert_id,provider_id) + PRIMARY KEY (expert_id, connector_id) ); CREATE TABLE expert_rules ( @@ -347,7 +339,7 @@ CREATE TABLE sessions ( CREATE TABLE model_calls ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - session_id uuid NOT NULL REFERENCES sessions (id), + session_id uuid REFERENCES sessions (id), user_id uuid NOT NULL REFERENCES users (id), model_id uuid NOT NULL REFERENCES models (id), request_id text, @@ -381,7 +373,7 @@ CREATE TABLE model_calls ( CREATE TABLE mcp_tool_calls ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - session_id uuid NOT NULL REFERENCES sessions (id), + session_id uuid REFERENCES sessions (id), user_id uuid NOT NULL REFERENCES users (id), connector_id uuid NOT NULL REFERENCES connectors (id), tool_id uuid NOT NULL REFERENCES mcp_tools (id), @@ -423,14 +415,51 @@ CREATE TABLE billing_quotas ( CREATE TABLE credit_accounts ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users (id) UNIQUE, + user_id uuid NOT NULL REFERENCES users (id), balance numeric(24, 6) NOT NULL DEFAULT 0, period_start_at timestamptz NOT NULL, period_end_at timestamptz NOT NULL, last_refreshed_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT credit_accounts_period_check CHECK (period_end_at > period_start_at) + frozen numeric(24,6) NOT NULL DEFAULT 0, + quota numeric(24,6) NOT NULL DEFAULT 0, + group_id uuid REFERENCES groups(id), + sequence bigint NOT NULL DEFAULT 0, + CONSTRAINT credit_accounts_period_check CHECK (period_end_at > period_start_at), + CONSTRAINT credit_accounts_amount_check CHECK (balance >= 0 AND frozen >= 0 AND frozen <= balance) +); + +CREATE TABLE billing_transactions ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + user_id uuid NOT NULL REFERENCES users(id), + account_id uuid NOT NULL REFERENCES credit_accounts(id), + session_id uuid REFERENCES sessions(id), + category text NOT NULL CHECK(category IN ('model','tool')), + resource_id uuid NOT NULL, + connector_id uuid REFERENCES connectors(id), + item_name text NOT NULL, + user_name text NOT NULL, + user_email text NOT NULL, + group_id uuid REFERENCES groups(id), + mode text NOT NULL CHECK(mode IN ('local','remote')), + status text NOT NULL CHECK(status IN ('created','reserved','running','settling','settled','released','rejected','unknown')), + reserve numeric(24,6) NOT NULL CHECK(reserve >= 0), + amount numeric(24,6), + raw_amount numeric(24,6), + pricing jsonb NOT NULL CHECK(jsonb_typeof(pricing)='object'), + usage jsonb NOT NULL DEFAULT '{}', + result text, + error_code text NOT NULL DEFAULT '', + idempotency_key text, + request_hash text NOT NULL DEFAULT '', + request_id text NOT NULL DEFAULT '', + attempts integer NOT NULL DEFAULT 0, + next_retry_at timestamptz, + started_at timestamptz NOT NULL DEFAULT now(), + completed_at timestamptz, + updated_at timestamptz NOT NULL DEFAULT now(), + CHECK(amount IS NULL OR amount >= 0) ); CREATE TABLE credit_ledger_entries ( @@ -454,6 +483,14 @@ CREATE TABLE credit_ledger_entries ( metadata jsonb NOT NULL DEFAULT '{}'::jsonb, occurred_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), + transaction_id uuid REFERENCES billing_transactions(id), + event_key text, + sequence bigint, + user_name text, + user_email text, + group_id uuid REFERENCES groups(id), + mode text NOT NULL DEFAULT 'local', + reverses_id uuid REFERENCES credit_ledger_entries(id), CONSTRAINT credit_ledger_entries_entry_type_check CHECK ( entry_type IN ('charge', 'grant', 'refund', 'reset', 'adjustment') ), @@ -479,6 +516,39 @@ CREATE TABLE credit_ledger_entries ( CONSTRAINT credit_ledger_entries_metadata_check CHECK (jsonb_typeof(metadata) = 'object') ); +CREATE TABLE wallet_user_bindings ( + user_id uuid PRIMARY KEY REFERENCES users(id), + external_user_id text NOT NULL UNIQUE, + verified_at timestamptz NOT NULL, + updated_by_user_id uuid NOT NULL REFERENCES users(id) +); + +CREATE TABLE wallet_billing_records ( + biz_id text PRIMARY KEY, + transaction_id uuid NOT NULL UNIQUE REFERENCES billing_transactions(id), + external_user_id text NOT NULL, + team_slug text NOT NULL DEFAULT '', + base_url text NOT NULL, + app_id integer NOT NULL, + status text NOT NULL CHECK(status IN ('pending','reserved','confirming','confirmed','rejected','unknown')), + frozen_amount_quota bigint NOT NULL CHECK(frozen_amount_quota >= 0), + actual_amount_quota bigint, + confirmation_status text, + error_code text NOT NULL DEFAULT '', + trace_id text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + confirmed_at timestamptz +); + +CREATE TABLE billing_migration_issues ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + subject text NOT NULL, + value jsonb NOT NULL, + reason text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + CREATE TABLE audits ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), actor_type text NOT NULL, @@ -496,11 +566,29 @@ CREATE TABLE audits ( error_message text, occurred_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), + request_id text, CONSTRAINT audits_actor_type_check CHECK (actor_type IN ('user', 'system')), CONSTRAINT audits_result_check CHECK (result IN ('success', 'failed')), CONSTRAINT audits_request_params_check CHECK (jsonb_typeof(request_params) = 'object') ); +CREATE TABLE email_codes ( + email text NOT NULL, + purpose text NOT NULL CHECK (purpose IN ('login', 'register', 'reset')), + code_hash text NOT NULL, + expires_at timestamptz NOT NULL, + attempts integer NOT NULL DEFAULT 0, + ready boolean NOT NULL DEFAULT false, + PRIMARY KEY (email, purpose) +); + +CREATE TABLE email_code_deliveries ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + email text NOT NULL, + ip_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + CREATE TABLE browser_sessions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), token_hash text NOT NULL UNIQUE, @@ -511,7 +599,7 @@ CREATE TABLE browser_sessions ( created_at timestamptz NOT NULL DEFAULT now(), revoked_at timestamptz, CONSTRAINT browser_sessions_authentication_method_check CHECK ( - authentication_method IN ('password', 'oauth') + authentication_method IN ('password', 'oauth', 'email_code') ), CONSTRAINT browser_sessions_expiry_check CHECK (expires_at > created_at) ); @@ -592,196 +680,3 @@ CREATE TABLE api_keys ( ), CONSTRAINT api_keys_expiry_check CHECK (expires_at > created_at) ); - -ALTER TABLE settings ADD COLUMN revision bigint NOT NULL DEFAULT 1; - -ALTER TABLE users ADD COLUMN billing_group_id uuid REFERENCES groups(id); - -ALTER TABLE credit_accounts DROP CONSTRAINT credit_accounts_user_id_key; - -ALTER TABLE credit_accounts ADD COLUMN frozen numeric(24,6) NOT NULL DEFAULT 0; - -ALTER TABLE credit_accounts ADD COLUMN quota numeric(24,6) NOT NULL DEFAULT 0; - -ALTER TABLE credit_accounts ADD COLUMN group_id uuid REFERENCES groups(id); - -ALTER TABLE credit_accounts ADD COLUMN sequence bigint NOT NULL DEFAULT 0; - -ALTER TABLE credit_accounts ADD CONSTRAINT credit_accounts_amount_check CHECK(balance >= 0 AND frozen >= 0 AND frozen <= balance) NOT VALID; - -ALTER TABLE model_calls ALTER COLUMN session_id DROP NOT NULL; - -ALTER TABLE mcp_tool_calls ALTER COLUMN session_id DROP NOT NULL; - -CREATE TABLE billing_transactions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id), - account_id uuid NOT NULL REFERENCES credit_accounts(id), - session_id uuid REFERENCES sessions(id), - category text NOT NULL CHECK(category IN ('model','tool')), - resource_id uuid NOT NULL, - connector_id uuid REFERENCES connectors(id), - item_name text NOT NULL, - user_name text NOT NULL, - user_email text NOT NULL, - group_id uuid REFERENCES groups(id), - mode text NOT NULL CHECK(mode IN ('local','remote')), - status text NOT NULL CHECK(status IN ('created','reserved','running','settling','settled','released','rejected','unknown')), - reserve numeric(24,6) NOT NULL CHECK(reserve >= 0), - amount numeric(24,6), - raw_amount numeric(24,6), - pricing jsonb NOT NULL CHECK(jsonb_typeof(pricing)='object'), - usage jsonb NOT NULL DEFAULT '{}', - result text, - error_code text NOT NULL DEFAULT '', - idempotency_key text, - request_hash text NOT NULL DEFAULT '', - request_id text NOT NULL DEFAULT '', - attempts integer NOT NULL DEFAULT 0, - next_retry_at timestamptz, - started_at timestamptz NOT NULL DEFAULT now(), - completed_at timestamptz, - updated_at timestamptz NOT NULL DEFAULT now(), - CHECK(amount IS NULL OR amount >= 0) -); - -ALTER TABLE credit_ledger_entries ADD COLUMN transaction_id uuid REFERENCES billing_transactions(id); - -ALTER TABLE credit_ledger_entries ADD COLUMN event_key text; - -ALTER TABLE credit_ledger_entries ADD COLUMN sequence bigint; - -ALTER TABLE credit_ledger_entries ADD COLUMN user_name text; - -ALTER TABLE credit_ledger_entries ADD COLUMN user_email text; - -ALTER TABLE credit_ledger_entries ADD COLUMN group_id uuid REFERENCES groups(id); - -ALTER TABLE credit_ledger_entries ADD COLUMN mode text NOT NULL DEFAULT 'local'; - -ALTER TABLE credit_ledger_entries ADD COLUMN reverses_id uuid REFERENCES credit_ledger_entries(id); - -CREATE TABLE wallet_user_bindings ( - user_id uuid PRIMARY KEY REFERENCES users(id), - external_user_id text NOT NULL UNIQUE, - verified_at timestamptz NOT NULL, - updated_by_user_id uuid NOT NULL REFERENCES users(id) -); - -CREATE TABLE wallet_billing_records ( - biz_id text PRIMARY KEY, - transaction_id uuid NOT NULL UNIQUE REFERENCES billing_transactions(id), - external_user_id text NOT NULL, - team_slug text NOT NULL DEFAULT '', - environment text NOT NULL, - app_id integer NOT NULL, - status text NOT NULL CHECK(status IN ('pending','reserved','confirming','confirmed','rejected','unknown')), - frozen_amount_quota bigint NOT NULL CHECK(frozen_amount_quota >= 0), - actual_amount_quota bigint, - confirmation_status text, - error_code text NOT NULL DEFAULT '', - trace_id text NOT NULL DEFAULT '', - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - confirmed_at timestamptz -); - -CREATE TABLE billing_migration_issues ( - id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, - subject text NOT NULL, - value jsonb NOT NULL, - reason text NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() -); - -ALTER TABLE credit_ledger_entries DISABLE TRIGGER credit_ledger_immutable; - -ALTER TABLE credit_ledger_entries ENABLE TRIGGER credit_ledger_immutable; - -ALTER TABLE audits ADD COLUMN request_id text; - -CREATE TABLE email_codes ( - email text NOT NULL, - purpose text NOT NULL CHECK (purpose IN ('login', 'register', 'reset')), - code_hash text NOT NULL, - expires_at timestamptz NOT NULL, - attempts integer NOT NULL DEFAULT 0, - ready boolean NOT NULL DEFAULT false, - PRIMARY KEY (email, purpose) -); - -CREATE TABLE email_code_deliveries ( - id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, - email text NOT NULL, - ip_hash text NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() -); - -ALTER TABLE browser_sessions DROP CONSTRAINT browser_sessions_authentication_method_check; - -ALTER TABLE browser_sessions ADD CONSTRAINT browser_sessions_authentication_method_check CHECK (authentication_method IN ('password', 'oauth', 'email_code')); - -ALTER TABLE resource_access_grants - ADD COLUMN all_users boolean NOT NULL DEFAULT false, - DROP CONSTRAINT resource_access_grants_subject_check, - ADD CONSTRAINT resource_access_grants_subject_check CHECK ( - (user_id IS NOT NULL)::integer + (group_id IS NOT NULL)::integer + all_users::integer = 1 - ); - -ALTER TABLE wallet_billing_records RENAME COLUMN environment TO base_url; - -ALTER TABLE user_identities - DROP CONSTRAINT user_identities_provider_check, - ADD CONSTRAINT user_identities_provider_check CHECK ( - provider IN ('github', 'google', 'microsoft', 'gitlab', 'oidc', 'baizhiyun') - ); - -ALTER TABLE experts - ADD COLUMN ownership_type text NOT NULL DEFAULT 'system' - CHECK (ownership_type IN ('system', 'user')), - ADD COLUMN owner_user_id uuid REFERENCES users(id); - -ALTER TABLE experts ALTER COLUMN owner_user_id SET NOT NULL; - -CREATE TABLE expert_connectors ( - expert_id uuid NOT NULL REFERENCES experts(id), - connector_id uuid NOT NULL REFERENCES connectors(id), - required boolean NOT NULL DEFAULT true, - tool_allowlist text[] NOT NULL DEFAULT '{}', - tool_denylist text[] NOT NULL DEFAULT '{}', - PRIMARY KEY (expert_id, connector_id) -); - -ALTER TABLE connectors ADD COLUMN icon_s3_key text NOT NULL DEFAULT ''; - -ALTER TABLE connector_credentials - DROP CONSTRAINT connector_credentials_connector_id_user_id_key, - ADD COLUMN name text NOT NULL DEFAULT '原有凭证' CHECK (char_length(btrim(name)) BETWEEN 1 AND 128), - ADD COLUMN revision bigint NOT NULL DEFAULT 1, - ADD COLUMN connection_status text NOT NULL DEFAULT 'unknown' CHECK (connection_status IN ('unknown','connected','error')), - ADD COLUMN last_checked_at timestamptz, - ADD COLUMN last_error text; - -ALTER TABLE connector_credentials DROP COLUMN method, DROP COLUMN status; - -ALTER TABLE connector_credentials ADD CONSTRAINT connector_credentials_id_connector_key UNIQUE(id, connector_id); - -ALTER TABLE mcp_tools ADD CONSTRAINT mcp_tools_credential_connector_fkey - FOREIGN KEY (credential_id, connector_id) REFERENCES connector_credentials(id, connector_id); - -ALTER TABLE connector_oauth_requests - ADD COLUMN credential_id uuid REFERENCES connector_credentials(id), - ADD COLUMN credential_revision bigint, - ADD COLUMN name text NOT NULL DEFAULT '原有凭证', - DROP COLUMN centralized; - -ALTER TABLE connector_oauth_requests ADD CONSTRAINT connector_oauth_requests_status_check - CHECK (status IN ('pending','processing','succeeded','failed','expired')); - -DROP TABLE expert_connector_providers; - -ALTER TABLE connectors DROP COLUMN provider_id; - -DROP TABLE connector_providers; - -ALTER TABLE experts DROP COLUMN default_model_id; diff --git a/monkeyai/backend/tools/connectorcheck.sql b/monkeyai/backend/tools/connectorcheck.sql deleted file mode 100644 index b60efc39..00000000 --- a/monkeyai/backend/tools/connectorcheck.sql +++ /dev/null @@ -1,34 +0,0 @@ --- 在旧版本数据库执行;只读取候选,不修改结构和数据。 -BEGIN READ ONLY; -SELECT link.expert_id, link.provider_id, candidate.candidates, - CASE jsonb_array_length(candidate.candidates) WHEN 0 THEN 'missing_connector' - WHEN 1 THEN 'ready' ELSE 'ambiguous_connector' END AS status -FROM ( - SELECT x.expert_id, x.provider_id, e.ownership_type, e.owner_user_id - FROM expert_connector_providers x JOIN experts e ON e.id = x.expert_id - WHERE e.deleted_at IS NULL -) link CROSS JOIN LATERAL ( -WITH RECURSIVE user_groups AS ( - SELECT g.id, g.parent_id FROM groups g JOIN group_users gu ON gu.group_id = g.id - WHERE gu.user_id = link.owner_user_id AND gu.removed_at IS NULL AND g.deleted_at IS NULL - UNION - SELECT p.id, p.parent_id FROM groups p JOIN user_groups child ON child.parent_id = p.id - WHERE p.deleted_at IS NULL -) -SELECT COALESCE(jsonb_agg(c.id ORDER BY c.id), '[]'::jsonb) AS candidates -FROM connectors c -WHERE c.provider_id = link.provider_id AND c.deleted_at IS NULL AND c.enabled - AND (link.ownership_type = 'system' AND c.ownership_type = 'system' - OR link.ownership_type = 'user' AND EXISTS ( - SELECT 1 FROM users u WHERE u.id = link.owner_user_id AND u.status = 'active' AND u.deleted_at IS NULL - ) AND (c.ownership_type = 'user' AND c.owner_user_id = link.owner_user_id - OR EXISTS (SELECT 1 FROM resource_access_grants g - WHERE g.resource_type = 'connector' AND g.resource_id = c.id - AND (g.all_users OR g.user_id = link.owner_user_id OR g.group_id IN (SELECT id FROM user_groups)))) - AND (c.ownership_type = 'user' - OR NOT EXISTS (SELECT 1 FROM settings WHERE key = 'billing' AND value->>'charging_mode' = 'remote') - OR EXISTS (SELECT 1 FROM user_identities i WHERE i.user_id = link.owner_user_id - AND i.provider = 'baizhiyun' AND i.deleted_at IS NULL))) -) candidate -ORDER BY link.expert_id, link.provider_id; -COMMIT; diff --git a/monkeyai/design/ai-resource-implementation-plan.md b/monkeyai/design/ai-resource-implementation-plan.md index 6405ad1f..e242e662 100644 --- a/monkeyai/design/ai-resource-implementation-plan.md +++ b/monkeyai/design/ai-resource-implementation-plan.md @@ -1,5 +1,9 @@ # 技能、专家、工具、规则功能完善方案 +> 2026-09-11 迁移收敛:按本轮重新部署要求,原 1–13 版已折叠到 `000001` 完整初始化结构,仅支持全新数据库。下文旧增量迁移及验收记录保留为实施历史,当前部署以 [数据库迁移说明](../backend/migrations/README.md) 为准。 + +> 本轮迁移收敛验收已完成:316 项 Go 测试全部通过,失败与跳过均为 0;`go vet ./...`、`make sqlc-check`、OpenAPI 重复字段与本地引用检查通过。PostgreSQL 18.6 验证 `version=1, dirty=false`、重复 up 无变化及带业务数据的 down/up;迁移镜像构建通过且只含一对 `000001` SQL。旧 13 版与新初始化的字段、索引、函数和触发器一致,余额约束从空库直接验证,钱包地址的非空约束使用最终字段名。代码已完成,现有部署数据库未操作。 + > 2026-09-11 实施更新:Connector 简化与多凭证认证已实施,完整方案见 [连接与多凭证认证设计](connector-auth-design.md)。本文保留早期实现历史,当前 Connector 契约以新方案和 OpenAPI 为准。 > 状态:本次管理后台、后端与 Agent 资源下发 API 已实现,本地验收完成,进入 PR 评审阶段。 diff --git a/monkeyai/design/billing-implementation-plan.md b/monkeyai/design/billing-implementation-plan.md index 46810fc9..45adf72e 100644 --- a/monkeyai/design/billing-implementation-plan.md +++ b/monkeyai/design/billing-implementation-plan.md @@ -1,5 +1,7 @@ # 计费管理完整链路方案 +> 2026-09-11 迁移收敛:按本轮重新部署要求,原 1–13 版已折叠到 `000001` 完整初始化结构,仅支持全新数据库。下文旧增量迁移及验收记录保留为实施历史,当前部署以 [数据库迁移说明](../backend/migrations/README.md) 为准。 + > 状态:P1–P3 已实现并通过本地自动化验收;P4 接入代码与替身测试已完成,真实钱包联调待提供环境、应用 ID 和证书;P5 本地页面与交付检查完成,远程验收仍待联调。 > > 基线:2026-09-07,`main` 提交 `9dd179d7`,已执行 `git pull --ff-only origin main`。 diff --git a/monkeyai/design/connector-auth-design.md b/monkeyai/design/connector-auth-design.md index eaab8d62..0dcdc901 100644 --- a/monkeyai/design/connector-auth-design.md +++ b/monkeyai/design/connector-auth-design.md @@ -1,6 +1,6 @@ # Connector 与多凭证认证设计 -> 状态:已实施,数据库迁移为 `000012_mcp_connector_credentials`;发布操作见 [迁移与接入说明](connector-migration.md)。 +> 状态:已实施,数据库已收敛为 `000001_initial_create_schema`,用于全新部署;发布操作见 [迁移与接入说明](connector-migration.md)。 > > 日期:2026-09-11。 > @@ -599,29 +599,20 @@ MCP 请求中的业务错误保持 HTTP 状态,并在 JSON-RPC `error.data.cod | OAuth 回调期间连接配置变化 | 回调写入失败,不能把旧应用 Token 记成新配置的凭证 | | 凭证存在但资源授权已撤销 | 后续目录、测试与调用拒绝,不以凭证存在代替权限检查 | -## 12. 现有数据与接口迁移 +## 12. 数据库初始化与接口切换 -增量迁移与只读预检查已提供。部署时在实际数据库执行迁移,不重建既有连接和凭证。 +2026-09-11 按重新部署要求,将原 1–13 版的最终结构收敛到 `000001_initial_create_schema`。此安排替代先前的增量转换方案,具体部署步骤见 [初始化与接入说明](connector-migration.md)。 -### 12.1 数据保留 +### 12.1 初始化结构 -1. Connector 已有 URL 和 OAuth 配置快照,保留这些实例值;图标从原 Provider 复制对象引用,不覆盖实例凭据。共享同一图标对象时,清理必须检查所有引用。 -2. 保留 Connector、Credential、Tool 的现有 ID,以及授权、分享、调用和计费历史。不能因去掉 Provider 重建所有连接。 -3. 原 Provider 禁用时,其 Connector 的有效禁用状态必须迁移到 Connector,不能在删除模板后意外恢复可用。 -4. 删除用户维度凭证唯一约束,添加名称、编辑版本和测试字段。原独立凭证使用“原有凭证”等可编辑名称,不猜测上游账号。 -5. 原凭证 `method` 和 `status` 移除前检查数据:撤销记录保留撤销时间;已过期且无刷新能力或明确无效的旧认证不能被迁移成可用。认证内容按最终连接方式清理、派生状态。 -6. 旧 Connector 的测试状态无法可靠归属每份用户凭证;独立凭证测试状态初始化为 `unknown`,不把某次用户测试复制成所有人的成功状态。有效工具目录继续保留。 -7. 切换前使未完成的旧 OAuth 事务结束为失败或过期,避免旧“按用户更新”的回调在新结构下写入。用户重新发起授权。 +- Connector 直接保存 URL、OAuth 配置和图标引用,不创建 Provider。 +- Credential 直接包含名称、编辑版本、测试状态与撤销时间;同一用户可创建多份凭证,集中凭证受部分唯一索引约束。 +- 工具使用凭证与连接的组合外键,OAuth 事务直接记录凭证 ID、版本和名称。 +- 专家直接关联 Connector,保留 required 与工具过滤配置,不创建旧 Provider 关联或执行候选映射。 -### 12.2 专家依赖迁移 +### 12.2 部署前提 -原 Provider 到 Connector 可能是一对多,不能自动把候选连接全部变成必需依赖,也不能随意选第一个。 - -- 只有一个符合专家归属及引用规则的有效 Connector 时,可以转换为直接关联,并保留 required 和工具过滤配置。 -- 没有候选或有多个候选时,迁移预检查输出专家、原 Provider、候选连接和原因,要求在实际迁移前明确映射。 -- 映射完整并验证后,才删除旧关联和 Provider。未解决映射时迁移停止,不静默删除依赖、不授予额外连接权限。 - -先执行 `backend/tools/connectorcheck.sql` 输出候选报告;有歧义时通过迁移连接参数 `monkeyai.connector_mappings` 指定映射。 +使用全新的 PostgreSQL 数据库或数据目录。初始化 SQL 不转换旧连接、凭证或历史交易;需要保留旧数据时应另行制定迁移方案,不能修改迁移版本号代替转换。`down` 删除全部业务结构,仅用于可丢弃测试库。 ### 12.3 接口切换 @@ -630,20 +621,20 @@ MCP 请求中的业务错误保持 HTTP 状态,并在 JSON-RPC `error.data.cod - 独立认证目录、工具测试、OAuth 重新授权和网关都显式携带凭证上下文。 - 专家 `providers` 改为 `connectors`,`connector_bindings` 的含义由模板绑定改为凭证绑定;旧字段不能继续按新语义解释。 - 对旧的独立认证调用返回明确的需要选择凭证错误,不通过“当前只有一份”长期保留隐式选择路径。 -- 后端、管理后台、Agent 消费契约和两份 OpenAPI 按同一版本发布。实际迁移窗口暂停旧写入,完成迁移后再启动新版本。 -- 新版本出现多凭证数据后,不能直接恢复旧唯一约束。回滚需另行解决多凭证数据归并,或恢复完整备份;不提供会静默删除凭证的 down 迁移。 +- 后端、管理后台、Agent 消费契约和两份 OpenAPI 按同一版本发布。新库初始化完成后再启动新版本。 +- 正式部署的回退需要保留完整数据库和对象存储备份;初始化 down 不能用作业务回退。 ## 13. 实施拆分与验收 | 工作单元 | 主要范围 | 交付结果 | | --- | --- | --- | -| 数据与 MCP 业务 | 增量迁移、`internal/mcp` SQL 与服务、sqlc 配置和生成结果 | 直接连接配置、凭证集合、OAuth/Header 多凭证、图标与网关 | +| 数据与 MCP 业务 | 初始化迁移、`internal/mcp` SQL 与服务、sqlc 配置和生成结果 | 直接连接配置、凭证集合、OAuth/Header 多凭证、图标与网关 | | 专家与资源解析 | `internal/expert`、`internal/agentconfig` | 直接连接依赖、凭证选择、目录与版本 | | 调用与计费集成 | `internal/app`、调用记录与幂等摘要 | 按实际凭证调用、记录与去重 | | 前端与接口集成 | 管理后台、两份 OpenAPI、Agent 契约 | 删除模板流程、凭证管理和选择、完整公开接口 | -| 文档与迁移交付 | API 说明、资源设计、迁移预检查报告 | 文档一致,明确数据转换与版本切换步骤 | +| 文档与迁移交付 | API 说明、资源设计、初始化说明 | 文档一致,明确新库部署与接口切换步骤 | -实施时遵守现有业务目录和集成点约束,不手工修改 sqlc 生成文件;schema 从迁移重新生成。迁移序号按实施分支的最新 main 分配,不在本文预占。 +实施时遵守现有业务目录和集成点约束,不手工修改 sqlc 生成文件;schema 从迁移重新生成。后续迁移序号按实施分支的最新 main 分配。 验收至少覆盖: @@ -670,7 +661,7 @@ MCP 请求中的业务错误保持 HTTP 状态,并在 JSON-RPC `error.data.cod - [x] 实施迁移、后端、前端及接口变更。 - [x] 完成本地实现验证、迁移预检查工具和隔离环境迁移演练。 -实现与本地验收已完成,结果见 [实施计划](connector-implementation-plan.md)。生产数据预检查、迁移与部署尚未执行,发布时按 [迁移与接入说明](connector-migration.md) 完成;Desktop/OhMyAgent 外部加载器按已交付的 API 契约接入。 +实现与本地验收已完成,结果见 [实施计划](connector-implementation-plan.md)。现有部署数据库未操作,新库初始化与部署尚未执行,发布时按 [迁移与接入说明](connector-migration.md) 完成;Desktop/OhMyAgent 外部加载器按已交付的 API 契约接入。 ## 14. 用户信息与凭证地址授权 diff --git a/monkeyai/design/connector-implementation-plan.md b/monkeyai/design/connector-implementation-plan.md index cc6e2a96..a2438ae4 100644 --- a/monkeyai/design/connector-implementation-plan.md +++ b/monkeyai/design/connector-implementation-plan.md @@ -1,5 +1,7 @@ # Connector 多凭证实施计划 +> 2026-09-11 迁移收敛:按本轮重新部署要求,原 1–13 版已折叠到 `000001` 完整初始化结构,仅支持全新数据库。下文旧增量迁移及验收记录保留为实施历史,当前部署以 [数据库迁移说明](../backend/migrations/README.md) 为准。 + 状态:多凭证认证、用户信息回包、全局 API Key 与凭证专属 MCP 地址均已完成实现与本地验收,通过 [PR #1275](https://github.com/chaitin/MonkeyCode/pull/1275) 交付,等待审查。依据 [设计方案](connector-auth-design.md)。 - [x] 同步 main,创建 `feat-connector-credentials` worktree,迁入已确认设计。 diff --git a/monkeyai/design/connector-migration.md b/monkeyai/design/connector-migration.md index 82114caa..2edc574b 100644 --- a/monkeyai/design/connector-migration.md +++ b/monkeyai/design/connector-migration.md @@ -1,52 +1,23 @@ -# Connector 迁移与接入 +# Connector 初始化与接入 -本次迁移为 `000012_mcp_connector_credentials`。后端、管理前端与 Agent 契约须同时切换;生产数据库尚未在本任务中执行迁移。 +当前数据库已收敛到 `000001_initial_create_schema`,直接创建连接、多凭证与专家连接关系。原 `000012` 增量转换及 Provider 映射预检查已移除。后端、管理前端与 Agent 契约须使用同一发布版本。 -## 升级步骤 +## 部署步骤 -1. 备份数据库及其引用的对象存储数据,暂停旧版本写入和 OAuth 回调。 -2. 在当前旧数据库执行只读预检查:`psql "$MONKEYAI_DATABASE_URL" -v ON_ERROR_STOP=1 -f tools/connectorcheck.sql`。报告输出专家、原 Provider、合法候选和 `ready / missing_connector / ambiguous_connector`,不会改表。 -3. 只有一个候选时自动迁移。零候选时先修复连接配置/启停及资源授权;多候选时提供明确映射,不能选择用户无权使用的个人连接。映射格式如下,所有 ID 均为真实 UUID: +1. 为本次重新部署准备全新的 PostgreSQL 数据库或数据目录。旧库如需保留数据,应先另行设计并演练数据迁移,不能直接执行本初始化版本或强制改版本号。 +2. 执行初始化迁移,确认 `version=1, dirty=false`,再次执行返回 `no change`。具体命令见 [数据库迁移说明](../backend/migrations/README.md)。 +3. 启动同版本后端及管理前端,配置连接、资源授权与专家依赖,由用户创建凭证或发起 OAuth 授权。 +4. 更新 Agent 的目录、resolve、认证和凭证网关接入,验证凭证隔离、共享撤权和工具调用。 -```json -{"专家 ID":{"原 Provider ID":"选择的 Connector ID"}} -``` +`down` 会删除全部业务数据,仅用于可丢弃测试库的重建验证。此轮未操作现有部署数据库。 -4. 将映射作为 PostgreSQL 会话设置 `monkeyai.connector_mappings` 传入执行迁移的连接。使用 migrate CLI 时可以把下列脚本保存在部署环境执行,`CONNECTOR_MAPPINGS_FILE` 指向 JSON 文件;没有歧义可以直接沿用原 migrate 命令。 +## 数据约束与验证 -```python -import json, os, subprocess -from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode +同一用户在同一连接下可持有多份同名凭证;部分唯一索引限制每个连接最多一份未撤销的集中凭证。工具通过 `(credential_id, connector_id)` 外键避免跨连接引用。专家直接关联 Connector,不再创建 Provider 或依赖映射。 -parts = urlsplit(os.environ["MONKEYAI_DATABASE_URL"]) -with open(os.environ["CONNECTOR_MAPPINGS_FILE"]) as file: - mapping = json.dumps(json.load(file), separators=(",", ":")) -query = dict(parse_qsl(parts.query)) -query["options"] = (query.get("options", "") + " -c monkeyai.connector_mappings=" + mapping).strip() -dsn = urlunsplit(parts._replace(query=urlencode(query))) -subprocess.run(["migrate", "-path", "migrations", "-database", dsn, "up"], check=True) -``` +本地集成测试覆盖完整初始化与回滚、重复凭证、集中凭证唯一性、跨连接工具外键、新 API、用户共享撤权、OAuth 与 Header 认证、工具隔离、会话选择和跨凭证幂等。真实第三方应用的回调登记和 Scopes 需要在部署环境完成。 -5. 迁移成功后再启动新后端及管理前端,更新 Agent 的认证、解析和网关接入。已进行中的旧授权事务结束为失败,用户重新发起授权。 -6. 核对连接/凭证/工具历史 ID、专家映射、停用状态、集中凭证、个人凭证目录和计费记录。先在备份副本完成演练,再切换正式环境。 - -迁移在单个事务内检查映射和转换。映射不全会输出候选及原因并回滚。migrate 可能已经记录 dirty 版本;只有确认事务回滚、仍为旧结构后,才将迁移版本恢复到执行前版本并重试,不能直接强制标记新版本成功。 - -## 数据处理 - -保留现有连接、凭证、工具 ID 和历史引用;保留实例 URL/OAuth 配置,复制旧图标引用并继承 Provider 的停用状态。工具和凭证按具体 ID 隔离,同名凭证可以并存。原独立凭证命名为“原有凭证”,测试状态初始化为 unknown。旧无效/撤销认证不会迁移成有效认证,认证方式不匹配的秘密会清除。 - -部分唯一索引只限制每个连接一份未撤销的集中凭证。工具增加 `(credential_id, connector_id)` 外键校验,防止跨连接引用。共享图标不立即删除;后续清理仍检查全部连接引用和备份窗口。 - -## 回滚 - -`down` 主动拒绝有损回滚。新版本产生多凭证后不能恢复旧单凭证唯一约束;需要恢复完整数据库和对象存储备份,或先另行制定不会丢凭证的数据归并方案。 - -## 验证范围 - -本地使用独立 PostgreSQL schema 与专用 RustFS Bucket 验证全量迁移、旧数据多候选阻断、显式映射、禁用/图标/ID 保留、重复凭证、新旧 API、用户共享撤权、OAuth 与 Header 认证、工具隔离、会话选择和跨凭证幂等。真实第三方应用的回调登记和 Scopes 需要在部署环境完成。 - -Desktop/OhMyAgent 的 MCP 加载器不在本仓库实现范围内。后端已提供完整目录、resolve、认证和凭证网关契约,消费端必须保存 resolve 返回的绑定,不能继续调用旧隐式网关。 +Desktop/OhMyAgent 的 MCP 加载器不在本仓库实现范围内。后端已提供目录、resolve、认证和凭证网关契约,消费端必须保存 resolve 返回的绑定。 ## 凭证地址与回包接入 diff --git a/monkeyai/design/mcp-proxy-plan.md b/monkeyai/design/mcp-proxy-plan.md index 0497a9d2..5fb8fbb0 100644 --- a/monkeyai/design/mcp-proxy-plan.md +++ b/monkeyai/design/mcp-proxy-plan.md @@ -1,5 +1,7 @@ # MCP 代理实施状态 +> 2026-09-11 迁移收敛:按本轮重新部署要求,原 1–13 版已折叠到 `000001` 完整初始化结构,仅支持全新数据库。下文旧增量迁移及验收记录保留为实施历史,当前部署以 [数据库迁移说明](../backend/migrations/README.md) 为准。 + 目标:补齐 MonkeyAI HTTP MCP 工具代理,使标准客户端可从资源目录取得入口,使用 `mcp:invoke` 调用密钥完成握手、工具发现和调用。 - [x] 同步 main,创建 `feat-mcp-proxy` worktree,确认既有授权和计费边界。