# 分支与 CI

> 通过 Pull Request 把变更从 feature 分支依次推进到 development、qa 和 main，并在任何内容进入安装实例之前，用公开的 JSON Schema 校验每个 Pull Request。

Source: https://docs.sommatic.ai/zh/git-sync/ci/ (updated 2026-11-26)

Git Sync 让你用现有工具搭建部署流水线：分支决定每个安装实例能看到什么，Pull Request 就是评审环节，
CI 检查则在有人到 Sommatic AI 中预览之前拦下有问题的文件。

## 分支流程

```text
feature/<change>  ──PR──▶  development  ──PR──▶  qa  ──PR──▶  main
                             │                    │             │
                        dev installation     review / QA   prod installation
```

- 在 `feature/*` 分支上工作，并向 `development` 发起 Pull Request。
- 每个安装实例只读取**一个**分支，在其环境文件和连接中设定：例如开发环境读取 `development`，生产环境读取 `main`。
- 通过 Pull Request 把变更从 `development` 推进到 `qa`，再从 `qa` 推进到 `main`。
- 只有在指向某安装实例所读分支的 Pull Request 合并后，才对该实例[预览并应用](https://docs.sommatic.ai/zh/git-sync/preview-and-apply.md)新的头部。
- 保护 `development`、`qa` 和 `main`：禁止直接推送，要求评审和检查通过。

> **说明: 应用跟随的是分支，而不是 Pull Request**
>
> 应用只会部署安装实例所读分支的头部。feature 分支上的提交无法被应用，因此 Pull Request 始终是把关环节。

## 每个 Pull Request 要检查什么

| 检查项                                | 原因                                  |
| ---------------------------------- | ----------------------------------- |
| 每个 `sommatic.json` 都通过包 Schema 校验。 | 清单是 Sommatic AI 首先读取的内容。            |
| 清单中列出的每个文件都存在，并通过资源头部 Schema 校验。   | 该 Schema 还会拒绝 `id`、`status` 等运行时字段。 |
| 每个文件头部的 `key` 与清单中的 key 一致。        | 不一致时预览会报错。                          |
| key 在整个仓库内唯一。                      | 一个 key 在每个安装实例中只对应一个资源。             |
| 每个环境文件都通过校验，并为每个 key 声明了 id。       | 未声明的资源会导致应用失败。                      |
| 不残留任何 `@@secret.REPLACE_ME@@`。     | 导出无法为密钥命名时会留下它。                     |

Schema 均已公开：

- [`https://docs.sommatic.ai/schemas/git-sync/package.schema.json`](https://docs.sommatic.ai/schemas/git-sync/package.schema.json)
- [`https://docs.sommatic.ai/schemas/git-sync/environment.schema.json`](https://docs.sommatic.ai/schemas/git-sync/environment.schema.json)
- [`https://docs.sommatic.ai/schemas/git-sync/resource-header.schema.json`](https://docs.sommatic.ai/schemas/git-sync/resource-header.schema.json)

它们使用 JSON Schema draft 2020-12，任何支持该版本的校验器都可以使用。

## 通用校验脚本

下面的脚本用 Node.js 和 Ajv 8 完成上述所有检查。把它保存到你的仓库中，例如 `tools/validate-sommatic.mjs`：

```javascript
// Usage: node tools/validate-sommatic.mjs <repo-root> <schemas-dir>
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative, dirname } from 'node:path';
import Ajv2020 from 'ajv/dist/2020.js';

const root = process.argv[2] || '.';
const schemaDir = process.argv[3] || 'schemas';
const ajv = new Ajv2020({ allErrors: true, strict: false });
const load = (path) => JSON.parse(readFileSync(path, 'utf8'));
const validate = {
  package: ajv.compile(load(join(schemaDir, 'package.schema.json'))),
  environment: ajv.compile(load(join(schemaDir, 'environment.schema.json'))),
  resource: ajv.compile(load(join(schemaDir, 'resource-header.schema.json'))),
};

const errors = [];
const check = (kind, file, data) => {
  if (!validate[kind](data)) {
    validate[kind].errors.forEach((error) => errors.push(`${file}: ${error.instancePath || '/'} ${error.message}`));
  }
};

const walk = (folder) =>
  readdirSync(folder).flatMap((name) => {
    const path = join(folder, name);
    if (['.git', 'node_modules'].includes(name)) return [];
    return statSync(path).isDirectory() ? walk(path) : [path];
  });

const files = walk(root).map((path) => relative(root, path));
const ignored = (path) => path.split('/').some((segment) => ['templates', '.github'].includes(segment));
const manifests = files.filter((path) => path.endsWith('sommatic.json') && !ignored(path));
const environments = files.filter((path) => /^environments\/[^/]+\.json$/.test(path));

const keys = new Set();
for (const manifestPath of manifests) {
  const manifest = load(join(root, manifestPath));
  check('package', manifestPath, manifest);
  const packageDir = dirname(manifestPath);
  for (const entry of [...(manifest.resources?.workflows || []), ...(manifest.resources?.knowledge || [])]) {
    if (keys.has(entry.key)) errors.push(`${manifestPath}: duplicated key ${entry.key}`);
    keys.add(entry.key);
    const filePath = join(packageDir, entry.path);
    if (!files.includes(filePath)) {
      errors.push(`${manifestPath}: ${entry.key} points to a missing file ${filePath}`);
      continue;
    }
    const text = readFileSync(join(root, filePath), 'utf8');
    const resource = JSON.parse(text);
    check('resource', filePath, resource);
    if (resource.sommatic?.key !== entry.key) errors.push(`${filePath}: header key is not ${entry.key}`);
    if (text.includes('@@secret.REPLACE_ME@@')) errors.push(`${filePath}: name the secret that replaced @@secret.REPLACE_ME@@`);
  }
}

for (const environmentPath of environments) {
  const environment = load(join(root, environmentPath));
  check('environment', environmentPath, environment);
  for (const key of keys) {
    if (!environment.resources?.[key]) errors.push(`${environmentPath}: resources has no id for ${key}`);
  }
}

if (errors.length) {
  console.error(errors.join('\n'));
  process.exit(1);
}
console.log(`OK: ${manifests.length} package(s), ${keys.size} resource(s), ${environments.length} environment(s)`);
```

脚本假定包和 `environments/` 位于仓库根目录。如果连接设置了根路径，请把该文件夹作为 `<repo-root>` 传入。

## 在 Pull Request 上运行

下面的 GitHub Actions 工作流会下载 Schema，并在每个指向部署分支的 Pull Request 上运行校验脚本：

```yaml
name: Validate Sommatic packages
on:
  pull_request:
    branches: [development, qa, main]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm install --no-save ajv@8
      - name: Download the Git Sync schemas
        run: |
          mkdir -p .sommatic-schemas
          for name in package environment resource-header; do
            curl -fsSL "https://docs.sommatic.ai/schemas/git-sync/$name.schema.json" -o ".sommatic-schemas/$name.schema.json"
          done
      - run: node tools/validate-sommatic.mjs . .sommatic-schemas
```

## 可选：预览 Pull Request

静态检查无法得知每个资源是否存在于安装实例中，也无法知道变更会对线上工作流产生什么影响，而预览可以，
并且不写入任何数据。持有开发环境令牌的 CI 任务可以调用预览，把 `ref` 设为 Pull Request 的头部提交；
只要有任何一项存在 `unresolved` 令牌或 `exists: false`，就让任务失败：

```bash
curl -s -X POST "$SOMMATIC_API/platform-infrastructure/git-sync/preview" \
  -H "Authorization: Bearer $SOMMATIC_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{ "repository_id": "<repository_id>", "path": "support", "ref": "<pull request head commit>", "include_content": false }'
```

请把令牌保存为 CI 密钥，绝不要放进仓库。

## 下一步

- [编码智能体操作手册](https://docs.sommatic.ai/zh/git-sync/agents.md): 面向智能体编写的同一流程。
- [预览与应用](https://docs.sommatic.ai/zh/git-sync/preview-and-apply.md): 合并之后再部署。
