Compare commits

..

1 Commits

Author SHA1 Message Date
kdletters 95a3b9f593 后台灰度预设补上游戏发布开关
Project CI / AI game creator shell Rust crates (pull_request) Successful in 1m14s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m45s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Successful in 6m46s
Project CI / Backend tests (pull_request) Successful in 6m23s
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Successful in 8m36s
Project CI / Native shell tests (pull_request) Successful in 7m8s
Project CI / Frontend tests (pull_request) Successful in 3m0s
Project CI / Repository checks (pull_request) Successful in 3m49s
Project CI / AI game creator shell web tests (pull_request) Successful in 3m11s
- admin-web:灰度发布配置的固定目标新增「游戏分发 → 游戏发布」(game-distribution:publish),前缀标签与描述说明「未配置或关闭时默认开放,开启后只放行白名单/灰度命中」。
- 默认语义:选中预设后保持 enabled=false,避免误把发布收紧成全关;需要灰度时再显式打开并填白名单/比例。
- 用例:新增「可选择游戏发布开关且默认不收紧」与「保存写入白名单与比例」两条后台用例。
- 文档:开发运维文档说明该键配置前不会出现在已有列表、必须从预设或手填新建一行。
2026-09-22 20:06:37 +08:00
408 changed files with 28898 additions and 1700 deletions
@@ -2641,6 +2641,48 @@ const databaseTableLabelMap: Record<string, string> = {
profile_recharge_order: '充值订单',
profile_feedback_submission: '反馈提交',
profile_save_archive: '存档记录',
story_session: '剧情会话',
story_event: '剧情事件',
npc_state: 'NPC 状态',
inventory_slot: '背包槽位',
battle_state: '战斗状态',
treasure_record: '宝藏记录',
quest_record: '任务记录',
quest_log: '任务日志',
player_progression: '玩家进度',
chapter_progression: '章节进度',
custom_world_profile: '自定义世界档案',
custom_world_session: '自定义世界会话',
custom_world_agent_session: '自定义世界 Agent 会话',
custom_world_agent_message: '自定义世界 Agent 消息',
custom_world_agent_operation: '自定义世界 Agent 操作',
custom_world_draft_card: '自定义世界草稿卡片',
custom_world_gallery_entry: '自定义世界画廊条目',
puzzle_agent_session: '拼图 Agent 会话',
puzzle_agent_message: '拼图 Agent 消息',
puzzle_work_profile: '拼图作品档案',
puzzle_event: '拼图事件',
puzzle_runtime_run: '拼图运行记录',
puzzle_leaderboard_entry: '拼图排行榜条目',
match3d_agent_session: '抓大鹅 Agent 会话',
match3d_agent_message: '抓大鹅 Agent 消息',
match3d_work_profile: '抓大鹅作品档案',
match3d_runtime_run: '抓大鹅运行记录',
square_hole_agent_session: '方洞挑战 Agent 会话',
square_hole_agent_message: '方洞挑战 Agent 消息',
square_hole_work_profile: '方洞挑战作品档案',
square_hole_runtime_run: '方洞挑战运行记录',
visual_novel_agent_session: '视觉小说 Agent 会话',
visual_novel_agent_message: '视觉小说 Agent 消息',
visual_novel_work_profile: '视觉小说作品档案',
visual_novel_runtime_run: '视觉小说运行记录',
visual_novel_runtime_history_entry: '视觉小说历史条目',
visual_novel_runtime_event: '视觉小说运行事件',
big_fish_creation_session: '大鱼吃小鱼创建会话',
big_fish_agent_message: '大鱼吃小鱼 Agent 消息',
big_fish_asset_slot: '大鱼吃小鱼资产槽位',
big_fish_event: '大鱼吃小鱼事件',
big_fish_runtime_run: '大鱼吃小鱼运行记录',
asset_object: '资产对象',
asset_entity_binding: '资产实体绑定',
asset_event: '资产事件',
@@ -2682,6 +2724,48 @@ const databaseTableDescriptionMap: Record<string, string> = {
profile_recharge_order: '充值订单表',
profile_feedback_submission: '反馈提交记录表',
profile_save_archive: '用户存档记录表',
story_session: '剧情会话表',
story_event: '剧情事件表',
npc_state: 'NPC 状态表',
inventory_slot: '背包槽位表',
battle_state: '战斗状态表',
treasure_record: '宝藏记录表',
quest_record: '任务记录表',
quest_log: '任务日志表',
player_progression: '玩家进度表',
chapter_progression: '章节进度表',
custom_world_profile: '自定义世界档案表',
custom_world_session: '自定义世界会话表',
custom_world_agent_session: '自定义世界 Agent 会话表',
custom_world_agent_message: '自定义世界 Agent 消息表',
custom_world_agent_operation: '自定义世界 Agent 操作表',
custom_world_draft_card: '自定义世界草稿卡片表',
custom_world_gallery_entry: '自定义世界画廊条目表',
puzzle_agent_session: '拼图 Agent 会话表',
puzzle_agent_message: '拼图 Agent 消息表',
puzzle_work_profile: '拼图作品档案表',
puzzle_event: '拼图事件表',
puzzle_runtime_run: '拼图运行记录表',
puzzle_leaderboard_entry: '拼图排行榜条目表',
match3d_agent_session: '抓大鹅 Agent 会话表',
match3d_agent_message: '抓大鹅 Agent 消息表',
match3d_work_profile: '抓大鹅作品档案表',
match3d_runtime_run: '抓大鹅运行记录表',
square_hole_agent_session: '方洞挑战 Agent 会话表',
square_hole_agent_message: '方洞挑战 Agent 消息表',
square_hole_work_profile: '方洞挑战作品档案表',
square_hole_runtime_run: '方洞挑战运行记录表',
visual_novel_agent_session: '视觉小说 Agent 会话表',
visual_novel_agent_message: '视觉小说 Agent 消息表',
visual_novel_work_profile: '视觉小说作品档案表',
visual_novel_runtime_run: '视觉小说运行记录表',
visual_novel_runtime_history_entry: '视觉小说历史条目表',
visual_novel_runtime_event: '视觉小说运行事件表',
big_fish_creation_session: '大鱼吃小鱼创建会话表',
big_fish_agent_message: '大鱼吃小鱼 Agent 消息表',
big_fish_asset_slot: '大鱼吃小鱼资产槽位表',
big_fish_event: '大鱼吃小鱼事件表',
big_fish_runtime_run: '大鱼吃小鱼运行记录表',
asset_object: '资产对象表',
asset_entity_binding: '资产实体绑定表',
asset_event: '资产事件表',
@@ -175,6 +175,86 @@ test('灰度发布页可选择模板库并默认启用零比例灰度', async ()
);
});
test('灰度发布页可选择游戏发布开关,默认保持「未开启即开放」语义', async () => {
const user = userEvent.setup();
render(
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
);
await screen.findByRole('button', { name: 'editor.new-toolbar' });
await user.selectOptions(screen.getByLabelText('Gate Key 前缀'), [
'game-distribution',
]);
expect((screen.getByLabelText('Gate Key') as HTMLInputElement).value).toBe(
'game-distribution:publish',
);
expect(
(screen.getByLabelText('Gate Key 目标') as HTMLSelectElement).value,
).toBe('publish');
// 该开关的语义是「未配置/关闭 = 默认开放」,所以选中后不能默认打开收紧。
expect((screen.getByLabelText('启用') as HTMLInputElement).checked).toBe(
false,
);
expect((screen.getByLabelText('灰度比例') as HTMLInputElement).value).toBe(
'0',
);
expect(
(screen.getByLabelText('描述') as HTMLTextAreaElement).value,
).toContain('游戏发布入口灰度');
});
test('灰度发布页保存游戏发布开关时写入白名单与比例', async () => {
const user = userEvent.setup();
vi.mocked(upsertAdminFeatureGateConfig).mockResolvedValueOnce({
gates: [
...configResponse.gates,
{
gateKey: 'game-distribution:publish',
enabled: true,
rolloutPercent: 20,
allowUserIds: ['user-internal'],
allowUserTags: [],
denyUserIds: [],
description: '游戏发布入口灰度',
updatedAt: '2026-09-22T10:00:00Z',
},
],
});
render(
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
);
await screen.findByRole('button', { name: 'editor.new-toolbar' });
await user.selectOptions(screen.getByLabelText('Gate Key 前缀'), [
'game-distribution',
]);
fireEvent.click(screen.getByLabelText('启用'));
fireEvent.change(screen.getByLabelText('灰度比例'), {
target: { value: '20' },
});
fireEvent.change(screen.getByLabelText('允许用户 ID'), {
target: { value: 'user-internal' },
});
fireEvent.change(screen.getByLabelText('描述'), {
target: { value: '游戏发布入口灰度' },
});
await user.click(screen.getByRole('button', { name: '保存配置' }));
await user.click(screen.getByRole('button', { name: '确认' }));
await waitFor(() =>
expect(upsertAdminFeatureGateConfig).toHaveBeenCalledWith('admin-token', {
gateKey: 'game-distribution:publish',
enabled: true,
rolloutPercent: 20,
allowUserIds: ['user-internal'],
allowUserTags: [],
denyUserIds: [],
description: '游戏发布入口灰度',
}),
);
});
test('灰度发布页保存时转换数组和百分比', async () => {
const user = userEvent.setup();
vi.mocked(upsertAdminFeatureGateConfig).mockResolvedValueOnce({
@@ -28,6 +28,7 @@ interface GateTargetOption {
const GATE_PREFIX_LABELS: Record<string, string> = {
'image-editor': '画布',
agc: '客户端',
'game-distribution': '游戏分发',
};
const FIXED_GATE_TARGETS: GateTargetOption[] = [
@@ -45,6 +46,14 @@ const FIXED_GATE_TARGETS: GateTargetOption[] = [
label: 'Agent 侧边栏',
description: '画布 Agent 入口灰度',
},
{
prefix: 'game-distribution',
suffix: 'publish',
key: 'game-distribution:publish',
label: '游戏发布',
description:
'游戏发布入口灰度:未配置或关闭时对已登录作者默认开放,开启后只放行白名单 / 灰度命中',
},
];
export function AdminGrayReleaseConfigPage({
@@ -6,7 +6,6 @@ import {
Component,
createContext,
isValidElement,
memo,
useContext,
} from 'react';
import ReactMarkdown, { type Components } from 'react-markdown';
@@ -303,15 +302,7 @@ const streamingMarkdownComponents: Components = {
p: StreamingMarkdownParagraph,
};
/**
* 解析器的输入只有 `text` / `role` / `streaming` / `preserveBlankLines` 这几个标量,所以
* 内容没变的旧消息在父级重渲染时可以直接跳过:Markdown 解析与语法高亮是这个组件里最贵的
* 两件事(`react-markdown` 每次渲染都会重建 `unified()` 处理器并重跑全部插件),而旧消息
* 的文本永远不会再改。
*/
export const ChatMarkdownMessage = memo(ChatMarkdownMessageImpl);
function ChatMarkdownMessageImpl({
export function ChatMarkdownMessage({
text,
role,
streaming = false,
@@ -326,13 +317,8 @@ function ChatMarkdownMessageImpl({
<ReactMarkdown
skipHtml
remarkPlugins={[remarkGfm]}
// 流式中不高亮:高亮要跑一遍完整 AST + highlight.js,而流式增量会让同一段代码
// 每来一个 chunk 就重新高亮一次(文本还在长,结果立刻作废)。文本定稿时
// `streaming` 变回 false,这一笔高亮自然补上。
rehypePlugins={
streaming || text.length > MAX_HIGHLIGHT_CHARACTERS
? []
: [rehypeHighlight]
text.length <= MAX_HIGHLIGHT_CHARACTERS ? [rehypeHighlight] : []
}
components={
streaming ? streamingMarkdownComponents : markdownComponents
@@ -1,5 +1,5 @@
import { ChevronDown, Lightbulb } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useState } from 'react';
import { AgentMessageContent } from '../../../../../../../../packages/shared/src/components/AgentMessageContent';
import { AgentProcessSummary } from '../../../../../../../../packages/shared/src/components/AgentProcessSummary';
@@ -12,9 +12,7 @@ import { agentProcessPreview } from '../../../../../features/project-workspace/a
* 折叠态是单行纯文本预览(Markdown 只取可见文字,符号不进预览);展开态复用助手正文的
* 安全 Markdown 链路。这里只有表现与展开态,思考内容本身由两条产品路径各自的事实源提供。
*/
export const AgentReasoning = memo(AgentReasoningImpl);
function AgentReasoningImpl({
export function AgentReasoning({
text,
label = '思考过程',
testId,
@@ -24,12 +22,7 @@ function AgentReasoningImpl({
testId?: string;
}) {
const [expanded, setExpanded] = useState(false);
/*
折叠态那一行预览是**完整 Markdown AST 解析**`remark-parse` + `unified`),和展开态
`react-markdown` 那次解析是两笔开销;上面那层 `memo` 让内容没变的思考块整个跳过,
这里的 `useMemo` 再兜一层,避免同一文本在真正重渲染时被重算。
*/
const preview = useMemo(() => agentProcessPreview(text), [text]);
const preview = agentProcessPreview(text);
return (
<AgentMessageContent
as="details"
@@ -797,15 +797,6 @@ Godot 编辑器操控复用既有 AGC 插件宿主、EditorAdapter、Runner 和
- 验证方式:运行评论弹层恢复竞态回归、完整 `appSurface.test.ts`,并执行类型、编码和 diff 检查。
- 关联文档:`docs/technical/【技术方案】立项策划AgentFast GDD-2026-08-10.md``apps/ai-game-creator-shell/src/features/project-workspace/GddApprovalCard.tsx`
## 2026-09-22 旧创作模板历史表从 schema 与生成绑定中删除
- 背景:旧创作模板的 63 张历史玩法表已经完成业务代码退役;release 在 2026-09-22 apply 前仍有 26 张表、5922 行历史数据。维护窗口内先完成可恢复备份,再执行固定清单清空,继续保留 table 定义、迁移白名单、旧行兼容分支和生成绑定会让当前 schema、客户端类型和迁移合同长期停留在退役状态。
- 决策:从 `spacetime-module` 可达源码删除旧 gameplay、自定义世界、Puzzle / Puzzle Clear、Bark Battle、Match3D、Jump Hop、Wooden Fish、Square Hole、Visual Novel 与 Big Fish 的 63 张表定义及专属类型;同步删除只服务这些表的 `clear_retired_database_tables` procedure、固定清单、migration 导入导出项和旧行归一化分支,并重新生成 `spacetime-client` bindings。`runtime_setting``runtime_snapshot``user_browse_history``creation_entry_config` 等现役表和通用迁移能力保持不变。
- 门禁处理:SpacetimeDB schema guard 只对本轮 63 个已确认 accessor 的从基线删除放行,其他表删除/改名以及字段级破坏性变更仍失败;该一次性白名单在删除结果进入后续主线基线后移除。生产发布仍必须单独完成冷备份、客户端兼容性和运行态确认,禁止用 SQL `DROP TABLE``--delete-data=always` 或系统表写入代替受控发布。
- 影响范围:`server-rs/crates/spacetime-module/src/{active.rs,migration.rs}`、旧表专属 module/legacy schema 文件、`server-rs/crates/spacetime-client/src/module_bindings*`、schema guard 及后端数据契约。
- 生产数据与发布闭环:`genarrative-prod` 在维护态、API/controller/worker 已停止时,以已授权 migration operator 执行 `clear_retired_database_tables`apply 返回 63 张表且每张 `cleared_row_count == row_count_before`,共清空 5922 行。apply 前后两次 `dry_run=true` 均为 63/63 全零,第二次在 10 分钟观察窗口结束后执行。清空前完成 files-minimal OSS 备份、latest/catalog 验真和 restore dry-run;随后将 release 从 `2.7.0` 直接切换到本地锁定并有 commit 校验的 `2.8.3 / 8e410d…` 二进制,再用 source commit `05a5ea4d8534b3f96d4d462c6cfda9b0775073df` 的 wasm 发布。发布后 schema 为 84 张表、旧表为 0、`clear_retired_database_tables` 为 0API/controller/worker 已恢复,维护退出,`genarrative.world``www.genarrative.world` 返回 200。
- 验证方式:`npm run spacetime:generate` 生成 766 个 binding 文件;`cargo check -p spacetime-client -p api-server``cargo test -p spacetime-module migration`21 passed)、`npm run check:server-rs-ddd``npm run check:spacetime-schema`84 tables)、`npm run check:spacetime-runtime-access`、schema guard 单测(9 passed)、`npm run check:encoding``npm run check:doc-index``git diff --check` 通过。
## 2026-09-02 旧玩法表采用两阶段退役清理
- 背景:旧创作模板的业务代码已退出现役编译链,但 SpacetimeDB 中的历史表仍需先完成数据清理;直接删除表定义会扩大 schema 迁移和客户端兼容风险。
@@ -49,8 +49,6 @@
按上游 [#5555](https://github.com/clockworklabs/SpacetimeDB/pull/5555) 的 retention 语义,只有最近 `retain-snapshots`(默认 2)份 snapshot 与覆盖它之后的 commitlog 段是重启所需,其余历史可丢;因此备份改为 `files + full + --minimal --retain-snapshots 2`release 实测 40G → 3.6G,热备不停服),不再做增量差异计算,也不需要 44.7G 冷备空间。
2026-09-22 的 release 清表窗口再次验证:41.2GiB 数据目录执行 `archive` 会因根盘不足失败;尝试非 minimal 的 `files + full + --stop-service` 虽通过空间预检,但在扫描 43GiB 后于 catalog 序列化阶段报 `RangeError: Invalid string length`。生产中等数据目录继续使用可验真的 `files + full + --minimal` 备份,并在 apply 前执行 `restore-files-state --dry-run`;非 minimal files 大库备份需要先修复 catalog 序列化上限,不能把失败备份当作通过。
## copyArtifacts 报「Unable to find project for artifact copy」的用户触发构建差异
Copy Artifact 插件在**非 SYSTEM 认证**下按「认证用户」判权:只有当被复制 Job 的 `CopyArtifactPermissionProperty`(仓库里由 Declarative 的 `copyArtifactPermission(...)` 维护)显式列出当前消费者,或者该 Job 对认证用户开放 Item.Read 时才放行;`ACL.SYSTEM2` 的定时构建会短路通过。因此会出现「定时调度一路成功、手动发布必挂」的现象(2026-09-21 手动发布 #6/#7 与同期的用户触发探测全部命中,定时调度 #104+ 正常)。`Genarrative-Agc-Global-Version-Issue` 生产权限模式的授权名单必须同时包含 `Genarrative-Scheduled-Revision-Trigger``Genarrative-Manual-Build-And-Deploy`;改完 `copyArtifactPermission` 后要先跑一次发号 Job 把 Job property 写回 Jenkins,只改仓库文件不生效。
File diff suppressed because it is too large Load Diff
@@ -678,7 +678,7 @@ journalctl -u genarrative-api -o cat | grep 'operation="release_rejected"'
发布事故或回滚窗口里用 `game-distribution:publish` 灰度开关控制写入,不需要改代码或重启:
- 开关位置:后台「灰度发布配置」(`GET/PUT /admin/api/feature-gates`),`gateKey = game-distribution:publish`
- 开关位置:后台「灰度发布配置」(`GET/PUT /admin/api/feature-gates`),`gateKey = game-distribution:publish`;后台预设「游戏分发 → 游戏发布」,选中后默认保持 `enabled=false`(即默认开放),需要收紧时再显式打开并填白名单 / 灰度比例。该键在配置前不会出现在已有开关列表里,必须从预设或手填 Gate Key 新建一行
- 语义:没有该 gate 行或 `enabled=false` 表示**默认开放**`enabled=true` 时只有 `allowUserIds` / `allowUserTags` / `rolloutPercent` 命中的作者能发布,`rolloutPercent=0` 且无白名单即**全部关闭**(等价紧急关闭投稿)。
- 关闭范围:创建游戏、创建版本、上传包、送审、撤回、作者下架,以及管理员**批准**(新版本激活)都返回 `503 GAME_DISTRIBUTION_PUBLISH_DISABLED`
- 始终可用:目录、详情、版本回读、发行网关(已公开游戏继续游玩)、`/my-games`、审核队列读取、**拒绝审核**与管理员**安全下架**。
@@ -1141,7 +1141,20 @@ SELECT * FROM profile_recharge_product_config ORDER BY sort_order ASC;
- 微信新用户的内部 `user_id` 改为不可复用的 `user_` 前缀 UUID 风格,避免清库后旧作品被后来的顺序号账号顶替。
- 当作品作者的 `owner_user_id` 找不到真实账号时,作品统一显示为占位作者:`失效作者`,公开陶泥号固定为 `SY-00000000`,占位账号 ID 为 `wx-openid-placeholder`
- 该占位账号只用于作品作者域,不扩展到全站其它身份域。
- 旧作品表退役后,迁移 JSON 回填工具 `scripts/rebind-orphan-work-owners.mjs` 已删除,不再提供回填脚本用法或当前操作入口;占位作者的显示与身份域语义继续保持上述规则
- 如需把历史孤儿作品批量回填到占位作者,使用 `scripts/rebind-orphan-work-owners.mjs` 先基于当前 auth 快照识别有效用户,再把缺失作者对应的作品表写回为占位 ID;脚本输入输出都基于 SpacetimeDB 迁移 JSON
### 回填脚本用法
```bash
node scripts/rebind-orphan-work-owners.mjs --in <exported-migration.json> --out <rebound-migration.json>
node scripts/rebind-orphan-work-owners.mjs --in <exported-migration.json> --dry-run
node scripts/rebind-orphan-work-owners.mjs --in <exported-migration.json> --out <rebound-migration.json> --placeholder-user-id wx-openid-placeholder
```
- `--in`SpacetimeDB 导出的迁移 JSON。
- `--out`:写回后的迁移 JSON 输出路径。
- `--dry-run`:只统计回填行数,不写文件。
- `--placeholder-user-id`:需要时可覆盖默认占位账号 ID。
## 维护页目标文件安全边界(2026-08-05)
+1 -78
View File
@@ -12,80 +12,6 @@ const tableCatalogPath =
'docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md';
const bindingsRoot = 'server-rs/crates/spacetime-client/src/module_bindings/';
const allowBreaking = process.env.SPACETIME_SCHEMA_GUARD_ALLOW_BREAKING === '1';
// 本次历史表退役的一次性迁移白名单。该清单只允许这些已确认表从基线消失;
// 待删除结果进入后续主线基线后必须删除本清单,其他表仍按既有破坏性变更路径失败。
export const APPROVED_RETIRED_TABLE_DELETIONS = Object.freeze([
'player_progression',
'chapter_progression',
'npc_state',
'story_session',
'story_event',
'inventory_slot',
'battle_state',
'treasure_record',
'quest_record',
'quest_log',
'custom_world_profile',
'custom_world_session',
'custom_world_agent_session',
'custom_world_agent_message',
'custom_world_agent_operation',
'custom_world_draft_card',
'custom_world_gallery_entry',
'puzzle_agent_session',
'puzzle_background_compile_task',
'puzzle_agent_message',
'puzzle_work_profile',
'puzzle_event',
'puzzle_runtime_run',
'puzzle_leaderboard_entry',
'puzzle_clear_agent_session',
'puzzle_clear_work_profile',
'puzzle_clear_runtime_run',
'puzzle_clear_event',
'bark_battle_draft_config',
'bark_battle_published_config',
'bark_battle_runtime_run',
'bark_battle_score_record',
'bark_battle_leaderboard_entry',
'bark_battle_work_stats_projection',
'bark_battle_personal_best_projection',
'match3d_agent_session',
'match3d_agent_message',
'match_3_d_work_profile',
'match3d_runtime_run',
'jump_hop_agent_session',
'jump_hop_work_profile',
'jump_hop_runtime_run',
'jump_hop_event',
'jump_hop_leaderboard_entry',
'wooden_fish_agent_session',
'wooden_fish_work_profile',
'wooden_fish_runtime_run',
'wooden_fish_event',
'square_hole_agent_session',
'square_hole_agent_message',
'square_hole_work_profile',
'square_hole_runtime_run',
'visual_novel_agent_session',
'visual_novel_agent_message',
'visual_novel_work_profile',
'visual_novel_runtime_run',
'visual_novel_runtime_history_entry',
'visual_novel_runtime_event',
'big_fish_creation_session',
'big_fish_agent_message',
'big_fish_asset_slot',
'big_fish_runtime_run',
'big_fish_event',
]);
const approvedRetiredTableDeletions = new Set(APPROVED_RETIRED_TABLE_DELETIONS);
export function isApprovedRetiredTableDeletion(accessor) {
return approvedRetiredTableDeletions.has(accessor);
}
function normalizePath(path) {
return path.replace(/\\/gu, '/');
}
@@ -713,7 +639,7 @@ function fieldDescription(field) {
return `${field.name}: ${field.type}`;
}
export function compareTables(baseTables, currentTables) {
function compareTables(baseTables, currentTables) {
const failures = [];
let schemaChanged = false;
let breakingChanged = false;
@@ -722,9 +648,6 @@ export function compareTables(baseTables, currentTables) {
const currentTable = currentTables.get(accessor);
if (!currentTable) {
schemaChanged = true;
if (isApprovedRetiredTableDeletion(accessor)) {
continue;
}
breakingChanged = true;
failures.push(
`${baseTable.path}:${baseTable.line}: SpacetimeDB 表 ${accessor} 被删除或改名。表删除/改名必须先询问用户并确认迁移计划。`,
@@ -1,9 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
APPROVED_RETIRED_TABLE_DELETIONS,
collectTablesFromSources,
compareTables,
isFormalGateEnvironment,
listReachableRustFiles,
resolveBaseRef,
@@ -38,15 +36,6 @@ function createGitResolver(entries: Record<string, string | null>) {
return (args: string[]) => entries[args.join(' ')] ?? null;
}
function collectTables(accessors: string[]) {
return collectTablesFromSources(
accessors.map((accessor, index) => ({
path: `${sourceRoot}/schema.rs`,
text: tableSource(`Table${index}`, accessor),
})),
).tables;
}
describe('SpacetimeDB schema guard base resolution', () => {
it('prefers an explicit Jenkins-provided base ref', () => {
expect(
@@ -136,61 +125,3 @@ describe('SpacetimeDB schema guard module reachability', () => {
expect(result.failures[0]).toMatch(/table accessor example /u);
});
});
describe('SpacetimeDB schema guard retired table deletion allowlist', () => {
it('allows exactly the 63 approved historical tables to disappear', () => {
expect(APPROVED_RETIRED_TABLE_DELETIONS).toHaveLength(63);
expect(new Set(APPROVED_RETIRED_TABLE_DELETIONS).size).toBe(63);
const result = compareTables(
collectTables([...APPROVED_RETIRED_TABLE_DELETIONS]),
new Map(),
);
expect(result.failures).toEqual([]);
expect(result.schemaChanged).toBe(true);
expect(result.breakingChanged).toBe(false);
});
it('still rejects deletion of a table outside the approved list', () => {
const result = compareTables(
collectTables([APPROVED_RETIRED_TABLE_DELETIONS[0], 'active_table']),
new Map(),
);
expect(result.failures).toHaveLength(1);
expect(result.failures[0]).toMatch(/active_table.*/u);
expect(result.schemaChanged).toBe(true);
expect(result.breakingChanged).toBe(true);
});
it('does not suppress retained-table field deletion or rename checks', () => {
const baseTables = collectTablesFromSources([
{
path: `${sourceRoot}/ranks.rs`,
text: `#[spacetimedb::table(accessor = retained_deleted_field)]\npub struct RetainedDeletedField {\n pub id: u64,\n pub title: String,\n}\n`,
},
{
path: `${sourceRoot}/titles.rs`,
text: `#[spacetimedb::table(accessor = retained_renamed_field)]\npub struct RetainedRenamedField {\n pub id: u64,\n pub title: String,\n}\n`,
},
]).tables;
const currentTables = collectTablesFromSources([
{
path: `${sourceRoot}/ranks.rs`,
text: `#[spacetimedb::table(accessor = retained_deleted_field)]\npub struct RetainedDeletedField {\n pub id: u64,\n}\n`,
},
{
path: `${sourceRoot}/titles.rs`,
text: `#[spacetimedb::table(accessor = retained_renamed_field)]\npub struct RetainedRenamedField {\n pub id: u64,\n pub name: String,\n}\n`,
},
]).tables;
const result = compareTables(baseTables, currentTables);
expect(result.failures).toHaveLength(2);
expect(result.failures.join('\n')).toMatch(//u);
expect(result.failures.join('\n')).toMatch(//u);
expect(result.breakingChanged).toBe(true);
});
});
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env node
import { readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
export const DEFAULT_ORPHAN_WORK_OWNER_USER_ID = 'wx-openid-placeholder';
export const WORK_OWNER_TABLES = [
'custom_world_profile',
'custom_world_gallery_entry',
'custom_world_session',
'custom_world_agent_session',
'custom_world_draft_card',
'puzzle_agent_session',
'puzzle_work_profile',
'bark_battle_draft_config',
'bark_battle_published_config',
'match3d_agent_session',
'match3d_work_profile',
'jump_hop_agent_session',
'jump_hop_work_profile',
'wooden_fish_agent_session',
'wooden_fish_work_profile',
'square_hole_agent_session',
'square_hole_work_profile',
'visual_novel_agent_session',
'visual_novel_work_profile',
'big_fish_creation_session',
];
const ROW_KEY_FIELDS = [
'profile_id',
'work_id',
'session_id',
'draft_id',
'gallery_entry_id',
'id',
];
if (isCliEntry()) {
runCli(process.argv.slice(2)).catch((error) => {
console.error(
`[rebind-orphan-work-owners] ${error instanceof Error ? error.message : String(error)}`,
);
process.exit(1);
});
}
export function rebindOrphanWorkOwnersInMigration(
migration,
{
placeholderUserId = DEFAULT_ORPHAN_WORK_OWNER_USER_ID,
validUserIds = [],
} = {},
) {
if (!migration || !Array.isArray(migration.tables)) {
throw new Error('迁移 JSON 必须包含 tables 数组。');
}
const normalizedPlaceholderUserId = placeholderUserId.trim();
const validUserIdSet = new Set(
(Array.isArray(validUserIds) ? validUserIds : [])
.map((value) => String(value).trim())
.filter(Boolean),
);
validUserIdSet.add(normalizedPlaceholderUserId);
const reboundRows = [];
for (const table of migration.tables) {
if (
!table ||
!WORK_OWNER_TABLES.includes(table.name) ||
!Array.isArray(table.rows)
) {
continue;
}
for (const row of table.rows) {
if (!row || typeof row !== 'object') {
continue;
}
const currentOwner =
typeof row.owner_user_id === 'string' ? row.owner_user_id.trim() : '';
if (
currentOwner === normalizedPlaceholderUserId ||
validUserIdSet.has(currentOwner)
) {
continue;
}
const originalOwner =
typeof row.owner_user_id === 'string' ? row.owner_user_id : '';
row.owner_user_id = normalizedPlaceholderUserId;
reboundRows.push({
table: table.name,
rowKey: resolveRowKey(row),
from: originalOwner,
to: normalizedPlaceholderUserId,
});
}
}
return { reboundRows, validUserCount: validUserIdSet.size };
}
function resolveRowKey(row) {
for (const field of ROW_KEY_FIELDS) {
const value = row[field];
if (typeof value === 'string' && value.trim()) {
return value;
}
}
return '<unknown>';
}
async function runCli(argv) {
const options = parseCliArgs(argv);
const inputPath = path.resolve(options.in);
const outputPath = path.resolve(options.out);
const migration = JSON.parse(await readFile(inputPath, 'utf8'));
const result = rebindOrphanWorkOwnersInMigration(migration, {
placeholderUserId: options.placeholderUserId,
validUserIds: collectValidUserIds(migration),
});
if (!options.dryRun) {
await writeFile(
outputPath,
`${JSON.stringify(migration, null, 2)}\n`,
'utf8',
);
}
console.log(
`[rebind-orphan-work-owners] ${options.dryRun ? 'dry-run' : `已写入 ${outputPath}`},回填 ${result.reboundRows.length}`,
);
}
function parseCliArgs(argv) {
const options = {
in: '',
out: '',
placeholderUserId: DEFAULT_ORPHAN_WORK_OWNER_USER_ID,
dryRun: false,
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const readValue = (name) => {
const value = argv[index + 1];
if (!value || value.startsWith('--')) {
throw new Error(`${name} 缺少参数值。`);
}
index += 1;
return value;
};
if (arg === '--in') {
options.in = readValue(arg);
} else if (arg === '--out') {
options.out = readValue(arg);
} else if (arg === '--placeholder-user-id') {
options.placeholderUserId = readValue(arg);
} else if (arg === '--dry-run') {
options.dryRun = true;
} else {
throw new Error(`未知参数: ${arg}`);
}
}
if (!options.in) {
throw new Error('必须传入 --in。');
}
if (!options.out && !options.dryRun) {
throw new Error('非 dry-run 必须传入 --out。');
}
return options;
}
function collectValidUserIds(migration) {
const result = new Set();
for (const table of migration.tables ?? []) {
if (!table || !Array.isArray(table.rows)) {
continue;
}
if (table.name === 'user_account') {
for (const row of table.rows) {
if (typeof row?.user_id === 'string' && row.user_id.trim()) {
result.add(row.user_id.trim());
}
}
}
}
return result;
}
function isCliEntry() {
const entry = process.argv[1];
return entry
? import.meta.url === `file://${entry.replace(/\\/gu, '/')}`
: false;
}
+60
View File
@@ -0,0 +1,60 @@
import { describe, expect, it } from 'vitest';
import { rebindOrphanWorkOwnersInMigration } from './rebind-orphan-work-owners.mjs';
const placeholderUserId = 'wx-openid-placeholder';
function table(name, rows) {
return { name, rows };
}
describe('rebindOrphanWorkOwnersInMigration', () => {
it('把作品表里认证表不存在的 owner_user_id 回填到占位用户', () => {
const migration = {
schema_version: 1,
exported_at_micros: 1,
tables: [
table('user_account', [
{ user_id: 'user_alive' },
{ user_id: placeholderUserId },
]),
table('puzzle_work_profile', [
{ profile_id: 'p1', owner_user_id: 'user_missing' },
{ profile_id: 'p2', owner_user_id: 'user_alive' },
{ profile_id: 'p3', owner_user_id: placeholderUserId },
]),
table('puzzle_agent_session', [
{ session_id: 'draft-1', owner_user_id: '' },
]),
table('tracking_event', [
{ event_id: 't1', owner_user_id: 'user_missing' },
]),
],
};
const result = rebindOrphanWorkOwnersInMigration(migration, {
placeholderUserId,
validUserIds: ['user_alive'],
});
expect(result.reboundRows).toEqual([
{
table: 'puzzle_work_profile',
rowKey: 'p1',
from: 'user_missing',
to: placeholderUserId,
},
{
table: 'puzzle_agent_session',
rowKey: 'draft-1',
from: '',
to: placeholderUserId,
},
]);
expect(migration.tables[1].rows[0].owner_user_id).toBe(placeholderUserId);
expect(migration.tables[1].rows[1].owner_user_id).toBe('user_alive');
expect(migration.tables[1].rows[2].owner_user_id).toBe(placeholderUserId);
expect(migration.tables[2].rows[0].owner_user_id).toBe(placeholderUserId);
expect(migration.tables[3].rows[0].owner_user_id).toBe('user_missing');
});
});
File diff suppressed because it is too large Load Diff
@@ -34,10 +34,10 @@ pub trait acknowledge_external_generation_job_summaries_and_return {
input: ExternalGenerationJobAcknowledgeInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<ExternalGenerationJobSummaryProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<ExternalGenerationJobSummaryProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -47,10 +47,10 @@ impl acknowledge_external_generation_job_summaries_and_return for super::RemoteP
input: ExternalGenerationJobAcknowledgeInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<ExternalGenerationJobSummaryProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<ExternalGenerationJobSummaryProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, ExternalGenerationJobSummaryProcedureResult>(
@@ -34,10 +34,10 @@ pub trait acknowledge_external_generation_jobs_and_return {
input: ExternalGenerationJobAcknowledgeInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<ExternalGenerationJobProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<ExternalGenerationJobProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -47,10 +47,10 @@ impl acknowledge_external_generation_jobs_and_return for super::RemoteProcedures
input: ExternalGenerationJobAcknowledgeInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<ExternalGenerationJobProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<ExternalGenerationJobProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, ExternalGenerationJobProcedureResult>(
@@ -31,10 +31,10 @@ pub trait activate_editor_canvas_layout_and_return {
input: EditorCanvasLayoutMigrationInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<EditorCanvasLayoutMigrationProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<EditorCanvasLayoutMigrationProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl activate_editor_canvas_layout_and_return for super::RemoteProcedures {
input: EditorCanvasLayoutMigrationInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<EditorCanvasLayoutMigrationProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<EditorCanvasLayoutMigrationProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, EditorCanvasLayoutMigrationProcedureResult>(
@@ -31,10 +31,10 @@ pub trait admin_disable_profile_redeem_code {
input: RuntimeProfileRedeemCodeAdminDisableInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileRedeemCodeAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileRedeemCodeAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl admin_disable_profile_redeem_code for super::RemoteProcedures {
input: RuntimeProfileRedeemCodeAdminDisableInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileRedeemCodeAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileRedeemCodeAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, RuntimeProfileRedeemCodeAdminProcedureResult>(
@@ -31,10 +31,10 @@ pub trait admin_disable_profile_task_config {
input: RuntimeProfileTaskConfigAdminDisableInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileTaskConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileTaskConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl admin_disable_profile_task_config for super::RemoteProcedures {
input: RuntimeProfileTaskConfigAdminDisableInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileTaskConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileTaskConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, RuntimeProfileTaskConfigAdminProcedureResult>(
@@ -31,10 +31,10 @@ pub trait admin_get_profile_wallet_and_return {
input: RuntimeProfileAdminWalletGetInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl admin_get_profile_wallet_and_return for super::RemoteProcedures {
input: RuntimeProfileAdminWalletGetInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, RuntimeProfileAdminWalletProcedureResult>(
@@ -31,10 +31,10 @@ pub trait admin_get_profile_wallet_config {
input: RuntimeProfileWalletConfigAdminGetInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileWalletConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileWalletConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl admin_get_profile_wallet_config for super::RemoteProcedures {
input: RuntimeProfileWalletConfigAdminGetInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileWalletConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileWalletConfigAdminProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, RuntimeProfileWalletConfigAdminProcedureResult>(
@@ -31,10 +31,10 @@ pub trait admin_get_profile_wallet_detail_and_return {
input: RuntimeProfileAdminWalletGetInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletDetailProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletDetailProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl admin_get_profile_wallet_detail_and_return for super::RemoteProcedures {
input: RuntimeProfileAdminWalletGetInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletDetailProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<RuntimeProfileAdminWalletDetailProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, RuntimeProfileAdminWalletDetailProcedureResult>(
@@ -37,13 +37,13 @@ pub trait admin_initialize_profile_wallet_consumption_projections_and_return {
input: RuntimeProfileWalletConsumptionProjectionInitializeInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<
RuntimeProfileWalletConsumptionProjectionInitializeProcedureResult,
__sdk::InternalError,
>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<
RuntimeProfileWalletConsumptionProjectionInitializeProcedureResult,
__sdk::InternalError,
>,
) + Send
+ 'static,
);
}
@@ -55,13 +55,13 @@ impl admin_initialize_profile_wallet_consumption_projections_and_return
input: RuntimeProfileWalletConsumptionProjectionInitializeInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<
RuntimeProfileWalletConsumptionProjectionInitializeProcedureResult,
__sdk::InternalError,
>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<
RuntimeProfileWalletConsumptionProjectionInitializeProcedureResult,
__sdk::InternalError,
>,
) + Send
+ 'static,
) {
self.imp.invoke_procedure_with_callback::<_, RuntimeProfileWalletConsumptionProjectionInitializeProcedureResult>(
"admin_initialize_profile_wallet_consumption_projections_and_return",
@@ -31,10 +31,10 @@ pub trait admin_list_editor_assets_and_return {
input: AdminEditorAssetListInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<AdminEditorAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<AdminEditorAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -44,10 +44,10 @@ impl admin_list_editor_assets_and_return for super::RemoteProcedures {
input: AdminEditorAssetListInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<AdminEditorAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<AdminEditorAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, AdminEditorAssetListProcedureResult>(
@@ -34,10 +34,10 @@ pub trait admin_list_editor_showcase_assets_and_return {
input: EditorShowcaseAssetAdminListInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<EditorShowcaseAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<EditorShowcaseAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
);
}
@@ -47,10 +47,10 @@ impl admin_list_editor_showcase_assets_and_return for super::RemoteProcedures {
input: EditorShowcaseAssetAdminListInput,
__callback: impl FnOnce(
&super::ProcedureEventContext,
Result<EditorShowcaseAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
&super::ProcedureEventContext,
Result<EditorShowcaseAssetListProcedureResult, __sdk::InternalError>,
) + Send
+ 'static,
) {
self.imp
.invoke_procedure_with_callback::<_, EditorShowcaseAssetListProcedureResult>(

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