Compare commits

..

6 Commits

Author SHA1 Message Date
kdletters 405b36e8d5 补充UI组件复用与共享库沉淀规范
Project CI / Repository checks (pull_request) Failing after 12s
Project CI / Backend tests (pull_request) Failing after 12s
Project CI / Native shell tests (pull_request) Successful in 14m37s
Project CI / Frontend tests (pull_request) Successful in 16m26s
在 AGENTS.md 增加 UI 组件优先复用与共享库沉淀原则

同步更新团队协作约定中的 UI 组件边界
2026-08-31 13:20:32 +08:00
kdletters 7e7ef50e40 继续扩展共享组件并收口入口页面
新增 PlatformBackActionButton 共享返回动作与行为测试

迁移登录、绑定手机号和世界实体目录的共享组件直引

扩展示展示页示例并同步组件库文档与决策记录
2026-08-31 11:53:04 +08:00
kdletters aadb09a9ea 继续收口共享组件并迁移业务页面
补充 PlatformToggleRow 共享整行开关组件与测试

将多个结果页、工作台和账号页面改用共享 Platform chrome

更新展示页、组件库文档与共享决策记录
2026-08-31 11:13:32 +08:00
kdletters 5d14af1324 补充共享整行开关组件
新增 PlatformToggleRow 共享实现与类型导出

