Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f1bfe3253 | ||
|
|
21a84b354e | ||
|
|
49548d7ed7 | ||
|
|
95ae10db67 | ||
|
|
652864fcd7 | ||
|
|
04e9bd8721 | ||
|
|
241b480a34 | ||
|
|
96418b3ff5 | ||
|
|
22a1b0b293 | ||
|
|
d28ed9d00d | ||
|
|
43fa9008a9 | ||
|
|
de10e135ed | ||
|
|
b47cf440b7 | ||
|
|
a8a8098b9a | ||
|
|
a93cb0e921 | ||
|
|
6e4a7d5c10 | ||
|
|
bc30587a0c | ||
|
|
68b7fe0511 | ||
|
|
4e25b120af | ||
|
|
3eeb574e6b | ||
|
|
35234edb3f | ||
|
|
af60b89dcf | ||
|
|
e07cf9e7f1 | ||
|
|
99f31354ba | ||
|
|
d014ddb661 |
No files matched your search
@@ -7,3 +7,7 @@
|
|||||||
|
|
||||||
# Local build/cache/scratch (DSH workspace tooling)
|
# Local build/cache/scratch (DSH workspace tooling)
|
||||||
/.build/
|
/.build/
|
||||||
|
|
||||||
|
# Local audit/experiment scratch (issue #25)
|
||||||
|
/.issue-work/
|
||||||
|
/.app-verify/
|
||||||
@@ -100,3 +100,6 @@
|
|||||||
[submodule "stdlib/text"]
|
[submodule "stdlib/text"]
|
||||||
path = stdlib/text
|
path = stdlib/text
|
||||||
url = https://git.cflmy.cn/cflmy/marqdo-std-text.git
|
url = https://git.cflmy.cn/cflmy/marqdo-std-text.git
|
||||||
|
[submodule "apps/harness"]
|
||||||
|
path = apps/harness
|
||||||
|
url = https://git.cflmy.cn/cflmy/marqdo-app-harness.git
|
||||||
+28
-7
@@ -32,15 +32,14 @@ steps:
|
|||||||
- python3 scripts/check-repo-conventions.py
|
- python3 scripts/check-repo-conventions.py
|
||||||
|
|
||||||
candidate:
|
candidate:
|
||||||
# Match the Linux/glibc environment already used by View for the RC.4 artifact.
|
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5@sha256:73481a35339157b1a3f3b23076517e96e302fbb5158e6ffcb1582acf22c6af94
|
||||||
image: mcr.microsoft.com/playwright:v1.49.0-noble
|
|
||||||
depends_on: [checkouts]
|
depends_on: [checkouts]
|
||||||
when: *needs_candidate
|
when: *needs_candidate
|
||||||
commands:
|
commands:
|
||||||
- |
|
- |
|
||||||
set -eu
|
set -eu
|
||||||
for attempt in 1 2 3; do
|
for attempt in 1 2 3; do
|
||||||
if apt-get -o Acquire::By-Hash=force -o Acquire::Retries=3 update --error-on=any; then
|
if apt-get -o Acquire::By-Hash=force -o Acquire::http::Timeout=30 update --error-on=any; then
|
||||||
break
|
break
|
||||||
fi
|
fi
|
||||||
if [ "$attempt" -eq 3 ]; then
|
if [ "$attempt" -eq 3 ]; then
|
||||||
@@ -48,8 +47,30 @@ steps:
|
|||||||
fi
|
fi
|
||||||
sleep 15
|
sleep 15
|
||||||
done
|
done
|
||||||
apt-get -o Acquire::Retries=3 install -y --no-install-recommends ca-certificates curl git python3 python3-jsonschema build-essential
|
apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 install -y --no-install-recommends python3-jsonschema util-linux
|
||||||
curl -fsSL --retry 3 https://sh.rustup.rs -o /tmp/marqdo-rustup.sh
|
unset MARQDO_BIN MARQDO_STDLIB_DIR
|
||||||
sh /tmp/marqdo-rustup.sh -y --profile minimal --default-toolchain 1.100.0 --no-modify-path
|
|
||||||
export PATH="$HOME/.cargo/bin:$PATH"
|
|
||||||
bash scripts/integration.sh
|
bash scripts/integration.sh
|
||||||
|
|
||||||
|
app:
|
||||||
|
# Dedicated Node lane: the app gitlink is built and tested against the same
|
||||||
|
# CLI/Bundle candidate the Rust candidate lane just produced. The Rust lane
|
||||||
|
# never installs Node or Electron.
|
||||||
|
image: node:24.22.3-bookworm
|
||||||
|
depends_on: [candidate]
|
||||||
|
when: *needs_candidate
|
||||||
|
commands:
|
||||||
|
- corepack enable
|
||||||
|
- corepack prepare pnpm@11.28.5 --activate
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
test -f .integration-work/app-candidate.json
|
||||||
|
export MARQDO_BIN="$(python3 -c 'import json;print(json.load(open(".integration-work/app-candidate.json"))["cli_path"])')"
|
||||||
|
export MARQDO_STDLIB_DIR="$(python3 -c 'import json;print(json.load(open(".integration-work/app-candidate.json"))["installed_dir"])')/stdlib"
|
||||||
|
test -x "$MARQDO_BIN"
|
||||||
|
test -f "$MARQDO_STDLIB_DIR/stdlib.json"
|
||||||
|
cd apps/harness
|
||||||
|
# The upstream hook installer refuses the submodule common config; CI
|
||||||
|
# is the documented skip path and hooks are not needed in this lane.
|
||||||
|
CI=true pnpm install --frozen-lockfile
|
||||||
|
pnpm run build
|
||||||
|
MARQDO_CI_OUT="$PWD/.ci" bash scripts/ci.sh
|
||||||
@@ -7,12 +7,22 @@ when:
|
|||||||
event: [manual, cron]
|
event: [manual, cron]
|
||||||
branch: [main]
|
branch: [main]
|
||||||
|
|
||||||
|
concurrency: 1
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
reconcile:
|
reconcile:
|
||||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
|
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5@sha256:8184439a201da451271f37596f4e38afeab16e044d7591853779887ef5ec28c1
|
||||||
environment:
|
environment:
|
||||||
MARQDO_GIT_TOKEN:
|
MARQDO_GIT_TOKEN:
|
||||||
from_secret: gitea_token
|
from_secret: gitea_reconcile_token
|
||||||
|
MARQDO_WOODPECKER_DISPATCH_TOKEN:
|
||||||
|
from_secret: woodpecker_reconcile_token
|
||||||
commands:
|
commands:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
domains="$(python3 scripts/check-layout.py --root-domain-paths)"
|
||||||
|
for domain in $domains; do
|
||||||
|
git submodule update --init -- "$domain"
|
||||||
|
done
|
||||||
|
- python3 scripts/check-layout.py --domain-paths
|
||||||
- python3 scripts/reconcile-releases.py --apply --published-after 2026-11-27T02:00:00Z --report-out reconcile-report.json
|
- python3 scripts/reconcile-releases.py --apply --published-after 2026-11-27T02:00:00Z --report-out reconcile-report.json
|
||||||
- cat reconcile-report.json
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# Marqdo 维护指引
|
# Marqdo 维护指引
|
||||||
|
|
||||||
1. 从 [各仓库任务](docs/REPOSITORY-TASKS.md)、[组件目录](components.toml) 与 [架构边界](docs/ARCHITECTURE.md) 确定**唯一**责任仓库:功能缺陷在功能仓库,领域合同/组合在领域聚合仓库,gitlink、跨领域集成、发行组合与治理在主仓库。主仓库和聚合仓库不实现子组件业务。
|
1. 从 [各仓库任务](docs/REPOSITORY-TASKS.md)、[组件目录](components.toml) 与 [架构边界](docs/ARCHITECTURE.md) 确定**唯一**责任仓库:功能缺陷在功能仓库,领域合同/组合在领域聚合仓库,gitlink、跨领域集成、发行组合与治理在主仓库。主仓库和聚合仓库不实现子组件业务。
|
||||||
2. 治理树最多两级:根 → 领域聚合(`kind = "domain"`)→ 功能组件。每个组件只有一个父级,全局 ID 与权威远端唯一,领域聚合仓库只做治理、合同、示例和组合验收。已发布的 `planned` 仓库可以挂载真实 gitlink。激活时登记实际 `entry`,只有通过验收的 active 组件计入完成率。
|
2. 治理树最多两级:根 → 领域聚合(`kind = "domain"`)→ 功能组件。每个组件只有一个父级,全局 ID 与权威远端唯一,领域聚合仓库只做治理、合同、示例和组合验收。根层另有 `kind = "app"` 产品应用(`app-<name>` → `apps/<name>`,`release = "optional"`):它是根 leaf,只消费 active 叶组件,不能被其它组件依赖,也不进入 base 发行。已发布的 `planned` 仓库可以挂载真实 gitlink。激活时登记实际 `entry`,只有通过验收的 active 组件计入完成率。
|
||||||
3. 找到或建立责任仓库的工单,按 `.gitea/ISSUE_TEMPLATE/change.md` 记录目标、当前提交、最小复现、公共契约、影响消费者和验收命令。跨仓库阻塞在上游开关联工单,并在消费者记录回归条件。不要按错误最终显示的仓库定责,找第一个违反公开合同的所有者。
|
3. 找到或建立责任仓库的工单,按 `.gitea/ISSUE_TEMPLATE/change.md` 记录目标、当前提交、最小复现、公共契约、影响消费者和验收命令。跨仓库阻塞在上游开关联工单,并在消费者记录回归条件。不要按错误最终显示的仓库定责,找第一个违反公开合同的所有者。
|
||||||
4. 在责任仓库独立修改、构建和测试。需要调整公共语义时,在 CLI 提交 ADR;调整 Web 作者面语义时,只在 `marqdo-ext-web` 的 [WEB-DESIGN 合同](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 走 ADR,并与实际消费者(Design/Preview)同候选验证;不得并列维护第二份现行规范或旧协议 fallback。
|
4. 在责任仓库独立修改、构建和测试。需要调整公共语义时,在 CLI 提交 ADR;调整 Web 作者面语义时,只在 `marqdo-ext-web` 的 [WEB-DESIGN 合同](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 走 ADR,并与实际消费者(Design/Preview)同候选验证;不得并列维护第二份现行规范或旧协议 fallback。
|
||||||
5. 逐层晋升:功能提交 C2 通过组件 CI → 领域 PR 更新 gitlink 至 C2 并通过领域 CI(B2)→ 主仓库 PR 更新领域 gitlink 至 B2 并通过根递归校验与受影响组合验收(A2)。先推送子仓库提交,再在主仓库提交精确 gitlink;区分组件 CI、公共契约 CI 和生态 CI 证据。以 [开发流程](docs/DEVELOPMENT.md) 为准。
|
5. 逐层晋升:功能提交 C2 通过组件 CI → 领域 PR 更新 gitlink 至 C2 并通过领域 CI(B2)→ 主仓库 PR 更新领域 gitlink 至 B2 并通过根递归校验与受影响组合验收(A2)。先推送子仓库提交,再在主仓库提交精确 gitlink;区分组件 CI、公共契约 CI 和生态 CI 证据。以 [开发流程](docs/DEVELOPMENT.md) 为准。
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ marqdo run hello.mq.md
|
|||||||
|
|
||||||
| 仓库 | 职责 |
|
| 仓库 | 职责 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|
| [marqdo-app-harness](https://git.cflmy.cn/cflmy/marqdo-app-harness) | 官方单用户应用:生态安装、文稿程序化执行、私人知识库与 `/mdh` 工作台(DSH 下游) |
|
||||||
| [marqdo-site](https://git.cflmy.cn/cflmy/marqdo-site) | 官网、入门文档、静态站点构建与托管 |
|
| [marqdo-site](https://git.cflmy.cn/cflmy/marqdo-site) | 官网、入门文档、静态站点构建与托管 |
|
||||||
| [marqdo-vscode](https://git.cflmy.cn/cflmy/marqdo-vscode) | VS Code 文件关联、编辑体验、CLI 集成与 VSIX 发布 |
|
| [marqdo-vscode](https://git.cflmy.cn/cflmy/marqdo-vscode) | VS Code 文件关联、编辑体验、CLI 集成与 VSIX 发布 |
|
||||||
|
|
||||||
@@ -131,5 +132,3 @@ python3 -m unittest discover -s tests/integration
|
|||||||
[各仓库任务](docs/REPOSITORY-TASKS.md) · [组件目录](components.toml) · [架构边界](docs/ARCHITECTURE.md) · [开发流程](docs/DEVELOPMENT.md) · [迁移台账](docs/MIGRATION.md) · [架构决策记录](docs/adr/README.md) · [AGENTS](AGENTS.md)
|
[各仓库任务](docs/REPOSITORY-TASKS.md) · [组件目录](components.toml) · [架构边界](docs/ARCHITECTURE.md) · [开发流程](docs/DEVELOPMENT.md) · [迁移台账](docs/MIGRATION.md) · [架构决策记录](docs/adr/README.md) · [AGENTS](AGENTS.md)
|
||||||
|
|
||||||
旧版实现与文档可在历史标签查阅。 [v2.9.1 历史树](https://git.cflmy.cn/cflmy/marqdo/src/tag/v2.9.1)
|
旧版实现与文档可在历史标签查阅。 [v2.9.1 历史树](https://git.cflmy.cn/cflmy/marqdo/src/tag/v2.9.1)
|
||||||
|
|
||||||
根仓 CI 的触发条件见 [开发流程](docs/DEVELOPMENT.md#递归校验与组合检查)。
|
|
||||||
Submodule
+1
Submodule apps/harness added at ee482a23c2.
+3
-4
@@ -16,9 +16,8 @@ Rules:
|
|||||||
- Images are public for anonymous pull; CI never needs registry push credentials.
|
- Images are public for anonymous pull; CI never needs registry push credentials.
|
||||||
- Component lanes contain only their own `scripts/*` entry command. No per-repo
|
- Component lanes contain only their own `scripts/*` entry command. No per-repo
|
||||||
image variance, apt installs, Rust toolchain downloads or CLI rebuilds.
|
image variance, apt installs, Rust toolchain downloads or CLI rebuilds.
|
||||||
- Core CLI keeps its specialized Rust/Windows-cross gates; the root ecosystem
|
- Core CLI keeps its specialized Rust/Windows-cross gates. The root ecosystem
|
||||||
candidate keeps its Playwright/rustup image because it must build consumers and
|
candidate uses the shared Rust toolchain to build the fixed CLI/Worker/Bundle
|
||||||
run Docker archive checks. These two exceptions are documented in the
|
combination. View and Web keep browser coverage in their own workflows.
|
||||||
repository conventions, not copied per component.
|
|
||||||
- The images are CI infrastructure, not product releases; their provenance is
|
- The images are CI infrastructure, not product releases; their provenance is
|
||||||
recorded here and in `docs/evidence/`.
|
recorded here and in `docs/evidence/`.
|
||||||
+1
-1
Submodule cli updated: 13affa76dd...63776735e9.
@@ -392,3 +392,15 @@ scope = "IANA 时区、DST 和高级日历"
|
|||||||
requires = ["cli", "std-system"]
|
requires = ["cli", "std-system"]
|
||||||
checks_with = []
|
checks_with = []
|
||||||
release = "optional"
|
release = "optional"
|
||||||
|
|
||||||
|
[[component]]
|
||||||
|
id = "app-harness"
|
||||||
|
path = "apps/harness"
|
||||||
|
kind = "app"
|
||||||
|
state = "active"
|
||||||
|
owner = "cflmy"
|
||||||
|
scope = "官方单用户智能体应用、Marqdo 生态安装与更新、文稿执行、私人知识库"
|
||||||
|
requires = ["cli"]
|
||||||
|
checks_with = ["knowledge", "view"]
|
||||||
|
release = "optional"
|
||||||
|
entry = "scripts/ci.sh"
|
||||||
@@ -18,12 +18,13 @@
|
|||||||
|
|
||||||
- **领域(`kind = "domain"`)**:工程治理角色,不是语言层也不是运行协议。领域仓库只登记直属子组件,可拥有 `components.toml`、`.gitmodules`、领域公共规范、跨组件集成测试、综合示例、发布装配脚本、ADR 与维护指南;禁止在其中建立 renderer、解析器、数据库驱动等生产实现,也禁止把子仓库源码复制进普通目录。领域 `requires = []`,`release` 为 `none`(普通领域)或 `base`(Stdlib Bundle 聚合)。
|
- **领域(`kind = "domain"`)**:工程治理角色,不是语言层也不是运行协议。领域仓库只登记直属子组件,可拥有 `components.toml`、`.gitmodules`、领域公共规范、跨组件集成测试、综合示例、发布装配脚本、ADR 与维护指南;禁止在其中建立 renderer、解析器、数据库驱动等生产实现,也禁止把子仓库源码复制进普通目录。领域 `requires = []`,`release` 为 `none`(普通领域)或 `base`(Stdlib Bundle 聚合)。
|
||||||
- **功能组件**:`kind` 仍为 `core/stdlib/extension/tool/test`,在责任仓库独立实现、测试和发版;`release` 与 `kind` 的对应关系不变(base/optional/none)。
|
- **功能组件**:`kind` 仍为 `core/stdlib/extension/tool/test`,在责任仓库独立实现、测试和发版;`release` 与 `kind` 的对应关系不变(base/optional/none)。
|
||||||
|
- **应用(`kind = "app"`)**:根层产品消费者,ID 为 `app-<name>`、路径为 `apps/<name>`、`release = "optional"`。应用是根 leaf,只依赖 active 的 `core/stdlib/extension/tool` 叶组件,不得被其它组件依赖,也不得登记在领域内。当前唯一应用为 `app-harness`(`apps/harness`)。
|
||||||
- **唯一归属**:一个功能只有一个权威实现,一个组件只有一个治理归属,一个公共边界只有一套现行合同。已有仓库直接复用,不能因为命名不符创建重复实现。
|
- **唯一归属**:一个功能只有一个权威实现,一个组件只有一个治理归属,一个公共边界只有一套现行合同。已有仓库直接复用,不能因为命名不符创建重复实现。
|
||||||
- **`planned` 纪律**:已有仓库可以通过 gitlink 固定已发布的开发提交。尚无提交的仓库登记在 [迁移台账](MIGRATION.md)。组件通过联合验收后才晋升为 `active` 并登记实际 `entry`。将直属组件迁入领域时,在同一根候选转移清单和 gitlink,保证一个组件只有一个父级。
|
- **`planned` 纪律**:已有仓库可以通过 gitlink 固定已发布的开发提交。尚无提交的仓库登记在 [迁移台账](MIGRATION.md)。组件通过联合验收后才晋升为 `active` 并登记实际 `entry`。将直属组件迁入领域时,在同一根候选转移清单和 gitlink,保证一个组件只有一个父级。
|
||||||
- **聚合准入**:功能拆分须至少有一种独立价值(独立维护责任、显著不同依赖/安全/平台边界、独立版本与制品、可重复独立验收)。若两个仓库几乎每个 PR 都必须一起改动且接口未稳定,应先收敛合同或合并,不能无限拆分。
|
- **聚合准入**:功能拆分须至少有一种独立价值(独立维护责任、显著不同依赖/安全/平台边界、独立版本与制品、可重复独立验收)。若两个仓库几乎每个 PR 都必须一起改动且接口未稳定,应先收敛合同或合并,不能无限拆分。
|
||||||
- **工具目录**(`tools/`)暂不聚合,现有四个 Tool 保持原路径。
|
- **工具目录**(`tools/`)暂不聚合,现有四个 Tool 保持原路径。
|
||||||
|
|
||||||
**当前状态**(以 [components.toml](../components.toml) 与 [迁移台账](MIGRATION.md) 为准):根仓库有六个核心/工具 active 组件(`cli`、`conformance`、`view`、`knowledge`、`prove`、`lint`)和六个已交付源码的 active 标准库组件(`std-collections/data/fs/io/system/text`)。`std-core/encoding/net` 与十八个独立扩展仍是根层 planned 子模块。`extensions/web` 是 **active 领域**:Design/Preview 在其领域 catalog 激活并登记真实入口,`web-components` 仍 planned。`marqdo-stdlib` 聚合仍在计划中。
|
**当前状态**(以 [components.toml](../components.toml) 与 [迁移台账](MIGRATION.md) 为准):根仓库有六个核心/工具 active 组件(`cli`、`conformance`、`view`、`knowledge`、`prove`、`lint`)和六个已交付源码的 active 标准库组件(`std-collections/data/fs/io/system/text`)。`std-core/encoding/net` 与十八个独立扩展仍是根层 planned 子模块。`extensions/web` 是 **active 领域**:Design/Preview 在其领域 catalog 激活并登记真实入口,`web-components` 仍 planned。`marqdo-stdlib` 聚合仍在计划中。根层 `app-harness` 是 active 应用:它组合 CLI、Bundle、Tool 与私人知识,不进入 CLI 基础发行,也不被任何组件依赖。
|
||||||
|
|
||||||
## 语言与产品层(不因仓库变多而改变)
|
## 语言与产品层(不因仓库变多而改变)
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
|
|||||||
- 校验器读取 Git tree 中固定提交的 catalog,不以工作区改动替代候选;`--checkouts` 需要子模块已初始化,缺失、错误 HEAD、脏工作区、错误入口都明确 FAIL/UNVERIFIED,不静默跳过。CI 先验证并检出直属子模块,再用 `--domain-paths` 校验领域的子模块远端,最后逐个领域检出直属子库。
|
- 校验器读取 Git tree 中固定提交的 catalog,不以工作区改动替代候选;`--checkouts` 需要子模块已初始化,缺失、错误 HEAD、脏工作区、错误入口都明确 FAIL/UNVERIFIED,不静默跳过。CI 先验证并检出直属子模块,再用 `--domain-paths` 校验领域的子模块远端,最后逐个领域检出直属子库。
|
||||||
- 没有 active 领域时,新校验规则同样接受合法的直属功能组件,这不是历史协议兼容。
|
- 没有 active 领域时,新校验规则同样接受合法的直属功能组件,这不是历史协议兼容。
|
||||||
- 未知的 active 入口、未声明的 gitlink、目录与 catalog 不一致都必须让候选失败。`planned` 不进入验收计数。
|
- 未知的 active 入口、未声明的 gitlink、目录与 catalog 不一致都必须让候选失败。`planned` 不进入验收计数。
|
||||||
|
- `python3 scripts/check-layout.py --active-entries` 从已验证的根与领域 checkout 输出验收计划。根集成按依赖顺序使用同一次安装的 CLI 和 Bundle 执行计划,领域验收晚于其 active 子组件。通用入口接收 `MARQDO_BIN`、`MARQDO_STDLIB_DIR` 和 `MARQDO_CI_OUT`,已有公共契约、真实 Tool 冷安装等组合门禁继续使用各自的现有入口。
|
||||||
|
- 根 Web 组合检查对该次构建的 Preview Tool 执行冷安装、`check`、`preview` 和 `handoff`。生产浏览器验收由 Web 聚合仓已有的 `scripts/domain-acceptance.sh` 负责。
|
||||||
- 根 `eco` 在 PR、`main` 推送和显式手动运行时执行。PR 始终保留 `layout` 状态。仅改动根 `README.md` 或 `docs/evidence/` 下的 Markdown 记录时,自动运行只执行轻量结构校验和脚本测试。混合改动、其他路径、缺失变更列表和手动运行都执行递归检出及完整生态验收。
|
- 根 `eco` 在 PR、`main` 推送和显式手动运行时执行。PR 始终保留 `layout` 状态。仅改动根 `README.md` 或 `docs/evidence/` 下的 Markdown 记录时,自动运行只执行轻量结构校验和脚本测试。混合改动、其他路径、缺失变更列表和手动运行都执行递归检出及完整生态验收。
|
||||||
|
|
||||||
## 三层验收
|
## 三层验收
|
||||||
@@ -80,6 +82,12 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 +
|
|||||||
|
|
||||||
经过授权的 webhook 入口由根 `scripts/webhook-adapter.py` 实现:先以仓库 webhook secret 校验 `X-Gitea-Signature`(HMAC-SHA256)原始 body,再只接受 `push`(非删除)与 `pull_request`(opened/synchronized/reopened)事件;仓库必须来自 accepted 根图的远端允许列表,base 使用 accepted 图当前固定 SHA(payload base 只作 hint),CI 聚合要求至少一个状态且全部 success、URL 为允许 CI 主机上的 https。校验通过后交给同一 `candidate-notify.py` 做可达性/去重/重放/基线重验与影响分析,输出计划(不合并、不推送、不建 PR)。通知丢失的恢复由同一脚本 `--reconcile` 承担:扫描允许列表仓库的开放 PR 与 head statuses,对未入账的成功候选执行同一验证(幂等状态文件,重复运行只报 duplicate);API transient 错误有限退避重试,401/403 立即失败,不把触发成功当作下游已处理。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。
|
经过授权的 webhook 入口由根 `scripts/webhook-adapter.py` 实现:先以仓库 webhook secret 校验 `X-Gitea-Signature`(HMAC-SHA256)原始 body,再只接受 `push`(非删除)与 `pull_request`(opened/synchronized/reopened)事件;仓库必须来自 accepted 根图的远端允许列表,base 使用 accepted 图当前固定 SHA(payload base 只作 hint),CI 聚合要求至少一个状态且全部 success、URL 为允许 CI 主机上的 https。校验通过后交给同一 `candidate-notify.py` 做可达性/去重/重放/基线重验与影响分析,输出计划(不合并、不推送、不建 PR)。通知丢失的恢复由同一脚本 `--reconcile` 承担:扫描允许列表仓库的开放 PR 与 head statuses,对未入账的成功候选执行同一验证(幂等状态文件,重复运行只报 duplicate);API transient 错误有限退避重试,401/403 立即失败,不把触发成功当作下游已处理。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。
|
||||||
|
|
||||||
|
正式发布对账使用 `python3 scripts/reconcile-releases.py --plan --published-after <ISO-8601 时间>`。从固定根及领域 tree 解析受管仓库,核对 Gitea tag、`release-evidence.json`、同 SHA Woodpecker 组件 CI 和资产字节摘要。根 `reconcile` 工作流从当前受保护的 `main` 串行运行,只检出领域聚合仓,使用 `gitea_reconcile_token` 以专用非管理员账号写追踪工单。`historical-baseline` 表示已登记历史输入,`blocked` 表示发布验证未通过,`tracked` 表示已记录经验证的发布。扫描完整且追踪写入成功时,已报告的发布阻塞保留为 `blocked`,工作流仍成功结束。消费者验收和父级接受均需各自的 CI 与 PR 证据。
|
||||||
|
|
||||||
|
消费者通过已接受 Git 树里的 `.woodpecker/upstream.yml` 接入派发。根只在该消费者的受保护默认分支精确匹配 gitlink 时触发,发送本仓任务编号和幂等键。Woodpecker 原生触发要求项目级 push 权限,该角色同时可以管理该项目的 CI secret。仅把这一角色授予专用非管理员 `marqdo-reconcile` 在已接入的消费者仓,并通过 Woodpecker 登录为该账号生成 token。根仓 `woodpecker_reconcile_token` 限于受保护 `main` 的 manual/cron 配置,部署时核对账号和具体仓权限。触发凭据只在根协调步骤使用,消费者测试无需该凭据。根报告通过已存在的同任务 Woodpecker 流水线识别重复或失联的触发结果。派发身份未配置或权限未就绪时,报告记录 `dispatch_status=unavailable` 和 `dispatch_error`,扫描与发布追踪仍完成且不被该基础设施限制判失败;权限阻塞单独登记,不能据此伪造已派发。
|
||||||
|
|
||||||
|
对已验证的发布,`--plan` 计算直接 active 消费者的输入摘要。受保护 `--apply` 按发布和消费者登记一条任务,基线变化时在原任务中记录新输入。输入附精确资产、依赖、消费者基线和根追踪编号。下游独立 CI 及批准后的晋升基于各自的真实结果。
|
||||||
|
|
||||||
## 发行与回滚
|
## 发行与回滚
|
||||||
|
|
||||||
- 组件可独立 SemVer 发布;领域可发布经过验证的组合制品;根生态 release 固定整个 gitlink 树。独立版本不代表维护多套现行协议。
|
- 组件可独立 SemVer 发布;领域可发布经过验证的组合制品;根生态 release 固定整个 gitlink 树。独立版本不代表维护多套现行协议。
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
- `planned` 仓库允许挂载真实开发提交,但**不计完成率**、不登记 `entry`、不要求发布制品;只能有 README/必要源码/最小测试,不得批量复制模板、CI 徽章、占位实现或假入口。
|
- `planned` 仓库允许挂载真实开发提交,但**不计完成率**、不登记 `entry`、不要求发布制品;只能有 README/必要源码/最小测试,不得批量复制模板、CI 徽章、占位实现或假入口。
|
||||||
- 从 `planned` 激活必须同时具备:真实实现、README(职责/构建/依赖/平台)、`AGENTS.md`(本仓边界与路由)、可执行 CI 入口、真实正反例、交付/发布方式、候选证据;并在父级 catalog 登记 `entry`。
|
- 从 `planned` 激活必须同时具备:真实实现、README(职责/构建/依赖/平台)、`AGENTS.md`(本仓边界与路由)、可执行 CI 入口、真实正反例、交付/发布方式、候选证据;并在父级 catalog 登记 `entry`。
|
||||||
- 只有规范/fixture 的仓库允许源码归档交付,不强制二进制;但必须有确定性归档与证据。
|
- 只有规范/fixture 的仓库允许源码归档交付,不强制二进制;但必须有确定性归档与证据。
|
||||||
|
- 应用(`kind = "app"`)只允许在根层登记,ID 为 `app-<name>`、路径为 `apps/<name>`、`release = "optional"`。应用依赖 active 叶组件,不能被其它组件依赖;激活时必须登记真实 `entry` 与独立 CI。
|
||||||
- `active` 仓库不得回退为"文档占位";若失去责任,必须记录替代仓库与迁移/归档计划。
|
- `active` 仓库不得回退为"文档占位";若失去责任,必须记录替代仓库与迁移/归档计划。
|
||||||
|
|
||||||
## 3. 角色与禁止事项
|
## 3. 角色与禁止事项
|
||||||
@@ -27,7 +28,9 @@
|
|||||||
| 所有者 | 应做 | 禁止 |
|
| 所有者 | 应做 | 禁止 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 功能仓库(core/stdlib/extension/tool/test) | 自身实现、测试、制品、发布、消费上游候选、修复本仓缺陷 | 实现其它仓库功能;依赖父仓或兄弟仓 checkout;复制其它仓实现/parser/合同;偷偷替换上游逻辑 |
|
| 功能仓库(core/stdlib/extension/tool/test) | 自身实现、测试、制品、发布、消费上游候选、修复本仓缺陷 | 实现其它仓库功能;依赖父仓或兄弟仓 checkout;复制其它仓实现/parser/合同;偷偷替换上游逻辑 |
|
||||||
|
| 应用仓库(app) | 下游产品装配、生态安装/更新、文稿执行与知识复用;独立 CI/发行 | 发布公共语言/运行时合同;复制生态生产源码;被基础组件依赖 |
|
||||||
| 领域聚合仓(`kind=domain`) | 领域合同、组合、领域候选 gitlink、领域验收、通知父仓 | 重复叶子实现;第二套调用协议;登记后代到根 catalog |
|
| 领域聚合仓(`kind=domain`) | 领域合同、组合、领域候选 gitlink、领域验收、通知父仓 | 重复叶子实现;第二套调用协议;登记后代到根 catalog |
|
||||||
|
| 应用仓(`kind=app`) | 产品装配、生态安装、文稿执行、私人知识与 UI;消费公开合同 | 复制 CLI/stdlib/ext/tool 源码;成为其它组件依赖;进入 base 发行;自建第二套解析器/锁 |
|
||||||
| 根仓库 | 展开依赖、传播协调、全局候选、递归集成、正式发行、滞后报告 | 实现子组件业务;批量直接改子仓代码;成为每个仓的构建前置 |
|
| 根仓库 | 展开依赖、传播协调、全局候选、递归集成、正式发行、滞后报告 | 实现子组件业务;批量直接改子仓代码;成为每个仓的构建前置 |
|
||||||
| CLI | 语言/通用能力、公开协议、CLI/Worker/基础产品打包 | 生态调度代码;反向依赖 stdlib 源码;物理拆仓 |
|
| CLI | 语言/通用能力、公开协议、CLI/Worker/基础产品打包 | 生态调度代码;反向依赖 stdlib 源码;物理拆仓 |
|
||||||
| Conformance | 独立公共契约运行验收 | 取代组件自测;伪造未支持平台的 PASS |
|
| Conformance | 独立公共契约运行验收 | 取代组件自测;伪造未支持平台的 PASS |
|
||||||
|
|||||||
@@ -32,6 +32,7 @@
|
|||||||
| `marqdo-lint` | 扩展静态规则和诊断定位,为可修复规则提供显式修复。 |
|
| `marqdo-lint` | 扩展静态规则和诊断定位,为可修复规则提供显式修复。 |
|
||||||
| `marqdo-site` | **大改**。用现行 CLI 和 View 重建官网与入门内容,验证新站和旧链接后切换托管。 |
|
| `marqdo-site` | **大改**。用现行 CLI 和 View 重建官网与入门内容,验证新站和旧链接后切换托管。 |
|
||||||
| `marqdo-vscode` | **大改**。按现行 CLI 重做诊断和运行适配,先完成高亮、静态诊断、显式运行和可安装的 VSIX。 |
|
| `marqdo-vscode` | **大改**。按现行 CLI 重做诊断和运行适配,先完成高亮、静态诊断、显式运行和可安装的 VSIX。 |
|
||||||
|
| `marqdo-app-harness` | **大改**。官方单用户应用(DSH 下游):产品 profile、生态安装/回退、文稿 PTC、私人知识、`/mdh` 工作台、独立 CI 与冷安装。父仓 `apps/harness`。 |
|
||||||
|
|
||||||
## 标准库
|
## 标准库
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# ADR 0002:应用层(app)准入与 Marqdo Harness
|
||||||
|
|
||||||
|
- 状态:已采纳(2026-11-28),实施工单为 `marqdo#25`(Application / P0)。
|
||||||
|
- 现行权威:`docs/ARCHITECTURE.md`、`docs/REPOSITORY-CONVENTIONS.md`、`components.toml`、`.gitmodules` 与 Git tree gitlink。本 ADR 记录决策,不构成第二套规范。
|
||||||
|
- 影响仓库:`marqdo`(根治理)、`marqdo-app-harness`(新应用仓库)。CLI、Std、Ext、Tool 的现行合同不因本 ADR 改变。
|
||||||
|
|
||||||
|
## 背景
|
||||||
|
|
||||||
|
生态此前只有 `core/stdlib/extension/tool/test/domain` 六种组件角色。Marqdo Harness
|
||||||
|
(MDH)是一个**产品消费者**:它组合已发布的 CLI、单一 Bundle、Tool 与 Ext,向最终
|
||||||
|
用户提供安装入口、文稿执行入口、私人知识库和成果复用。它既不发布语言/运行时合同,
|
||||||
|
也不被任何基础组件依赖。直接复用 `tool` 或 `extension` 会把产品应用错误地放进
|
||||||
|
`requires` 图,导致 CLI 基础发行被应用反向阻塞。
|
||||||
|
|
||||||
|
## 决策
|
||||||
|
|
||||||
|
### 1. 新增根层 `kind = "app"`
|
||||||
|
|
||||||
|
- 只允许出现在根治理层(`depth == 0`),不允许登记在领域聚合仓库内。
|
||||||
|
- ID 固定为 `app-<name>`,路径固定为 `apps/<name>`,权威远端固定为
|
||||||
|
`https://git.cflmy.cn/cflmy/marqdo-<id>.git`(即 `marqdo-app-harness.git`)。
|
||||||
|
- `release = "optional"`:应用不属于 CLI 基础发行,不进入 `base` 装配。
|
||||||
|
- 应用是根 leaf:仓库自身不得再登记 `components.toml`、`.gitmodules` 或任何
|
||||||
|
gitlink。父仓只固定其提交,不读取其内部子模块。
|
||||||
|
- `requires` 只能指向 active 的 `core/stdlib/extension/tool` 叶组件;不得指向
|
||||||
|
`domain`、`test` 或另一个 `app`。任何其它 kind 都不得以 app 为依赖目标。
|
||||||
|
- `checks_with` 仍只表示协同验收,不是安装依赖。
|
||||||
|
- 首期只登记一个应用,不建立 `marqdo-app` 聚合仓库;未来第二个独立应用出现时
|
||||||
|
再以新 ADR 评估是否聚合。
|
||||||
|
|
||||||
|
### 2. `app-harness` 的上游与产品身份
|
||||||
|
|
||||||
|
- 应用仓库为 `cflmy/marqdo-app-harness`,路径 `apps/harness`。
|
||||||
|
- 保留 DSH 的 Git 历史、MIT `LICENSE` 与第三方声明;`origin` 为 Gitea 权威远端,
|
||||||
|
`upstream` 为 `https://git.cflmy.cn/cflmy/deepseek-harness.git`(DSH 权威镜像)。
|
||||||
|
GitHub 官方仓库只作为审计与回馈来源,不进入父仓 `.gitmodules`。
|
||||||
|
- 发布名、包名(`@marqdo/*`)、命令(`mdh`)、应用标识和发行地址与 DeepSeek 官方
|
||||||
|
DSH 完全分离;不得复用官方上传工作流或凭证。
|
||||||
|
- 首版支持平台以真实证据为准:Linux x86_64 / glibc ≥ 2.39;Node 24.22.3、
|
||||||
|
pnpm 11.28.5(由选定 DSH 提交与锁文件决定)。Web 默认 loopback。
|
||||||
|
|
||||||
|
### 3. 产品装配
|
||||||
|
|
||||||
|
- 唯一正式产品入口为 `mdh` 启动器,唯一产品 profile 为 `mdh`,组合为
|
||||||
|
`dsh-base` + `dsh-web-app` + 下游 `@marqdo/mdh-bundle`。
|
||||||
|
- 下游产品包集中在 fork 的 `packages/marqdo/*`,不散改上游包;必须修改的上游文件
|
||||||
|
逐项记录在 `docs/mdh/upstream-delta.md`。
|
||||||
|
- DSH 的 Node PTC 模型入口在产品 profile 中关闭;面向模型的文稿执行只经由
|
||||||
|
`marqdo_program` 一条组合入口。上游 PTC 源码保留用于同步与基线,不作为第二个
|
||||||
|
用户可选执行模式。
|
||||||
|
- 应用运行数据使用独立 `MDH_HOME`;DSH 会话放在 `MDH_HOME/harness`,不覆盖用户
|
||||||
|
已有的 DSH 数据。
|
||||||
|
|
||||||
|
### 4. 晋升门槛
|
||||||
|
|
||||||
|
1. M0:登记 planned 条目并固定真实初始提交;`app-harness` 仍不计完成率,不登记
|
||||||
|
`entry`。
|
||||||
|
2. MDH-01..09 完成应用自身实现、独立 CI、冷安装与真实候选证据后,应用仓库登记
|
||||||
|
`entry = "scripts/ci.sh"` 并推送。
|
||||||
|
3. MDH-10:根 PR 只更新 gitlink、catalog、集成调度与证据;应用加入 `requires` 的
|
||||||
|
组件必须已 active。根 Node lane 使用与 CLI/Bundle/Tool 相同的候选身份运行真实
|
||||||
|
应用验收。
|
||||||
|
4. 应用激活前不得成为 CLI 独立发行的前置;应用失败不得阻断合法的 CLI 基础发行,
|
||||||
|
但包含 app 的根生态候选必须如实记录失败,禁止静默跳过。
|
||||||
|
|
||||||
|
## 后果
|
||||||
|
|
||||||
|
- `scripts/check-layout.py` 增加 app kind、路径/远端/依赖方向校验与正反例;
|
||||||
|
`kinds` 与 `release` 的既有约束保持不变。
|
||||||
|
- `scripts/integration.sh` 增加显式 app 分派,传入真实 CLI/Bundle/Tool 候选身份;
|
||||||
|
未知 active 项继续失败。
|
||||||
|
- `docs/ARCHITECTURE.md`、`docs/REPOSITORY-TASKS.md`、`docs/REPOSITORY-CONVENTIONS.md`
|
||||||
|
登记应用层职责与边界;根 README 给出应用入口。
|
||||||
|
- 应用仓库必须遵守仓库规范最低集(README、AGENTS、`scripts/ci.sh`、正反例、
|
||||||
|
独立 CI、证据),并在 `AGENTS.md` 保留 `marqdo:repo-conventions v1` 标记。
|
||||||
|
|
||||||
|
## 非目标
|
||||||
|
|
||||||
|
公共知识共享插件、知识市场、多租户/云托管、桌面签名、独立 TUI、完整 host-binding
|
||||||
|
PTC 与自动发布用户成果均不在本 ADR 与首版范围内;它们需要独立工单与 ADR。
|
||||||
@@ -5,3 +5,4 @@
|
|||||||
| ADR | 状态 | 主题 |
|
| ADR | 状态 | 主题 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| [0001](0001-hierarchical-ecosystem-and-web-domain.md) | 已采纳(实施记录) | 分层生态治理(根→领域→功能)与 Web 原型设计领域合同 |
|
| [0001](0001-hierarchical-ecosystem-and-web-domain.md) | 已采纳(实施记录) | 分层生态治理(根→领域→功能)与 Web 原型设计领域合同 |
|
||||||
|
| [0002](0002-application-layer-and-harness-admission.md) | 已采纳(实施中) | 根层 `app` 角色、`marqdo-app-harness` 准入、DSH 上游与产品装配边界 |
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Marqdo Harness 根消费者验收证据(2026-11-28)
|
||||||
|
|
||||||
|
本文件记录主仓库对 `marqdo-app-harness` 的接入证据。应用自身状态与未验证范围以
|
||||||
|
`apps/harness/docs/mdh/STATUS.md` 为准;本文件不重复、也不改写那些结论。
|
||||||
|
|
||||||
|
## 身份
|
||||||
|
|
||||||
|
| 对象 | 身份 |
|
||||||
|
| --- | --- |
|
||||||
|
| 主仓库候选 | 本提交(`git rev-parse HEAD`) |
|
||||||
|
| 应用 gitlink | `apps/harness` → `ee482a23c2e0ae3ca4c2b56281ea82e9fb58619d` |
|
||||||
|
| 应用 origin | `https://git.cflmy.cn/cflmy/marqdo-app-harness.git` |
|
||||||
|
| DSH 上游 | `4b399c39a6d1479cd84ca591b4d7c88e24d38a96`(`dsh-v0.2.3-alpha.2`) |
|
||||||
|
| CLI gitlink | `63776735e924ade279cdf59d5c733dc24bfdabbb`(`v3.0.0-rc.6`) |
|
||||||
|
| CLI 资产 | sha256 `8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3` |
|
||||||
|
| Std Bundle | tree digest `sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7` |
|
||||||
|
|
||||||
|
## 根治理校验
|
||||||
|
|
||||||
|
| 命令 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| `python3 scripts/check-layout.py` | 通过;`app-harness apps/harness d28c5e4051... active` |
|
||||||
|
| `python3 -m unittest tests.integration.test_layout` | 60 tests PASS;含 app 路径/远端/前缀/release/嵌套/依赖方向负例 |
|
||||||
|
| `python3 scripts/check-repo-conventions.py` | PASS(38 components);应用 README/AGENTS/entry 真实存在 |
|
||||||
|
|
||||||
|
## 组合调度
|
||||||
|
|
||||||
|
- `scripts/integration.sh` 的 active entry 分派对 `app:app-harness:scripts/ci.sh` 使用独立 `app` gate。
|
||||||
|
- Rust candidate lane 仍只构建一个 CLI/Worker/Bundle 制品,并在安装后写出稳定的
|
||||||
|
`.integration-work/app-candidate.json`:归档 SHA-256、CLI source SHA、Bundle digest、
|
||||||
|
安装目录、CLI 绝对路径与应用 gitlink。
|
||||||
|
- `.woodpecker/eco.yml` 增加专用 Node lane(`node:24.22.3-bookworm`),消费同一
|
||||||
|
candidate manifest,`pnpm install --frozen-lockfile && pnpm run build` 后运行
|
||||||
|
`apps/harness/scripts/ci.sh`;Rust lane 不安装 Node/Electron。
|
||||||
|
- 未知 active entry 仍以非零退出失败,不静默跳过;应用为 `release = "optional"`,
|
||||||
|
其失败不阻断合法 CLI 基础发行,但包含 app 的根候选会如实记录失败。
|
||||||
|
|
||||||
|
## 应用侧已复核证据
|
||||||
|
|
||||||
|
证据全文见 `apps/harness/docs/mdh/evidence/`。
|
||||||
|
|
||||||
|
- 上游基线 `pnpm install --frozen-lockfile` 与 `pnpm run build`:10/10 gates PASS。
|
||||||
|
- 下游 28 项测试:27 PASS;网络安装测试在 `MDH_TEST_INSTALL=1` 下 PASS(rc.5→rc.6→回退)。
|
||||||
|
- 真实 CLI 执行 factorial `n=5` → `{"type":"int","decimal":"120"}`;除零 → `failed`;摘要不符 → `incomplete`。
|
||||||
|
- 真实 `marqdo-knowledge` 编译/查询:`mode=compiled`,命中带精确源路径、摘要、span 与通道。
|
||||||
|
- `/mdh` 页面与 API:200;cross-site / 错误 Host / 不匹配 Origin → 403。
|
||||||
|
- `scripts/package.sh`:预构建归档冷组合 PASS(748,901,507 bytes,sha256 `21a532d2949a25bae76a41b2a4e0f08d06f39a084db2f02a1cd1506ad5a24617`)。
|
||||||
|
|
||||||
|
## UNVERIFIED
|
||||||
|
|
||||||
|
- 父仓 PR#48 的 Woodpecker pipeline 已真实运行;首次 candidate 失败于 app-candidate manifest 把摘要字符串误转为 `Path`,已修复并等待 rerun 通过。Node lane 尚未在该次 pipeline 中执行完成。
|
||||||
|
- 真实模型两轮任务(任务 A/B)未运行:本机没有模型凭据,没有用 fixture 冒充。
|
||||||
|
- 浏览器自动化未运行;页面与 API 通过真实 HTTP 请求验证。
|
||||||
|
- 上游同步演练未运行:镜像 HEAD 等于基线,没有更新的提交。
|
||||||
|
- 候选归档未签名,未在第二台干净主机或更低 glibc 上冷安装。
|
||||||
+47
-5
@@ -32,10 +32,14 @@ ROOT = Path(__file__).resolve().parents[1]
|
|||||||
NAME = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
|
NAME = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
|
||||||
FIELDS = {"id", "path", "kind", "state", "owner", "scope", "requires", "checks_with", "release"}
|
FIELDS = {"id", "path", "kind", "state", "owner", "scope", "requires", "checks_with", "release"}
|
||||||
ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
|
ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
|
||||||
ROOT_DIRS = {".gitea", ".woodpecker", "ci", "docs", "examples", "scripts"}
|
ROOT_DIRS = {".gitea", ".woodpecker", "apps", "ci", "docs", "examples", "scripts"}
|
||||||
CATEGORY_READMES = {"stdlib/README.md", "extensions/README.md"}
|
CATEGORY_READMES = {"stdlib/README.md", "extensions/README.md"}
|
||||||
RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"}
|
RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"}
|
||||||
DOMAIN_RELEASE = {"none", "base"}
|
DOMAIN_RELEASE = {"none", "base"}
|
||||||
|
# An app is a root-only, optional product consumer: it owns no runtime contract
|
||||||
|
# and never becomes a dependency of another component. Its id carries the
|
||||||
|
# `app-` prefix that maps onto `apps/<name>`.
|
||||||
|
APP_RELEASE = {"optional"}
|
||||||
DOMAIN_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
|
DOMAIN_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
|
||||||
DOMAIN_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts", "tests"}
|
DOMAIN_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts", "tests"}
|
||||||
DOMAIN_CHILD_KINDS = {"stdlib", "extension", "tool"}
|
DOMAIN_CHILD_KINDS = {"stdlib", "extension", "tool"}
|
||||||
@@ -106,6 +110,8 @@ def expected_root_path(component):
|
|||||||
return f"tools/{id}"
|
return f"tools/{id}"
|
||||||
if kind == "domain":
|
if kind == "domain":
|
||||||
return "stdlib" if id == "stdlib" else f"extensions/{id}"
|
return "stdlib" if id == "stdlib" else f"extensions/{id}"
|
||||||
|
if kind == "app":
|
||||||
|
return f"apps/{id.removeprefix('app-')}" if id.startswith("app-") else None
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@@ -149,11 +155,16 @@ def check_component(raw, depth, label, by_id, paths, path_keys):
|
|||||||
require(id not in items and len(set(items)) == len(items), f"{label}: invalid {key}: {id}")
|
require(id not in items and len(set(items)) == len(items), f"{label}: invalid {key}: {id}")
|
||||||
|
|
||||||
kind = raw["kind"]
|
kind = raw["kind"]
|
||||||
require(kind in RELEASE_ROLES or kind == "domain", f"{label}: unknown kind: {id}: {kind!r}")
|
require(kind in RELEASE_ROLES or kind in {"domain", "app"},
|
||||||
|
f"{label}: unknown kind: {id}: {kind!r}")
|
||||||
if kind == "domain":
|
if kind == "domain":
|
||||||
require(depth == 0, f"{label}: domain kind is only allowed at the root layer: {id}")
|
require(depth == 0, f"{label}: domain kind is only allowed at the root layer: {id}")
|
||||||
require(raw["release"] in DOMAIN_RELEASE, f"{label}: invalid release role: {id}")
|
require(raw["release"] in DOMAIN_RELEASE, f"{label}: invalid release role: {id}")
|
||||||
require(raw["requires"] == [], f"{label}: domain requires must be empty: {id}")
|
require(raw["requires"] == [], f"{label}: domain requires must be empty: {id}")
|
||||||
|
elif kind == "app":
|
||||||
|
require(depth == 0, f"{label}: app kind is only allowed at the root layer: {id}")
|
||||||
|
require(id.startswith("app-"), f"{label}: app id must start with 'app-': {id}")
|
||||||
|
require(raw["release"] in APP_RELEASE, f"{label}: invalid release role: {id}")
|
||||||
else:
|
else:
|
||||||
require(depth == 0 or kind in DOMAIN_CHILD_KINDS,
|
require(depth == 0 or kind in DOMAIN_CHILD_KINDS,
|
||||||
f"{label}: component kind is not allowed inside a domain: {id} ({kind})")
|
f"{label}: component kind is not allowed inside a domain: {id} ({kind})")
|
||||||
@@ -385,8 +396,13 @@ def validate_graph(layers):
|
|||||||
source_kind = component["kind"]
|
source_kind = component["kind"]
|
||||||
require(target_kind != "domain",
|
require(target_kind != "domain",
|
||||||
f"{layer.label}: requires must not target a domain: {id} -> {dependency}")
|
f"{layer.label}: requires must not target a domain: {id} -> {dependency}")
|
||||||
|
require(target_kind != "app",
|
||||||
|
f"{layer.label}: app components cannot be dependencies: {id} -> {dependency}")
|
||||||
if source_kind in {"core", "domain"}:
|
if source_kind in {"core", "domain"}:
|
||||||
require(False, f"{layer.label}: dependency violation: {id} must not require {dependency}")
|
require(False, f"{layer.label}: dependency violation: {id} must not require {dependency}")
|
||||||
|
if source_kind == "app":
|
||||||
|
require(target_kind in {"core", "stdlib", "extension", "tool"},
|
||||||
|
f"{layer.label}: app dependency violation: {id} -> {dependency}")
|
||||||
if source_kind == "stdlib":
|
if source_kind == "stdlib":
|
||||||
require(target_kind in {"core", "stdlib"},
|
require(target_kind in {"core", "stdlib"},
|
||||||
f"{layer.label}: stdlib dependency violation: {id} -> {dependency}")
|
f"{layer.label}: stdlib dependency violation: {id} -> {dependency}")
|
||||||
@@ -423,22 +439,48 @@ def validate(revision, checkouts, expand_domains=False):
|
|||||||
return layers
|
return layers
|
||||||
|
|
||||||
|
|
||||||
|
def active_entries(layers):
|
||||||
|
root = layers[0]
|
||||||
|
root_domains = {root.repo / path: item["id"] for path, item in root.linked.items()
|
||||||
|
if item["kind"] == "domain"}
|
||||||
|
entries = {}
|
||||||
|
requirements = {}
|
||||||
|
for layer in layers:
|
||||||
|
parent = root_domains.get(layer.repo)
|
||||||
|
for path, item in sorted(layer.linked.items()):
|
||||||
|
if item["state"] != "active":
|
||||||
|
continue
|
||||||
|
component_id = item["id"]
|
||||||
|
relative = (layer.repo / path).relative_to(root.repo).as_posix()
|
||||||
|
entries[component_id] = (component_id, item["kind"], relative, item["entry"])
|
||||||
|
requirements[component_id] = list(item["requires"])
|
||||||
|
if parent in requirements:
|
||||||
|
requirements[parent].append(component_id)
|
||||||
|
for component_id in graphlib.TopologicalSorter(requirements).static_order():
|
||||||
|
yield entries[component_id]
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="Validate a Marqdo ecosystem Git tree")
|
parser = argparse.ArgumentParser(description="Validate a Marqdo ecosystem Git tree")
|
||||||
parser.add_argument("revision", nargs="?", default="HEAD")
|
parser.add_argument("revision", nargs="?", default="HEAD")
|
||||||
parser.add_argument("--checkouts", action="store_true")
|
parser.add_argument("--checkouts", action="store_true")
|
||||||
paths = parser.add_mutually_exclusive_group()
|
paths = parser.add_mutually_exclusive_group()
|
||||||
paths.add_argument("--active-paths", action="store_true", help="print only direct active component paths")
|
paths.add_argument("--active-paths", action="store_true", help="print only direct active component paths")
|
||||||
|
paths.add_argument("--active-entries", action="store_true", help="print validated active entries in dependency order")
|
||||||
paths.add_argument("--domain-paths", action="store_true", help="validate domain URLs and print domain paths")
|
paths.add_argument("--domain-paths", action="store_true", help="validate domain URLs and print domain paths")
|
||||||
|
paths.add_argument("--root-domain-paths", action="store_true", help="print root domain gitlinks before checkout")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
try:
|
try:
|
||||||
revision = git("rev-parse", "--verify", args.revision + "^{commit}").strip()
|
revision = git("rev-parse", "--verify", args.revision + "^{commit}").strip()
|
||||||
layers = validate(revision, args.checkouts, expand_domains=args.domain_paths)
|
layers = validate(revision, args.checkouts or args.active_entries, expand_domains=args.domain_paths)
|
||||||
if args.active_paths:
|
if args.active_entries:
|
||||||
|
for entry in active_entries(layers):
|
||||||
|
print("\t".join(entry))
|
||||||
|
elif args.active_paths:
|
||||||
for path, component in sorted(layers[0].linked.items()):
|
for path, component in sorted(layers[0].linked.items()):
|
||||||
if component["state"] == "active":
|
if component["state"] == "active":
|
||||||
print(path)
|
print(path)
|
||||||
elif args.domain_paths:
|
elif args.domain_paths or args.root_domain_paths:
|
||||||
for path, component in sorted(layers[0].linked.items()):
|
for path, component in sorted(layers[0].linked.items()):
|
||||||
if component["kind"] == "domain":
|
if component["kind"] == "domain":
|
||||||
print(path)
|
print(path)
|
||||||
|
|||||||
+40
-77
@@ -11,8 +11,8 @@ The affected set is computed in the order the development contract requires:
|
|||||||
1. changed or removed leaves;
|
1. changed or removed leaves;
|
||||||
2. reverse transitive closure over `requires` edges from the union of both
|
2. reverse transitive closure over `requires` edges from the union of both
|
||||||
graphs (removed edges cannot hide a consumer);
|
graphs (removed edges cannot hide a consumer);
|
||||||
3. parent domains of affected components;
|
3. `checks_with` and reverse dependency fixed point;
|
||||||
4. `checks_with` fixed point (co-validation is not a build prerequisite).
|
4. parent domains of affected components in both graphs.
|
||||||
|
|
||||||
When a domain cannot be expanded (missing object/checkout) the result is marked
|
When a domain cannot be expanded (missing object/checkout) the result is marked
|
||||||
UNVERIFIED and the whole domain is treated as affected rather than silently
|
UNVERIFIED and the whole domain is treated as affected rather than silently
|
||||||
@@ -217,37 +217,42 @@ def changed_components(
|
|||||||
def affected_set(
|
def affected_set(
|
||||||
accepted: dict[str, dict], candidate: dict[str, dict], changed: list[dict]
|
accepted: dict[str, dict], candidate: dict[str, dict], changed: list[dict]
|
||||||
) -> tuple[list[str], list[str], list[str]]:
|
) -> tuple[list[str], list[str], list[str]]:
|
||||||
graph = {**accepted, **candidate}
|
dependents: dict[str, set[str]] = {}
|
||||||
dependents: dict[str, set[str]] = {component_id: set() for component_id in graph}
|
partners: dict[str, set[str]] = {}
|
||||||
for component in graph.values():
|
parents: dict[str, set[str]] = {}
|
||||||
for dependency in component.get("requires", []):
|
for graph in (accepted, candidate):
|
||||||
dependents.setdefault(dependency, set()).add(component["id"])
|
for component_id, component in graph.items():
|
||||||
|
for dependency in component.get("requires", []):
|
||||||
|
dependents.setdefault(dependency, set()).add(component_id)
|
||||||
|
for partner in component.get("checks_with", []):
|
||||||
|
partners.setdefault(component_id, set()).add(partner)
|
||||||
|
partners.setdefault(partner, set()).add(component_id)
|
||||||
|
if component.get("parent"):
|
||||||
|
parents.setdefault(component_id, set()).add(component["parent"])
|
||||||
|
|
||||||
affected = {item["id"] for item in changed}
|
affected = {item["id"] for item in changed}
|
||||||
queue = list(affected)
|
queue = list(affected)
|
||||||
|
while queue:
|
||||||
|
for consumer in dependents.get(queue.pop(), set()) - affected:
|
||||||
|
affected.add(consumer)
|
||||||
|
queue.append(consumer)
|
||||||
|
|
||||||
|
build_affected = affected.copy()
|
||||||
|
queue = list(affected)
|
||||||
while queue:
|
while queue:
|
||||||
current = queue.pop()
|
current = queue.pop()
|
||||||
for consumer in dependents.get(current, set()):
|
additions = (partners.get(current, set()) | dependents.get(current, set())) - affected
|
||||||
if consumer not in affected:
|
affected.update(additions)
|
||||||
affected.add(consumer)
|
queue.extend(additions)
|
||||||
queue.append(consumer)
|
co_validation = {partner for current in affected for partner in partners.get(current, set())}
|
||||||
|
co_validation -= build_affected
|
||||||
|
|
||||||
domains = set()
|
domains = set()
|
||||||
for component_id in list(affected):
|
queue = list(affected)
|
||||||
parent = graph[component_id].get("parent")
|
while queue:
|
||||||
while parent:
|
for parent in parents.get(queue.pop(), set()) - affected - domains:
|
||||||
if parent not in affected:
|
domains.add(parent)
|
||||||
domains.add(parent)
|
queue.append(parent)
|
||||||
parent = graph[parent].get("parent") if parent in graph else None
|
|
||||||
co_validation: set[str] = set()
|
|
||||||
while True:
|
|
||||||
additions = set()
|
|
||||||
for component_id in affected:
|
|
||||||
for partner in graph[component_id].get("checks_with", []):
|
|
||||||
if partner not in affected:
|
|
||||||
additions.add(partner)
|
|
||||||
if not additions:
|
|
||||||
break
|
|
||||||
affected |= additions
|
|
||||||
co_validation |= additions
|
|
||||||
return sorted(affected), sorted(domains), sorted(co_validation)
|
return sorted(affected), sorted(domains), sorted(co_validation)
|
||||||
|
|
||||||
|
|
||||||
@@ -261,56 +266,14 @@ def consumers_of(component_id: str, revision: str) -> dict:
|
|||||||
revision_sha = resolve(ROOT, revision)
|
revision_sha = resolve(ROOT, revision)
|
||||||
graph, unverified = load_graph(ROOT, revision_sha, "root")
|
graph, unverified = load_graph(ROOT, revision_sha, "root")
|
||||||
if component_id not in graph:
|
if component_id not in graph:
|
||||||
graph, unverified = load_graph(ROOT, revision_sha, "root")
|
unverified.append(
|
||||||
return {
|
f"unknown component {component_id!r} at {revision_sha}; scope widened"
|
||||||
"schema": SCHEMA,
|
)
|
||||||
"schema_version": SCHEMA_VERSION,
|
fallback = "full" if unverified else None
|
||||||
"accepted": {"ref": revision, "revision": revision_sha},
|
|
||||||
"component": component_id,
|
|
||||||
"affected": sorted(graph),
|
|
||||||
"checks_with": [],
|
|
||||||
"domain_ancestors": [],
|
|
||||||
"fallback": "full",
|
|
||||||
"unverified": unverified
|
|
||||||
+ [f"unknown component {component_id!r} at {revision_sha}; scope widened"],
|
|
||||||
}
|
|
||||||
dependents: dict[str, set[str]] = {key: set() for key in graph}
|
|
||||||
for component in graph.values():
|
|
||||||
for dependency in component.get("requires", []):
|
|
||||||
dependents.setdefault(dependency, set()).add(component["id"])
|
|
||||||
affected = {component_id}
|
|
||||||
queue = [component_id]
|
|
||||||
while queue:
|
|
||||||
current = queue.pop()
|
|
||||||
for consumer in dependents.get(current, set()):
|
|
||||||
if consumer not in affected:
|
|
||||||
affected.add(consumer)
|
|
||||||
queue.append(consumer)
|
|
||||||
domains = set()
|
|
||||||
for item in list(affected):
|
|
||||||
parent = graph[item].get("parent")
|
|
||||||
while parent:
|
|
||||||
if parent not in affected:
|
|
||||||
domains.add(parent)
|
|
||||||
parent = graph[parent].get("parent") if parent in graph else None
|
|
||||||
co_validation: set[str] = set()
|
|
||||||
while True:
|
|
||||||
additions = {
|
|
||||||
partner
|
|
||||||
for item in affected
|
|
||||||
for partner in graph[item].get("checks_with", [])
|
|
||||||
if partner not in affected
|
|
||||||
}
|
|
||||||
if not additions:
|
|
||||||
break
|
|
||||||
affected |= additions
|
|
||||||
co_validation |= additions
|
|
||||||
fallback = None
|
|
||||||
if unverified:
|
if unverified:
|
||||||
affected = set(graph)
|
affected, domains, co_validation = sorted(graph), [], []
|
||||||
domains = set()
|
else:
|
||||||
co_validation = set()
|
affected, domains, co_validation = affected_set(graph, graph, [{"id": component_id}])
|
||||||
fallback = "full"
|
|
||||||
return {
|
return {
|
||||||
"schema": SCHEMA,
|
"schema": SCHEMA,
|
||||||
"schema_version": SCHEMA_VERSION,
|
"schema_version": SCHEMA_VERSION,
|
||||||
|
|||||||
+167
-98
@@ -10,12 +10,31 @@ set -euo pipefail
|
|||||||
|
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
root="$PWD"
|
root="$PWD"
|
||||||
active="$(python3 scripts/check-layout.py --checkouts --active-paths)"
|
plan="$(python3 scripts/check-layout.py --active-entries)"
|
||||||
expected=$'cli\nextensions/web\nstdlib/collections\nstdlib/data\nstdlib/fs\nstdlib/io\nstdlib/system\nstdlib/text\ntests/conformance\ntools/knowledge\ntools/lint\ntools/prove\ntools/view'
|
declare -a gates=()
|
||||||
if [[ "$active" != "$expected" ]]; then
|
cli_smoke=
|
||||||
echo "UNVERIFIED: update the integration plan for the changed active component set" >&2
|
while IFS=$'\t' read -r id kind path entry; do
|
||||||
exit 1
|
case "$kind:$id:$entry" in
|
||||||
fi
|
core:cli:tools/release/smoke.py) cli_smoke="$path/$entry"; gate=core ;;
|
||||||
|
stdlib:*:scripts/test.sh) gate=stdlib ;;
|
||||||
|
test:conformance:scripts/build_all.sh) gate=conformance ;;
|
||||||
|
domain:web:scripts/domain-acceptance.sh) gate=web ;;
|
||||||
|
app:app-harness:scripts/ci.sh) gate=app ;;
|
||||||
|
tool:view:scripts/acceptance.sh) gate=view ;;
|
||||||
|
tool:knowledge:scripts/ci.sh) gate=knowledge ;;
|
||||||
|
tool:prove:scripts/package-tool.sh) gate=prove ;;
|
||||||
|
tool:lint:scripts/package-tool.sh) gate=lint ;;
|
||||||
|
tool:*:scripts/ci.sh|tool:*:scripts/integration.sh|extension:*:scripts/ci.sh|extension:*:scripts/integration.sh|test:*:scripts/ci.sh|test:*:scripts/integration.sh)
|
||||||
|
gate=entry
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "UNVERIFIED: unsupported integration entry $id ($kind): $entry" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
gates+=("$gate")
|
||||||
|
done <<< "$plan"
|
||||||
|
test -n "$cli_smoke"
|
||||||
|
|
||||||
mkdir -p .integration-work
|
mkdir -p .integration-work
|
||||||
work="$(mktemp -d "$root/.integration-work/run.XXXXXX")"
|
work="$(mktemp -d "$root/.integration-work/run.XXXXXX")"
|
||||||
@@ -32,6 +51,7 @@ python3 --version
|
|||||||
python3 -c 'import jsonschema'
|
python3 -c 'import jsonschema'
|
||||||
python3 scripts/check-layout.py --checkouts > "$work/layout.txt"
|
python3 scripts/check-layout.py --checkouts > "$work/layout.txt"
|
||||||
cat "$work/layout.txt"
|
cat "$work/layout.txt"
|
||||||
|
printf '%s\n' "$plan" > "$work/active-entries.tsv"
|
||||||
|
|
||||||
# Recursive impact analysis against the accepted root commit: the change set
|
# Recursive impact analysis against the accepted root commit: the change set
|
||||||
# comes from the recursively expanded (global_id, parent, remote, SHA, state)
|
# comes from the recursively expanded (global_id, parent, remote, SHA, state)
|
||||||
@@ -75,7 +95,7 @@ python3 cli/tools/release/package.py \
|
|||||||
--source-sha "$source_sha" --version "$version" \
|
--source-sha "$source_sha" --version "$version" \
|
||||||
--stdlib-dir "$work/stdlib" --out-dir "$work/dist" | tee "$work/package.json"
|
--stdlib-dir "$work/stdlib" --out-dir "$work/dist" | tee "$work/package.json"
|
||||||
archive="$(find "$work/dist" -maxdepth 1 -name 'marqdo-*.tar.gz' -print -quit)"
|
archive="$(find "$work/dist" -maxdepth 1 -name 'marqdo-*.tar.gz' -print -quit)"
|
||||||
python3 cli/tools/release/smoke.py --archive "$archive"
|
python3 "$cli_smoke" --archive "$archive"
|
||||||
mkdir -p "$work/install"
|
mkdir -p "$work/install"
|
||||||
tar -xzf "$archive" -C "$work/install"
|
tar -xzf "$archive" -C "$work/install"
|
||||||
installed="$(find "$work/install" -mindepth 1 -maxdepth 1 -type d -print -quit)"
|
installed="$(find "$work/install" -mindepth 1 -maxdepth 1 -type d -print -quit)"
|
||||||
@@ -85,106 +105,154 @@ test "$(cat "$installed/SOURCE_SHA")" = "$source_sha"
|
|||||||
test "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' "$installed/stdlib/stdlib.json")" = "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' "$work/stdlib/stdlib.json")"
|
test "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' "$installed/stdlib/stdlib.json")" = "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' "$work/stdlib/stdlib.json")"
|
||||||
sha256sum "$archive" "$MARQDO_BIN" "$installed/marqdo-provider-worker"
|
sha256sum "$archive" "$MARQDO_BIN" "$installed/marqdo-provider-worker"
|
||||||
|
|
||||||
# 4. Root stdlib acceptance: component entries, explicit Packages, composition
|
# Fixed identity handoff for the Node application lane. The manifest is a
|
||||||
# fixtures and fail-closed negatives with the same installed CLI/Bundle.
|
# consumer input, not a new lock: it names the exact archive, CLI source,
|
||||||
python3 scripts/acceptance-stdlib.py \
|
# Bundle digest and installed binary produced above.
|
||||||
--cli "$MARQDO_BIN" --bundle "$work/stdlib" \
|
python3 - "$work" "$archive" "$source_sha" "$bundle_digest" "$bundle_aliases" "$installed" "$root" <<'PY'
|
||||||
--work "$work/stdlib-acceptance" --evidence "$work/stdlib-acceptance.json"
|
import hashlib, json, pathlib, subprocess, sys
|
||||||
|
work = pathlib.Path(sys.argv[1])
|
||||||
|
archive = pathlib.Path(sys.argv[2])
|
||||||
|
source_sha = sys.argv[3]
|
||||||
|
bundle_digest = sys.argv[4]
|
||||||
|
aliases = sys.argv[5]
|
||||||
|
installed = pathlib.Path(sys.argv[6])
|
||||||
|
root = pathlib.Path(sys.argv[7])
|
||||||
|
manifest = {
|
||||||
|
'schema': 'marqdo.app-candidate',
|
||||||
|
'schema_version': 1,
|
||||||
|
'candidate_root': str(root),
|
||||||
|
'archive': str(archive),
|
||||||
|
'archive_sha256': 'sha256:' + hashlib.sha256(archive.read_bytes()).hexdigest(),
|
||||||
|
'installed_dir': str(installed),
|
||||||
|
'cli_path': str(installed / 'marqdo'),
|
||||||
|
'cli_source_sha': source_sha,
|
||||||
|
'stdlib_tree_digest': bundle_digest,
|
||||||
|
'stdlib_aliases_digest': aliases,
|
||||||
|
'platform': 'x86_64-unknown-linux-gnu',
|
||||||
|
'app_gitlink': subprocess.check_output(
|
||||||
|
['git', '-C', str(root / 'apps/harness'), 'rev-parse', 'HEAD'], text=True).strip(),
|
||||||
|
}
|
||||||
|
(work / 'app-candidate.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||||
|
(work.parent / 'app-candidate.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||||
|
print(json.dumps(manifest, indent=2))
|
||||||
|
PY
|
||||||
|
|
||||||
# 5. Frozen independent public-contract fixtures against the same CLI.
|
# Tool consumers use the same candidate installation and the catalog order.
|
||||||
python3 cli/tools/ci/verify_extension_contracts.py \
|
|
||||||
--source-repo cli --tested-sha "$source_sha" --cli "$MARQDO_BIN" \
|
|
||||||
--release-info "$installed/RELEASE_INFO.json" \
|
|
||||||
--fixtures tests/conformance --out "$work/conformance.json"
|
|
||||||
|
|
||||||
|
|
||||||
# 5.5 Web domain: component entries from the pinned domain gitlink, then a cold
|
|
||||||
# install of the same-built web Tool with a generic check/preview/handoff run.
|
|
||||||
# The candidate image uses a minimal Rust profile; component entries run
|
# The candidate image uses a minimal Rust profile; component entries run
|
||||||
# fmt/clippy, so add those components once when the active toolchain lacks them.
|
# fmt/clippy, so add those components once when the active toolchain lacks them.
|
||||||
if command -v rustup >/dev/null 2>&1 \
|
if command -v rustup >/dev/null 2>&1 \
|
||||||
&& ! rustup component list --installed 2>/dev/null | grep -qx 'rustfmt.*'; then
|
&& ! rustup component list --installed 2>/dev/null | grep -qx 'rustfmt.*'; then
|
||||||
rustup component add rustfmt clippy
|
rustup component add rustfmt clippy
|
||||||
fi
|
fi
|
||||||
(
|
|
||||||
cd extensions/web/design
|
run_consumer() (
|
||||||
MARQDO_BIN="$MARQDO_BIN" scripts/ci.sh
|
cd "$root/$path"
|
||||||
)
|
export MARQDO_CI_OUT="$work/components/$id"
|
||||||
(
|
mkdir -p "$MARQDO_CI_OUT"
|
||||||
cd extensions/web/preview
|
case "$gate" in
|
||||||
MARQDO_BIN="$MARQDO_BIN" scripts/ci.sh
|
entry)
|
||||||
)
|
MARQDO_STDLIB_DIR="$installed/stdlib" "./$entry"
|
||||||
web_tool="$root/extensions/web/preview/dist/marqdo-web-preview/tool.json"
|
;;
|
||||||
test -f "$web_tool"
|
web)
|
||||||
export MARQDO_TOOL_HOME="$work/web-tool-home"
|
web_tool="$PWD/preview/dist/marqdo-web-preview/tool.json"
|
||||||
cli_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
export MARQDO_TOOL_HOME="$MARQDO_CI_OUT/tool-home"
|
||||||
"$MARQDO_BIN" tool install "$web_tool"
|
cli_before="$(sha256sum "$MARQDO_BIN")"
|
||||||
"$MARQDO_BIN" web check extensions/web/examples/research-workspace/index.mq.md \
|
"$MARQDO_BIN" tool install "$web_tool"
|
||||||
--unit 工作台 --root extensions/web/examples/research-workspace
|
example=examples/research-workspace
|
||||||
"$MARQDO_BIN" web preview extensions/web/examples/research-workspace/index.mq.md \
|
"$MARQDO_BIN" web check "$example/index.mq.md" --unit 工作台 --root "$example"
|
||||||
--unit 工作台 --root extensions/web/examples/research-workspace --out "$work/web-preview"
|
"$MARQDO_BIN" web preview "$example/index.mq.md" --unit 工作台 --root "$example" \
|
||||||
test -f "$work/web-preview/index.html"
|
--out "$MARQDO_CI_OUT/preview"
|
||||||
"$MARQDO_BIN" web handoff extensions/web/examples/research-workspace/index.mq.md \
|
test -s "$MARQDO_CI_OUT/preview/index.html"
|
||||||
--unit 工作台 --root extensions/web/examples/research-workspace --out "$work/web-handoff.md"
|
"$MARQDO_BIN" web handoff "$example/index.mq.md" --unit 工作台 --root "$example" \
|
||||||
test -s "$work/web-handoff.md"
|
--out "$MARQDO_CI_OUT/handoff.md"
|
||||||
"$MARQDO_BIN" tool remove web
|
test -s "$MARQDO_CI_OUT/handoff.md"
|
||||||
cli_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
"$MARQDO_BIN" tool remove web
|
||||||
test "$cli_before" = "$cli_after"
|
test "$(sha256sum "$MARQDO_BIN")" = "$cli_before"
|
||||||
echo "web domain: component entries + cold Tool install PASS"
|
;;
|
||||||
# 6. Existing consumers, same installed binary and adjacent Bundle.
|
app)
|
||||||
(
|
# The Rust candidate lane builds the one CLI/Bundle artifact and
|
||||||
cd tools/view
|
# emits its identity. The dedicated Node lane runs scripts/ci.sh
|
||||||
export MARQDO_TOOL_HOME="$work/view-registry"
|
# against that exact artifact; this lane must not install Node.
|
||||||
scripts/package.sh
|
test -x "$PWD/$entry"
|
||||||
"$MARQDO_BIN" tool install dist/marqdo-view/tool.json
|
echo "APP_LANE: candidate manifest $work/app-candidate.json"
|
||||||
"$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md
|
;;
|
||||||
"$MARQDO_BIN" view export examples/tables-math --out "$work/view-export"
|
view)
|
||||||
setsid "$MARQDO_BIN" view examples/control-flow --port 0 --no-open >"$work/view-server.log" 2>&1 &
|
export MARQDO_TOOL_HOME="$work/view-registry"
|
||||||
view_pid=$!
|
scripts/package.sh
|
||||||
stop_view() {
|
"$MARQDO_BIN" tool install dist/marqdo-view/tool.json
|
||||||
kill -- "-$view_pid" 2>/dev/null || true
|
"$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md
|
||||||
wait "$view_pid" 2>/dev/null || true
|
"$MARQDO_BIN" view export examples/tables-math --out "$work/view-export"
|
||||||
}
|
setsid "$MARQDO_BIN" view examples/control-flow --port 0 --no-open >"$work/view-server.log" 2>&1 &
|
||||||
trap stop_view EXIT
|
view_pid=$!
|
||||||
view_url=""
|
stop_view() {
|
||||||
for attempt in {1..100}; do
|
kill -- "-$view_pid" 2>/dev/null || true
|
||||||
view_url="$(grep -m1 -o 'http://127\.0\.0\.1:[0-9]\+/' "$work/view-server.log" || true)"
|
wait "$view_pid" 2>/dev/null || true
|
||||||
if [[ -n "$view_url" ]] || ! kill -0 "$view_pid" 2>/dev/null; then
|
}
|
||||||
break
|
trap stop_view EXIT
|
||||||
fi
|
view_url=""
|
||||||
sleep 0.1
|
for attempt in {1..100}; do
|
||||||
done
|
view_url="$(grep -m1 -o 'http://127\.0\.0\.1:[0-9]\+/' "$work/view-server.log" || true)"
|
||||||
if [[ -z "$view_url" ]]; then
|
if [[ -n "$view_url" ]] || ! kill -0 "$view_pid" 2>/dev/null; then
|
||||||
cat "$work/view-server.log" >&2
|
break
|
||||||
exit 1
|
fi
|
||||||
fi
|
sleep 0.1
|
||||||
python3 scripts/acceptance-run.py "$view_url"
|
done
|
||||||
stop_view
|
if [[ -z "$view_url" ]]; then
|
||||||
trap - EXIT
|
cat "$work/view-server.log" >&2
|
||||||
python3 scripts/check-observation.py stream-snapshot
|
exit 1
|
||||||
"$MARQDO_BIN" tool remove view
|
fi
|
||||||
if "$MARQDO_BIN" view --version; then
|
python3 scripts/acceptance-run.py "$view_url"
|
||||||
echo "view still dispatches after removal" >&2
|
stop_view
|
||||||
exit 1
|
trap - EXIT
|
||||||
fi
|
python3 scripts/check-observation.py stream-snapshot
|
||||||
)
|
"$MARQDO_BIN" tool remove view
|
||||||
(
|
if "$MARQDO_BIN" view --version; then
|
||||||
cd tools/knowledge
|
echo "view still dispatches after removal" >&2
|
||||||
MARQDO_TEST_BIN="$MARQDO_BIN" cargo test --locked --test core_cli --test compile
|
exit 1
|
||||||
)
|
fi
|
||||||
(
|
;;
|
||||||
cd tools/prove
|
knowledge)
|
||||||
cargo test --locked --test analysis_document --test document_contract
|
MARQDO_TEST_BIN="$MARQDO_BIN" cargo test --locked --test core_cli --test compile
|
||||||
)
|
;;
|
||||||
(
|
prove)
|
||||||
cd tools/lint
|
cargo test --locked --test analysis_document --test document_contract
|
||||||
export MARQDO_TOOL_HOME="$work/lint-registry"
|
;;
|
||||||
scripts/package-tool.sh "$work/lint"
|
lint)
|
||||||
"$MARQDO_BIN" tool install "$work/lint/tool.json"
|
export MARQDO_TOOL_HOME="$work/lint-registry"
|
||||||
"$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json
|
"./$entry" "$work/lint"
|
||||||
"$MARQDO_BIN" tool remove lint
|
"$MARQDO_BIN" tool install "$work/lint/tool.json"
|
||||||
|
"$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json
|
||||||
|
"$MARQDO_BIN" tool remove lint
|
||||||
|
;;
|
||||||
|
esac
|
||||||
)
|
)
|
||||||
|
|
||||||
|
stdlib_accepted=false
|
||||||
|
index=0
|
||||||
|
while IFS=$'\t' read -r -u 3 id kind path entry; do
|
||||||
|
gate="${gates[index]}"
|
||||||
|
index=$((index + 1))
|
||||||
|
echo "candidate gate: $id ($path/$entry)"
|
||||||
|
case "$gate" in
|
||||||
|
core) ;; # CLI/Worker packaging and smoke ran before consumer gates.
|
||||||
|
stdlib)
|
||||||
|
if [ "$stdlib_accepted" = false ]; then
|
||||||
|
python3 scripts/acceptance-stdlib.py \
|
||||||
|
--cli "$MARQDO_BIN" --bundle "$work/stdlib" \
|
||||||
|
--work "$work/stdlib-acceptance" --evidence "$work/stdlib-acceptance.json"
|
||||||
|
stdlib_accepted=true
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
conformance)
|
||||||
|
python3 cli/tools/ci/verify_extension_contracts.py \
|
||||||
|
--source-repo cli --tested-sha "$source_sha" --cli "$MARQDO_BIN" \
|
||||||
|
--release-info "$installed/RELEASE_INFO.json" \
|
||||||
|
--fixtures "$path" --out "$work/conformance.json"
|
||||||
|
;;
|
||||||
|
*) run_consumer ;;
|
||||||
|
esac
|
||||||
|
done 3<<< "$plan"
|
||||||
|
|
||||||
# 7. Evidence identity for the accepted candidate.
|
# 7. Evidence identity for the accepted candidate.
|
||||||
root_commit="$(git rev-parse HEAD)"
|
root_commit="$(git rev-parse HEAD)"
|
||||||
python3 - "$work" "$root_commit" "$source_sha" "$bundle_digest" "$bundle_aliases" "$archive" <<'PY'
|
python3 - "$work" "$root_commit" "$source_sha" "$bundle_digest" "$bundle_aliases" "$archive" <<'PY'
|
||||||
@@ -202,6 +270,7 @@ evidence = {
|
|||||||
"stdlib_aliases_digest": sys.argv[5],
|
"stdlib_aliases_digest": sys.argv[5],
|
||||||
"archive": archive.name,
|
"archive": archive.name,
|
||||||
"archive_sha256": "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest(),
|
"archive_sha256": "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest(),
|
||||||
|
"active_entries": [line.split("\t") for line in (work / "active-entries.tsv").read_text().splitlines()],
|
||||||
"impact": (
|
"impact": (
|
||||||
{
|
{
|
||||||
"changed": impact["changed"],
|
"changed": impact["changed"],
|
||||||
|
|||||||
+606
-280
@@ -1,349 +1,675 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Release discovery and idempotent tracking for the Marqdo ecosystem.
|
"""Verify published releases and reconcile their tracking Issues (marqdo#10)."""
|
||||||
|
|
||||||
Reads the authoritative catalog/gitlinks to derive managed repositories, scans
|
|
||||||
Gitea releases (including prereleases), verifies tag/source identity and asset
|
|
||||||
size/SHA-256, and creates one tracking Issue per release in the root repository.
|
|
||||||
It never updates gitlinks, never publishes, and never trusts a release body as a
|
|
||||||
command. The same implementation backs the Woodpecker manual/cron reconcile
|
|
||||||
workflow, so a lost notification is recovered by the next successful scan.
|
|
||||||
|
|
||||||
State/idempotency is the root Issue itself: the body carries a stable marker
|
|
||||||
`<!-- marqdo:release-reconcile repository=<full> tag=<tag> -->` and the fixed
|
|
||||||
`release-tracking` label. A concurrent run can create a duplicate only if both
|
|
||||||
scan before either issue is visible; the workflow serializes runs.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import datetime
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import http.client
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import tomllib
|
|
||||||
import urllib.error
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import impact
|
||||||
|
|
||||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||||
API_BASE = os.environ.get("MARQDO_GITEA_API", "https://git.cflmy.cn/api/v1")
|
FORGE = "https://git.cflmy.cn"
|
||||||
ROOT_REPOSITORY = os.environ.get("MARQDO_ROOT_REPOSITORY", "cflmy/marqdo")
|
CI = "https://ci.cflmy.cn"
|
||||||
|
ROOT_REPOSITORY = "cflmy/marqdo"
|
||||||
LABEL = "release-tracking"
|
LABEL = "release-tracking"
|
||||||
|
RECONCILE_ACCOUNT = "marqdo-reconcile"
|
||||||
|
INDEX = "release-evidence.json"
|
||||||
|
PAGE_SIZE = 50
|
||||||
|
MAX_PAGES = 100
|
||||||
|
MAX_INDEX_BYTES = 1024 * 1024
|
||||||
MAX_ASSET_BYTES = 256 * 1024 * 1024
|
MAX_ASSET_BYTES = 256 * 1024 * 1024
|
||||||
MAX_ASSETS = 128
|
MAX_ASSETS = 128
|
||||||
|
MAX_DEPENDENCIES = 256
|
||||||
|
SHA = re.compile(r"[0-9a-f]{40}")
|
||||||
|
DIGEST = re.compile(r"[0-9a-f]{64}")
|
||||||
|
BASENAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,254}")
|
||||||
|
TAG = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,127}")
|
||||||
|
REPOSITORY = re.compile(r"https://git\.cflmy\.cn/(cflmy/[A-Za-z0-9-]+)\.git")
|
||||||
|
HISTORICAL_CLI = ("cflmy/marqdo-cli", "v3.0.0-rc.5",
|
||||||
|
"c44b0f943875d563bb7c170f8ccd3fd56a82360f")
|
||||||
|
|
||||||
|
|
||||||
class ReconcileError(Exception):
|
class ReconcileError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ApiUnavailable(ReconcileError):
|
||||||
|
"""The API could not supply the facts needed to complete the scan."""
|
||||||
|
|
||||||
|
|
||||||
|
def http_error(method, path, status):
|
||||||
|
error = ApiUnavailable if status in {401, 403, 429} or status >= 500 else ReconcileError
|
||||||
|
return error(f"{method} {path}: HTTP {status}")
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, request, fp, code, message, headers, newurl):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
class Gitea:
|
class Gitea:
|
||||||
def __init__(self, token: str, base: str = API_BASE):
|
def __init__(self, token: str, dispatch_token: str = ""):
|
||||||
self.token = token
|
self.token = token
|
||||||
self.base = base.rstrip("/")
|
self.dispatch_token = dispatch_token
|
||||||
|
self.opener = urllib.request.build_opener(NoRedirect())
|
||||||
|
|
||||||
def request(self, method: str, path: str, data=None, raw=False):
|
def open(self, method, url, data=None, authorization=None):
|
||||||
body = json.dumps(data).encode() if data is not None else None
|
headers = {}
|
||||||
request = urllib.request.Request(
|
if authorization:
|
||||||
self.base + path,
|
headers["Authorization"] = authorization
|
||||||
method=method,
|
if data is not None:
|
||||||
data=body,
|
headers["Content-Type"] = "application/json"
|
||||||
headers={
|
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
"Authorization": f"token {self.token}",
|
return self.opener.open(request, timeout=30)
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
def request(self, method, base, path, data=None, authorization=None):
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(request, timeout=90) as response:
|
with self.open(method, base + path, data, authorization) as response:
|
||||||
content = response.read()
|
payload = response.read(8 * MAX_INDEX_BYTES + 1)
|
||||||
if raw:
|
require(len(payload) <= 8 * MAX_INDEX_BYTES, "API response exceeds size limit")
|
||||||
return content
|
return json.loads(payload)
|
||||||
return json.loads(content) if content else None
|
|
||||||
except urllib.error.HTTPError as error:
|
except urllib.error.HTTPError as error:
|
||||||
raise ReconcileError(f"{method} {path}: HTTP {error.code}") from error
|
raise http_error(method, path, error.code) from error
|
||||||
except urllib.error.URLError as error:
|
except (OSError, ValueError, http.client.HTTPException) as error:
|
||||||
raise ReconcileError(f"{method} {path}: {error}") from error
|
raise ApiUnavailable(f"{method} {path}: {error}") from error
|
||||||
|
|
||||||
def get(self, path: str):
|
def get(self, path):
|
||||||
return self.request("GET", path)
|
return self.request("GET", FORGE + "/api/v1", path,
|
||||||
|
authorization=f"token {self.token}" if self.token else None)
|
||||||
|
|
||||||
def post(self, path: str, data):
|
def post(self, path, data):
|
||||||
return self.request("POST", path, data)
|
return self.request("POST", FORGE + "/api/v1", path,
|
||||||
|
json.dumps(data).encode(), f"token {self.token}")
|
||||||
|
|
||||||
def download(self, url: str) -> bytes:
|
def ci(self, path):
|
||||||
request = urllib.request.Request(url, headers={"Authorization": f"token {self.token}"})
|
return self.request("GET", CI + "/api", path)
|
||||||
with urllib.request.urlopen(request, timeout=120) as response:
|
|
||||||
size = int(response.headers.get("Content-Length", "0"))
|
def dispatch_ci(self, path, data=None):
|
||||||
if size > MAX_ASSET_BYTES:
|
return self.request("GET" if data is None else "POST", CI + "/api", path,
|
||||||
raise ReconcileError(f"asset exceeds {MAX_ASSET_BYTES} bytes: {url}")
|
None if data is None else json.dumps(data).encode(),
|
||||||
data = response.read(MAX_ASSET_BYTES + 1)
|
f"Bearer {self.dispatch_token}")
|
||||||
if len(data) > MAX_ASSET_BYTES:
|
|
||||||
raise ReconcileError(f"asset exceeds {MAX_ASSET_BYTES} bytes: {url}")
|
def asset(self, path, size, *, index=False):
|
||||||
return data
|
limit = MAX_INDEX_BYTES if index else MAX_ASSET_BYTES
|
||||||
|
require(type(size) is int and 0 < size <= limit, "invalid asset size")
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
payload = bytearray()
|
||||||
|
received = 0
|
||||||
|
try:
|
||||||
|
with self.open("GET", FORGE + path) as response:
|
||||||
|
while chunk := response.read(min(1024 * 1024, size - received + 1)):
|
||||||
|
received += len(chunk)
|
||||||
|
require(received <= size, f"asset {path} size mismatch")
|
||||||
|
digest.update(chunk)
|
||||||
|
if index:
|
||||||
|
payload.extend(chunk)
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
raise http_error("GET", path, error.code) from error
|
||||||
|
except (OSError, http.client.HTTPException) as error:
|
||||||
|
raise ApiUnavailable(f"GET {path}: {error}") from error
|
||||||
|
require(received == size, f"asset {path} size mismatch")
|
||||||
|
return digest.hexdigest(), bytes(payload)
|
||||||
|
|
||||||
|
|
||||||
def repository_from_url(url: str) -> str:
|
def require(condition, message):
|
||||||
match = re.match(r"https://git\.cflmy\.cn/([^/]+/[^/]+?)(?:\.git)?$", url)
|
if not condition:
|
||||||
if not match:
|
raise ReconcileError(message)
|
||||||
raise ReconcileError(f"non-canonical repository URL: {url}")
|
|
||||||
return match.group(1)
|
|
||||||
|
|
||||||
|
|
||||||
def submodule_repositories(repo_root: Path) -> dict[str, str]:
|
def match(pattern, value):
|
||||||
path = repo_root / ".gitmodules"
|
return isinstance(value, str) and pattern.fullmatch(value) is not None
|
||||||
result: dict[str, str] = {}
|
|
||||||
if not path.is_file():
|
|
||||||
return result
|
def exact_fields(value, fields, optional=()):
|
||||||
current = None
|
return (isinstance(value, dict) and set(fields) <= value.keys()
|
||||||
for line in path.read_text().splitlines():
|
and value.keys() <= set(fields) | set(optional))
|
||||||
line = line.strip()
|
|
||||||
if line.startswith("[submodule "):
|
|
||||||
current = None
|
def unique_object(pairs):
|
||||||
elif line.startswith("path =") and current is None:
|
result = dict(pairs)
|
||||||
current = line.split("=", 1)[1].strip()
|
require(len(result) == len(pairs), "release evidence contains duplicate JSON fields")
|
||||||
elif line.startswith("url =") and current:
|
|
||||||
result[current] = repository_from_url(line.split("=", 1)[1].strip())
|
|
||||||
current = None
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def managed_repositories(root: Path) -> dict[str, str]:
|
def pages(client, path, **params):
|
||||||
"""catalog id/path -> owner/name for direct components and domain children."""
|
for page in range(1, MAX_PAGES + 1):
|
||||||
catalog = tomllib.loads((root / "components.toml").read_text())
|
query = urllib.parse.urlencode(dict(params, limit=PAGE_SIZE, page=page))
|
||||||
remotes = submodule_repositories(root)
|
batch = client.get(f"{path}?{query}")
|
||||||
managed: dict[str, str] = {}
|
require(isinstance(batch, list) and all(isinstance(item, dict) for item in batch),
|
||||||
for component in catalog.get("component", []):
|
f"{path}: invalid page {page}")
|
||||||
path = component.get("path", "")
|
require(len(batch) <= PAGE_SIZE, f"{path}: invalid page size")
|
||||||
if path in remotes:
|
yield from batch
|
||||||
managed[f"{component.get('id')}@{path}"] = remotes[path]
|
if len(batch) < PAGE_SIZE:
|
||||||
if component.get("kind") == "domain":
|
return
|
||||||
domain = root / path
|
raise ReconcileError(f"{path}: pagination limit reached")
|
||||||
domain_remotes = submodule_repositories(domain)
|
|
||||||
domain_catalog = domain / "components.toml"
|
|
||||||
if not domain_catalog.is_file():
|
|
||||||
continue
|
|
||||||
for child in tomllib.loads(domain_catalog.read_text()).get("component", []):
|
|
||||||
child_path = f"{path}/{child.get('path', '')}"
|
|
||||||
if child_path in domain_remotes:
|
|
||||||
managed[f"{child.get('id')}@{child_path}"] = domain_remotes[child_path]
|
|
||||||
return managed
|
|
||||||
|
|
||||||
|
|
||||||
def verify_assets(client: Gitea, release: dict) -> list[dict]:
|
def timestamp(value):
|
||||||
assets = release.get("assets") or []
|
try:
|
||||||
if len(assets) > MAX_ASSETS:
|
result = datetime.datetime.fromisoformat(value)
|
||||||
raise ReconcileError(f"release has more than {MAX_ASSETS} assets")
|
except (TypeError, ValueError) as error:
|
||||||
verified = []
|
raise ReconcileError("invalid release timestamp") from error
|
||||||
for asset in assets:
|
require(result.tzinfo is not None, "release timestamp requires a time zone")
|
||||||
name = asset.get("name", "")
|
return result.astimezone(datetime.timezone.utc)
|
||||||
if not name or "/" in name or name in (".", ".."):
|
|
||||||
raise ReconcileError(f"unsafe asset name: {name!r}")
|
|
||||||
url = asset.get("browser_download_url")
|
|
||||||
if not url:
|
|
||||||
raise ReconcileError(f"asset {name} has no download URL")
|
|
||||||
data = client.download(url)
|
|
||||||
if asset.get("size") is not None and int(asset["size"]) != len(data):
|
|
||||||
raise ReconcileError(f"asset {name} size mismatch")
|
|
||||||
digest = hashlib.sha256(data).hexdigest()
|
|
||||||
verified.append({"name": name, "size": len(data), "sha256": digest})
|
|
||||||
return verified
|
|
||||||
|
|
||||||
|
|
||||||
def release_marker(repository: str, tag: str) -> str:
|
def managed_repositories(root):
|
||||||
|
try:
|
||||||
|
revision = impact.resolve(root, "HEAD")
|
||||||
|
graph, unverified = impact.load_graph(root, revision, "root")
|
||||||
|
except impact.ImpactError as error:
|
||||||
|
raise ReconcileError(str(error)) from error
|
||||||
|
require(not unverified, "; ".join(unverified))
|
||||||
|
managed = {}
|
||||||
|
for cid, item in sorted(graph.items()):
|
||||||
|
if not item["sha"]:
|
||||||
|
continue
|
||||||
|
remote = item["remote"] or ""
|
||||||
|
canonical = REPOSITORY.fullmatch(remote)
|
||||||
|
require(canonical is not None, f"{cid}: non-canonical repository")
|
||||||
|
repository = canonical[1]
|
||||||
|
require(repository not in managed, f"duplicate repository {repository}")
|
||||||
|
path = item["path"]
|
||||||
|
if item["parent"]:
|
||||||
|
path = f"{graph[item['parent']]['path']}/{path}"
|
||||||
|
managed[repository] = {**item, "path": path, "repository": repository}
|
||||||
|
return revision, graph, managed
|
||||||
|
|
||||||
|
|
||||||
|
def ci_repository(client, repository):
|
||||||
|
repo = client.ci(f"/repos/lookup/{repository}")
|
||||||
|
forge_repo = client.get(f"/repos/{repository}")
|
||||||
|
require(isinstance(repo, dict) and repo.get("full_name") == repository
|
||||||
|
and type(repo.get("id")) is int and repo["id"] > 0
|
||||||
|
and isinstance(forge_repo, dict) and type(forge_repo.get("id")) is int
|
||||||
|
and repo.get("forge_remote_id") == str(forge_repo["id"]),
|
||||||
|
"CI repository identity mismatch")
|
||||||
|
return repo["id"], forge_repo
|
||||||
|
|
||||||
|
|
||||||
|
def verify_pipeline(client, repository, source_sha, evidence):
|
||||||
|
require(exact_fields(evidence, {"pipeline_number", "url", "source_sha"}),
|
||||||
|
"invalid component CI evidence")
|
||||||
|
number = evidence["pipeline_number"]
|
||||||
|
require(type(number) is int and number > 0 and evidence["source_sha"] == source_sha,
|
||||||
|
"release has no component CI evidence for its exact SHA")
|
||||||
|
repo_id, _ = ci_repository(client, repository)
|
||||||
|
expected_url = f"{CI}/repos/{repo_id}/pipeline/{number}"
|
||||||
|
require(evidence["url"] == expected_url, "component CI URL mismatch")
|
||||||
|
pipeline = client.ci(f"/repos/{repo_id}/pipelines/{number}")
|
||||||
|
workflow = "main" if repository == "cflmy/marqdo-cli" else "ci"
|
||||||
|
require(isinstance(pipeline, dict) and pipeline.get("number") == number
|
||||||
|
and pipeline.get("commit") == source_sha and pipeline.get("status") == "success"
|
||||||
|
and pipeline.get("event") in {"push", "pull_request", "manual"}
|
||||||
|
and any(w.get("name") == workflow and w.get("state") == "success"
|
||||||
|
and any(step.get("type") == "commands" and step.get("state") == "success"
|
||||||
|
for step in w.get("children", []))
|
||||||
|
for w in pipeline.get("workflows", [])), "component CI did not verify the exact SHA")
|
||||||
|
|
||||||
|
|
||||||
|
def asset_path(repository, tag, asset):
|
||||||
|
name = asset.get("name")
|
||||||
|
require(match(BASENAME, name), "unsafe release asset name")
|
||||||
|
escaped = urllib.parse.quote(name, safe="")
|
||||||
|
path = f"/{repository}/releases/download/{urllib.parse.quote(tag, safe='')}/{escaped}"
|
||||||
|
require(asset.get("browser_download_url") == FORGE + path,
|
||||||
|
f"asset {name} has a non-canonical URL")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def verify_release(client, repository, component, tag, release, graph):
|
||||||
|
identity = client.get(f"/repos/{repository}/tags/{urllib.parse.quote(tag, safe='')}")
|
||||||
|
require(isinstance(identity, dict) and identity.get("name") == tag
|
||||||
|
and isinstance(identity.get("commit"), dict)
|
||||||
|
and match(SHA, identity["commit"].get("sha")), "invalid release tag identity")
|
||||||
|
source_sha = identity["commit"]["sha"]
|
||||||
|
attachments = release.get("assets")
|
||||||
|
require(isinstance(attachments, list) and 0 < len(attachments) <= MAX_ASSETS + 1,
|
||||||
|
"missing or excessive release assets")
|
||||||
|
assets = {}
|
||||||
|
for asset in attachments:
|
||||||
|
require(isinstance(asset, dict), "invalid release asset")
|
||||||
|
path = asset_path(repository, tag, asset)
|
||||||
|
name = asset["name"]
|
||||||
|
require(name not in assets, "duplicate release asset")
|
||||||
|
assets[name] = (path, asset.get("size"))
|
||||||
|
if INDEX not in assets and (repository, tag, source_sha) == HISTORICAL_CLI:
|
||||||
|
return {"source_sha": source_sha, "historical": True}
|
||||||
|
|
||||||
|
require(INDEX in assets, "release evidence index missing")
|
||||||
|
index_digest, payload = client.asset(*assets.pop(INDEX), index=True)
|
||||||
|
try:
|
||||||
|
evidence = json.loads(payload, object_pairs_hook=unique_object)
|
||||||
|
except (UnicodeDecodeError, ValueError, RecursionError) as error:
|
||||||
|
raise ReconcileError("invalid release evidence JSON") from error
|
||||||
|
require(exact_fields(evidence, {"repository", "component_id", "tag", "source_sha",
|
||||||
|
"ci", "assets", "dependencies"}), "invalid release evidence fields")
|
||||||
|
require((evidence["repository"], evidence["component_id"], evidence["tag"], evidence["source_sha"])
|
||||||
|
== (repository, component["id"], tag, source_sha), "release evidence identity mismatch")
|
||||||
|
verify_pipeline(client, repository, source_sha, evidence["ci"])
|
||||||
|
|
||||||
|
dependencies = evidence["dependencies"]
|
||||||
|
require(isinstance(dependencies, list) and len(dependencies) <= MAX_DEPENDENCIES,
|
||||||
|
"invalid release dependency list")
|
||||||
|
seen = set()
|
||||||
|
for dependency in dependencies:
|
||||||
|
require(exact_fields(dependency, {"id", "source_sha"}, {"asset_sha256"})
|
||||||
|
and isinstance(dependency["id"], str) and dependency["id"] in graph
|
||||||
|
and dependency["id"] not in seen and dependency["id"] != component["id"]
|
||||||
|
and match(SHA, dependency["source_sha"])
|
||||||
|
and ("asset_sha256" not in dependency or match(DIGEST, dependency["asset_sha256"])),
|
||||||
|
"invalid release dependency identity")
|
||||||
|
seen.add(dependency["id"])
|
||||||
|
require(set(component["requires"]) <= seen, "release evidence is missing a declared dependency")
|
||||||
|
|
||||||
|
records = evidence["assets"]
|
||||||
|
require(isinstance(records, list) and 0 < len(records) == len(assets),
|
||||||
|
"release evidence does not cover the published assets")
|
||||||
|
for item in records:
|
||||||
|
require(exact_fields(item, {"name", "size", "target", "sha256"})
|
||||||
|
and match(BASENAME, item["name"]) and item["name"] in assets
|
||||||
|
and match(BASENAME, item["target"]) and match(DIGEST, item["sha256"])
|
||||||
|
and type(item["size"]) is int, "invalid release asset evidence")
|
||||||
|
path, size = assets.pop(item["name"])
|
||||||
|
require(size == item["size"], f"asset {item['name']} size mismatch")
|
||||||
|
digest, _ = client.asset(path, size)
|
||||||
|
require(digest == item["sha256"], f"asset {item['name']} digest mismatch")
|
||||||
|
return {"source_sha": source_sha, "index_sha256": index_digest,
|
||||||
|
"ci": evidence["ci"], "assets": records, "dependencies": dependencies}
|
||||||
|
|
||||||
|
|
||||||
|
def release_marker(repository, tag):
|
||||||
return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->"
|
return f"<!-- marqdo:release-reconcile repository={repository} tag={tag} -->"
|
||||||
|
|
||||||
|
|
||||||
def existing_issues(client: Gitea, label: str = LABEL) -> list[dict]:
|
def identity_marker(entry):
|
||||||
issues = client.get(
|
return f"<!-- marqdo:verified-release {entry['source_sha']} {entry['index_sha256']} -->"
|
||||||
f"/repos/{ROOT_REPOSITORY}/issues?state=all&limit=100&type=issues&labels={label}"
|
|
||||||
)
|
|
||||||
return issues if isinstance(issues, list) else []
|
|
||||||
|
|
||||||
|
|
||||||
def ensure_label(client: Gitea) -> int:
|
def consumer_inputs(entry, graph):
|
||||||
labels = client.get(f"/repos/{ROOT_REPOSITORY}/labels?limit=100")
|
release_key = hashlib.sha256(
|
||||||
for item in labels or []:
|
f"{entry['repository']}\n{entry['tag']}\n{entry['source_sha']}".encode()
|
||||||
if item.get("name") == LABEL:
|
).hexdigest()
|
||||||
return int(item["id"])
|
release = {key: entry[key] for key in ("repository", "tag", "source_sha", "index_sha256")}
|
||||||
created = client.post(
|
release["assets"] = sorted(entry["assets"], key=lambda asset: asset["name"])
|
||||||
f"/repos/{ROOT_REPOSITORY}/labels",
|
release["dependencies"] = sorted(entry["dependencies"], key=lambda dependency: dependency["id"])
|
||||||
{"name": LABEL, "color": "#bfd4f2", "description": "Release tracking created by reconcile"},
|
conflicts = [dependency["id"] for dependency in release["dependencies"]
|
||||||
)
|
if dependency["source_sha"] != graph[dependency["id"]]["sha"]]
|
||||||
return int(created["id"])
|
tasks = []
|
||||||
|
for consumer_id in entry["direct_consumers"]:
|
||||||
|
consumer = graph[consumer_id]
|
||||||
|
remote = REPOSITORY.fullmatch(consumer.get("remote") or "")
|
||||||
|
require(remote is not None and match(SHA, consumer.get("sha")),
|
||||||
|
f"{consumer_id}: consumer is missing its managed repository or accepted SHA")
|
||||||
|
inputs = {
|
||||||
|
"release": release,
|
||||||
|
"consumer": {"id": consumer_id, "source_sha": consumer["sha"]},
|
||||||
|
"accepted_dependencies": [
|
||||||
|
{"id": dep, "source_sha": graph[dep]["sha"]} for dep in sorted(consumer["requires"])
|
||||||
|
if dep != entry["component"]
|
||||||
|
],
|
||||||
|
}
|
||||||
|
digest = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
||||||
|
key = hashlib.sha256(f"{release_key}\n{consumer_id}\n{digest}".encode()).hexdigest()
|
||||||
|
tasks.append({"consumer": consumer_id, "repository": remote[1], "key": key, "digest": digest,
|
||||||
|
"baseline_sha": consumer["sha"], "inputs": inputs,
|
||||||
|
"status": "waiting-for-dependencies" if conflicts else "pending",
|
||||||
|
"different_dependencies": conflicts})
|
||||||
|
return release_key, tasks
|
||||||
|
|
||||||
|
|
||||||
def discover(client: Gitea, root: Path) -> list[dict]:
|
def tracking_body(entry):
|
||||||
entries = []
|
lines = [entry["marker"], f"## {entry['repository']} {entry['tag']}",
|
||||||
for key, repository in sorted(managed_repositories(root).items()):
|
"", f"- Component: {entry['component']} ({entry['path']})",
|
||||||
releases = client.get(f"/repos/{repository}/releases?limit=50")
|
f"- Published: {entry['published_at']}", f"- Accepted gitlink: {entry['accepted_sha']}",
|
||||||
for release in releases or []:
|
f"- Release: {FORGE}/{entry['repository']}/releases/tag/{entry['tag']}"]
|
||||||
if release.get("draft"):
|
if "error" in entry:
|
||||||
continue
|
return "\n".join(lines + ["", "## Blocked", "", f"- {entry['error']}"])
|
||||||
tag = release.get("tag_name")
|
return "\n".join(lines + ["", identity_marker(entry),
|
||||||
if not tag:
|
f"- Source SHA: {entry['source_sha']}", f"- Index SHA-256: {entry['index_sha256']}",
|
||||||
continue
|
f"- Component CI: {entry['ci']['url']}",
|
||||||
marker = release_marker(repository, tag)
|
"", "## Verified assets", "",
|
||||||
entries.append(
|
*(f"- {a['name']} ({a['target']}, {a['size']} bytes): {a['sha256']}" for a in entry["assets"]),
|
||||||
{
|
"", "## Pending consumer validation", "",
|
||||||
"component": key.split("@", 1)[0],
|
f"- Direct consumers: {', '.join(entry['direct_consumers']) or 'none'}",
|
||||||
"path": key.split("@", 1)[1],
|
*(f"- {task['consumer']} at {task['baseline_sha']}: {task['status']} (inputs {task['digest']})"
|
||||||
"repository": repository,
|
for task in entry["consumer_tasks"]),
|
||||||
"tag": tag,
|
f"- Affected: {', '.join(entry['affected']) or 'none'}",
|
||||||
"name": release.get("name") or tag,
|
f"- Governance owner: {entry['governance_owner']}"])
|
||||||
"prerelease": bool(release.get("prerelease")),
|
|
||||||
"url": release.get("html_url"),
|
|
||||||
"published_at": release.get("published_at") or release.get("created_at"),
|
def is_writer(record):
|
||||||
"marker": marker,
|
return (record.get("user") or {}).get("login") == RECONCILE_ACCOUNT
|
||||||
"assets": release.get("assets") or [],
|
|
||||||
|
|
||||||
|
def tracking_comments(client, issues_url, tracker):
|
||||||
|
if not is_writer(tracker):
|
||||||
|
return []
|
||||||
|
comments_url = f"{issues_url}/{tracker['number']}/comments"
|
||||||
|
return [comment.get("body") or "" for comment in pages(client, comments_url)
|
||||||
|
if is_writer(comment)]
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_tracking_note(client, issues_url, tracker, entry, comments):
|
||||||
|
if not is_writer(tracker):
|
||||||
|
entry["tracking_update"] = "tracker author differs from configured account"
|
||||||
|
return
|
||||||
|
note = tracking_body(entry)
|
||||||
|
if note not in comments and note != tracker.get("body"):
|
||||||
|
client.post(f"{issues_url}/{tracker['number']}/comments", {"body": note})
|
||||||
|
|
||||||
|
|
||||||
|
def verify_apply_context(client, root_sha):
|
||||||
|
writer = client.get("/user")
|
||||||
|
require(isinstance(writer, dict) and writer.get("login") == RECONCILE_ACCOUNT
|
||||||
|
and writer.get("is_admin") is False, "apply requires the non-admin reconcile account")
|
||||||
|
root = client.get(f"/repos/{ROOT_REPOSITORY}")
|
||||||
|
require(isinstance(root, dict) and root.get("default_branch") == "main",
|
||||||
|
"apply requires the root default branch")
|
||||||
|
verify_root_base(client, root_sha)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_root_base(client, root_sha):
|
||||||
|
branch = client.get(f"/repos/{ROOT_REPOSITORY}/branches/main")
|
||||||
|
require(isinstance(branch, dict) and branch.get("protected") is True
|
||||||
|
and (branch.get("commit") or {}).get("id") == root_sha,
|
||||||
|
"apply requires the current protected root commit")
|
||||||
|
|
||||||
|
|
||||||
|
def register_consumer_tasks(client, root_sha, entry, issue_cache):
|
||||||
|
for task in entry["consumer_tasks"]:
|
||||||
|
issues_url = f"/repos/{task['repository']}/issues"
|
||||||
|
marker = f"<!-- marqdo:upstream release={entry['release_key']} consumer={task['consumer']} -->"
|
||||||
|
body = "\n".join([
|
||||||
|
marker,
|
||||||
|
f"<!-- marqdo:candidate-inputs {task['key']} -->",
|
||||||
|
"",
|
||||||
|
f"- Root tracking issue: {FORGE}/{ROOT_REPOSITORY}/issues/{entry['issue']}",
|
||||||
|
f"- Root candidate: {root_sha}",
|
||||||
|
f"- Consumer baseline: {task['baseline_sha']}",
|
||||||
|
f"- Input digest: {task['digest']}",
|
||||||
|
f"- State: {task['status']}",
|
||||||
|
"",
|
||||||
|
"```json",
|
||||||
|
json.dumps(task["inputs"], ensure_ascii=False, sort_keys=True, indent=2),
|
||||||
|
"```",
|
||||||
|
])
|
||||||
|
try:
|
||||||
|
if issues_url not in issue_cache:
|
||||||
|
issue_cache[issues_url] = list(pages(client, issues_url, state="all", type="issues"))
|
||||||
|
issues = issue_cache[issues_url]
|
||||||
|
matches = [issue for issue in issues if is_writer(issue)
|
||||||
|
and (issue.get("body") or "").splitlines()[:1] == [marker]]
|
||||||
|
require(len(matches) <= 1, "multiple matching consumer tasks")
|
||||||
|
if matches:
|
||||||
|
issue = matches[0]
|
||||||
|
if issue["state"] == "open":
|
||||||
|
comments = tracking_comments(client, issues_url, issue)
|
||||||
|
key_line = f"<!-- marqdo:candidate-inputs {task['key']} -->"
|
||||||
|
baselines = [note.splitlines() for note in [issue["body"], *comments]
|
||||||
|
if note.splitlines()[:1] == [marker]]
|
||||||
|
if not {key_line, f"- Root candidate: {root_sha}"} <= set(baselines[-1]):
|
||||||
|
verify_root_base(client, root_sha)
|
||||||
|
client.post(f"{issues_url}/{issue['number']}/comments", {"body": body})
|
||||||
|
else:
|
||||||
|
task["registration"] = "closed"
|
||||||
|
else:
|
||||||
|
verify_root_base(client, root_sha)
|
||||||
|
issue = client.post(issues_url, {
|
||||||
|
"title": f"[upstream] {entry['component']} {entry['tag']} for {task['consumer']}",
|
||||||
|
"body": body,
|
||||||
|
})
|
||||||
|
issues.append(issue)
|
||||||
|
task["issue"] = issue["number"]
|
||||||
|
task.setdefault("registration", "recorded")
|
||||||
|
except ReconcileError as error:
|
||||||
|
task.update(registration="blocked", error=str(error))
|
||||||
|
|
||||||
|
|
||||||
|
def verify_dispatch_identity(client):
|
||||||
|
actor = client.dispatch_ci("/user")
|
||||||
|
require(isinstance(actor, dict) and actor.get("login") == RECONCILE_ACCOUNT
|
||||||
|
and not actor.get("admin") and not actor.get("admin_env"),
|
||||||
|
"dispatch requires the non-admin reconcile account in Woodpecker")
|
||||||
|
|
||||||
|
|
||||||
|
def dispatch_consumer(client, root_sha, task, published_at, can_start):
|
||||||
|
repo_id, forge_repo = ci_repository(client, task["repository"])
|
||||||
|
branch = forge_repo.get("default_branch")
|
||||||
|
require(match(BASENAME, branch), "consumer has an unsupported default branch name")
|
||||||
|
protected = client.get(f"/repos/{task['repository']}/branches/{branch}")
|
||||||
|
require(protected.get("protected") is True
|
||||||
|
and (protected.get("commit") or {}).get("id") == task["baseline_sha"],
|
||||||
|
"consumer default branch is unprotected or differs from the accepted gitlink")
|
||||||
|
ref = urllib.parse.urlencode({"ref": task["baseline_sha"]})
|
||||||
|
try:
|
||||||
|
config = client.get(f"/repos/{task['repository']}/contents/.woodpecker/upstream.yml?{ref}")
|
||||||
|
except ReconcileError as error:
|
||||||
|
if str(error).endswith(": HTTP 404"):
|
||||||
|
task["dispatch_status"] = "no-upstream-workflow"
|
||||||
|
return False
|
||||||
|
raise
|
||||||
|
require(config.get("type") == "file", "consumer upstream workflow is not a repository file")
|
||||||
|
|
||||||
|
api = f"/repos/{repo_id}"
|
||||||
|
permissions = client.dispatch_ci(f"{api}/permissions")
|
||||||
|
require(permissions.get("push") is True and permissions.get("admin") is False,
|
||||||
|
"dispatch needs project-level push permission without project admin")
|
||||||
|
require(type(task["issue"]) is int and task["issue"] > 0, "invalid consumer issue number")
|
||||||
|
key = hashlib.sha256(f"{root_sha}\n{task['key']}".encode()).hexdigest()
|
||||||
|
variables = {"MARQDO_UPSTREAM_ISSUE": str(task["issue"]), "MARQDO_UPSTREAM_TASK": key}
|
||||||
|
|
||||||
|
def corresponds(pipeline):
|
||||||
|
return (type(pipeline.get("number")) is int and pipeline["number"] > 0
|
||||||
|
and pipeline.get("event") == "manual" and pipeline.get("branch") == branch
|
||||||
|
and pipeline.get("selected_workflow") == "upstream"
|
||||||
|
and pipeline.get("author") == RECONCILE_ACCOUNT
|
||||||
|
and pipeline.get("commit") == task["baseline_sha"]
|
||||||
|
and pipeline.get("variables") == variables)
|
||||||
|
|
||||||
|
# Check Woodpecker's actual runs, including an accepted POST whose response
|
||||||
|
# was lost. A failed run remains evidence until the task inputs change.
|
||||||
|
pipelines = f"{api}/pipelines"
|
||||||
|
for page in range(1, MAX_PAGES + 1):
|
||||||
|
query = urllib.parse.urlencode(dict(event="manual", branch=branch, after=published_at,
|
||||||
|
page=page, perPage=PAGE_SIZE))
|
||||||
|
records = client.dispatch_ci(f"{pipelines}?{query}")
|
||||||
|
require(isinstance(records, list) and len(records) <= PAGE_SIZE, "invalid CI pipeline page")
|
||||||
|
existing = next((pipeline for pipeline in records if corresponds(pipeline)), None)
|
||||||
|
if existing or len(records) < PAGE_SIZE:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise ReconcileError("CI pipeline pagination limit reached")
|
||||||
|
started = False
|
||||||
|
if existing is None:
|
||||||
|
if not can_start:
|
||||||
|
task["dispatch_status"] = "queued-for-dispatch"
|
||||||
|
return False
|
||||||
|
verify_root_base(client, root_sha)
|
||||||
|
existing = client.dispatch_ci(pipelines, {"branch": branch, "workflow": "upstream",
|
||||||
|
"variables": variables})
|
||||||
|
require(isinstance(existing, dict) and corresponds(existing),
|
||||||
|
"dispatched pipeline differs from the intended consumer task")
|
||||||
|
started = True
|
||||||
|
task["dispatch_status"] = existing["status"]
|
||||||
|
task["pipeline"] = f"{CI}/repos/{repo_id}/pipeline/{existing['number']}"
|
||||||
|
return started
|
||||||
|
|
||||||
|
|
||||||
|
def reconcile(client, root=PROJECT_ROOT, apply=False, report_out=None, cutoff=None, dispatch=False):
|
||||||
|
root_sha, graph, managed = managed_repositories(root)
|
||||||
|
cutoff_time = timestamp(cutoff) if cutoff else None
|
||||||
|
issues_url = f"/repos/{ROOT_REPOSITORY}/issues"
|
||||||
|
issues = list(pages(client, issues_url, state="all", type="issues", labels=LABEL))
|
||||||
|
if apply:
|
||||||
|
verify_apply_context(client, root_sha)
|
||||||
|
dispatch_status, dispatch_error, starts = "disabled", None, 0
|
||||||
|
if apply and dispatch:
|
||||||
|
try:
|
||||||
|
verify_dispatch_identity(client)
|
||||||
|
dispatch_status = "enabled"
|
||||||
|
except ReconcileError as error:
|
||||||
|
dispatch_status, dispatch_error = "unavailable", str(error)
|
||||||
|
labels = f"/repos/{ROOT_REPOSITORY}/labels"
|
||||||
|
label_id = next((x["id"] for x in pages(client, labels) if x.get("name") == LABEL), None) if apply else None
|
||||||
|
results, errors, consumer_issues = [], {}, {}
|
||||||
|
for repository, component in managed.items():
|
||||||
|
known_tags = set()
|
||||||
|
try:
|
||||||
|
releases = list(pages(client, f"/repos/{repository}/releases"))
|
||||||
|
for release in releases:
|
||||||
|
if release.get("draft"):
|
||||||
|
continue
|
||||||
|
tag = release.get("tag_name")
|
||||||
|
require(match(TAG, tag), "invalid release tag in listing")
|
||||||
|
require(tag not in known_tags, f"duplicate release in paginated listing: {tag}")
|
||||||
|
known_tags.add(tag)
|
||||||
|
published = timestamp(release.get("published_at") or release.get("created_at"))
|
||||||
|
marker = release_marker(repository, tag)
|
||||||
|
trackers = [issue for issue in issues
|
||||||
|
if (issue.get("body") or "").splitlines()[:1] == [marker]]
|
||||||
|
if cutoff_time and published < cutoff_time and not trackers:
|
||||||
|
continue
|
||||||
|
entry = {
|
||||||
|
"component": component["id"], "path": component["path"], "repository": repository,
|
||||||
|
"tag": tag, "marker": marker, "published_at": published.isoformat(),
|
||||||
|
"accepted_sha": component["sha"],
|
||||||
|
"component_state": component["state"],
|
||||||
}
|
}
|
||||||
)
|
comments = tracking_comments(client, issues_url, trackers[0]) if len(trackers) == 1 else []
|
||||||
return entries
|
recorded = comments + ([trackers[0].get("body") or ""] if trackers and
|
||||||
|
is_writer(trackers[0]) else [])
|
||||||
|
try:
|
||||||
|
require(len(trackers) <= 1, "multiple release tracking Issues")
|
||||||
|
entry.update(verify_release(client, repository, component, tag, release, graph))
|
||||||
|
if entry.get("historical"):
|
||||||
|
entry["status"] = "historical-baseline"
|
||||||
|
else:
|
||||||
|
affected, domains, co_validation = impact.affected_set(
|
||||||
|
graph, graph, [{"id": component["id"]}])
|
||||||
|
direct = [cid for cid, item in graph.items()
|
||||||
|
if component["id"] in item["requires"]]
|
||||||
|
entry.update(status="pending", affected=affected, domains=domains,
|
||||||
|
checks_with=co_validation,
|
||||||
|
direct_consumers=sorted(cid for cid in direct if graph[cid]["state"] == "active"),
|
||||||
|
planned_consumers=sorted(cid for cid in direct if graph[cid]["state"] == "planned"),
|
||||||
|
governance_owner=component["parent"] or ROOT_REPOSITORY)
|
||||||
|
old = {line for body in recorded for line in body.splitlines()
|
||||||
|
if line.startswith("<!-- marqdo:verified-release ")}
|
||||||
|
require(not old or old == {identity_marker(entry)},
|
||||||
|
"published release identity or index digest changed")
|
||||||
|
entry["release_key"], entry["consumer_tasks"] = consumer_inputs(entry, graph)
|
||||||
|
except ApiUnavailable:
|
||||||
|
raise
|
||||||
|
except ReconcileError as error:
|
||||||
|
entry.update(status="blocked", error=str(error))
|
||||||
|
|
||||||
|
if trackers:
|
||||||
def published_after(entry: dict, cutoff: str | None) -> bool:
|
entry["issue"] = trackers[0]["number"]
|
||||||
if not cutoff:
|
if entry["status"] == "pending" and any(
|
||||||
return True
|
identity_marker(entry) in body.splitlines() for body in recorded):
|
||||||
published = entry.get("published_at")
|
entry["status"] = "tracked"
|
||||||
if not published:
|
if apply and len(trackers) == 1 and entry["status"] in {"pending", "tracked", "blocked"}:
|
||||||
return False
|
ensure_tracking_note(client, issues_url, trackers[0], entry, comments)
|
||||||
return published >= cutoff
|
elif apply and entry["status"] in {"pending", "blocked"}:
|
||||||
|
require(label_id is not None, f"tracking label {LABEL!r} is missing")
|
||||||
|
created = client.post(issues_url, {
|
||||||
def reconcile(
|
"title": f"[release] {repository} {tag}", "labels": [label_id],
|
||||||
client: Gitea,
|
"body": tracking_body(entry),
|
||||||
root: Path = PROJECT_ROOT,
|
})
|
||||||
apply: bool = False,
|
entry["issue"] = created["number"]
|
||||||
report_out: Path | None = None,
|
if entry["status"] == "pending":
|
||||||
cutoff: str | None = None,
|
entry["status"] = "created"
|
||||||
) -> dict:
|
if (apply and entry.get("consumer_tasks") and not entry.get("tracking_update")
|
||||||
entries = [entry for entry in discover(client, root) if published_after(entry, cutoff)]
|
and entry["status"] in {"created", "pending", "tracked"}
|
||||||
known = {issue.get("body") or "" for issue in existing_issues(client)}
|
and (not trackers or trackers[0]["state"] == "open")):
|
||||||
results = []
|
register_consumer_tasks(client, root_sha, entry, consumer_issues)
|
||||||
label_id = ensure_label(client) if apply else None
|
if dispatch_status == "enabled":
|
||||||
for entry in entries:
|
for task in entry["consumer_tasks"]:
|
||||||
marker = entry["marker"]
|
if task["status"] != "pending" or task["registration"] != "recorded":
|
||||||
if any(marker in body for body in known):
|
continue
|
||||||
results.append({**entry, "status": "tracked"})
|
try:
|
||||||
continue
|
starts += dispatch_consumer(client, root_sha, task, entry["published_at"],
|
||||||
if not apply:
|
can_start=starts < 4)
|
||||||
verified = []
|
except ReconcileError as error:
|
||||||
status = "pending"
|
task.update(dispatch_status="blocked", dispatch_error=str(error))
|
||||||
else:
|
results.append(entry)
|
||||||
try:
|
prefix = f"<!-- marqdo:release-reconcile repository={repository} tag="
|
||||||
verified = verify_assets(client, {"assets": entry["assets"]})
|
for issue in issues:
|
||||||
except ReconcileError as error:
|
marker = (issue.get("body") or "").partition("\n")[0]
|
||||||
results.append(
|
if marker.startswith(prefix) and marker.endswith(" -->"):
|
||||||
{**entry, "assets": [], "status": f"asset-verify-failed: {error}"}
|
tag = marker[len(prefix):-4]
|
||||||
)
|
if match(TAG, tag) and tag not in known_tags:
|
||||||
continue
|
error = "previously tracked release is absent from the public list"
|
||||||
status = "created"
|
entry = {"repository": repository, "component": component["id"],
|
||||||
body = render_issue(entry, verified)
|
"tag": tag, "issue": issue["number"], "status": "blocked",
|
||||||
try:
|
"error": error}
|
||||||
issue = client.post(
|
if apply and is_writer(issue):
|
||||||
f"/repos/{ROOT_REPOSITORY}/issues",
|
note = f"{marker}\n\n## Blocked\n\n- {error}"
|
||||||
{
|
if note not in tracking_comments(client, issues_url, issue):
|
||||||
"title": f"[release] {entry['repository']} {entry['tag']}",
|
client.post(f"{issues_url}/{issue['number']}/comments", {"body": note})
|
||||||
"body": body,
|
results.append(entry)
|
||||||
"labels": [label_id],
|
except ReconcileError as error:
|
||||||
},
|
errors[repository] = str(error)
|
||||||
)
|
|
||||||
if issue:
|
|
||||||
known.add(body)
|
|
||||||
entry = {**entry, "issue": issue.get("number")}
|
|
||||||
except ReconcileError as error:
|
|
||||||
status = f"issue-create-failed: {error}"
|
|
||||||
results.append({**entry, "assets": verified, "status": status})
|
|
||||||
report = {
|
report = {
|
||||||
"schema": "marqdo.release-reconcile.v1",
|
"schema": "marqdo.release-reconcile.v1", "schema_version": 1,
|
||||||
"schema_version": 1,
|
"root_repository": ROOT_REPOSITORY, "root_sha": root_sha,
|
||||||
"generated_at": __import__("datetime").datetime.now(
|
"apply": apply, "repositories": len(managed), "releases": len(results),
|
||||||
__import__("datetime").timezone.utc
|
"scan_complete": not errors, "scan_errors": errors, "results": results,
|
||||||
).isoformat(),
|
"dispatch_status": dispatch_status,
|
||||||
"apply": apply,
|
"counts": {status: sum(item["status"] == status for item in results)
|
||||||
"root_repository": ROOT_REPOSITORY,
|
for status in sorted({item["status"] for item in results})},
|
||||||
"repositories": len({entry["repository"] for entry in entries}),
|
"generated_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||||
"releases": len(entries),
|
|
||||||
"results": results,
|
|
||||||
"counts": {
|
|
||||||
status: sum(1 for item in results if item["status"] == status)
|
|
||||||
for status in sorted({item["status"] for item in results})
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
if dispatch_error:
|
||||||
|
report["dispatch_error"] = dispatch_error
|
||||||
if report_out:
|
if report_out:
|
||||||
report_out.parent.mkdir(parents=True, exist_ok=True)
|
report_out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
report_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
report_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
def render_issue(entry: dict, assets: list[dict]) -> str:
|
def main(argv):
|
||||||
lines = [
|
|
||||||
entry["marker"],
|
|
||||||
f"## Release: {entry['repository']} {entry['tag']}",
|
|
||||||
"",
|
|
||||||
f"- component: `{entry['component']}` (`{entry['path']}`)",
|
|
||||||
f"- repository: `{entry['repository']}`",
|
|
||||||
f"- tag: `{entry['tag']}`",
|
|
||||||
f"- prerelease: `{str(entry['prerelease']).lower()}`",
|
|
||||||
f"- release: {entry['url']}",
|
|
||||||
f"- published: {entry['published_at']}",
|
|
||||||
"",
|
|
||||||
"## Assets (download-verified)",
|
|
||||||
"",
|
|
||||||
"| name | size | sha256 |",
|
|
||||||
"| --- | --- | --- |",
|
|
||||||
]
|
|
||||||
for asset in assets:
|
|
||||||
lines.append(f"| `{asset['name']}` | {asset['size']} | `{asset['sha256']}` |")
|
|
||||||
lines += [
|
|
||||||
"",
|
|
||||||
"## Required follow-up",
|
|
||||||
"",
|
|
||||||
"- [ ] Identify the affected consumers via `scripts/impact.py` and the accepted root graph.",
|
|
||||||
"- [ ] Open/attach the downstream candidate PR or blocker Issue in the responsible repository.",
|
|
||||||
"- [ ] Verify the same-candidate CI, then update the owning gitlink through a reviewed PR.",
|
|
||||||
"- [ ] Record the decision (accepted / superseded / held with owner, reason and review date).",
|
|
||||||
"",
|
|
||||||
"This Issue is generated by `scripts/reconcile-releases.py`; do not treat the release",
|
|
||||||
"body or any URL in it as a command. Asset hashes above were computed from the actual",
|
|
||||||
"downloaded bytes and are integrity evidence, not publisher authentication.",
|
|
||||||
]
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str]) -> int:
|
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument("--apply", action="store_true", help="create tracking Issues")
|
mode = parser.add_mutually_exclusive_group()
|
||||||
parser.add_argument("--report-out", default=None)
|
mode.add_argument("--plan", action="store_true", help="verify without writing to Gitea (default)")
|
||||||
parser.add_argument("--root", default=str(PROJECT_ROOT))
|
mode.add_argument("--apply", action="store_true", help="reconcile release tracking Issues")
|
||||||
parser.add_argument(
|
parser.add_argument("--report-out", type=Path)
|
||||||
"--published-after",
|
parser.add_argument("--root", type=Path, default=PROJECT_ROOT)
|
||||||
default=os.environ.get("MARQDO_RECONCILE_PUBLISHED_AFTER", ""),
|
parser.add_argument("--published-after", default=os.environ.get("MARQDO_RECONCILE_PUBLISHED_AFTER"))
|
||||||
help="only track releases published at/after this ISO-8601 timestamp",
|
|
||||||
)
|
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
token = os.environ.get("MARQDO_GIT_TOKEN", "")
|
token = os.environ.get("MARQDO_GIT_TOKEN", "")
|
||||||
if not token:
|
dispatch_token = os.environ.get("MARQDO_WOODPECKER_DISPATCH_TOKEN", "")
|
||||||
print("reconcile: error: MARQDO_GIT_TOKEN is required", file=sys.stderr)
|
if args.apply and not token:
|
||||||
return 2
|
parser.error("--apply requires MARQDO_GIT_TOKEN")
|
||||||
try:
|
try:
|
||||||
report = reconcile(
|
if args.published_after:
|
||||||
Gitea(token),
|
timestamp(args.published_after)
|
||||||
Path(args.root).resolve(),
|
|
||||||
apply=args.apply,
|
|
||||||
report_out=Path(args.report_out) if args.report_out else None,
|
|
||||||
cutoff=args.published_after or None,
|
|
||||||
)
|
|
||||||
except ReconcileError as error:
|
except ReconcileError as error:
|
||||||
print(f"reconcile: error: {error}", file=sys.stderr)
|
parser.error(str(error))
|
||||||
return 2
|
try:
|
||||||
|
report = reconcile(Gitea(token, dispatch_token), args.root.resolve(), args.apply,
|
||||||
|
args.report_out, args.published_after, dispatch=bool(dispatch_token))
|
||||||
|
except (OSError, ReconcileError) as error:
|
||||||
|
print(f"reconcile: {error}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||||
failed = any(
|
return int(not report["scan_complete"] or any(
|
||||||
item["status"].startswith(("asset-verify-failed", "issue-create-failed"))
|
"tracking_update" in item
|
||||||
for item in report["results"]
|
or any(task.get("registration") == "blocked" or task.get("dispatch_status") == "blocked"
|
||||||
)
|
for task in item.get("consumer_tasks", []))
|
||||||
return 1 if failed else 0
|
for item in report["results"]))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -2,9 +2,8 @@
|
|||||||
|
|
||||||
Builds real temporary Git repositories for two root candidates and asserts the
|
Builds real temporary Git repositories for two root candidates and asserts the
|
||||||
ordering required by the development contract: changed leaves, reverse
|
ordering required by the development contract: changed leaves, reverse
|
||||||
`requires` closure over the union graph, parent domains, then `checks_with`
|
`requires` closure over the union graph, `checks_with` fixed point, then
|
||||||
fixed point; undetermined scope widens to the full candidate instead of being
|
parent domains. Undetermined scope widens to the full candidate.
|
||||||
skipped.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import importlib.util
|
import importlib.util
|
||||||
@@ -207,6 +206,19 @@ class ImpactTest(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertIn("std-text", report["affected"])
|
self.assertIn("std-text", report["affected"])
|
||||||
|
|
||||||
|
def test_removed_requires_edge_remains_in_the_impact_scope(self):
|
||||||
|
leaves = self.leaf_shas()
|
||||||
|
first = self.make_tree(COMPONENTS_V1, leaves)
|
||||||
|
without_dependency = COMPONENTS_V1.replace(
|
||||||
|
'requires = ["cli", "std-core"]', 'requires = ["cli"]'
|
||||||
|
)
|
||||||
|
second = self.make_tree(without_dependency, leaves)
|
||||||
|
before, _ = impact.load_graph(self.root, first, "before")
|
||||||
|
after, _ = impact.load_graph(self.root, second, "after")
|
||||||
|
affected, _, partners = impact.affected_set(before, after, [{"id": "std-core"}])
|
||||||
|
self.assertIn("std-text", affected)
|
||||||
|
self.assertIn("probe", partners)
|
||||||
|
|
||||||
def test_domain_gitlink_change_expands_to_child_identity(self):
|
def test_domain_gitlink_change_expands_to_child_identity(self):
|
||||||
child = init(self.root / "extensions/web")
|
child = init(self.root / "extensions/web")
|
||||||
write(child / "components.toml", catalog(
|
write(child / "components.toml", catalog(
|
||||||
|
|||||||
@@ -105,6 +105,24 @@ checks_with = ["web-preview"]
|
|||||||
release = "optional"
|
release = "optional"
|
||||||
'''
|
'''
|
||||||
|
|
||||||
|
APP = '''
|
||||||
|
[[component]]
|
||||||
|
id = "app-harness"
|
||||||
|
path = "apps/harness"
|
||||||
|
kind = "app"
|
||||||
|
state = "planned"
|
||||||
|
owner = "maintainer"
|
||||||
|
scope = "official single-user agent application"
|
||||||
|
requires = ["cli"]
|
||||||
|
checks_with = []
|
||||||
|
release = "optional"
|
||||||
|
'''
|
||||||
|
|
||||||
|
APP_ACTIVE = APP.replace('state = "planned"', 'state = "active"').replace(
|
||||||
|
'release = "optional"', 'release = "optional"\nentry = "scripts/ci.sh"')
|
||||||
|
|
||||||
|
APP_URL = "https://git.cflmy.cn/cflmy/marqdo-app-harness.git"
|
||||||
|
|
||||||
|
|
||||||
def catalog(*blocks):
|
def catalog(*blocks):
|
||||||
return "".join(blocks)
|
return "".join(blocks)
|
||||||
@@ -185,6 +203,119 @@ class LayoutTests(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(ValueError, "invalid submodule URL"):
|
with self.assertRaisesRegex(ValueError, "invalid submodule URL"):
|
||||||
layout.validate("HEAD", False)
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def root_fixture(self, metadata, modules, links, files=None):
|
||||||
|
(self.root / "components.toml").write_text(metadata)
|
||||||
|
if 'id = "cli"' in metadata and "path = cli" not in modules:
|
||||||
|
modules += f'[submodule "cli"]\npath = cli\nurl = {CORE_URL}\n'
|
||||||
|
if 'id = "cli"' in metadata and "cli" not in links:
|
||||||
|
links = {**links, "cli": self.sha}
|
||||||
|
(self.root / ".gitmodules").write_text(modules)
|
||||||
|
for relative, content in (files or {}).items():
|
||||||
|
path = self.root / relative
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(content)
|
||||||
|
self.git("add", "-A")
|
||||||
|
for path, sha in links.items():
|
||||||
|
self.git("update-index", "--add", "--cacheinfo", f"160000,{sha},{path}")
|
||||||
|
self.git("-c", "user.name=Test", "-c", "user.email=test@example.invalid",
|
||||||
|
"commit", "-qm", "app fixture")
|
||||||
|
|
||||||
|
def test_accepts_a_planned_app_gitlink(self):
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP,
|
||||||
|
f'[submodule "cli"]\npath = cli\nurl = {CORE_URL}\n'
|
||||||
|
f'[submodule "apps/harness"]\npath = apps/harness\nurl = {APP_URL}\n',
|
||||||
|
{"cli": self.sha, "apps/harness": self.sha})
|
||||||
|
root = layout.validate("HEAD", False)[0]
|
||||||
|
self.assertEqual(root.linked["apps/harness"]["kind"], "app")
|
||||||
|
self.assertEqual(root.linked["apps/harness"]["state"], "planned")
|
||||||
|
|
||||||
|
def test_rejects_an_app_outside_the_apps_path(self):
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP.replace('path = "apps/harness"', 'path = "apps/other"'),
|
||||||
|
f'[submodule "other"]\npath = apps/other\nurl = {APP_URL}\n',
|
||||||
|
{"apps/other": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "invalid path: app-harness: apps/other"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_an_app_id_without_the_app_prefix(self):
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP.replace('id = "app-harness"', 'id = "harness"'),
|
||||||
|
f'[submodule "harness"]\npath = apps/harness\nurl = {APP_URL}\n',
|
||||||
|
{"apps/harness": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "app id must start with 'app-'"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_a_wrong_app_remote(self):
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP,
|
||||||
|
f'[submodule "harness"]\npath = apps/harness\nurl = '
|
||||||
|
f'https://git.cflmy.cn/cflmy/marqdo-harness.git\n',
|
||||||
|
{"apps/harness": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "invalid submodule URL: apps/harness"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_an_app_with_a_base_release_role(self):
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP.replace('release = "optional"', 'release = "base"'),
|
||||||
|
f'[submodule "harness"]\npath = apps/harness\nurl = {APP_URL}\n',
|
||||||
|
{"apps/harness": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "invalid release role: app-harness"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_an_app_dependency_on_a_domain(self):
|
||||||
|
domain = WEB_DOMAIN.replace('state = "active"', 'state = "planned"').replace(
|
||||||
|
'entry = "scripts/integration.sh"\n', '')
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + domain + APP.replace('requires = ["cli"]', 'requires = ["cli", "web"]'),
|
||||||
|
f'[submodule "harness"]\npath = apps/harness\nurl = {APP_URL}\n',
|
||||||
|
{"apps/harness": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "requires must not target a domain: app-harness -> web"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_an_app_dependency_on_another_app(self):
|
||||||
|
second = APP.replace('id = "app-harness"', 'id = "app-other"').replace(
|
||||||
|
'path = "apps/harness"', 'path = "apps/other"').replace(
|
||||||
|
'requires = ["cli"]', 'requires = ["cli", "app-harness"]')
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP + second,
|
||||||
|
f'[submodule "harness"]\npath = apps/harness\nurl = {APP_URL}\n'
|
||||||
|
f'[submodule "other"]\npath = apps/other\nurl = '
|
||||||
|
f'https://git.cflmy.cn/cflmy/marqdo-app-other.git\n',
|
||||||
|
{"apps/harness": self.sha, "apps/other": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "app components cannot be dependencies: app-other -> app-harness"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_a_component_dependency_on_an_app(self):
|
||||||
|
view = '''
|
||||||
|
[[component]]
|
||||||
|
id = "view"
|
||||||
|
path = "tools/view"
|
||||||
|
kind = "tool"
|
||||||
|
state = "active"
|
||||||
|
owner = "maintainer"
|
||||||
|
scope = "read and observe"
|
||||||
|
requires = ["cli", "app-harness"]
|
||||||
|
checks_with = []
|
||||||
|
release = "optional"
|
||||||
|
entry = "scripts/acceptance.sh"
|
||||||
|
'''
|
||||||
|
self.root_fixture(
|
||||||
|
CLI + APP_ACTIVE + view,
|
||||||
|
f'[submodule "cli"]\npath = cli\nurl = {CORE_URL}\n'
|
||||||
|
f'[submodule "harness"]\npath = apps/harness\nurl = {APP_URL}\n'
|
||||||
|
f'[submodule "view"]\npath = tools/view\nurl = https://git.cflmy.cn/cflmy/marqdo-view.git\n',
|
||||||
|
{"cli": self.sha, "apps/harness": self.sha, "tools/view": self.sha})
|
||||||
|
with self.assertRaisesRegex(ValueError, "app components cannot be dependencies: view -> app-harness"):
|
||||||
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_rejects_an_app_inside_a_domain(self):
|
||||||
|
nested = {"id": "app-nested", "path": "harness", "kind": "app", "state": "planned",
|
||||||
|
"owner": "maintainer", "scope": "nested", "requires": [], "checks_with": [],
|
||||||
|
"release": "optional"}
|
||||||
|
with self.assertRaisesRegex(ValueError, "app kind is only allowed at the root layer"):
|
||||||
|
layout.check_component(nested, 1, "fixture domain", {}, set(), set())
|
||||||
|
|
||||||
def test_rejects_unstaged_checkout(self):
|
def test_rejects_unstaged_checkout(self):
|
||||||
self.candidate()
|
self.candidate()
|
||||||
with self.assertRaisesRegex(ValueError, "missing submodule checkout"):
|
with self.assertRaisesRegex(ValueError, "missing submodule checkout"):
|
||||||
@@ -334,6 +465,27 @@ class HierarchicalLayoutTests(unittest.TestCase):
|
|||||||
layout.validate("HEAD", True)
|
layout.validate("HEAD", True)
|
||||||
layout.validate("HEAD", False)
|
layout.validate("HEAD", False)
|
||||||
|
|
||||||
|
def test_active_entries_use_the_dependency_order_and_include_a_new_leaf(self):
|
||||||
|
design = self.leaf("design")
|
||||||
|
catalog_text = DOMAIN.replace('state = "planned"', 'state = "active"').replace(
|
||||||
|
'checks_with = ["web-preview"]\nrelease = "optional"',
|
||||||
|
'checks_with = ["web-preview"]\nrelease = "optional"\nentry = "scripts/ci.sh"',
|
||||||
|
)
|
||||||
|
self.assemble(domain_catalog=catalog_text, design=design,
|
||||||
|
extra_domain_link=("components", design[1]), domain_modules={
|
||||||
|
"design": "https://git.cflmy.cn/cflmy/marqdo-web-design.git",
|
||||||
|
"preview": "https://git.cflmy.cn/cflmy/marqdo-web-preview.git",
|
||||||
|
"components": "https://git.cflmy.cn/cflmy/marqdo-web-components.git",
|
||||||
|
})
|
||||||
|
layers = layout.validate("HEAD", True)
|
||||||
|
entries = list(layout.active_entries(layers))
|
||||||
|
ids = [entry[0] for entry in entries]
|
||||||
|
self.assertIn(("web-components", "extension", "extensions/web/components", "scripts/ci.sh"), entries)
|
||||||
|
self.assertLess(ids.index("cli"), ids.index("web-design"))
|
||||||
|
self.assertLess(ids.index("web-design"), ids.index("web-preview"))
|
||||||
|
self.assertLess(ids.index("web-components"), ids.index("web"))
|
||||||
|
self.assertEqual(set(ids), {"cli", "web", "web-design", "web-preview", "web-components"})
|
||||||
|
|
||||||
def test_accepts_a_planned_domain_and_planned_child_gitlinks(self):
|
def test_accepts_a_planned_domain_and_planned_child_gitlinks(self):
|
||||||
web = WEB_DOMAIN.replace('state = "active"', 'state = "planned"').replace(
|
web = WEB_DOMAIN.replace('state = "active"', 'state = "planned"').replace(
|
||||||
'entry = "scripts/integration.sh"\n', '')
|
'entry = "scripts/integration.sh"\n', '')
|
||||||
@@ -416,6 +568,63 @@ entry = "scripts/acceptance.sh"
|
|||||||
with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\) leaf web-design \(design\): leaf must not register gitlinks"):
|
with self.assertRaisesRegex(ValueError, r"domain web \(extensions/web\) leaf web-design \(design\): leaf must not register gitlinks"):
|
||||||
layout.validate("HEAD", True)
|
layout.validate("HEAD", True)
|
||||||
|
|
||||||
|
def test_accepts_an_active_app_leaf_checkout(self):
|
||||||
|
core = self.leaf("core", entry="scripts/test.sh")
|
||||||
|
app = self.leaf("harness")
|
||||||
|
self.root_repo(catalog(CLI, APP_ACTIVE), {"cli": core[1], "apps/harness": app[1]},
|
||||||
|
{"cli": CORE_URL, "apps/harness": APP_URL})
|
||||||
|
self.clone(core[0], self.root / "cli", core[1])
|
||||||
|
self.clone(app[0], self.root / "apps/harness", app[1])
|
||||||
|
layers = layout.validate("HEAD", True)
|
||||||
|
self.assertEqual(layers[0].linked["apps/harness"]["kind"], "app")
|
||||||
|
entries = list(layout.active_entries(layers))
|
||||||
|
self.assertIn(("app-harness", "app", "apps/harness", "scripts/ci.sh"), entries)
|
||||||
|
ids = [entry[0] for entry in entries]
|
||||||
|
self.assertLess(ids.index("cli"), ids.index("app-harness"))
|
||||||
|
|
||||||
|
def test_rejects_an_app_with_a_nested_gitlink(self):
|
||||||
|
core = self.leaf("core", entry="scripts/test.sh")
|
||||||
|
app = self.leaf_with_gitlink("harness")
|
||||||
|
self.root_repo(catalog(CLI, APP_ACTIVE), {"cli": core[1], "apps/harness": app[1]},
|
||||||
|
{"cli": CORE_URL, "apps/harness": APP_URL})
|
||||||
|
self.clone(core[0], self.root / "cli", core[1])
|
||||||
|
self.clone(app[0], self.root / "apps/harness", app[1])
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValueError, r"leaf app-harness \(apps/harness\): leaf must not register gitlinks"):
|
||||||
|
layout.validate("HEAD", True)
|
||||||
|
|
||||||
|
def test_rejects_an_app_registered_by_a_domain_catalog(self):
|
||||||
|
nested = '''
|
||||||
|
[[component]]
|
||||||
|
id = "app-nested"
|
||||||
|
path = "nested-app"
|
||||||
|
kind = "app"
|
||||||
|
state = "planned"
|
||||||
|
owner = "maintainer"
|
||||||
|
scope = "not allowed inside a domain"
|
||||||
|
requires = []
|
||||||
|
checks_with = []
|
||||||
|
release = "optional"
|
||||||
|
'''
|
||||||
|
core = self.leaf("core", entry="scripts/test.sh")
|
||||||
|
design = self.leaf("design")
|
||||||
|
preview = self.leaf("preview")
|
||||||
|
nested_leaf = self.leaf("nested-app")
|
||||||
|
domain_repo, domain_sha = self.domain(
|
||||||
|
DOMAIN + nested,
|
||||||
|
{"design": design[1], "preview": preview[1], "nested-app": nested_leaf[1]},
|
||||||
|
modules={
|
||||||
|
"design": "https://git.cflmy.cn/cflmy/marqdo-web-design.git",
|
||||||
|
"preview": "https://git.cflmy.cn/cflmy/marqdo-web-preview.git",
|
||||||
|
"nested-app": APP_URL,
|
||||||
|
})
|
||||||
|
self.root_repo(catalog(CLI, WEB_DOMAIN), {"cli": core[1], "extensions/web": domain_sha},
|
||||||
|
{"cli": CORE_URL,
|
||||||
|
"extensions/web": "https://git.cflmy.cn/cflmy/marqdo-ext-web.git"})
|
||||||
|
self.clone(domain_repo, self.root / "extensions/web", domain_sha)
|
||||||
|
with self.assertRaisesRegex(ValueError, "app kind is only allowed at the root layer: app-nested"):
|
||||||
|
layout.validate("HEAD", False, expand_domains=True)
|
||||||
|
|
||||||
# -- catalog and layer failures ----------------------------------------
|
# -- catalog and layer failures ----------------------------------------
|
||||||
|
|
||||||
def test_rejects_a_missing_domain_catalog(self):
|
def test_rejects_a_missing_domain_catalog(self):
|
||||||
|
|||||||
@@ -1,131 +1,379 @@
|
|||||||
"""Release reconcile discovery/idempotency tests (issue #10 §6/§7)."""
|
"""Release reconciliation tests for marqdo#10."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
import importlib.util
|
import importlib.util
|
||||||
|
import io
|
||||||
import json
|
import json
|
||||||
import tempfile
|
import os
|
||||||
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
|
from contextlib import redirect_stdout
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
from urllib.parse import parse_qs, urlsplit
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[2]
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
SPEC = importlib.util.spec_from_file_location(
|
SPEC = importlib.util.spec_from_file_location(
|
||||||
"reconcile_releases", ROOT / "scripts" / "reconcile-releases.py"
|
"reconcile_releases", ROOT / "scripts" / "reconcile-releases.py"
|
||||||
)
|
)
|
||||||
reconcile = importlib.util.module_from_spec(SPEC)
|
reconcile = importlib.util.module_from_spec(SPEC)
|
||||||
SPEC.loader.exec_module(reconcile)
|
with patch.object(sys, "path", [str(ROOT / "scripts"), *sys.path]):
|
||||||
|
SPEC.loader.exec_module(reconcile)
|
||||||
|
|
||||||
|
REPO = "cflmy/marqdo-std-text"
|
||||||
|
SOURCE = "a" * 40
|
||||||
|
BASE = "b" * 40
|
||||||
|
TAG = "v0.1.0-rc.1"
|
||||||
|
PUBLISHED = "2026-11-27T08:00:00+08:00"
|
||||||
|
ASSET = "text-source.tar.gz"
|
||||||
|
ISSUES = "/repos/cflmy/marqdo/issues"
|
||||||
|
CONSUMER_ISSUES = "/repos/cflmy/marqdo-ext-archive/issues"
|
||||||
|
FORGE = reconcile.FORGE
|
||||||
|
ACTOR = {"login": reconcile.RECONCILE_ACCOUNT}
|
||||||
|
COMPONENT = {"id": "std-text", "sha": BASE, "path": "stdlib/text",
|
||||||
|
"parent": None, "requires": [], "checks_with": [], "state": "active"}
|
||||||
|
|
||||||
|
|
||||||
class FakeGitea:
|
class FakeForge:
|
||||||
def __init__(self, releases=None, assets=None, issues=None):
|
def __init__(self):
|
||||||
self.releases = releases or {}
|
self.writes = []
|
||||||
self.asset_bytes = assets or {}
|
self.issues = []
|
||||||
self.issues = list(issues or [])
|
self.consumer_issues = []
|
||||||
self.posts = []
|
self.comments = {}
|
||||||
self.label_created = False
|
self.pages = []
|
||||||
|
self.pipeline_reads = []
|
||||||
|
self.downloads = []
|
||||||
|
self.blobs = {ASSET: b"abc"}
|
||||||
|
self.evidence = {
|
||||||
|
"repository": REPO, "component_id": COMPONENT["id"], "tag": TAG, "source_sha": SOURCE,
|
||||||
|
"ci": {"pipeline_number": 12, "source_sha": SOURCE,
|
||||||
|
"url": f"{reconcile.CI}/repos/8/pipeline/12"},
|
||||||
|
"assets": [{"name": ASSET, "size": 3, "target": "source",
|
||||||
|
"sha256": hashlib.sha256(self.blobs[ASSET]).hexdigest()}],
|
||||||
|
"dependencies": [],
|
||||||
|
}
|
||||||
|
self.release = {"tag_name": TAG, "draft": False, "prerelease": True,
|
||||||
|
"published_at": PUBLISHED}
|
||||||
|
self.releases = [self.release]
|
||||||
|
self.protected = True
|
||||||
|
self.root_sha = BASE
|
||||||
|
self.tag_sha = SOURCE
|
||||||
|
self.pipeline_sha = SOURCE
|
||||||
|
self.wrong_account = False
|
||||||
|
self.fail_page = None
|
||||||
|
self.refresh_assets()
|
||||||
|
|
||||||
def get(self, path):
|
def refresh_assets(self):
|
||||||
if path.startswith("/repos/") and path.endswith("/labels?limit=100"):
|
self.blobs[reconcile.INDEX] = json.dumps(self.evidence).encode()
|
||||||
return [{"id": 5, "name": reconcile.LABEL}] if self.label_created else []
|
self.release["assets"] = [
|
||||||
if "/issues?" in path:
|
{"name": name, "size": len(blob),
|
||||||
return self.issues
|
"browser_download_url": f"{FORGE}/{REPO}/releases/download/{TAG}/{name}"}
|
||||||
for repository, releases in self.releases.items():
|
for name, blob in self.blobs.items()
|
||||||
if path == f"/repos/{repository}/releases?limit=50":
|
]
|
||||||
return releases
|
|
||||||
return []
|
def get(self, url):
|
||||||
|
parsed = urlsplit(url)
|
||||||
|
path = parsed.path
|
||||||
|
query = parse_qs(parsed.query)
|
||||||
|
if query:
|
||||||
|
page = int(query["page"][0])
|
||||||
|
self.pages.append((path, page))
|
||||||
|
if path.endswith("/releases") and page == self.fail_page:
|
||||||
|
raise reconcile.ReconcileError("API HTTP 503")
|
||||||
|
records = {
|
||||||
|
f"/repos/{REPO}/releases": self.releases,
|
||||||
|
ISSUES: self.issues,
|
||||||
|
CONSUMER_ISSUES: self.consumer_issues,
|
||||||
|
"/repos/cflmy/marqdo/labels": [{"id": 5, "name": reconcile.LABEL}],
|
||||||
|
**self.comments,
|
||||||
|
}.get(path, [])
|
||||||
|
return records[(page - 1) * reconcile.PAGE_SIZE: page * reconcile.PAGE_SIZE]
|
||||||
|
|
||||||
|
return {
|
||||||
|
f"/repos/{REPO}": {"id": 10},
|
||||||
|
f"/repos/{REPO}/tags/{TAG}": {"name": TAG, "commit": {"sha": self.tag_sha}},
|
||||||
|
"/repos/cflmy/marqdo": {"default_branch": "main"},
|
||||||
|
"/repos/cflmy/marqdo/branches/main": {"protected": self.protected,
|
||||||
|
"commit": {"id": self.root_sha}},
|
||||||
|
"/user": ({"login": "admin", "is_admin": True} if self.wrong_account
|
||||||
|
else {**ACTOR, "is_admin": False}),
|
||||||
|
}[path]
|
||||||
|
|
||||||
|
def ci(self, path):
|
||||||
|
self.pipeline_reads.append(path)
|
||||||
|
if path == f"/repos/lookup/{REPO}":
|
||||||
|
return {"id": 8, "full_name": REPO, "forge_remote_id": "10"}
|
||||||
|
if path == "/repos/8/pipelines/12":
|
||||||
|
return {"number": 12, "commit": self.pipeline_sha, "status": "success", "event": "push",
|
||||||
|
"workflows": [{"name": "ci", "state": "success",
|
||||||
|
"children": [{"type": "commands", "state": "success"}]}]}
|
||||||
|
raise AssertionError(path)
|
||||||
|
|
||||||
|
def asset(self, path, size, *, index=False):
|
||||||
|
self.downloads.append(path)
|
||||||
|
data = self.blobs[path.rsplit("/", 1)[1]]
|
||||||
|
if len(data) != size:
|
||||||
|
raise reconcile.ReconcileError("asset size mismatch")
|
||||||
|
return hashlib.sha256(data).hexdigest(), data if index else b""
|
||||||
|
|
||||||
def post(self, path, data):
|
def post(self, path, data):
|
||||||
self.posts.append((path, data))
|
self.writes.append((path, data))
|
||||||
if path.endswith("/labels"):
|
item = {"body": data["body"], "user": ACTOR, "state": "open"}
|
||||||
self.label_created = True
|
if path in {ISSUES, CONSUMER_ISSUES}:
|
||||||
return {"id": 5, "name": data["name"]}
|
issues = self.issues if path == ISSUES else self.consumer_issues
|
||||||
if path.endswith("/issues"):
|
item["number"] = 100 + len(issues)
|
||||||
issue = {"number": 100 + len(self.issues), "body": data["body"], "title": data["title"]}
|
issues.append(item)
|
||||||
self.issues.append(issue)
|
else:
|
||||||
return issue
|
self.comments.setdefault(path, []).append(item)
|
||||||
return {}
|
return item
|
||||||
|
|
||||||
def download(self, url):
|
|
||||||
data = self.asset_bytes.get(url)
|
|
||||||
if data is None:
|
|
||||||
raise AssertionError(f"unexpected asset download {url}")
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def release(repository="cflmy/marqdo-cli", tag="v0.0.1", asset_url="https://example.invalid/a.tar.gz", draft=False):
|
|
||||||
return {
|
|
||||||
"tag_name": tag,
|
|
||||||
"name": tag,
|
|
||||||
"draft": draft,
|
|
||||||
"prerelease": True,
|
|
||||||
"html_url": f"https://git.cflmy.cn/{repository}/releases/tag/{tag}",
|
|
||||||
"published_at": "2026-11-27T00:00:00Z",
|
|
||||||
"assets": [{"name": "a.tar.gz", "size": 3, "browser_download_url": asset_url}],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class ReconcileTest(unittest.TestCase):
|
class ReconcileTest(unittest.TestCase):
|
||||||
def test_dry_run_discovers_releases_without_writing(self):
|
def setUp(self):
|
||||||
client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
|
graph = {COMPONENT["id"]: COMPONENT}
|
||||||
report = reconcile.reconcile(client, ROOT, apply=False)
|
catalog = (BASE, graph, {REPO: COMPONENT})
|
||||||
self.assertFalse(client.posts)
|
mocked = patch.object(reconcile, "managed_repositories", return_value=catalog)
|
||||||
self.assertGreaterEqual(report["releases"], 1)
|
mocked.start()
|
||||||
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
|
self.addCleanup(mocked.stop)
|
||||||
|
self.forge = FakeForge()
|
||||||
|
|
||||||
|
def run_scan(self, **kwargs):
|
||||||
|
return reconcile.reconcile(self.forge, **kwargs)
|
||||||
|
|
||||||
|
def test_native_dispatch_reuses_a_run_for_the_same_task_and_root(self):
|
||||||
|
task = {"repository": REPO, "baseline_sha": BASE, "issue": 42, "key": "c" * 64}
|
||||||
|
routes = {
|
||||||
|
f"/repos/{REPO}/branches/master": {"protected": True, "commit": {"id": BASE}},
|
||||||
|
f"/repos/{REPO}/contents/.woodpecker/upstream.yml?ref={BASE}": {"type": "file"},
|
||||||
|
"/repos/cflmy/marqdo/branches/main": {"protected": True, "commit": {"id": BASE}},
|
||||||
|
}
|
||||||
|
runs = []
|
||||||
|
posts = []
|
||||||
|
|
||||||
|
def dispatch(path, data=None):
|
||||||
|
if path == "/repos/8/permissions":
|
||||||
|
return {"push": True, "admin": False}
|
||||||
|
if data is None:
|
||||||
|
self.assertTrue(path.startswith("/repos/8/pipelines?"))
|
||||||
|
return runs
|
||||||
|
self.assertEqual(path, "/repos/8/pipelines")
|
||||||
|
self.assertEqual(data["branch"], "master")
|
||||||
|
self.assertEqual(data["workflow"], "upstream")
|
||||||
|
self.assertEqual(data["variables"]["MARQDO_UPSTREAM_ISSUE"], "42")
|
||||||
|
posts.append(data)
|
||||||
|
runs.append({"number": 15, "status": "pending", "author": ACTOR["login"],
|
||||||
|
"event": "manual", "branch": data["branch"], "commit": BASE,
|
||||||
|
"selected_workflow": data["workflow"], "variables": data["variables"]})
|
||||||
|
return runs[-1]
|
||||||
|
|
||||||
|
with (patch.object(reconcile, "ci_repository", return_value=(8, {"default_branch": "master"})),
|
||||||
|
patch.object(self.forge, "get", side_effect=routes.__getitem__),
|
||||||
|
patch.object(self.forge, "dispatch_ci", side_effect=dispatch, create=True)):
|
||||||
|
self.assertTrue(reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True))
|
||||||
|
self.assertFalse(reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True))
|
||||||
|
self.assertEqual(task["pipeline"], f"{reconcile.CI}/repos/8/pipeline/15")
|
||||||
|
self.assertEqual(len(posts), 1)
|
||||||
|
routes[f"/repos/{REPO}/branches/master"]["protected"] = False
|
||||||
|
with self.assertRaisesRegex(reconcile.ReconcileError, "unprotected"):
|
||||||
|
reconcile.dispatch_consumer(self.forge, BASE, task, PUBLISHED, True)
|
||||||
|
self.assertEqual(len(posts), 1)
|
||||||
|
|
||||||
|
def test_dispatch_rejects_owner_or_admin_identity_before_writing_to_ci(self):
|
||||||
|
for identity in ({"login": "cflmy"}, {**ACTOR, "admin": True}):
|
||||||
|
with patch.object(self.forge, "dispatch_ci", return_value=identity, create=True) as ci:
|
||||||
|
report = self.run_scan(apply=True, dispatch=True)
|
||||||
|
ci.assert_called_once_with("/user")
|
||||||
|
self.assertTrue(report["scan_complete"])
|
||||||
|
self.assertEqual(report["dispatch_status"], "unavailable")
|
||||||
|
|
||||||
|
def test_unavailable_dispatch_does_not_fail_a_complete_scan(self):
|
||||||
|
with (patch.dict(os.environ, {"MARQDO_GIT_TOKEN": "fixture",
|
||||||
|
"MARQDO_WOODPECKER_DISPATCH_TOKEN": "fixture"}),
|
||||||
|
patch.object(reconcile, "Gitea", return_value=self.forge),
|
||||||
|
patch.object(self.forge, "dispatch_ci", return_value={"login": "cflmy"}, create=True),
|
||||||
|
redirect_stdout(io.StringIO()) as stdout):
|
||||||
|
result = reconcile.main(["--apply"])
|
||||||
|
self.assertEqual(result, 0)
|
||||||
|
report = json.loads(stdout.getvalue())
|
||||||
|
self.assertTrue(report["scan_complete"])
|
||||||
|
self.assertEqual(report["dispatch_status"], "unavailable")
|
||||||
|
self.assertIn("non-admin reconcile account", report["dispatch_error"])
|
||||||
|
|
||||||
|
def test_dry_run_fully_verifies_without_writing(self):
|
||||||
|
report = self.run_scan()
|
||||||
|
self.assertEqual(self.forge.writes, [])
|
||||||
|
entry, = report["results"]
|
||||||
self.assertEqual(entry["status"], "pending")
|
self.assertEqual(entry["status"], "pending")
|
||||||
self.assertEqual(entry["tag"], "v0.0.1")
|
self.assertEqual(entry["source_sha"], SOURCE)
|
||||||
|
self.assertEqual(entry["governance_owner"], "cflmy/marqdo")
|
||||||
|
self.assertEqual(len(self.forge.downloads), 2)
|
||||||
|
self.assertEqual(len(self.forge.pipeline_reads), 2)
|
||||||
|
|
||||||
def test_apply_verifies_assets_and_creates_marked_issue(self):
|
def test_consumer_inputs_are_tied_to_assets_dependencies_and_accepted_sha(self):
|
||||||
client = FakeGitea(
|
consumer = {"id": "archive", "state": "active", "sha": "c" * 40,
|
||||||
releases={"cflmy/marqdo-cli": [release()]},
|
"remote": FORGE + "/cflmy/marqdo-ext-archive.git",
|
||||||
assets={"https://example.invalid/a.tar.gz": b"abc"},
|
"requires": ["std-text", "cli"], "checks_with": []}
|
||||||
)
|
cli = {"id": "cli", "state": "active", "sha": "d" * 40,
|
||||||
report = reconcile.reconcile(client, ROOT, apply=True)
|
"requires": [], "checks_with": []}
|
||||||
created = [data for path, data in client.posts if path.endswith("/issues")]
|
graph = {item["id"]: item for item in (COMPONENT, consumer, cli)}
|
||||||
self.assertEqual(len(created), 1)
|
with patch.object(reconcile, "managed_repositories", return_value=(BASE, graph, {REPO: COMPONENT})):
|
||||||
body = created[0]["body"]
|
entry, = self.run_scan()["results"]
|
||||||
self.assertIn(reconcile.release_marker("cflmy/marqdo-cli", "v0.0.1"), body)
|
task, = entry["consumer_tasks"]
|
||||||
self.assertIn("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", body)
|
self.assertEqual(task["consumer"], "archive")
|
||||||
self.assertEqual(created[0]["labels"], [5])
|
self.assertEqual(task["baseline_sha"], consumer["sha"])
|
||||||
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
|
self.assertEqual(task["inputs"]["release"]["assets"][0]["name"], ASSET)
|
||||||
|
self.assertEqual(task["inputs"]["accepted_dependencies"], [{"id": "cli", "source_sha": cli["sha"]}])
|
||||||
|
self.assertEqual(task["status"], "pending")
|
||||||
|
cli["sha"] = "e" * 40
|
||||||
|
first_key = task["key"]
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
task, = entry["consumer_tasks"]
|
||||||
|
self.assertNotEqual(task["key"], first_key)
|
||||||
|
self.forge.evidence["dependencies"] = [{"id": "cli", "source_sha": "d" * 40}]
|
||||||
|
self.forge.refresh_assets()
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
task, = entry["consumer_tasks"]
|
||||||
|
self.assertEqual(task["status"], "waiting-for-dependencies")
|
||||||
|
self.assertEqual(task["different_dependencies"], ["cli"])
|
||||||
|
self.assertEqual(self.forge.writes, [])
|
||||||
|
|
||||||
|
def test_apply_creates_one_consumer_issue_and_records_new_inputs_in_it(self):
|
||||||
|
consumer = {"id": "archive", "state": "active", "sha": "c" * 40,
|
||||||
|
"remote": FORGE + "/cflmy/marqdo-ext-archive.git",
|
||||||
|
"requires": ["std-text"], "checks_with": []}
|
||||||
|
graph = {item["id"]: item for item in (COMPONENT, consumer)}
|
||||||
|
with patch.object(reconcile, "managed_repositories", return_value=(BASE, graph, {REPO: COMPONENT})):
|
||||||
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
|
task, = entry["consumer_tasks"]
|
||||||
|
self.assertEqual(task["registration"], "recorded")
|
||||||
|
self.assertEqual(task["issue"], 100)
|
||||||
|
self.assertIn(FORGE + "/cflmy/marqdo/issues/100", self.forge.consumer_issues[0]["body"])
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.assertEqual(len(self.forge.writes), 2)
|
||||||
|
consumer["sha"] = "e" * 40
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.assertEqual(len(self.forge.consumer_issues), 1)
|
||||||
|
self.assertEqual(len(self.forge.comments[CONSUMER_ISSUES + "/100/comments"]), 1)
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.assertEqual(len(self.forge.comments[CONSUMER_ISSUES + "/100/comments"]), 1)
|
||||||
|
new_root = "f" * 40
|
||||||
|
self.forge.root_sha = new_root
|
||||||
|
with patch.object(reconcile, "managed_repositories", return_value=(new_root, graph, {REPO: COMPONENT})):
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
notes = self.forge.comments[CONSUMER_ISSUES + "/100/comments"]
|
||||||
|
self.assertEqual(len(notes), 2)
|
||||||
|
self.assertIn(f"- Root candidate: {new_root}", notes[-1]["body"])
|
||||||
|
|
||||||
|
def test_apply_creates_one_verified_tracker_then_rechecks_it(self):
|
||||||
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
self.assertEqual(entry["status"], "created")
|
self.assertEqual(entry["status"], "created")
|
||||||
|
self.assertEqual(entry["issue"], 100)
|
||||||
def test_second_scan_is_idempotent(self):
|
self.assertEqual(self.forge.writes[0][1]["labels"], [5])
|
||||||
client = FakeGitea(
|
body = self.forge.issues[0]["body"]
|
||||||
releases={"cflmy/marqdo-cli": [release()]},
|
self.assertIn(reconcile.release_marker(REPO, TAG), body)
|
||||||
assets={"https://example.invalid/a.tar.gz": b"abc"},
|
self.assertIn(reconcile.identity_marker(entry), body)
|
||||||
)
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
reconcile.reconcile(client, ROOT, apply=True)
|
|
||||||
posts_after_first = len(client.posts)
|
|
||||||
report = reconcile.reconcile(client, ROOT, apply=True)
|
|
||||||
self.assertEqual(len(client.posts), posts_after_first)
|
|
||||||
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
|
|
||||||
self.assertEqual(entry["status"], "tracked")
|
self.assertEqual(entry["status"], "tracked")
|
||||||
|
self.assertEqual(len(self.forge.writes), 1)
|
||||||
|
self.assertEqual(len(self.forge.downloads), 4)
|
||||||
|
|
||||||
def test_published_after_filter_skips_historical_releases(self):
|
def test_partial_upload_and_wrong_ci_sha_block_once(self):
|
||||||
client = FakeGitea(releases={"cflmy/marqdo-cli": [release()]})
|
self.forge.pipeline_sha = BASE
|
||||||
skipped = reconcile.reconcile(client, ROOT, apply=False, cutoff="2026-11-28T00:00:00Z")
|
for _ in range(2):
|
||||||
self.assertFalse([item for item in skipped["results"] if item["repository"] == "cflmy/marqdo-cli"])
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
kept = reconcile.reconcile(client, ROOT, apply=False, cutoff="2026-11-26T00:00:00Z")
|
self.assertEqual(entry["status"], "blocked")
|
||||||
self.assertTrue([item for item in kept["results"] if item["repository"] == "cflmy/marqdo-cli"])
|
self.assertIn("exact SHA", entry["error"])
|
||||||
|
self.assertEqual(len(self.forge.writes), 1)
|
||||||
|
self.forge.pipeline_sha = SOURCE
|
||||||
|
self.forge.release["assets"].pop(0)
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
self.assertEqual(entry["status"], "blocked")
|
||||||
|
self.assertIn("cover the published assets", entry["error"])
|
||||||
|
|
||||||
def test_draft_releases_are_ignored(self):
|
def test_recorded_release_block_does_not_fail_a_complete_operational_scan(self):
|
||||||
client = FakeGitea(releases={"cflmy/marqdo-cli": [release(draft=True)]})
|
self.forge.pipeline_sha = BASE
|
||||||
report = reconcile.reconcile(client, ROOT, apply=False)
|
with (patch.dict(os.environ, {"MARQDO_GIT_TOKEN": "fixture"}),
|
||||||
self.assertFalse([item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"])
|
patch.object(reconcile, "Gitea", return_value=self.forge),
|
||||||
|
redirect_stdout(io.StringIO()) as stdout):
|
||||||
|
result = reconcile.main(["--apply"])
|
||||||
|
self.assertEqual(result, 0)
|
||||||
|
report = json.loads(stdout.getvalue())
|
||||||
|
self.assertTrue(report["scan_complete"])
|
||||||
|
self.assertEqual(report["results"][0]["status"], "blocked")
|
||||||
|
self.assertEqual(len(self.forge.issues), 1)
|
||||||
|
|
||||||
def test_asset_size_mismatch_and_unsafe_name_are_rejected(self):
|
def test_asset_api_outage_leaves_the_scan_incomplete(self):
|
||||||
bad_size = FakeGitea(
|
with patch.object(self.forge, "asset", side_effect=reconcile.http_error("GET", "/asset", 503)):
|
||||||
releases={"cflmy/marqdo-cli": [release()]},
|
report = self.run_scan(apply=True)
|
||||||
assets={"https://example.invalid/a.tar.gz": b"abcdef"},
|
self.assertFalse(report["scan_complete"])
|
||||||
)
|
self.assertEqual(report["scan_errors"][REPO], "GET /asset: HTTP 503")
|
||||||
report = reconcile.reconcile(bad_size, ROOT, apply=True)
|
self.assertEqual(self.forge.writes, [])
|
||||||
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
|
|
||||||
self.assertTrue(entry["status"].startswith("asset-verify-failed"))
|
def test_validated_tracker_detects_an_updated_index_and_disappearing_release(self):
|
||||||
self.assertFalse([path for path, _ in bad_size.posts if path.endswith("/issues")])
|
self.run_scan(apply=True)
|
||||||
unsafe = release()
|
self.forge.evidence["assets"][0]["target"] = "x86_64-unknown-linux-gnu"
|
||||||
unsafe["assets"][0]["name"] = "../escape.tar.gz"
|
self.forge.refresh_assets()
|
||||||
client = FakeGitea(releases={"cflmy/marqdo-cli": [unsafe]}, assets={"https://example.invalid/a.tar.gz": b"abc"})
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
report = reconcile.reconcile(client, ROOT, apply=True)
|
self.assertEqual(entry["status"], "blocked")
|
||||||
entry = [item for item in report["results"] if item["repository"] == "cflmy/marqdo-cli"][0]
|
self.assertIn("index digest changed", entry["error"])
|
||||||
self.assertTrue(entry["status"].startswith("asset-verify-failed"))
|
self.assertEqual(len(self.forge.issues), 1)
|
||||||
|
self.forge.releases = []
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
self.assertIn("absent", entry["error"])
|
||||||
|
|
||||||
|
def test_previously_blocked_tracker_records_verified_identity_in_bot_comment(self):
|
||||||
|
self.forge.pipeline_sha = BASE
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.forge.pipeline_sha = SOURCE
|
||||||
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
|
self.assertEqual(entry["status"], "pending")
|
||||||
|
self.assertIn(reconcile.identity_marker(entry), self.forge.writes[-1][1]["body"])
|
||||||
|
entry, = self.run_scan(apply=True)["results"]
|
||||||
|
self.assertEqual(entry["status"], "tracked")
|
||||||
|
self.assertEqual(len(self.forge.writes), 2)
|
||||||
|
|
||||||
|
def test_uses_normalized_publish_timestamp_and_skips_draft(self):
|
||||||
|
self.assertEqual(self.run_scan(cutoff="2026-11-27T00:00:01Z")["results"], [])
|
||||||
|
self.assertTrue(self.run_scan(cutoff="2026-11-27T00:00:00Z")["results"])
|
||||||
|
self.forge.release["draft"] = True
|
||||||
|
self.assertEqual(self.run_scan()["results"], [])
|
||||||
|
|
||||||
|
def test_multiple_pages_and_partial_list_error(self):
|
||||||
|
self.forge.releases = [{"draft": True}] * reconcile.PAGE_SIZE + [self.forge.release]
|
||||||
|
report = self.run_scan()
|
||||||
|
self.assertTrue(report["scan_complete"])
|
||||||
|
self.assertEqual(len(report["results"]), 1)
|
||||||
|
self.assertIn((f"/repos/{REPO}/releases", 2), self.forge.pages)
|
||||||
|
self.forge.fail_page = 2
|
||||||
|
report = self.run_scan(apply=True)
|
||||||
|
self.assertFalse(report["scan_complete"])
|
||||||
|
self.assertEqual(report["scan_errors"][REPO], "API HTTP 503")
|
||||||
|
self.assertEqual(self.forge.writes, [])
|
||||||
|
|
||||||
|
def test_asset_location_name_and_digest_are_checked(self):
|
||||||
|
asset = self.forge.release["assets"][0]
|
||||||
|
asset["browser_download_url"] = "https://invalid.example/capture"
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
self.assertIn("non-canonical URL", entry["error"])
|
||||||
|
self.assertEqual(self.forge.downloads, [])
|
||||||
|
self.forge.refresh_assets()
|
||||||
|
self.forge.release["assets"][0]["name"] = "../escape.tar.gz"
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
self.assertIn("unsafe release asset name", entry["error"])
|
||||||
|
self.forge.refresh_assets()
|
||||||
|
self.forge.blobs[ASSET] = b"xxx"
|
||||||
|
entry, = self.run_scan()["results"]
|
||||||
|
self.assertIn("digest mismatch", entry["error"])
|
||||||
|
|
||||||
|
def test_apply_requires_current_protected_branch_and_non_admin_identity(self):
|
||||||
|
self.forge.protected = False
|
||||||
|
with self.assertRaisesRegex(reconcile.ReconcileError, "protected root"):
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.forge.wrong_account = True
|
||||||
|
with self.assertRaisesRegex(reconcile.ReconcileError, "non-admin"):
|
||||||
|
self.run_scan(apply=True)
|
||||||
|
self.assertEqual(self.forge.writes, [])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+1
-1
Submodule tools/knowledge updated: a1a223f53f...3cc477de60.
Reference in new issue
Block a user