保留 common 兼容出口并补充组件行为测试
2026-08-31 11:01:39 +08:00
kdletters 328da5e6eb 扩展共享组件库并接入当前项目
Project CI / Frontend tests (pull_request) Successful in 3m10s
Project CI / Native shell tests (pull_request) Successful in 12m4s
Project CI / Repository checks (pull_request) Failing after 12s
Project CI / Backend tests (pull_request) Failing after 12s
- 收口平台异步、筛选、图标、信息、列表、运行态和统计组件到共享包
- 新增 Label、Checkbox、Skeleton、Table 语义基础组件
- 展示页与代表性业务页面改用共享 canonical 导出并补齐交互反馈
- 同步共享样式、组件测试和前端架构决策文档
2026-08-28 18:26:10 +08:00
kdletters bbd895d7c2 补齐共享 UI 组件库与展示页交互
Project CI / Frontend tests (pull_request) Successful in 3m21s
Project CI / Repository checks (pull_request) Failing after 11s
Project CI / Backend tests (pull_request) Failing after 9s
Project CI / Native shell tests (pull_request) Successful in 12m36s
- 新增 shadcn canonical UI 源码、共享样式与组件导出
- 新增 /components 共享组件展示页及路由测试
- 补齐平台组件筛选、排序、上传预览和异步状态交互
- 同步网站与客户端构建别名、依赖和项目文档
2026-08-27 15:12:50 +08:00
2882 changed files with 661168 additions and 117430 deletions
+1 -1
View File
@@ -1 +1 @@
{ "containers": [], "config": {} }
{"containers":[],"config":{}}
-16
View File
@@ -1,16 +0,0 @@
# Genarrative Codex 项目工具
`.codex/` 是仓库级 Codex 工具目录,保存项目共享的 skills、插件资源、hooks 和相关配置模板。它只描述如何协作和加载工具,不承载项目业务知识。
## 目录约定
- `.codex/skills/` 是项目专属 skill 根目录。每个 skill 以目录中的 `SKILL.md` 为入口,配套的参考资料和脚本放在同一目录下。
- `.codex/plugins/` 保存随仓库分发的项目插件资源及其参考资料。当前的 `game-studio` 插件提供浏览器游戏设计、原型、2D/3D 技术栈、素材管线和 playtest 工作流;是否启用遵循当前 Codex 的插件加载机制,不依赖旧工具的环境变量或个人配置脚本。
- `.codex/hooks/``.codex/environments/` 等目录保存项目工具链所需的 hooks 和环境模板;它们不替代项目代码中的运行时配置。
- 长期有效的产品、架构、接口、排障和协作知识统一放在 `docs/``docs/project-memory/`,不复制到本目录。
## 使用边界
进入仓库后先读根目录 `AGENTS.md`,再按任务路由读取对应 skill。SpacetimeDB 的通用概念、Rust 服务端、CLI、TypeScript 客户端和 MCP 用法由已安装的官方插件提供;项目约束和入口由 `.codex/skills/genarrative-spacetimedb/SKILL.md` 统一编排。
个人 `~/.codex` 配置、凭据、会话、环境变量和本地路径不得复制到仓库。若本目录内容与当前代码或最新 `docs/` 冲突,以代码和最新文档为准,并修正过期工具说明。
+11 -23
View File
@@ -7,33 +7,23 @@ import { fileURLToPath } from 'node:url';
const scriptDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(scriptDir, '..', '..');
const logDir = resolve(repoRoot, '.codex', 'logs');
const hasCodegraphConfig = existsSync(
resolve(repoRoot, '.codegraph', 'config.json'),
);
const hasCodegraphConfig = existsSync(resolve(repoRoot, '.codegraph', 'config.json'));
const npmCommand = process.platform === 'win32' ? 'cmd' : 'npm';
if (!hasCodegraphConfig) {
console.log(
'[codex-hook] 未发现 .codegraph/config.json,跳过 CodeGraph 同步。',
);
console.log('[codex-hook] 未发现 .codegraph/config.json,跳过 CodeGraph 同步。');
process.exit(0);
}
const result = spawnSync(
npmCommand,
process.platform === 'win32'
? ['/d', '/s', '/c', 'npm run codegraph:sync']
: ['run', 'codegraph:sync'],
{
cwd: repoRoot,
shell: false,
encoding: 'utf8',
env: {
...process.env,
NO_COLOR: process.env.NO_COLOR ?? '1',
},
const result = spawnSync(npmCommand, process.platform === 'win32' ? ['/d', '/s', '/c', 'npm run codegraph:sync'] : ['run', 'codegraph:sync'], {
cwd: repoRoot,
shell: false,
encoding: 'utf8',
env: {
...process.env,
NO_COLOR: process.env.NO_COLOR ?? '1',
},
);
});
mkdirSync(logDir, { recursive: true });
if (result.stdout) {
@@ -54,9 +44,7 @@ if (result.signal) {
}
if ((result.status ?? 0) !== 0) {
console.error(
'[codex-hook] CodeGraph 同步失败,请手动运行 npm run codegraph:sync 查看详情。',
);
console.error('[codex-hook] CodeGraph 同步失败,请手动运行 npm run codegraph:sync 查看详情。');
process.exit(result.status ?? 1);
}
@@ -1,4 +0,0 @@
interface:
display_name: 'Game Playtest'
short_description: 'Run browser-game playtests and QA'
default_prompt: 'Playtest the browser game, check core interactions and visual state changes, and report concrete issues.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Game Studio'
short_description: 'Route browser-game work to the right path'
default_prompt: 'Help me choose the right browser-game stack and workflow before implementation starts.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Game UI Frontend'
short_description: 'Design browser-game HUDs, menus, and overlays'
default_prompt: 'Design a browser-game UI layer that supports the play experience without crowding the playfield.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Phaser 2D Game'
short_description: 'Build 2D browser games with Phaser'
default_prompt: 'Implement this 2D browser game with Phaser, TypeScript, and a clear gameplay architecture.'
@@ -1,4 +0,0 @@
interface:
display_name: 'React Three Fiber Game'
short_description: 'Build React-hosted 3D browser games'
default_prompt: 'Build this 3D browser game with React Three Fiber and keep the 3D runtime aligned with the React app shell.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Sprite Pipeline'
short_description: 'Generate and normalize 2D sprite animations'
default_prompt: 'Create and normalize 2D sprite animation assets for a browser game with consistent scale and anchors.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Three WebGL Game'
short_description: 'Build browser-game runtimes with Three.js'
default_prompt: 'Implement this browser-game runtime with plain Three.js and keep the scene architecture easy to debug.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Web 3D Asset Pipeline'
short_description: 'Prepare and optimize browser-game 3D assets'
default_prompt: 'Prepare these browser-game 3D assets for shipping as predictable runtime-ready GLB or glTF files.'
@@ -1,4 +0,0 @@
interface:
display_name: 'Web Game Foundations'
short_description: 'Set browser-game architecture before implementation'
default_prompt: 'Establish the core architecture for this browser game before implementation starts.'
-7
View File
@@ -1,7 +0,0 @@
# Genarrative 项目 skills
`.codex/skills/` 是仓库级、可通过 Git 共享的项目专属 skill 根目录。每个目录的 `SKILL.md` 是唯一入口;较长的参考资料、示例和脚本放在该 skill 的 `references/``assets/``scripts/` 下。
项目 skill 负责把当前仓库的目录、契约、验证门禁和历史约束串起来,不重复维护通用框架知识。涉及 SpacetimeDB 时,先读 `genarrative-spacetimedb/SKILL.md`,由它路由到已安装的官方 SpacetimeDB 插件 skills。
长期项目知识放在 `docs/``docs/project-memory/`;不要把个人配置、密钥、会话、缓存或临时计划写入本目录。发现 skill 与代码或最新文档不一致时,按当前实现更新 skill,并同步必要的项目文档。
@@ -1,6 +1,6 @@
interface:
display_name: 'Genarrative External Editor API'
short_description: 'Route async canvas generation safely'
default_prompt: 'Use $genarrative-external-editor-api to discover the hosted integration, prepare a canvas session, and submit and poll asset generation into the canvas and library.'
display_name: "Genarrative External Editor API"
short_description: "Route async canvas generation safely"
default_prompt: "Use $genarrative-external-editor-api to discover the hosted integration, prepare a canvas session, and submit and poll asset generation into the canvas and library."
policy:
allow_implicit_invocation: true
@@ -6,16 +6,16 @@ All paths below are relative to `https://www.genarrative.world`. Discovery and S
## Project and Canvas Operations
| Operation | Method and path | Minimum input |
| -------------------- | ------------------------------------------------------------- | -------------------------------------------------------------- |
| List projects | `GET /api/external/v1/editor/projects` | Authentication; optional `view=full\|summary` (default `full`) |
| Create project | `POST /api/external/v1/editor/projects` | Optional `title` |
| Load recent project | `GET /api/external/v1/editor/projects/recent` | Authentication |
| Get project | `GET /api/external/v1/editor/projects/{projectId}` | `projectId` |
| Delete project | `DELETE /api/external/v1/editor/projects/{projectId}` | `projectId` |
| Rename project | `PATCH /api/external/v1/editor/projects/{projectId}/metadata` | `title` |
| Save canvas | `PATCH /api/external/v1/editor/projects/{projectId}/canvas` | `viewport`, `layers`, `expectedRevision` |
| Add project resource | `POST /api/external/v1/editor/projects/{projectId}/resources` | `imageSrc`, `width`, `height`, `sourceType` |
| Operation | Method and path | Minimum input |
| --- | --- | --- |
| List projects | `GET /api/external/v1/editor/projects` | Authentication; optional `view=full\|summary` (default `full`) |
| Create project | `POST /api/external/v1/editor/projects` | Optional `title` |
| Load recent project | `GET /api/external/v1/editor/projects/recent` | Authentication |
| Get project | `GET /api/external/v1/editor/projects/{projectId}` | `projectId` |
| Delete project | `DELETE /api/external/v1/editor/projects/{projectId}` | `projectId` |
| Rename project | `PATCH /api/external/v1/editor/projects/{projectId}/metadata` | `title` |
| Save canvas | `PATCH /api/external/v1/editor/projects/{projectId}/canvas` | `viewport`, `layers`, `expectedRevision` |
| Add project resource | `POST /api/external/v1/editor/projects/{projectId}/resources` | `imageSrc`, `width`, `height`, `sourceType` |
Canvas save uses optimistic revision control. Pass the last authoritative `expectedRevision`; on conflict, reload instead of replaying a stale full layout.
@@ -28,18 +28,18 @@ Project listing supports two views:
## Asset and Upload Operations
| Operation | Method and path | Minimum input |
| --------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------- |
| Create direct-upload ticket | `POST /api/external/v1/assets/direct-upload-tickets` | `legacyPrefix`, `fileName` |
| Confirm uploaded object | `POST /api/external/v1/assets/objects/confirm` | `objectKey`, `assetKind` |
| Get signed read URL | `GET /api/external/v1/assets/read-url` | `objectKey` or `legacyPublicPath` |
| Read asset library | `GET /api/external/v1/editor/assets/library` | Authentication |
| Create folder | `POST /api/external/v1/editor/assets/folders` | `label` |
| Update folder | `PATCH /api/external/v1/editor/assets/folders/{folderId}` | `label` or `collapsed` |
| Delete folder | `DELETE /api/external/v1/editor/assets/folders/{folderId}` | `folderId` |
| Create asset record | `POST /api/external/v1/editor/assets` | `folderId`, `label`, `imageSrc`, `width`, `height`, `sourceType` |
| Update asset record | `PATCH /api/external/v1/editor/assets/{assetId}` | `label` or `folderId` |
| Delete asset record | `DELETE /api/external/v1/editor/assets/{assetId}` | `assetId` |
| Operation | Method and path | Minimum input |
| --- | --- | --- |
| Create direct-upload ticket | `POST /api/external/v1/assets/direct-upload-tickets` | `legacyPrefix`, `fileName` |
| Confirm uploaded object | `POST /api/external/v1/assets/objects/confirm` | `objectKey`, `assetKind` |
| Get signed read URL | `GET /api/external/v1/assets/read-url` | `objectKey` or `legacyPublicPath` |
| Read asset library | `GET /api/external/v1/editor/assets/library` | Authentication |
| Create folder | `POST /api/external/v1/editor/assets/folders` | `label` |
| Update folder | `PATCH /api/external/v1/editor/assets/folders/{folderId}` | `label` or `collapsed` |
| Delete folder | `DELETE /api/external/v1/editor/assets/folders/{folderId}` | `folderId` |
| Create asset record | `POST /api/external/v1/editor/assets` | `folderId`, `label`, `imageSrc`, `width`, `height`, `sourceType` |
| Update asset record | `PATCH /api/external/v1/editor/assets/{assetId}` | `label` or `folderId` |
| Delete asset record | `DELETE /api/external/v1/editor/assets/{assetId}` | `assetId` |
Upload is a three-step client flow: create a ticket, POST the file and returned fields directly to the OSS form endpoint, then confirm the returned `objectKey`. See `authentication-and-safety.md` before implementing this flow.
@@ -47,17 +47,17 @@ Upload is a three-step client flow: create a ticket, POST the file and returned
Every generation row requires a stable `Idempotency-Key` header and returns HTTP `202` with an asynchronous submission, not the generated media.
| Capability | POST path | Required body fields | Common optional body fields |
| ------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Image generation | `/api/external/v1/editor/images/generations` | `prompt` | `kind`, `style`, `model`, `aspectRatio`, `imageSize`, `size`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Image edit/redraw | `/api/external/v1/editor/images/edits` | `prompt`, `sourceReferenceId` | `referenceImageSrcs`, `model`, `size`, `projectId`, `assetFolderId`, `assetLabel`, `targetLayerId`, `canvasCompletion` |
| Background removal | `/api/external/v1/editor/images/background-removals` | `sourceImageSrc` | `projectId`, `sourceResourceId`, `targetLayerId`, static-image `assetKind`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Icon spritesheet | `/api/external/v1/editor/icon-spritesheets/generations` | `referenceId`, `iconDescriptions` | `sliceLayout`, `style`, `referenceImageSrcs`, `screenColor`, `model`, `aspectRatio`, `imageSize`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| UI asset extraction | `/api/external/v1/editor/ui-designs/assets/extractions` | `sourceImageSrc`, `aspectRatio`, `imageSize` | `screenColor`, `model`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `spritesheetLabel`, `canvasCompletion` |
| Character animation | `/api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` | `projectId`, `sourceResourceId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Video generation | `/api/external/v1/editor/videos/generations` | `prompt`, `model`, `aspectRatio`, `durationSeconds`, `resolution`, `mode`, `sound` | `referenceImageSrcs`, `referenceVideoSrcs`, `referenceAudioSrcs`, `webSearchEnabled`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Sound effect | `/api/external/v1/editor/audios/sound-effects/generations` | `prompt` | `model`, `duration`, `loop`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Background music | `/api/external/v1/editor/audios/background-music/generations` | `gptDescriptionPrompt`, `makeInstrumental` | `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Capability | POST path | Required body fields | Common optional body fields |
| --- | --- | --- | --- |
| Image generation | `/api/external/v1/editor/images/generations` | `prompt` | `kind`, `style`, `model`, `aspectRatio`, `imageSize`, `size`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Image edit/redraw | `/api/external/v1/editor/images/edits` | `prompt`, `sourceReferenceId` | `referenceImageSrcs`, `model`, `size`, `projectId`, `assetFolderId`, `assetLabel`, `targetLayerId`, `canvasCompletion` |
| Background removal | `/api/external/v1/editor/images/background-removals` | `sourceImageSrc` | `projectId`, `sourceResourceId`, `targetLayerId`, static-image `assetKind`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Icon spritesheet | `/api/external/v1/editor/icon-spritesheets/generations` | `referenceId`, `iconDescriptions` | `sliceLayout`, `style`, `referenceImageSrcs`, `screenColor`, `model`, `aspectRatio`, `imageSize`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| UI asset extraction | `/api/external/v1/editor/ui-designs/assets/extractions` | `sourceImageSrc`, `aspectRatio`, `imageSize` | `screenColor`, `model`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `spritesheetLabel`, `canvasCompletion` |
| Character animation | `/api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` | `projectId`, `sourceResourceId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Video generation | `/api/external/v1/editor/videos/generations` | `prompt`, `model`, `aspectRatio`, `durationSeconds`, `resolution`, `mode`, `sound` | `referenceImageSrcs`, `referenceVideoSrcs`, `referenceAudioSrcs`, `webSearchEnabled`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
| Sound effect | `/api/external/v1/editor/audios/sound-effects/generations` | `prompt` | `model`, `duration`, `loop`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
| Background music | `/api/external/v1/editor/audios/background-music/generations` | `gptDescriptionPrompt`, `makeInstrumental` | `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
Poll all nine through:
@@ -81,14 +81,14 @@ Supply the `operationId` returned by submission. Poll no faster than `pollAfterM
After confirming a local upload, pass its stable `objectKey` into operations that accept object references:
| Target capability | Field |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Image generation | `referenceImageSrcs` |
| Image edit/redraw | `sourceReferenceId` must be a registered project resource ID or asset ID; additional references remain in `referenceImageSrcs` |
| Icon spritesheet | Register the primary spec as an `assetKind="icon-spec"` project resource or asset, then pass its returned ID as `referenceId`; additional style references remain in `referenceImageSrcs` |
| UI design extraction | `sourceImageSrc`; additional references in `referenceImageSrcs` |
| Character animation | `sourceImageSrc` |
| Video with image references | `referenceImageSrcs` |
| Target capability | Field |
| --- | --- |
| Image generation | `referenceImageSrcs` |
| Image edit/redraw | `sourceReferenceId` must be a registered project resource ID or asset ID; additional references remain in `referenceImageSrcs` |
| Icon spritesheet | Register the primary spec as an `assetKind="icon-spec"` project resource or asset, then pass its returned ID as `referenceId`; additional style references remain in `referenceImageSrcs` |
| UI design extraction | `sourceImageSrc`; additional references in `referenceImageSrcs` |
| Character animation | `sourceImageSrc` |
| Video with image references | `referenceImageSrcs` |
For image edit/redraw, confirming an upload is not sufficient: create a project resource or asset-library record first, then pass that record's ID as `sourceReferenceId`. The main source never accepts objectKey, URL, Data URL, or Blob URL. Use video/audio reference arrays only with models that support them. Do not pass an expiring signed read URL as a generation reference.
@@ -43,24 +43,24 @@ Infer what is already clear and ask only for missing fields that block the selec
## Intent Map
| User intent | MCP/REST capability |
| ----------------------------------------------------------------------- | ---------------------------------------------------------------- |
| Generate a background, character, spec, UI mockup, or publication image | Image generation |
| Redraw, retouch, or replace an existing image | Image edit |
| Remove the background from an existing image | Background removal |
| Generate from a local reference | Upload and confirm the local file, then image generation or edit |
| Build a reusable transparent icon/game atlas from a visual spec | Icon spritesheet generation |
| Extract marked assets from an existing UI design | UI design asset extraction |
| Animate a character into frames | Character animation generation |
| Generate video | Video generation |
| Generate a sound effect | Sound-effect generation |
| Generate background music/BGM | Background-music generation |
| Upload a local image/audio/video asset | Upload ticket -> OSS form upload -> object confirm |
| Save viewport/layers | Canvas save |
| Create, load, rename, or delete a canvas | Project operations |
| Organize folders and asset records | Asset-library operations |
| Obtain temporary access to private media | Signed read URL |
| Check generation progress or retrieve its result | Generation query |
| User intent | MCP/REST capability |
| --- | --- |
| Generate a background, character, spec, UI mockup, or publication image | Image generation |
| Redraw, retouch, or replace an existing image | Image edit |
| Remove the background from an existing image | Background removal |
| Generate from a local reference | Upload and confirm the local file, then image generation or edit |
| Build a reusable transparent icon/game atlas from a visual spec | Icon spritesheet generation |
| Extract marked assets from an existing UI design | UI design asset extraction |
| Animate a character into frames | Character animation generation |
| Generate video | Video generation |
| Generate a sound effect | Sound-effect generation |
| Generate background music/BGM | Background-music generation |
| Upload a local image/audio/video asset | Upload ticket -> OSS form upload -> object confirm |
| Save viewport/layers | Canvas save |
| Create, load, rename, or delete a canvas | Project operations |
| Organize folders and asset records | Asset-library operations |
| Obtain temporary access to private media | Signed read URL |
| Check generation progress or retrieve its result | Generation query |
Do not present an API menu unless the request is genuinely ambiguous. Ask a follow-up when two routes create different artifacts, for example “处理这张图” could mean edit, extract marked UI assets, or use it as a reference for a new generation.
@@ -3,8 +3,8 @@ name: genarrative-play-type-integration
description: 在 Genarrative 中新增或补齐一个创作入口/玩法类型时,按入口配置、前端分流、契约、后端接口、工作台、独立生成页、结果页、发布、统一作品详情、正式 runtime、公开 read model、基础统计与作品架/广场的顺序接入。
license: MIT
metadata:
author: Genarrative Team
version: '1.0'
author: Hermes Agent
version: "1.0"
---
# Genarrative 新增玩法创作工具平台 SOP
@@ -90,14 +90,13 @@ metadata:
12. **旧数据策略**:旧草稿、旧发布配置、旧分享码是迁移、降级展示、重新生成,还是明确不兼容。
- `AGENTS.md`
- `docs/project-memory/shared-memory/`
- `.hermes/shared-memory/`
- `CONTEXT.md`
- `docs/README.md`
- `docs/【玩法创作】平台入口与玩法链路-2026-05-15.md`
- 相关玩法 PRD 或设计文档
- `.codex/skills/genarrative-play-type-integration/references/genarrative-analytics-tracking-runtime.md`(涉及正式 runtime 埋点时)
如果文档不能精确指导字段、契约、资产槽位、生成流程和恢复语义,先补文档再编码。新增长期约定时同步 `docs/project-memory/shared-memory/`
如果文档不能精确指导字段、契约、资产槽位、生成流程和恢复语义,先补文档再编码。新增长期约定时同步 `.hermes/shared-memory/`
### 2. 定玩法边界
@@ -1,126 +0,0 @@
---
name: genarrative-spacetimedb
description: Genarrative 的 SpacetimeDB 项目适配规范。用于涉及 SpacetimeDB 架构、Rust module、schema、migration、reducer、procedure、view、绑定生成、CLI、MCP、发布、调试或运行时核验的任务。
---
# Genarrative SpacetimeDB 项目指导
本 skill 只保存 Genarrative 的项目约束和操作边界;SpacetimeDB 的通用 API、语言 SDK 和 CLI 手册由已安装的官方插件提供。项目规则覆盖插件示例中的默认值或与本仓库冲突的建议。
## 官方插件依赖
开始 SpacetimeDB 任务时,按任务范围读取官方插件 skill:
- `spacetimedb:concepts`:核心语义、表、reducer、procedure、view、订阅和身份。
- `spacetimedb:rust-server`Rust module、表属性、访问器、迁移兼容性和 SDK API。
- `spacetimedb:cli`:初始化、构建、发布、生成绑定、SQL、调用、日志和 server 管理。
- `spacetimedb:typescript-client`:前端生成绑定、订阅和 TypeScript 客户端 SDK;其它语言客户端按需读取插件对应 skill。
- `spacetimedb:mcp`:通过已连接的 MCP 操作运行中的数据库;没有 MCP 工具时使用 CLI 等价命令。
如果当前环境尚未安装插件,使用:
```bash
codex plugin marketplace add clockworklabs/SpacetimeDB --sparse .agents --sparse codex-plugin
codex plugin add spacetimedb\@spacetimedb-plugins
```
插件不可用时,以当前源码、`docs/`、生成绑定和仓库脚本为准,不凭记忆发明 SpacetimeDB API。
## 架构边界
Genarrative 的唯一有效后端路线是:
```text
server-rs + Axum + SpacetimeDB
```
- `module-*`:领域模型、命令、应用规则、领域事件和领域错误;不得直接依赖 Axum、SpacetimeDB table/reducer/procedure、`spacetime-client`、外部平台或文件系统。
- `spacetime-module`SpacetimeDB 表、reducer、procedure、view、migration、事务 adapter 和 row mapper。
- `spacetime-client`:后端访问 SpacetimeDB 的 typed facade;其它后端 crate 不直接创建第二套访问路径。
- `api-server`HTTP、SSE、BFF 和外部副作用编排。
- `platform-*`:OSS、LLM、认证、语音等外部平台能力。
- `shared-contracts` / `packages/shared`:前后端 DTO、公开契约和无业务真相的共享 TypeScript 代码。
- 前端只负责表现、交互、临时 UI 状态和后端结果渲染,不绕过 BFF/投影直接读取私有表或推导正式业务状态。
SpacetimeDB 是数据和事务层,不替代 `api-server` BFF、`spacetime-client` facade 或公开 read model。插件提供的“SpacetimeDB 可替代传统服务端”通用描述不能改变本项目边界。
## 语义与安全不变量
- Reducer 是原子事务写路径,不向调用者返回业务数据;读取通过订阅、read model、view 或 BFF。
- Reducer 必须确定性执行:不得访问文件系统、网络、系统时钟或外部随机源;使用 `ctx.timestamp``ctx.rng()` / `ctx.random()` 等 SpacetimeDB 能力。
- 授权使用上下文中的 `ctx.sender()`(或当前语言对应 API),不信任调用参数传入的身份。
- Auto-increment ID 不是排序依据;需要顺序时使用时间戳或显式序列字段。
- Private table 是后端事实;用户可见状态通过 BFF、投影或明确的 public table/view 暴露。公共表仍只能由 reducer/procedure 写入。
- Procedure 在 2.8 已稳定,可使用显式事务和 `ctx.http`Genarrative 默认仍把外部 provider 协议放在 `platform-*`,把编排放在 `api-server`,除非当前架构明确要求 module procedure。
- Event table 必须显式订阅,按插入事件消费;不要依赖其持久化行或 `OnUpdate`。需要更新回调时使用持久表或带主键的 procedural view。
- Standalone MCP 是 operator/developer 集成面,不是 BFF、facade 或公开 read model 的替代品。MCP/SQL/CLI 的写入都必须有明确授权;日常 smoke 优先只读。
## Schema 与迁移
修改现有 SpacetimeDB persistent table 时:
1. 新字段只能追加到 Rust 表结构体末尾,并设置明确的 `#[default(...)]`
2. 删除、改名、重排、改类型或破坏性约束变更前,必须先询问用户并确认迁移计划。
3. 同步更新 `server-rs/crates/spacetime-module/src/migration.rs`、后端架构文档中的表目录、生成绑定和相关契约/测试。
4. 运行:
```bash
npm run spacetime:generate
npm run check:spacetime-schema
```
Event table 的较宽松自动迁移规则不适用于 persistent table,不能借此绕过上述门禁。以当前源码和 `docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md` 为 schema 真相。
## CLI、目标 server 与本地开发
- 优先使用仓库 wrapper`npm run dev:spacetime`、`npm run dev:api-server`、`npm run spacetime:generate`。
- 直接使用 CLI 时始终显式传 `--server` 或 `--server-url`;不要依赖默认云端目标或个人 CLI 默认 server。
- 不新增 `maincloud` / `MAINCLOUD` 命令、环境变量、脚本或文档;历史残留只按历史处理。
- 人工命令、本地联调、排障步骤和文档示例禁止使用 `spacetime --root-dir`;本地数据隔离使用项目脚本或 `--data-dir`。
- `spacetime publish` 的 `--delete-data=always` 只在明确授权的破坏性操作中使用;schema 冲突优先按项目脚本和受控迁移流程处理。
- 项目 SpacetimeDB crate、SDK、CLI/standalone 和生成 bindings 按 `2.8.3` 对齐;官方发行资产、Rust crates 和容器镜像使用 `v2.8.3` 版本标签,仓库额外固定 CLI commit `8e410d2842147bd8e5a32a9589cc00c19f7478e2`。升级时核对 Cargo 精确 pin、实际 CLI 和运行中服务二进制,不把本地 CLI 重装当作仓库升级。
本地开发默认由项目启动器管理端口;实际监听地址以 `.app/dev-stack.json` 和启动日志为准,不能从文档默认端口推断当前目标。发布后确认 api-server 使用的是同一 database、server 和 token。
## MCP 与运行时核验
如果当前会话暴露 SpacetimeDB MCP 工具,读取运行中的数据库优先使用 typed MCP:先 `list_databases` / `get_schema`,再做只读 SQL 或 `ping`;调用 reducer 或 SQL 写入前确认目标、身份和授权。没有 MCP 工具时使用显式目标的 CLI。2.8 standalone 的 MCP HTTP endpoint 是 `POST /v1/database/{name_or_identity}/mcp`,提供 `ping`、`get_schema`、`sql`、`call`;升级 smoke 在隔离数据库中只做 `initialize`、`tools/list`、`ping`、`get_schema`,除非写入明确属于任务范围。
排查“服务健康但业务不可用”时按顺序核对:
1. SpacetimeDB standalone 是否运行(本地优先 `npm run dev:spacetime`,主机侧核对 systemd)。
2. module 是否发布到 api-server 实际使用的同一个 server/database。
3. 生成绑定是否来自当前 module。
4. api-server 的 database、server URL 和 token 是否一致。
5. reducer/procedure 是否真正被调用;区分超时、权限、schema 不存在和业务错误。
6. `/healthz` / `/readyz` 通过但业务仍失败时,继续检查 API 日志和公开路由,不把健康检查当作业务成功证明。
主机升级需核对运行中进程而非只看 PATH:
```bash
type -a spacetime
spacetime --version
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
readlink -f "/proc/${pid}/exe"
"/proc/${pid}/exe" --version
curl -fsS http://127.0.0.1:3101/v1/ping
```
## 修改后的最小验证
按范围执行定向测试/类型检查,并至少运行:
```bash
npm run check:encoding
git diff --check
```
涉及 schema 时追加 `npm run spacetime:generate` 和 `npm run check:spacetime-schema`;涉及 API 时按当前后端文档启动 `npm run dev:api-server` 并检查 `/healthz`。无法运行的验证要在交付说明中标记为未验证并说明原因。
## 参考入口
- `docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md`
- `docs/【开发运维】本地开发验证与生产运维-2026-05-15.md`
- `server-rs/README.md`
- `scripts/check-spacetime-schema-guard.mjs`
- `scripts/check-server-rs-ddd-boundaries.mjs`
@@ -1,7 +1,7 @@
interface:
display_name: 'GPT Image 2 VectorEngine'
short_description: 'Generate project thumbnails through VectorEngine'
brand_color: '#10B981'
default_prompt: 'Use $gpt-image-2-apimart to dry-run or generate puzzle template thumbnails through VectorEngine.'
display_name: "GPT Image 2 VectorEngine"
short_description: "Generate project thumbnails through VectorEngine"
brand_color: "#10B981"
default_prompt: "Use $gpt-image-2-apimart to dry-run or generate puzzle template thumbnails through VectorEngine."
policy:
allow_implicit_invocation: true
@@ -257,8 +257,7 @@ async function fetchJson(url, options, timeoutMs) {
}
function shouldFallbackImageModel(error) {
const raw =
`${error?.message || ''}\n${error?.vectorEngineBody || ''}`.toLowerCase();
const raw = `${error?.message || ''}\n${error?.vectorEngineBody || ''}`.toLowerCase();
if (error?.vectorEngineResponseParse) {
return !containsContentRejection(raw);
}
@@ -311,10 +310,11 @@ async function requestImagePayload(env, entry) {
},
env.timeoutMs,
);
const base64Image = decodeStrictBase64Image(
extractBase64Images(payload)[0],
);
if (extractImageUrls(payload)[0] || base64Image) {
const base64Image = decodeStrictBase64Image(extractBase64Images(payload)[0]);
if (
extractImageUrls(payload)[0] ||
base64Image
) {
return payload;
}
const error = new Error(`VectorEngine returned no image for ${entry.id}`);
@@ -350,9 +350,7 @@ async function downloadUrl(url, timeoutMs) {
};
} catch (error) {
if (error?.name === 'AbortError') {
throw new Error(
`Generated image download timed out after ${timeoutMs}ms`,
);
throw new Error(`Generated image download timed out after ${timeoutMs}ms`);
}
throw error;
} finally {
@@ -372,9 +370,7 @@ async function generateOne(env, entry, outDir) {
} else if (b64Images[0]) {
const bytes = decodeStrictBase64Image(b64Images[0]);
if (!bytes) {
throw new Error(
`VectorEngine returned invalid base64 image for ${entry.id}`,
);
throw new Error(`VectorEngine returned invalid base64 image for ${entry.id}`);
}
image = {
bytes,
@@ -12,11 +12,7 @@ const promptsPath = path.join(
'assets',
'puzzle-template-prompts.json',
);
const defaultOutDir = path.join(
repoRoot,
'public',
'puzzle-creation-templates',
);
const defaultOutDir = path.join(repoRoot, 'public', 'puzzle-creation-templates');
const defaultTimeoutMs = 1000000;
const preferredImageModel = 'gpt-image-2';
const fallbackImageModel = 'gpt-image-2-c';
@@ -227,8 +223,7 @@ async function fetchJson(url, options, timeoutMs) {
}
function shouldFallbackImageModel(error) {
const raw =
`${error?.message || ''}\n${error?.vectorEngineBody || ''}`.toLowerCase();
const raw = `${error?.message || ''}\n${error?.vectorEngineBody || ''}`.toLowerCase();
if (error?.vectorEngineResponseParse) {
return !containsContentRejection(raw);
}
@@ -281,15 +276,14 @@ async function requestImagePayload(env, template) {
},
env.timeoutMs,
);
const base64Image = decodeStrictBase64Image(
extractBase64Images(payload)[0],
);
if (extractImageUrls(payload)[0] || base64Image) {
const base64Image = decodeStrictBase64Image(extractBase64Images(payload)[0]);
if (
extractImageUrls(payload)[0] ||
base64Image
) {
return payload;
}
const error = new Error(
`VectorEngine returned no image for ${template.id}`,
);
const error = new Error(`VectorEngine returned no image for ${template.id}`);
error.vectorEngineResponseParse = true;
error.vectorEngineBody = JSON.stringify(payload).slice(0, 600);
throw error;
@@ -322,9 +316,7 @@ async function downloadUrl(url, timeoutMs) {
};
} catch (error) {
if (error?.name === 'AbortError') {
throw new Error(
`Generated image download timed out after ${timeoutMs}ms`,
);
throw new Error(`Generated image download timed out after ${timeoutMs}ms`);
}
throw error;
} finally {
@@ -344,9 +336,7 @@ async function generateOne(env, template, outDir) {
} else if (b64Images[0]) {
const bytes = decodeStrictBase64Image(b64Images[0]);
if (!bytes) {
throw new Error(
`VectorEngine returned invalid base64 image for ${template.id}`,
);
throw new Error(`VectorEngine returned invalid base64 image for ${template.id}`);
}
image = {
bytes,
+178
View File
@@ -0,0 +1,178 @@
---
name: spacetimedb-cli
description: SpacetimeDB 2.7 CLI reference for Genarrative. Use for spacetime build, publish, generate, call, sql, logs, server management, local dev, explicit server targeting, version checks, and remote runtime verification.
---
# SpacetimeDB CLI
Use this skill when working with the `spacetime` CLI in Genarrative. Prefer repository scripts when they exist, and keep every operation pinned to an explicit target server or local process.
## Genarrative Rules
- Do not rely on the default SpacetimeDB cloud target. Pass `--server` or `--server-url` explicitly in scripts, docs, smoke tests, and manual troubleshooting.
- Do not introduce `maincloud` / `MAINCLOUD` commands, env vars, or docs. Treat old references as historical residue.
- Do not use `spacetime --root-dir` in manual commands or docs. Use project scripts, `--data-dir`, explicit `--server`, or the configured running service.
- For repository version upgrades, update `server-rs/Cargo.toml` exact pins, regenerate bindings, and verify the actual CLI/runtime version. Do not treat a local CLI reinstall as a repo upgrade.
- For host upgrades, verify the running service binary, not just shell PATH: `systemctl show ... MainPID` -> `/proc/$pid/exe --version` -> `/v1/ping`.
## Core Commands
```bash
# Build module
spacetime build
spacetime build --debug
# Publish to an explicit server
spacetime publish my-database --server http://127.0.0.1:3101 --yes=migrate,break-clients
# Destructive publish only when explicitly intended
spacetime publish my-database --server http://127.0.0.1:3101 --delete-data=always --yes=delete-data,migrate
# Delete data only for breaking schema conflicts
spacetime publish my-database --server http://127.0.0.1:3101 --delete-data=on-conflict --yes=migrate
# Generate bindings
spacetime generate --lang typescript|csharp|rust|unrealcpp --out-dir ./bindings --module-path ./server
```
## Genarrative Local Workflow
```bash
# Prefer project wrappers
npm run dev:spacetime
npm run dev:api-server
npm run spacetime:generate
# Query local database
spacetime sql my-db --server http://127.0.0.1:3101 "SELECT * FROM players"
# Logs
spacetime logs my-db --server http://127.0.0.1:3101 -f
```
## Database Interaction
```bash
# SQL / describe
spacetime sql my-db --server http://127.0.0.1:3101 "SELECT * FROM users"
spacetime describe my-db --server http://127.0.0.1:3101 --json
spacetime describe my-db table users --server http://127.0.0.1:3101 --json
# Reducer/procedure calls. Arguments are positional JSON values.
spacetime call --server http://127.0.0.1:3101 my-db my_reducer '"value"' '123'
# 2.5+ accepts hex strings for Identity arguments without full JSON tuple syntax.
spacetime call --server http://127.0.0.1:3101 my-db reducer_needing_identity 0xabc123...
# Subscribe from CLI
spacetime subscribe my-db "SELECT * FROM users" --num-updates 10 --server http://127.0.0.1:3101
```
## Standalone MCP Endpoint (2.7)
SpacetimeDB 2.7 standalone exposes an authenticated JSON-RPC MCP endpoint at
`POST /v1/database/{name_or_identity}/mcp`. It advertises `ping`, `get_schema`,
`sql`, and `call`. The SQL and reducer tools execute with the bearer token's
identity, so keep routine smoke checks read-only.
```bash
curl -fsS \
-H "Authorization: Bearer ${SPACETIME_TOKEN}" \
-H 'Content-Type: application/json' \
--data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"genarrative-smoke","version":"1.0.0"}}}' \
http://127.0.0.1:3101/v1/database/my-db/mcp
curl -fsS \
-H "Authorization: Bearer ${SPACETIME_TOKEN}" \
-H 'Content-Type: application/json' \
--data '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ping","arguments":{"message":"genarrative"}}}' \
http://127.0.0.1:3101/v1/database/my-db/mcp
```
For repository upgrade validation, also call `tools/list` and the read-only
`get_schema` tool against an isolated local database. Do not use `sql` or `call`
for writes unless that mutation is explicitly in scope.
## Server & Auth
```bash
spacetime server list
spacetime server add local --url http://localhost:3000 --default
spacetime server add genarrative-dev --url http://127.0.0.1:3101
spacetime server ping genarrative-dev
spacetime login
spacetime login --token <token>
spacetime login show
spacetime logout
```
## Version & Runtime Verification
```bash
# CLI resolution can be misleading; compare all candidates when diagnosing.
type -a spacetime
spacetime --version
spacetime version list
# Verify a systemd service binary actually changed.
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
readlink -f "/proc/${pid}/exe"
"/proc/${pid}/exe" --version
curl -fsS http://127.0.0.1:3101/v1/ping
```
## Flags
| Flag | Description |
|------|-------------|
| `--server`, `-s` | Target server nickname, host, or URL |
| `--yes`, `-y` | Non-interactive prompt skipping; in 2.6+ use scoped values |
| `--delete-data`, `-c` | Publish data policy: `always`, `on-conflict`, or `never` |
| `--module-path`, `-p` | Module project path |
| `--bin-path`, `-b` | Publish/generate from compiled wasm |
| `--no-config` | Ignore `spacetime.json` |
| `--env` | Select config file layering environment |
## Troubleshooting
### Not Logged In
```bash
spacetime login
```
### Server Not Responding
```bash
spacetime server ping <server>
curl -fsS http://127.0.0.1:3101/v1/ping
```
For local Genarrative work, start SpacetimeDB first with `npm run dev:spacetime`, then start `npm run dev:api-server`.
### Schema Conflict
```bash
spacetime publish my-db --server http://127.0.0.1:3101 --delete-data=on-conflict --yes=migrate
```
Use `--delete-data=always` only with explicit approval.
### Version Mismatch
```bash
rg -n 'spacetimedb' server-rs/Cargo.toml
spacetime --version
spacetime version list
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
"/proc/${pid}/exe" --version
```
## Notes
- Procedure calls remain stable in 2.7; module HTTP handlers/webhooks and RLS capabilities still require their documented gates.
- 2.5 fixed `publish --delete-data` config fallback; 2.6 kept that behavior and improved CLI binary distribution; 2.7 adds `spacetime sql --format json` and database `lock` / `unlock`.
- The official 2.7.0 Linux release archives and container image currently use the `v2.7.0-hotfix3` asset tag while binaries report `2.7.0`; keep the asset tag distinct from the runtime version check.
- Do not assume `spacetime version install 2.7.0` selected hotfix3: stale updater metadata can install bare-tag commit `a08663c7...`. For the current release, verify CLI commit `d220349a...` and use the official hotfix3 archive or repository provision flow when it differs.
- Genarrative scripts should pass `--server` or `--server-url` explicitly instead of relying on CLI defaults.
+119
View File
@@ -0,0 +1,119 @@
---
name: spacetimedb-concepts
description: Understand SpacetimeDB 2.7 architecture, reducer/procedure/table/view semantics, schema evolution, subscriptions, identity, and Genarrative-specific backend boundaries. Use when designing or reviewing SpacetimeDB-backed features.
---
# SpacetimeDB Core Concepts
SpacetimeDB is a relational database that also executes application logic in uploaded modules. In Genarrative, it is the data and transaction layer behind `server-rs + Axum + SpacetimeDB`, not a replacement for the `api-server` BFF or external platform adapters.
## Genarrative Boundaries
- Domain rules live in `module-*`.
- SpacetimeDB tables, reducers, procedures, migrations, row mappers, and read models live in `spacetime-module`.
- Backend access goes through `spacetime-client` facades.
- HTTP/SSE/BFF and external orchestration stay in `api-server`.
- External side effects stay in `platform-*`.
- Frontend renders backend truth and must not bypass BFF/projections to invent formal business state.
## Critical Rules
1. **Reducers are transactional**: they do not return data to callers. Read through subscriptions, read models, views, or BFF endpoints.
2. **Reducers are deterministic**: no filesystem, network, wall-clock, or external RNG. Use `ctx.timestamp`, `ctx.rng()` / `ctx.random()`, and tables.
3. **Procedures are stable in 2.7**: they can use explicit transactions and outgoing HTTP via `ctx.http`.
4. **Identity comes from context**: use `ctx.sender()` or language equivalent for authorization. Never trust identity passed as an argument.
5. **Auto-increment IDs are not ordering guarantees**: gaps are normal. Use timestamps or explicit sequence columns for ordering.
6. **Schema changes need migration discipline**: existing Genarrative table fields must be appended with defaults; update migration code, table catalog, generated bindings, and run `npm run check:spacetime-schema`.
## Tables
- Private tables are the default; only reducers/procedures and database owners can access them.
- Public tables are exposed to clients through subscriptions. Writes still go through reducers/procedures.
- Organize data by access pattern when bandwidth or update frequency differs.
- Existing persistent tables in Genarrative are conservative: no rename, delete, reorder, or type changes without a user-approved migration plan.
## Reducers
Reducers are deterministic transactional functions. They are the primary client-invoked mutation path.
- No global mutable state.
- No filesystem, network, timers, or non-deterministic RNG.
- Return `Result<(), String>` for expected sender-visible errors.
- Use `ctx.sender()` for authorization.
- Store persistent state in tables.
## Procedures
Procedures are stable in 2.7. They can be scheduled, can open explicit transactions with `with_tx` / `try_with_tx`, and can use outgoing HTTP (`ctx.http`).
Genarrative default: keep external provider protocols in `platform-*` and orchestration in `api-server` unless a task explicitly moves a workflow into a module procedure.
Module HTTP handlers/webhooks and RLS `client_visibility_filter` remain subject to their documented gates in 2.7.
## Views
Views expose computed read-only data. SpacetimeDB 2.7 supports primary keys on procedural views in Rust, TypeScript, C#, and C++. Clients can receive update events when subscribed to such views with primary keys. Ensure the view never returns duplicate primary keys, because that can fail view refresh and roll back the triggering transaction.
## Event Tables
Event tables broadcast reducer/procedure-specific facts to subscribers and must be subscribed explicitly. They are excluded from `subscribe_to_all_tables()`.
Since 2.6, event tables support broader layout-altering automigrations, including column removal, reordering, and type changes that regular tables reject. This relaxed migration behavior is for event-only tables, not persistent tables.
Event-table primary keys and constraints are transaction-scoped. They can reject duplicate event rows within one transaction, but event rows are not retained in client cache, so clients observe event tables through insert callbacks only. Do not design Genarrative event tables around `OnUpdate` / `on_update` / `onUpdate`; use a persistent table or a primary-keyed procedural view when update callbacks are required.
Official 2.4.1 through 2.7 release notes document primary-key-backed update callbacks for procedural views, not event tables.
## Subscriptions
1. Subscribe to SQL queries or generated table/query builders.
2. Receive initial matching rows.
3. Receive updates when subscribed rows change.
4. Render from subscribed data, not reducer return values.
Best practices:
- Group subscriptions by lifetime.
- Subscribe to new data before unsubscribing old data during transitions.
- Avoid overlapping queries that duplicate row delivery.
- Use indexes for subscribed filters.
## Standalone MCP
SpacetimeDB 2.7 standalone exposes `POST /v1/database/{name_or_identity}/mcp`
using MCP JSON-RPC protocol `2025-06-18`. Its tools are `ping`, `get_schema`,
`sql`, and `call`; SQL and reducer calls run with the authenticated caller's
identity. In Genarrative this is an operator/developer integration surface, not
a replacement for `api-server` BFF routes, `spacetime-client` facades, or public
read models. Upgrade smoke should use an isolated local database and restrict
itself to `initialize`, `tools/list`, `ping`, and `get_schema` unless writes are
explicitly intended.
## 2.2.0 to 2.7.0 Delta
Genarrative introduced SpacetimeDB around 2.2.0. Important changes since then:
- **2.2.0**: v3 WebSocket transport and TS SDK default, safer production operations (`lock`/`unlock`, safer `delete`, better `publish --yes`), TS React `useProcedure`, table clearing APIs, empty-table drop automigration, primary-key migration fixes, bytes-key B-tree support, durability hardening.
- **2.3.0**: first-party Godot SDK, more WebSocket pipelining/batching, HTTP/2 backend support, Vue `useProcedure`, Unity 6 WebGL support, commitlog compression/throughput improvements, Rust `DbContext` generics, `ReducerContext::identity` deprecated in favor of `database_identity`, connection lifecycle and unsubscribe fixes.
- **2.4.0**: unstable module HTTP handlers/webhooks, faster synchronous WASM reducer runtime, commitlog resume truncation fix for silent data loss risk, better commitlog decode context, V8 heap metrics for procedure workers, JS execution-time billing regression reverted.
- **2.4.1**: Rust and TypeScript procedural views can declare primary keys, enabling `OnUpdate` events for subscribed views; fixed index schema from ST tables.
- **2.5.0**: procedures are stable, C# procedural views gain primary keys, event tables allow broader layout-altering automigrations, BTreeSet storage makes row insertion deterministic and avoids accidentally quadratic bulk insert behavior, `wasm_memory_bytes` billing metric semantics changed, template version constraints unified, `publish --delete-data` config fallback fixed, CLI `call` accepts hex Identity arguments.
- **2.6.0**: procedural-view primary keys are available across Rust, TypeScript, and C#, commitlog gains `max_segment_size` / `write_buffer_size` / `preallocate_segments`, the default write buffer increases for throughput, event-table automigrations improve, and CLI binary distribution expands.
- **2.6.1**: procedure contexts again receive the caller `Identity` and `ConnectionId`; generated TypeScript `Option<T>` fields use optional keys; `spacetime init --template` lists available templates when no template argument is supplied.
- **2.7.0**: existing tables can add unique or primary-key constraints when current data satisfies them; standalone exposes an authenticated database MCP endpoint; Rust adds context-capability and table-accessor traits; `spacetime sql --format json` and database locking are available; view cleanup, backing-table migration, connection metrics, and memory metrics improve. Official current release assets use the `v2.7.0-hotfix3` tag while binaries report `2.7.0`.
## Debugging Checklist
1. Is the Genarrative SpacetimeDB server running? Use `npm run dev:spacetime` locally or host-local `systemctl`.
2. Is the module published to the same server the API uses?
3. Are generated bindings current? Use `npm run spacetime:generate`.
4. Is `api-server` using the same database and token?
5. Is the reducer/procedure actually called?
6. Did `/healthz` / `/readyz` pass while business SpacetimeDB calls still timeout? Inspect API logs and public route behavior.
## Editing Behavior
- Make the smallest change necessary.
- Do not invent SpacetimeDB APIs; verify against current docs, generated bindings, or source.
- For Genarrative schema edits, update migration code, table catalog/docs, generated bindings, and relevant tests.
- After schema edits, run `npm run spacetime:generate` and `npm run check:spacetime-schema`.
+280
View File
@@ -0,0 +1,280 @@
---
name: spacetimedb-rust
description: Develop SpacetimeDB 2.7 server modules in Rust for Genarrative. Use when writing or reviewing tables, reducers, procedures, views, migrations, row mappers, schema changes, and module logic.
---
# SpacetimeDB Rust Module Development
Use this skill for Rust code in `server-rs/crates/spacetime-module` and related Genarrative schema/migration work.
## Genarrative Rules
- Keep domain rules in `module-*`; keep SpacetimeDB tables, reducers, procedures, views, mappers, and transaction adapters in `spacetime-module`.
- Existing table fields must be appended at the end with explicit defaults. Do not rename, remove, reorder, or change field types without a user-confirmed migration plan.
- After schema changes, update `migration.rs`, table catalog/docs, generated bindings, and run `npm run spacetime:generate` plus `npm run check:spacetime-schema`.
- Private tables are backend facts. Expose user-visible state through BFF endpoints/read models rather than direct client SQL.
## Hallucinated APIs: Do Not Use
```rust
#[derive(Table)] // Tables use #[table], not derive
#[derive(Reducer)] // Reducers use #[reducer], not derive
#[derive(SpacetimeType)] // Do not derive this on #[table] structs
pub fn reducer(ctx: &mut ReducerContext) {} // Use &ReducerContext
ctx.db.player // Use ctx.db.player()
ctx.db.player.find(id) // Use ctx.db.player().id().find(&id)
ctx.sender // Use ctx.sender()
ctx.db.user().name().update(..) // Update by primary key only
spacetimedb = { version = "...", features = ["unstable"] } // Not needed for procedures since 2.5
```
## Required Patterns
```rust
use spacetimedb::{reducer, table, Identity, ReducerContext, Table, Timestamp};
use spacetimedb::SpacetimeType; // Custom types only, not tables
#[table(accessor = player, public)]
pub struct Player {
#[primary_key]
#[auto_inc]
pub id: u64,
pub owner: Identity,
pub name: String,
pub created_at: Timestamp,
}
#[reducer]
pub fn create_player(ctx: &ReducerContext, name: String) -> Result<(), String> {
if name.trim().is_empty() {
return Err("name required".to_string());
}
ctx.db.player().try_insert(Player {
id: 0,
owner: ctx.sender(),
name,
created_at: ctx.timestamp,
})?;
Ok(())
}
```
Hard requirements:
- Import `Table` for table operations.
- Use `accessor = identifier`, not string literals.
- Use `ctx.sender()` for authorization.
- Use `ctx.rng()` / `ctx.random()` / `ctx.new_uuid_*()` for deterministic randomness and UUIDs.
- Use `Result<(), String>` for expected sender errors; avoid panics except impossible states.
- Use `try_insert()` in `Result` reducers when constraint violations should be reported cleanly.
## Tables
```rust
#[spacetimedb::table(accessor = game_tick_schedule, scheduled(game_tick))]
pub struct GameTickSchedule {
#[primary_key]
#[auto_inc]
pub scheduled_id: u64,
pub scheduled_at: ScheduleAt,
}
```
Table attributes:
| Attribute | Description |
|-----------|-------------|
| `accessor = identifier` | API name used in `ctx.db.{accessor}()` |
| `public` | Visible to clients via subscriptions |
| `event` | Transient event table |
| `scheduled(function_name)` | Schedule table that triggers a reducer/procedure |
| `index(accessor = idx, btree(columns = [a, b]))` | Multi-column index |
Column attributes:
| Attribute | Description |
|-----------|-------------|
| `#[primary_key]` | One primary key per table |
| `#[auto_inc]` | Auto-generates integer values when inserting `0` |
| `#[unique]` | Unique constraint and `find()` accessor |
| `#[index(btree)]` | B-tree index and `filter()` accessor |
| `#[default(...)]` | Required for new fields on existing Genarrative tables |
## Genarrative Schema Change Pattern
```rust
#[spacetimedb::table(accessor = creation_entry_config, public)]
pub struct CreationEntryConfig {
#[primary_key]
pub id: u64,
pub existing_field: String,
// Append new fields at the end and provide a default.
#[default(false)]
pub new_flag: bool,
}
```
Then update `migration.rs`, table catalog/docs, generated bindings, and run:
```bash
npm run spacetime:generate
npm run check:spacetime-schema
```
## Table Operations
```rust
let row = ctx.db.player().insert(Player { id: 0, owner, name, created_at });
ctx.db.player().try_insert(row)?;
let by_id = ctx.db.player().id().find(&123u64);
for player in ctx.db.player().owner().filter(&ctx.sender()) {}
for player in ctx.db.player().level().filter(&(18u32..=65u32)) {}
for player in ctx.db.player().iter() {}
let count = ctx.db.player().count();
if let Some(player) = ctx.db.player().id().find(&id) {
ctx.db.player().id().update(Player { name: new_name, ..player });
}
ctx.db.player().id().delete(&id);
```
For delete/update based on non-PK filters, collect keys first to avoid iterator invalidation.
## Indexes
```rust
#[spacetimedb::table(
accessor = score,
public,
index(accessor = by_player_level, btree(columns = [player_id, level]))
)]
pub struct Score {
pub player_id: u32,
pub level: u32,
pub points: i64,
}
for row in ctx.db.score().by_player_level().filter(&(42,)) {}
for row in ctx.db.score().by_player_level().filter(&(42, 5)) {}
```
## Event Tables
```rust
#[table(accessor = damage_event, public, event)]
pub struct DamageEvent {
pub target: Identity,
pub amount: u32,
}
#[reducer]
fn deal_damage(ctx: &ReducerContext, target: Identity, amount: u32) {
ctx.db.damage_event().insert(DamageEvent { target, amount });
}
```
Event tables must be subscribed explicitly and are excluded from `subscribe_to_all_tables()`.
Since 2.6, event tables support broader layout-altering automigrations than regular tables, including column removal, reordering, and type changes. This relaxed migration policy does not apply to persistent tables.
Event-table primary keys and constraints are enforced only within the current transaction. They do not make event rows persistent, and client SDKs expose event tables as insert-only event streams. Do not rely on `OnUpdate` / `on_update` / `onUpdate` for event tables; use a persistent table or a primary-keyed procedural view when update callbacks are required.
Official 2.4.1 through 2.7 release notes tie primary-key-backed update callbacks to procedural views, not event tables.
## Views
```rust
#[spacetimedb::view(accessor = my_players, public, primary_key = id)]
pub fn my_players(ctx: &spacetimedb::ViewContext) -> Vec<Player> {
ctx.db.player().owner().filter(&ctx.sender()).collect()
}
```
Rust and TypeScript gained primary key support for procedural views in 2.4.1. With primary keys, clients can receive update events when subscribed to such views. Avoid duplicate primary keys in view results.
## Lifecycle & Scheduled Reducers
```rust
#[spacetimedb::reducer(init)]
pub fn init(ctx: &ReducerContext) -> Result<(), String> { Ok(()) }
#[spacetimedb::reducer(client_connected)]
pub fn on_connect(ctx: &ReducerContext) -> Result<(), String> { Ok(()) }
#[spacetimedb::reducer(client_disconnected)]
pub fn on_disconnect(ctx: &ReducerContext) -> Result<(), String> { Ok(()) }
use spacetimedb::{ScheduleAt, TimeDuration};
ctx.db.game_tick_schedule().insert(GameTickSchedule {
scheduled_id: 0,
scheduled_at: ScheduleAt::Interval(std::time::Duration::from_millis(100).into()),
});
let run_at = ctx.timestamp + std::time::Duration::from_secs(60);
ctx.db.game_tick_schedule().insert(GameTickSchedule {
scheduled_id: 0,
scheduled_at: ScheduleAt::Time(run_at),
});
```
For scheduled reducers, check `ctx.sender_auth().is_internal()` when the reducer should only be system-triggered.
## Procedures
Procedures remain stable in 2.7 and no longer require the `unstable` feature.
```rust
use spacetimedb::{procedure, ProcedureContext};
#[procedure]
fn save_external_data(ctx: &mut ProcedureContext, url: String) -> Result<(), String> {
let body = ctx.http.get(url).send()?.text()?;
ctx.try_with_tx(|tx| {
tx.db.external_data().insert(ExternalData { id: 0, content: body });
Ok(())
})?;
Ok(())
}
```
| Reducers | Procedures |
|----------|------------|
| `&ReducerContext` | `&mut ProcedureContext` |
| Direct `ctx.db` access | Use `with_tx()` / `try_with_tx()` |
| No HTTP/network | Outgoing HTTP via `ctx.http` |
| Deterministic transaction path | Side-effect-capable workflow path |
In Genarrative, keep external provider protocols in `platform-*` by default unless the architecture explicitly moves that workflow into the module.
## Identity & Auth
```rust
fn require_owner(ctx: &ReducerContext, owner: &Identity) -> Result<(), String> {
if ctx.sender() != *owner {
return Err("Not authorized".to_string());
}
Ok(())
}
```
`ReducerContext::identity` is deprecated since 2.3; use the current database/module identity API when needed, and use `ctx.sender()` for caller identity.
## Commands
```bash
spacetime build
spacetime publish my_database --server http://127.0.0.1:3101 --module-path . --yes=migrate
spacetime publish my_database --server http://127.0.0.1:3101 --delete-data=on-conflict --module-path . --yes=migrate
spacetime logs my_database --server http://127.0.0.1:3101
spacetime call --server http://127.0.0.1:3101 my_database create_player '"Alice"'
spacetime sql my_database --server http://127.0.0.1:3101 "SELECT * FROM player"
npm run spacetime:generate
npm run check:spacetime-schema
```
@@ -2,7 +2,7 @@
name: wechatpay-basic-payment
description: 微信支付基础支付解决方案,涵盖支付、退款账单、分账、商户进件、开户意愿确认,提供选型/代码示例/业务速查/质量评估/排障五大能力。Use when user mentions "JSAPI支付", "APP支付", "H5支付", "Native支付", "小程序支付", "付款码支付", "合单支付", "特约商户进件", "开户意愿确认", or asks to "推荐支付方式", "要支付接口代码示例", "排查支付或退款问题".
author: wechatpay
version: '1.0'
version: "1.0"
---
# 微信支付基础支付 & 合单支付接入指引
@@ -14,11 +14,10 @@ version: '1.0'
1. **所有问题必须得到用户明确回答后才能继续。** 如果一次提出了多个问题,必须逐一检查每个问题是否都已获得用户的明确答复。对于未回答的问题,必须再次追问,**严禁对未回答的问题自行假设、推断或使用默认值**。
2. **接入模式前置确认**:任何能力使用前须先确认**商户模式**或**服务商模式**,已明确则无需重复。两种模式的核心差异见 → [📄 接入模式说明.md](./references/3-商户与服务商通用/接入指南/接入模式说明.md)。
3. **分步确认协议**(简单知识问答除外,需要帮用户排查、分析或执行操作时必须遵守):
- **① 明确需求**:先理解用户问题,给出初步判断或原因分析,不要一上来就堆参数清单
- **② 征得同意**:主动提出下一步能做什么,**等用户明确同意后**才继续,严禁用户没表态就开始收集参数或执行操作
- **③ 收集信息**:用户同意后再告知需要哪些信息并逐项收集,收齐才能执行
- **④ 执行前确认**:准备执行操作前,简要说明即将做什么,确认用户同意后再执行;涉及线上环境须额外提示风险。
- **① 明确需求**:先理解用户问题,给出初步判断或原因分析,不要一上来就堆参数清单。
- **② 征得同意**:主动提出下一步能做什么,**等用户明确同意后**才继续,严禁用户没表态就开始收集参数或执行操作
- **③ 收集信息**:用户同意后再告知需要哪些信息并逐项收集,收齐才能执行
- **④ 执行前确认**:准备执行操作前,简要说明即将做什么,确认用户同意后再执行;涉及线上环境须额外提示风险
## 能力概览
@@ -49,12 +48,10 @@ version: '1.0'
> ‼️ **支付方式仅「下单」和「调起支付」接口需确认,其他接口无需询问支付方式。** 用户请求查单、关单、退款、回调处理、账单等通用接口时,只需确认接入模式和开发语言,无需询问支付方式——这些接口各支付方式完全相同。**但合单支付的查单、关单、回调使用专用接口,需确认用户是基础支付还是合单支付。**
>
> ‼️ **用户语言非 Java/Go 时**(本 skill 仅维护 Java/Go 示例):**禁止**直接生成跨语言代码。流程:
>
> 1. 用 `AskQuestion` 获明确同意(文案需明示「参考实现 / 非官方维护 / 须自行 review 与测试」),未同意只发官方 Java/Go 原文。
> 2. 同意后以官方 Java 示例为基准翻译生成业务代码「参考实现」;再用纯文字问是否翻 Java 公库(SDK 工具类 + HTTP 客户端),未明确要不贴。每段代码前附下方免责块。
>
> > ⚠️ 以下代码为**跨语言参考实现**,由 AI 参考官方 Java 示例翻译生成,并非微信支付官方维护。
> >
> > - 请**逐行 review** 签名构造、HTTP 调用、字段命名、回调解密等关键逻辑。
> > - 上线前必须在测试环境完整验证,建议先以官方 Java/Go 示例打通主链路作为对照。
> > - 出现接入问题时以官方 Java/Go 示例为准。
@@ -121,4 +118,4 @@ version: '1.0'
在使用过程中遇到问题、有改进建议,或者想和其他开发者交流接入经验,欢迎扫码添加企业微信进群,与官方团队和社区开发者一起讨论:
![微信支付 Skills 交流群二维码](https://raw.githubusercontent.com/wechatpay-apiv3/wechatpay-skills/main/wechatpay-basic-payment/assets/qrcode.jpg)
![微信支付 Skills 交流群二维码](https://raw.githubusercontent.com/wechatpay-apiv3/wechatpay-skills/main/wechatpay-basic-payment/assets/qrcode.jpg)

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