SaylorTwift HF Staff commited on
Commit
499d3d5
·
verified ·
1 Parent(s): 58a9693

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .github/ISSUE_TEMPLATE/bug.md +25 -0
  2. .github/ISSUE_TEMPLATE/config.yml +1 -0
  3. .github/ISSUE_TEMPLATE/feature.md +13 -0
  4. .github/ISSUE_TEMPLATE/task.md +13 -0
  5. .github/issue-management/README.i18n.yaml +6 -0
  6. .github/issue-management/README.md +93 -0
  7. .github/issue-management/README.zh.md +93 -0
  8. .github/issue-management/config.json +19 -0
  9. .github/issue-management/github.mjs +300 -0
  10. .github/issue-management/lifecycle.mjs +155 -0
  11. .github/issue-management/policy.mjs +29 -0
  12. .github/issue-management/policy.test.mjs +1077 -0
  13. .github/issue-management/pull-request.mjs +126 -0
  14. .github/issue-management/rules.mjs +303 -0
  15. .github/issue-management/selective-preflight.json +1 -0
  16. .github/preview-sizing/README.i18n.yaml +6 -0
  17. .github/preview-sizing/README.md +35 -0
  18. .github/preview-sizing/README.zh.md +35 -0
  19. .github/review-ownership/README.md +44 -0
  20. .github/review-ownership/approval-policy.json +12 -0
  21. .github/review-ownership/check-approval.mjs +376 -0
  22. .github/review-ownership/check-approval.test.mjs +348 -0
  23. .github/workflows/build-exe-for-python-sdk.yml +504 -0
  24. .github/workflows/build-preview-cloudflare.yml +170 -0
  25. .github/workflows/ci-master.yml +523 -0
  26. .github/workflows/ci.yml +740 -0
  27. .github/workflows/docs-pages.yml +93 -0
  28. .github/workflows/e2e.yml +123 -0
  29. .github/workflows/expected-filenames.yml +28 -0
  30. .github/workflows/issue-lifecycle.yml +57 -0
  31. .github/workflows/issue-policy.yml +58 -0
  32. .github/workflows/node-addon-system-release.yml +188 -0
  33. .github/workflows/node-addon-system.yml +168 -0
  34. .github/workflows/pi-ai-provider-e2e.yml +72 -0
  35. .github/workflows/python-release.yml +248 -0
  36. .github/workflows/release-publish.yml +131 -0
  37. .github/workflows/release-vendor-publish.yml +114 -0
  38. .github/workflows/release-vendor.yml +107 -0
  39. .github/workflows/release.yml +180 -0
  40. .github/workflows/sandbox.yml +141 -0
  41. .github/workflows/weighted-approval-review-event.yml +17 -0
  42. .github/workflows/weighted-approval.yml +37 -0
  43. apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl +27 -0
  44. apps/web/tests/expected/agent-preset-authoring/copy-dialog.expected.md +14 -0
  45. apps/web/tests/expected/agent-preset-authoring/created.expected.md +90 -0
  46. apps/web/tests/expected/agent-preset-authoring/damaged.expected.md +102 -0
  47. apps/web/tests/expected/agent-preset-authoring/section.expected.md +73 -0
  48. apps/web/tests/expected/agent-preset-selection/header.expected.md +12 -0
  49. apps/web/tests/expected/agent-preset-selection/hero.expected.md +8 -0
  50. apps/web/tests/expected/agent-preset-selection/menu.expected.md +8 -0
.github/ISSUE_TEMPLATE/bug.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug
3
+ about: 记录现有预期行为的失效
4
+ type: Bug
5
+ ---
6
+
7
+ ## Summary
8
+
9
+ <!-- 简要说明发生了什么错误,以及受影响的用户或场景。 -->
10
+
11
+ ## Reproduction
12
+
13
+ <!-- 列出能稳定触发问题的最小步骤、输入或代码。 -->
14
+
15
+ ## Current behavior
16
+
17
+ <!-- 说明实际结果,并附上必要的错误信息、日志或截图。 -->
18
+
19
+ ## Expected behavior
20
+
21
+ <!-- 说明正确结果。 -->
22
+
23
+ ## Environment
24
+
25
+ <!-- 说明相关版本、平台、配置或运行条件。 -->
.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ blank_issues_enabled: false
.github/ISSUE_TEMPLATE/feature.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature
3
+ about: 新增或有意改变可观察行为
4
+ type: Feature
5
+ ---
6
+
7
+ ## Motivation
8
+
9
+ <!-- 说明当前问题、受影响的用户,以及为什么需要这项变化。 -->
10
+
11
+ ## Behavior
12
+
13
+ <!-- 说明预期的用户、模型或系统可观察行为。 -->
.github/ISSUE_TEMPLATE/task.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Task
3
+ about: 明确的非 Feature、非 Bug 工作
4
+ type: Task
5
+ ---
6
+
7
+ ## Summary
8
+
9
+ <!-- 简要说明需要完成的工作。 -->
10
+
11
+ ## Deliverables
12
+
13
+ <!-- 列出需要提交或更新的代码、文档、配置或结论。 -->
.github/issue-management/README.i18n.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write .github/issue-management/README.md
5
+ README.md: a936b9358810fd3a8b8104609a5523e305e1aaa5
6
+ README.zh.md: df743cac581c2125df9ac9e76f04d2528204eb74
.github/issue-management/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ description: "Issue policy enforcement, Project access, and lifecycle events for repository maintainers."
3
+ ---
4
+
5
+ # Issue management
6
+
7
+ English | [中文](README.zh.md)
8
+
9
+ ## Summary
10
+
11
+ Contributors can link Issues as context without coupling pull-request validation to Project availability. Resolving references additionally enforce Project Priority. The required `Issue policy` job and the separate lifecycle workflow use trusted default-branch code.
12
+
13
+ ## Table of Contents
14
+
15
+ - [Pull-request policy](#pull-request-policy)
16
+ - [Lifecycle events](#lifecycle-events)
17
+ - [Configuration and limitations](#configuration-and-limitations)
18
+ - [Module ownership](#module-ownership)
19
+ - [Verification](#verification)
20
+ - [Dev Note](#dev-note)
21
+
22
+ -----
23
+
24
+ <a id="pull-request-policy"></a>
25
+ ## Pull-request policy
26
+
27
+ [Issue policy](../workflows/issue-policy.yml) applies to non-draft, human-authored PRs with a requested review or submitted review. Exempt PRs finish successfully without resolving Issue references, minting a Project App token, or querying ProjectV2. Eligibility uses live repository state before expensive reads; the required job remains present for subscribed events. Final validation re-reads live state: preflight is not a cached verdict or an exemption for metadata edits.
28
+
29
+ Selective preflight requires [selective-preflight.json](selective-preflight.json) in the trusted checkout. Without that marker, the workflow preserves legacy behavior: human PRs receive a Project token and full legacy validation; Bot/App PRs skip both. A failed supported preflight fails the job rather than falling back.
30
+
31
+ Eligible PRs need at least one same-repository Issue reference, exactly one canonical `kind/*`, at least one `area/*`, and at most one `p0`–`p3` label. Unsupported kinds, retired aliases, and `source/*` labels fail validation; [label taxonomy](../../.agents/notes/implemented/process/2026-08-08-unified-github-label-taxonomy.md) owns their meanings.
32
+
33
+ - Informational references, such as `Refs #3624`, establish context. Validation uses REST to distinguish Issues from PR numbers and does not read their Project fields. An informational-only PR can carry its own Priority without matching the referenced Issue.
34
+ - Resolving references use closing keywords such as `Fixes #123`, `Closes #123`, or `Resolves #123`. Only references that resolve to actual Issues require Project reads during validation. A PR Priority must match the highest resolving-Issue Priority; a resolving PR with a Priority label requires every resolving Issue to have Priority. If all resolving Priorities are empty, the PR may omit Priority.
35
+ - References inside HTML comments, code fences, or inline code do not count. Cross-repository references and references to PRs do not satisfy the Issue requirement.
36
+
37
+ REST reads use the repository `GITHUB_TOKEN`. Project validation uses a separate App token with Issues and organization Projects read permissions. Missing required Project access or invalid field configuration fails validation rather than bypassing resolving-Issue Priority checks.
38
+
39
+ -----
40
+
41
+ <a id="lifecycle-events"></a>
42
+ ## Lifecycle events
43
+
44
+ [Issue lifecycle](../workflows/issue-lifecycle.yml) mutates Project data independently of PR validation eligibility. PR opened/reopened events and body edits can advance resolving Issues to `In progress`; title-only edits do not. Review requests target `In review`. Changes-requested reviews target `In progress`, with the [human-ownership and terminal-status protections](../../.agents/notes/implemented/process/2026-08-10-event-directed-pr-review-status.md).
45
+
46
+ Approval-only and comment-only reviews do not allocate a lifecycle runner. PR pushes and label changes, and Issue assignment changes, do not trigger lifecycle work. Other subscribed Issue events maintain membership, state, and audit comments; exact subscriptions live in the workflow.
47
+
48
+ PR opening initializes an empty Project `Start Date` for every referenced Issue, including informational references, using the PR creation date in the configured time zone. This lifecycle operation can add Project membership and needs Project write access; the informational-reference read exemption applies only to PR validation. [Planning-field ownership](../../.agents/notes/implemented/process/2026-09-02-project-local-issue-planning-fields.md) defines date preservation.
49
+
50
+ -----
51
+
52
+ <a id="configuration-and-limitations"></a>
53
+ ## Configuration and limitations
54
+
55
+ [config.json](config.json) selects the repository, Project, field names, statuses, lifecycle actor, and time zone. The policy reads the Project custom single-select `Priority` field, not a native organization Issue Priority field. Maintainers set Project Priority manually; skill guidance that directs edits to native Issue fields does not populate this value. Issue audits remove PR-only kinds and retired label aliases before validating the remaining metadata. There is no field migration or Priority synchronization.
56
+
57
+ Lifecycle processing is event-driven, not a reconciler. Omitted events do not repair Project state, and concurrent Project mutations have no atomic compare-and-swap. Selective evaluation does not redesign required-check authority or guarantee measured Actions-minute savings. The [selective-evaluation decision](../../.agents/notes/implemented/process/2026-09-07-selective-issue-policy-evaluation.md) records the trade-offs.
58
+
59
+ -----
60
+
61
+ <a id="module-ownership"></a>
62
+ ## Module ownership
63
+
64
+ Maintainers reuse the owning module directly; [policy.mjs](policy.mjs) only reads the event file, dispatches commands, and reports command failures. The [module-ownership decision](../../.agents/notes/implemented/process/2026-09-07-issue-policy-module-ownership.md) explains this separation.
65
+
66
+ <details>
67
+ <summary>Implementation owners</summary>
68
+
69
+ [rules.mjs](rules.mjs) owns pure validation, reference parsing, status decisions, and date conversion. [github.mjs](github.mjs) owns credential selection, REST/GraphQL transport, Issue/Project reads, and Project membership and field writes.
70
+
71
+ [pull-request.mjs](pull-request.mjs) assembles read-only PR snapshots and runs policy preflight and validation, including their workflow outputs. [lifecycle.mjs](lifecycle.mjs) reuses the PR reference reader and shared rules to coordinate Project mutations, Issue label repairs, and audit comments. Snapshot readers do not mutate GitHub; the shared transport also supports writes, so importing it does not restrict a caller's permissions.
72
+
73
+ </details>
74
+
75
+ -----
76
+
77
+ <a id="verification"></a>
78
+ ## Verification
79
+
80
+ The focused, keyless policy suite runs from the repository root:
81
+
82
+ ```sh
83
+ node --test .github/issue-management/policy.test.mjs
84
+ ```
85
+
86
+ [Workflow tests](../../scripts/ci-workflow.spec.ts) verify trigger and permission declarations. Local tests do not establish live GitHub delivery, App installation access, or actual runner cost; repository maintainers verify those in Actions.
87
+
88
+ -----
89
+
90
+ <a id="dev-note"></a>
91
+ ## Dev Note
92
+
93
+ None.
.github/issue-management/README.zh.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ description: "面向仓库维护者的 Issue 策略强制范围、Project 访问与生命周期事件参考。"
3
+ ---
4
+
5
+ # Issue 管理
6
+
7
+ [English](README.md) | 中文
8
+
9
+ ## 摘要
10
+
11
+ 贡献者可以引用 Issue 作为背景,而无需让 PR(Pull Request)校验依赖 Project 可用性。解决型引用还会强制检查 Project Priority。必需的 `Issue policy` job 与独立的生命周期工作流使用受信任的默认分支代码。
12
+
13
+ ## 目录
14
+
15
+ - [PR 策略](#pull-request-policy)
16
+ - [生命周期事件](#lifecycle-events)
17
+ - [配置与限制](#configuration-and-limitations)
18
+ - [模块归属](#module-ownership)
19
+ - [验证](#verification)
20
+ - [开发备注](#dev-note)
21
+
22
+ -----
23
+
24
+ <a id="pull-request-policy"></a>
25
+ ## PR 策略
26
+
27
+ [Issue policy](../workflows/issue-policy.yml)适用于已请求评审或已有评审、非草稿且由人类创建的 PR。豁免 PR 成功结束,不解析 Issue 引用、不签发 Project App token,也不查询 ProjectV2。工作流在昂贵读取前根据仓库实时状态判断强制范围;订阅事件仍保留必需 job。最终校验重新读取实时状态:预检不是缓存结论,也不是元数据编辑的豁免。
28
+
29
+ 选择性预检要求受信任的检出中存在 [selective-preflight.json](selective-preflight.json)。缺少该标记时,工作流保留旧版行为:人类 PR 获取 Project token 并执行完整旧版校验;Bot/App PR 跳过两者。受支持的预检执行失败时,job 失败而不回退。
30
+
31
+ 强制范围内的 PR 至少需要一个同仓库 Issue 引用、恰好一个规范的 `kind/*`、至少一个 `area/*`,以及最多一个 `p0`–`p3` 标签。不支持的 kind、退役别名和 `source/*` 标签会使校验失败;[标签分类](../../.agents/notes/implemented/process/2026-08-08-unified-github-label-taxonomy.zh.md)定义其含义。
32
+
33
+ - 信息型引用(如 `Refs #3624`)提供背景。校验通过 REST 区分 Issue 与 PR 编号,不读取这些引用的 Project 字段。仅含信息型引用的 PR 可以使用自己的 Priority,无需匹配所引用的 Issue。
34
+ - 解决型引用使用关闭关键词,如 `Fixes #123`、`Closes #123` 或 `Resolves #123`。校验期间只有解析为实际 Issue 的解决型引用需要读取 Project。PR Priority 必须匹配被解决 Issue 中的最高 Priority;带 Priority 标签的解决型 PR 要求每个被解决 Issue 均有 Priority。若所有被解决 Issue 的 Priority 均为空,PR 可以省略 Priority。
35
+ - HTML 注释、代码围栏或行内代码中的引用不计入。跨仓库引用与指向 PR 的引用不能满足 Issue 引用要求。
36
+
37
+ REST 读取使用仓库 `GITHUB_TOKEN`。Project 校验使用独立的 App token,具有 Issues 和组织 Projects 读取权限。缺少所需 Project 访问权限或字段配置无效时,校验失败,而不是绕过解决型 Issue 的 Priority 检查。
38
+
39
+ -----
40
+
41
+ <a id="lifecycle-events"></a>
42
+ ## 生命周期事件
43
+
44
+ [Issue lifecycle](../workflows/issue-lifecycle.yml)独立于 PR 校验强制范围修改 Project 数据。PR 打开、重新打开和正文编辑可将解决型 Issue 推进至 `In progress`;仅编辑标题不会。请求评审以 `In review` 为目标。请求修改的评审以 `In progress` 为目标,并遵守[人工状态归属与终态保护](../../.agents/notes/implemented/process/2026-08-10-event-directed-pr-review-status.zh.md)。
45
+
46
+ 仅批准或仅评论的评审不分配生命周期 runner。PR 推送与标签变更,以及 Issue 指派变更,不触发生命周期工作。其他已订阅的 Issue 事件维护 Project 归属、状态及审计评论;精确订阅列表由工作流定义。
47
+
48
+ PR 打开时,工作流按配置时区中的 PR 创建日期,为每个被引用 Issue(包括信息型引用)初始化空的 Project `Start Date`。此生命周期操作可以添加 Project 归属,并需要 Project 写权限;信息型引用的读取豁免仅适用于 PR 校验。[规划字段归属](../../.agents/notes/implemented/process/2026-09-02-project-local-issue-planning-fields.zh.md)定义日期保留规则。
49
+
50
+ -----
51
+
52
+ <a id="configuration-and-limitations"></a>
53
+ ## 配置与限制
54
+
55
+ [config.json](config.json)选择仓库、Project、字段名、状态、生命周期操作者和时区。策略读取 Project 自定义单选 `Priority` 字段,而非组织原生 Issue Priority 字段。维护者手动设置 Project Priority;指引编辑原生 Issue 字段的 skill 不会填充该值。Issue 审计先移除 PR 专用 kind 标签和已停用的标签别名,再校验其余元数据。不提供字段迁移或 Priority 同步。
56
+
57
+ 生命周期处理由事件驱动,不是协调器。被省略的事件不会修复 Project 状态,并发 Project mutation 也没有原子比较并交换保护。选择性求值不重新设计必需检查的权威来源,也不保证已测得的 Actions 分钟节省。[选择性求值决策](../../.agents/notes/implemented/process/2026-09-07-selective-issue-policy-evaluation.zh.md)记录取舍。
58
+
59
+ -----
60
+
61
+ <a id="module-ownership"></a>
62
+ ## 模块归属
63
+
64
+ 维护者直接复用所属模块;[policy.mjs](policy.mjs)仅负责读取事件文件、分派命令并报告命令失败。[模块归属决策](../../.agents/notes/implemented/process/2026-09-07-issue-policy-module-ownership.zh.md)解释此职责分离。
65
+
66
+ <details>
67
+ <summary>实现职责</summary>
68
+
69
+ [rules.mjs](rules.mjs)拥有纯校验、引用解析、状态决策和日期转换。[github.mjs](github.mjs)拥有凭据选择、REST/GraphQL 传输、Issue/Project 读取,以及 Project 归属与字段写入。
70
+
71
+ [pull-request.mjs](pull-request.mjs)组装只读 PR 快照,并执行策略预检和校验,包括其工作流输出。[lifecycle.mjs](lifecycle.mjs)复用 PR 引用读取器与共享规则,协调 Project mutation、Issue 标签修复和审计评论。快照读取器不修改 GitHub;共享传输也支持写入,因此导入该模块不会限制调用方权限。
72
+
73
+ </details>
74
+
75
+ -----
76
+
77
+ <a id="verification"></a>
78
+ ## 验证
79
+
80
+ 在仓库根目录运行聚焦的无密钥策略测试:
81
+
82
+ ```sh
83
+ node --test .github/issue-management/policy.test.mjs
84
+ ```
85
+
86
+ [工作流测试](../../scripts/ci-workflow.spec.ts)验证触发器与权限声明。本地测试不能证明 GitHub 实际事件交付、App 安装访问权限或实际 runner 成本;仓库维护者在 Actions 中验证这些内容。
87
+
88
+ -----
89
+
90
+ <a id="dev-note"></a>
91
+ ## 开发备注
92
+
93
+ 无。
.github/issue-management/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "organization": "deepseek-harness",
3
+ "repository": "deepseek-harness",
4
+ "projectNumber": 1,
5
+ "projectTitle": "DSH Issue Management",
6
+ "lifecycleActor": "dsh-issue-management",
7
+ "priorityField": "Priority",
8
+ "startDateField": "Start Date",
9
+ "projectTimeZone": "Asia/Shanghai",
10
+ "statuses": [
11
+ "Inbox",
12
+ "Backlog",
13
+ "Ready",
14
+ "In progress",
15
+ "In review",
16
+ "Done",
17
+ "No action"
18
+ ]
19
+ }
.github/issue-management/github.mjs ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** GitHub transport, Issue/Project readers, and Project membership and field writes. */
2
+
3
+ import process from 'node:process'
4
+
5
+ import config from './config.json' with { type: 'json' }
6
+
7
+ const API_VERSION = '2026-03-10'
8
+
9
+ function token() {
10
+ const value = process.env.GH_TOKEN || process.env.GITHUB_TOKEN
11
+ if (!value) throw new Error('GH_TOKEN 或 GITHUB_TOKEN 未设置')
12
+ return value
13
+ }
14
+
15
+ function projectToken() {
16
+ return process.env.PROJECT_TOKEN || token()
17
+ }
18
+
19
+ /**
20
+ * Send one GitHub REST request; HTTP failures retain the method, path, status, and body.
21
+ * @param {string} path API path including any query string.
22
+ * @param {object} options Fetch options; allow404 returns null for a 404.
23
+ * @returns {Promise<object|null>} Decoded JSON, or null for an allowed 404 or a 204.
24
+ */
25
+ export async function api(path, options = {}) {
26
+ const { allow404 = false, ...requestOptions } = options
27
+ const response = await fetch(`${process.env.GITHUB_API_URL ?? 'https://api.github.com'}${path}`, {
28
+ ...requestOptions,
29
+ headers: {
30
+ Accept: 'application/vnd.github+json',
31
+ Authorization: `Bearer ${token()}`,
32
+ 'X-GitHub-Api-Version': API_VERSION,
33
+ 'User-Agent': 'dsh-issue-policy',
34
+ ...options.headers,
35
+ },
36
+ })
37
+ if (allow404 && response.status === 404) return null
38
+ if (!response.ok) {
39
+ const body = await response.text()
40
+ throw new Error(`${requestOptions.method ?? 'GET'} ${path}: ${response.status} ${body}`)
41
+ }
42
+ if (response.status === 204) return null
43
+ return response.json()
44
+ }
45
+
46
+ /**
47
+ * Send one Project-authenticated GraphQL request; reject joined GraphQL error messages.
48
+ * @param {string} query GraphQL document.
49
+ * @param {object} variables GraphQL variables.
50
+ * @returns {Promise<object>} GraphQL data.
51
+ */
52
+ export async function graphql(query, variables) {
53
+ const result = await api('/graphql', {
54
+ method: 'POST',
55
+ body: JSON.stringify({ query, variables }),
56
+ headers: {
57
+ Authorization: `Bearer ${projectToken()}`,
58
+ 'Content-Type': 'application/json',
59
+ },
60
+ })
61
+ if (result.errors?.length) throw new Error(result.errors.map((error) => error.message).join('; '))
62
+ return result.data
63
+ }
64
+
65
+ /**
66
+ * Read one Issue together with its Project planning values.
67
+ * @param {number} number Same-repository Issue number.
68
+ * @param {string|null|undefined} status Optional known Project status.
69
+ * @returns {Promise<object|null>} Issue snapshot, or null when the number identifies a pull request.
70
+ */
71
+ export async function issueSnapshot(number, status = undefined) {
72
+ const issue = await api(`/repos/${config.organization}/${config.repository}/issues/${number}`)
73
+ if (issue.pull_request) return null
74
+ const context = await projectContext(number)
75
+ return {
76
+ number,
77
+ nodeId: issue.node_id,
78
+ labels: issue.labels.map((label) => label.name),
79
+ type: issue.type?.name ?? null,
80
+ priority: context.item?.priorityValue?.name ?? null,
81
+ status: status === undefined ? (context.item?.fieldValueByName?.name ?? null) : status,
82
+ state: issue.state,
83
+ stateReason: issue.state_reason ?? null,
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Read and validate the configured Project fields and one Issue’s membership.
89
+ * @param {number} number Same-repository Issue number.
90
+ * @param {boolean} includeStatusActor Include the latest matching status-event actor.
91
+ * @param {boolean} includeStartDate Include and validate the Project Start Date field.
92
+ * @returns {Promise<object>} Project, Issue, fields, optional item, and status actor; never writes.
93
+ */
94
+ export async function projectContext(number, includeStatusActor = false, includeStartDate = false) {
95
+ const data = await graphql(
96
+ `query(
97
+ $organization: String!
98
+ $repository: String!
99
+ $number: Int!
100
+ $project: Int!
101
+ $includeStatusActor: Boolean!
102
+ $includeStartDate: Boolean!
103
+ $priorityField: String!
104
+ $startDateField: String!
105
+ ) {
106
+ organization(login: $organization) {
107
+ projectV2(number: $project) {
108
+ id
109
+ title
110
+ fields(first: 50) {
111
+ nodes {
112
+ ... on ProjectV2Field {
113
+ id
114
+ name
115
+ dataType
116
+ isIssueField
117
+ }
118
+ ... on ProjectV2SingleSelectField {
119
+ id
120
+ name
121
+ dataType
122
+ isIssueField
123
+ options { id name }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+ repository(owner: $organization, name: $repository) {
130
+ issue(number: $number) {
131
+ id
132
+ timelineItems(last: 100, itemTypes: [PROJECT_V2_ITEM_STATUS_CHANGED_EVENT])
133
+ @include(if: $includeStatusActor) {
134
+ nodes {
135
+ ... on ProjectV2ItemStatusChangedEvent {
136
+ actor { login }
137
+ project { id }
138
+ status
139
+ }
140
+ }
141
+ }
142
+ projectItems(first: 20, includeArchived: true) {
143
+ nodes {
144
+ id
145
+ project { id }
146
+ fieldValueByName(name: "Status") {
147
+ ... on ProjectV2ItemFieldSingleSelectValue { name optionId }
148
+ }
149
+ priorityValue: fieldValueByName(name: $priorityField) {
150
+ ... on ProjectV2ItemFieldSingleSelectValue { name optionId }
151
+ }
152
+ startDateValue: fieldValueByName(name: $startDateField)
153
+ @include(if: $includeStartDate) {
154
+ ... on ProjectV2ItemFieldDateValue { date }
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ }`,
161
+ {
162
+ organization: config.organization,
163
+ repository: config.repository,
164
+ number,
165
+ project: config.projectNumber,
166
+ includeStatusActor,
167
+ includeStartDate,
168
+ priorityField: config.priorityField,
169
+ startDateField: config.startDateField,
170
+ },
171
+ )
172
+ const project = data.organization?.projectV2
173
+ const issue = data.repository?.issue
174
+ if (!project || project.title !== config.projectTitle) throw new Error('目标 Project 不存在或标题不匹配')
175
+ if (!issue) throw new Error(`#${number} 不存在`)
176
+ const statusField = project.fields.nodes.find((field) => field?.name === 'Status')
177
+ if (!statusField) throw new Error('Project 缺少 Status 字段')
178
+ const priorityField = project.fields.nodes.find((field) => field?.name === config.priorityField)
179
+ if (!priorityField) throw new Error(`Project 缺少 ${config.priorityField} 字段`)
180
+ if (priorityField.dataType !== 'SINGLE_SELECT') {
181
+ throw new Error(`Project ${config.priorityField} 字段必须为 Single Select`)
182
+ }
183
+ if (priorityField.isIssueField) {
184
+ throw new Error(`Project ${config.priorityField} 字段必须为 Project custom field`)
185
+ }
186
+ const startDateField = includeStartDate
187
+ ? project.fields.nodes.find((field) => field?.name === config.startDateField)
188
+ : null
189
+ if (includeStartDate && !startDateField) {
190
+ throw new Error(`Project 缺少 ${config.startDateField} 字段`)
191
+ }
192
+ if (startDateField && startDateField.dataType !== 'DATE') {
193
+ throw new Error(`Project ${config.startDateField} 字段必须为 Date`)
194
+ }
195
+ if (startDateField?.isIssueField) {
196
+ throw new Error(`Project ${config.startDateField} 字段必须为 Project Date 字段`)
197
+ }
198
+ const item = issue.projectItems.nodes.find((candidate) => candidate.project.id === project.id)
199
+ const latestStatusEvent = issue.timelineItems?.nodes
200
+ ?.filter((event) => event?.project?.id === project.id)
201
+ .at(-1)
202
+ const statusActor =
203
+ latestStatusEvent && latestStatusEvent.status === item?.fieldValueByName?.name
204
+ ? (latestStatusEvent.actor?.login ?? null)
205
+ : null
206
+ return { project, issue, statusField, priorityField, startDateField, item, statusActor }
207
+ }
208
+
209
+ /**
210
+ * Read Project membership and add the Issue when absent.
211
+ * @param {number} number Same-repository Issue number.
212
+ * @param {boolean} includeStartDate Include and validate the Project Start Date field.
213
+ * @returns {Promise<object>} Project context with an existing or newly added item.
214
+ */
215
+ export async function ensureProjectItem(number, includeStartDate = false) {
216
+ const context = await projectContext(number, false, includeStartDate)
217
+ if (context.item) return context
218
+ const data = await graphql(
219
+ `mutation($projectId: ID!, $contentId: ID!) {
220
+ addProjectV2ItemById(input: {projectId: $projectId, contentId: $contentId}) {
221
+ item { id }
222
+ }
223
+ }`,
224
+ { projectId: context.project.id, contentId: context.issue.id },
225
+ )
226
+ return {
227
+ ...context,
228
+ item: {
229
+ id: data.addProjectV2ItemById.item.id,
230
+ fieldValueByName: null,
231
+ priorityValue: null,
232
+ startDateValue: null,
233
+ },
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Initialize one Issue's Project Start Date when it is empty.
239
+ * @param {number} number Same-repository Issue number.
240
+ * @param {string} date Date in YYYY-MM-DD form.
241
+ * @returns {Promise<void>} Resolves after the conditional Project update.
242
+ */
243
+ export async function initializeIssueStartDate(number, date) {
244
+ const context = await ensureProjectItem(number, true)
245
+ if (context.item.startDateValue?.date) return
246
+ await graphql(
247
+ `mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $date: Date!) {
248
+ updateProjectV2ItemFieldValue(input: {
249
+ projectId: $projectId,
250
+ itemId: $itemId,
251
+ fieldId: $fieldId,
252
+ value: {date: $date}
253
+ }) { projectV2Item { id } }
254
+ }`,
255
+ {
256
+ projectId: context.project.id,
257
+ itemId: context.item.id,
258
+ fieldId: context.startDateField.id,
259
+ date,
260
+ },
261
+ )
262
+ }
263
+
264
+ /**
265
+ * Write the named Status option unless the supplied item already has it.
266
+ * @param {object} context Project context with an item and Status options.
267
+ * @param {string} status Configured Status option name.
268
+ * @returns {Promise<void>} Resolves after the optional update; rejects an unknown option.
269
+ */
270
+ export async function updateStatus(context, status) {
271
+ const option = context.statusField.options.find((candidate) => candidate.name === status)
272
+ if (!option) throw new Error(`Status 不存在:${status}`)
273
+ if (context.item.fieldValueByName?.name === status) return
274
+ await graphql(
275
+ `mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
276
+ updateProjectV2ItemFieldValue(input: {
277
+ projectId: $projectId,
278
+ itemId: $itemId,
279
+ fieldId: $fieldId,
280
+ value: {singleSelectOptionId: $optionId}
281
+ }) { projectV2Item { id } }
282
+ }`,
283
+ {
284
+ projectId: context.project.id,
285
+ itemId: context.item.id,
286
+ fieldId: context.statusField.id,
287
+ optionId: option.id,
288
+ },
289
+ )
290
+ }
291
+
292
+ /**
293
+ * Ensure Project membership before updating an Issue’s Status.
294
+ * @param {number} number Same-repository Issue number.
295
+ * @param {string} status Configured Status option name.
296
+ * @returns {Promise<void>} Resolves after membership and Status updates.
297
+ */
298
+ export async function setStatus(number, status) {
299
+ await updateStatus(await ensureProjectItem(number), status)
300
+ }
.github/issue-management/lifecycle.mjs ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Repository event orchestration and Issue audit comments. */
2
+
3
+ import config from './config.json' with { type: 'json' }
4
+ import {
5
+ api,
6
+ ensureProjectItem,
7
+ initializeIssueStartDate,
8
+ issueSnapshot,
9
+ projectContext,
10
+ setStatus,
11
+ updateStatus,
12
+ } from './github.mjs'
13
+ import { lifecyclePullRequestSnapshot } from './pull-request.mjs'
14
+ import {
15
+ isInvalidIssueLabel,
16
+ nextResolvingIssueStatus,
17
+ projectDate,
18
+ resolvingIssueStatusCommand,
19
+ validateIssue,
20
+ } from './rules.mjs'
21
+
22
+ const AUDIT_MARKER = '<!-- dsh-issue-policy -->'
23
+
24
+ /**
25
+ * Initialize every referenced Issue from a newly opened PR.
26
+ * @param {{createdAt: string, references: {all: number[]}}} pull Pull-request snapshot.
27
+ * @param {string} action Pull-request event action.
28
+ * @param {(number: number, date: string) => Promise<void>} initialize Date writer.
29
+ * @returns {Promise<void>} Resolves after all eligible Issues are processed.
30
+ */
31
+ export async function initializePullRequestStartDates(
32
+ pull,
33
+ action,
34
+ initialize = initializeIssueStartDate,
35
+ ) {
36
+ if (action !== 'opened') return
37
+ const date = projectDate(pull.createdAt)
38
+ for (const number of pull.references.all) await initialize(number, date)
39
+ }
40
+
41
+ async function upsertAudit(number, errors) {
42
+ const comments = await api(
43
+ `/repos/${config.organization}/${config.repository}/issues/${number}/comments?per_page=100`,
44
+ )
45
+ const existing = comments.find(
46
+ (comment) => comment.user?.type === 'Bot' && comment.body?.includes(AUDIT_MARKER),
47
+ )
48
+ if (errors.length === 0) {
49
+ if (existing) {
50
+ await api(`/repos/${config.organization}/${config.repository}/issues/comments/${existing.id}`, {
51
+ method: 'DELETE',
52
+ })
53
+ }
54
+ return
55
+ }
56
+ const body = `${AUDIT_MARKER}\n⚠️ Issue policy 未通过:\n\n${errors.map((error) => `- ${error}`).join('\n')}`
57
+ if (existing) {
58
+ if (existing.body === body) return
59
+ await api(`/repos/${config.organization}/${config.repository}/issues/comments/${existing.id}`, {
60
+ method: 'PATCH',
61
+ body: JSON.stringify({ body }),
62
+ headers: { 'Content-Type': 'application/json' },
63
+ })
64
+ } else {
65
+ await api(`/repos/${config.organization}/${config.repository}/issues/${number}/comments`, {
66
+ method: 'POST',
67
+ body: JSON.stringify({ body }),
68
+ headers: { 'Content-Type': 'application/json' },
69
+ })
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Remove pull-request kinds and retired aliases from one Issue snapshot.
75
+ * @param {{number: number, labels: string[]}} issue Issue snapshot.
76
+ * @returns {Promise<object>} Snapshot containing only labels that remain on the Issue.
77
+ */
78
+ export async function repairIssueLabels(issue) {
79
+ const invalidLabels = issue.labels.filter(isInvalidIssueLabel)
80
+ for (const label of invalidLabels) {
81
+ await api(
82
+ `/repos/${config.organization}/${config.repository}/issues/${issue.number}/labels/${encodeURIComponent(label)}`,
83
+ { method: 'DELETE', allow404: true },
84
+ )
85
+ }
86
+ return {
87
+ ...issue,
88
+ labels: issue.labels.filter((label) => !isInvalidIssueLabel(label)),
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Repair deterministic Issue metadata violations and publish the remaining audit result.
94
+ * @param {number} number Same-repository Issue number.
95
+ * @param {string[]} extraErrors Errors supplied by the triggering lifecycle operation.
96
+ * @param {string|null|undefined} status Optional known Project status.
97
+ * @returns {Promise<string[]>} Violations that remain after repair.
98
+ */
99
+ export async function auditIssue(number, extraErrors = [], status = undefined) {
100
+ const issue = await issueSnapshot(number, status)
101
+ if (!issue) return []
102
+ const repairedIssue = await repairIssueLabels(issue)
103
+ const errors = [...extraErrors, ...validateIssue(repairedIssue)]
104
+ await upsertAudit(number, errors)
105
+ return errors
106
+ }
107
+
108
+ async function transitionResolvingIssues(pull, command) {
109
+ for (const number of pull.references.resolving) {
110
+ const context = await projectContext(number, command === 'changes-requested')
111
+ const target = nextResolvingIssueStatus(
112
+ context.item?.fieldValueByName?.name ?? null,
113
+ command,
114
+ context.statusActor,
115
+ )
116
+ if (!target) continue
117
+ // TODO: Replace this latest-state guard with per-Issue serialization or a
118
+ // conditional ProjectV2 update; GraphQL currently has no compare-and-swap.
119
+ await updateStatus(context, target)
120
+ await auditIssue(number)
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Apply repository lifecycle events; irrelevant PR events perform no requests.
126
+ * @param {string} eventName GitHub event name.
127
+ * @param {object} event GitHub event payload.
128
+ * @returns {Promise<void>} Resolves after lifecycle updates and audits.
129
+ */
130
+ export async function runLifecycle(eventName, event) {
131
+ if (eventName === 'issues') {
132
+ const number = event.issue.number
133
+ if (event.action === 'opened') await setStatus(number, 'Inbox')
134
+ if (event.action === 'closed') {
135
+ const target = event.issue.state_reason === 'not_planned' ? 'No action' : 'Done'
136
+ await setStatus(number, target)
137
+ }
138
+ if (event.action === 'reopened') {
139
+ await setStatus(number, 'Inbox')
140
+ }
141
+ await ensureProjectItem(number)
142
+ await auditIssue(number)
143
+ return
144
+ }
145
+
146
+ if (eventName === 'pull_request' || eventName === 'pull_request_review') {
147
+ const command = resolvingIssueStatusCommand(eventName, event)
148
+ if (!command) return
149
+ const pull = await lifecyclePullRequestSnapshot(event.pull_request.number)
150
+ await transitionResolvingIssues(pull, command)
151
+ if (eventName === 'pull_request') {
152
+ await initializePullRequestStartDates(pull, event.action)
153
+ }
154
+ }
155
+ }
.github/issue-management/policy.mjs ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs'
4
+ import process from 'node:process'
5
+ import { pathToFileURL } from 'node:url'
6
+
7
+ /** Command-line dispatch for PR policy checks and Issue lifecycle events. */
8
+ import { runLifecycle } from './lifecycle.mjs'
9
+ import { runPullRequestCheck, runPullRequestPreflight } from './pull-request.mjs'
10
+
11
+ function readEvent() {
12
+ if (!process.env.GITHUB_EVENT_PATH) throw new Error('GITHUB_EVENT_PATH 未设置')
13
+ return JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'))
14
+ }
15
+
16
+ async function main(argv) {
17
+ const [command] = argv
18
+ if (command === 'pr-preflight') await runPullRequestPreflight(readEvent())
19
+ else if (command === 'pr') await runPullRequestCheck(readEvent())
20
+ else if (command === 'lifecycle') await runLifecycle(process.env.GITHUB_EVENT_NAME, readEvent())
21
+ else throw new Error('用法:policy.mjs pr-preflight|pr|lifecycle')
22
+ }
23
+
24
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
25
+ main(process.argv.slice(2)).catch((error) => {
26
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
27
+ process.exitCode = 1
28
+ })
29
+ }
.github/issue-management/policy.test.mjs ADDED
@@ -0,0 +1,1077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from 'node:assert/strict'
2
+ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { spawnSync } from 'node:child_process'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import test from 'node:test'
7
+
8
+ import { api, graphql, initializeIssueStartDate, issueSnapshot } from './github.mjs'
9
+ import { auditIssue, initializePullRequestStartDates, repairIssueLabels, runLifecycle } from './lifecycle.mjs'
10
+ import {
11
+ lifecyclePullRequestSnapshot,
12
+ pullRequestSnapshot,
13
+ runPullRequestCheck,
14
+ runPullRequestPreflight,
15
+ } from './pull-request.mjs'
16
+ import {
17
+ nextResolvingIssueStatus,
18
+ parseReferences,
19
+ projectDate,
20
+ retainIssueReferences,
21
+ resolvingIssueStatusCommand,
22
+ requiresPullRequestPolicy,
23
+ validateIssue,
24
+ validatePullRequest,
25
+ } from './rules.mjs'
26
+
27
+ const projectGraphqlData = ({
28
+ projectItem = true,
29
+ priority = null,
30
+ priorityField = true,
31
+ priorityType = 'SINGLE_SELECT',
32
+ priorityIsIssueField = false,
33
+ startDate = null,
34
+ startDateField = true,
35
+ startDateType = 'DATE',
36
+ startDateIsIssueField = false,
37
+ } = {}) => ({
38
+ organization: {
39
+ projectV2: {
40
+ id: 'project-id',
41
+ title: 'DSH Issue Management',
42
+ fields: {
43
+ nodes: [
44
+ {
45
+ id: 'status-field-id',
46
+ name: 'Status',
47
+ dataType: 'SINGLE_SELECT',
48
+ isIssueField: false,
49
+ options: [],
50
+ },
51
+ ...(priorityField
52
+ ? [
53
+ {
54
+ id: 'priority-project-field-id',
55
+ name: 'Priority',
56
+ dataType: priorityType,
57
+ isIssueField: priorityIsIssueField,
58
+ options: [],
59
+ },
60
+ ]
61
+ : []),
62
+ ...(startDateField
63
+ ? [
64
+ {
65
+ id: 'start-date-field-id',
66
+ name: 'Start Date',
67
+ dataType: startDateType,
68
+ isIssueField: startDateIsIssueField,
69
+ },
70
+ ]
71
+ : []),
72
+ ],
73
+ },
74
+ },
75
+ },
76
+ repository: {
77
+ issue: {
78
+ id: 'issue-id',
79
+ projectItems: {
80
+ nodes: projectItem
81
+ ? [
82
+ {
83
+ id: 'item-id',
84
+ project: { id: 'project-id' },
85
+ fieldValueByName: { name: 'Inbox', optionId: 'inbox-option-id' },
86
+ priorityValue:
87
+ priority === null ? null : { name: priority, optionId: `${priority}-option-id` },
88
+ startDateValue: startDate === null ? null : { date: startDate },
89
+ },
90
+ ]
91
+ : [],
92
+ },
93
+ },
94
+ },
95
+ })
96
+
97
+ const mockGraphql = (t, resolve) => {
98
+ const requests = []
99
+ const previousToken = process.env.GH_TOKEN
100
+ process.env.GH_TOKEN = 'test-token'
101
+ t.after(() => {
102
+ if (previousToken === undefined) delete process.env.GH_TOKEN
103
+ else process.env.GH_TOKEN = previousToken
104
+ })
105
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
106
+ assert.equal(url, 'https://api.github.com/graphql')
107
+ assert.equal(options.headers.Authorization, 'Bearer test-token')
108
+ const request = JSON.parse(options.body)
109
+ requests.push(request)
110
+ return Response.json({ data: resolve(request, requests.length - 1) })
111
+ })
112
+ return requests
113
+ }
114
+
115
+ const legalIssue = {
116
+ labels: [],
117
+ type: 'Idea',
118
+ priority: null,
119
+ status: 'In review',
120
+ state: 'open',
121
+ stateReason: null,
122
+ }
123
+
124
+ const canonicalKinds = [
125
+ 'kind/feature',
126
+ 'kind/bug-fix',
127
+ 'kind/doc',
128
+ 'kind/testing',
129
+ 'kind/cleanup',
130
+ 'kind/dependency',
131
+ ]
132
+
133
+ // Keep an independent oracle rather than importing the implementation's reserved set.
134
+ const legacyLabels = [
135
+ 'kind/bug',
136
+ 'kind/documentation',
137
+ 'feature',
138
+ 'bug-fix',
139
+ 'doc',
140
+ 'cleanup',
141
+ 'testing',
142
+ 'dependencies',
143
+ 'ci',
144
+ 'cli',
145
+ 'llm',
146
+ 'web-search',
147
+ ]
148
+
149
+ const reviewedPull = (labels) => ({
150
+ isDraft: false,
151
+ authorType: 'User',
152
+ reviewRequestCount: 1,
153
+ reviewCount: 0,
154
+ labels,
155
+ references: { all: [2], resolving: [], related: [2] },
156
+ issues: new Map([[2, { priority: null }]]),
157
+ })
158
+
159
+ test('keeps only Bug, Feature, and Task Issue templates with used frontmatter', () => {
160
+ const directory = new URL('../ISSUE_TEMPLATE/', import.meta.url)
161
+ assert.deepEqual(readdirSync(directory).sort(), ['bug.md', 'config.yml', 'feature.md', 'task.md'])
162
+
163
+ for (const file of ['bug.md', 'feature.md', 'task.md']) {
164
+ const source = readFileSync(new URL(file, directory), 'utf8')
165
+ const frontmatter = source.match(/^---\n([\s\S]*?)\n---/)?.[1] ?? ''
166
+ const keys = frontmatter
167
+ .split('\n')
168
+ .filter(Boolean)
169
+ .map((line) => line.slice(0, line.indexOf(':')))
170
+ .sort()
171
+ assert.deepEqual(keys, ['about', 'name', 'type'], file)
172
+ assert.match(source, /^## /m, file)
173
+ assert.match(source, /<!-- [^\n]+ -->/, file)
174
+ assert.doesNotMatch(source, /<details\b/i, file)
175
+ }
176
+ assert.equal(
177
+ readFileSync(new URL('config.yml', directory), 'utf8'),
178
+ 'blank_issues_enabled: false\n',
179
+ )
180
+ })
181
+
182
+ test('keeps Feature Issues limited to motivation and behavior', () => {
183
+ const source = readFileSync(
184
+ new URL('../ISSUE_TEMPLATE/feature.md', import.meta.url),
185
+ 'utf8',
186
+ )
187
+ assert.deepEqual(
188
+ [...source.matchAll(/^## .+$/gm)].map(([heading]) => heading),
189
+ ['## Motivation', '## Behavior'],
190
+ )
191
+ })
192
+
193
+ test('keeps Bug Issues limited to the problem report', () => {
194
+ const source = readFileSync(new URL('../ISSUE_TEMPLATE/bug.md', import.meta.url), 'utf8')
195
+ assert.deepEqual(
196
+ [...source.matchAll(/^## .+$/gm)].map(([heading]) => heading),
197
+ ['## Summary', '## Reproduction', '## Current behavior', '## Expected behavior', '## Environment'],
198
+ )
199
+ })
200
+
201
+ test('keeps Task Issues limited to summary and deliverables', () => {
202
+ const source = readFileSync(new URL('../ISSUE_TEMPLATE/task.md', import.meta.url), 'utf8')
203
+ assert.deepEqual(
204
+ [...source.matchAll(/^## .+$/gm)].map(([heading]) => heading),
205
+ ['## Summary', '## Deliverables'],
206
+ )
207
+ })
208
+
209
+ test('structures the pull request template around motivation, changes, and testing', () => {
210
+ const source = readFileSync(new URL('../pull_request_template.md', import.meta.url), 'utf8')
211
+ for (const heading of ['## Motivation', '## Changes', '## Testing']) {
212
+ assert.match(source, new RegExp(`^${heading.replaceAll('#', '\\#')}$`, 'm'))
213
+ }
214
+ assert.doesNotMatch(source, /^### /m)
215
+ assert.match(
216
+ source,
217
+ /<!-- 高层次说明命令[^\n]+ -->\n<!-- 高层次说明用户[^\n]+ -->/,
218
+ )
219
+ assert.match(source, /- <!-- [^\n]+ -->\n\n <details>\n <summary>Proof<\/summary>/)
220
+ assert.equal(source.match(/<details>/g)?.length, 1)
221
+ assert.equal(source.match(/<\/details>/g)?.length, 1)
222
+ })
223
+
224
+ test('ignores Issue title, body presentation, and assignee ownership', () => {
225
+ assert.deepEqual(
226
+ validateIssue({
227
+ ...legalIssue,
228
+ title: '[Bug] English title',
229
+ body: `Owner: @octocat\n\n${'visible '.repeat(60)}<details open>unclosed`,
230
+ assignees: ['octocat', 'hubot'],
231
+ }),
232
+ [],
233
+ )
234
+ })
235
+
236
+ test('allows optional metadata in every open Status', () => {
237
+ assert.deepEqual(validateIssue(legalIssue), [])
238
+ for (const status of ['Inbox', 'Backlog', 'Ready', 'In progress', 'In review']) {
239
+ assert.deepEqual(validateIssue({ ...legalIssue, status }), [])
240
+ }
241
+ })
242
+
243
+ test('reserves PR kind and legacy labels for pull requests', () => {
244
+ for (const label of [
245
+ ...canonicalKinds,
246
+ 'kind/experimental',
247
+ ...legacyLabels,
248
+ ]) {
249
+ assert.ok(
250
+ validateIssue({ ...legalIssue, labels: [label] }).some((error) =>
251
+ error.startsWith('Issue 不得使用 PR kind 或旧版标签:'),
252
+ ),
253
+ label,
254
+ )
255
+ }
256
+ assert.deepEqual(validateIssue({ ...legalIssue, labels: ['area/web', 'source/member'] }), [])
257
+ })
258
+
259
+ test('removes reserved labels from Issues before validation', async (t) => {
260
+ const previousToken = process.env.GH_TOKEN
261
+ process.env.GH_TOKEN = 'test-token'
262
+ t.after(() => {
263
+ if (previousToken === undefined) delete process.env.GH_TOKEN
264
+ else process.env.GH_TOKEN = previousToken
265
+ })
266
+ const requests = []
267
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
268
+ requests.push({ url, method: options.method })
269
+ assert.equal(options.headers.Authorization, 'Bearer test-token')
270
+ if (url.endsWith('/labels/bug-fix')) {
271
+ return Response.json({ message: 'Label does not exist' }, { status: 404 })
272
+ }
273
+ return Response.json([])
274
+ })
275
+
276
+ const issue = {
277
+ ...legalIssue,
278
+ number: 42,
279
+ labels: ['area/web', 'kind/bug-fix', 'bug-fix', 'source/member'],
280
+ }
281
+ const repaired = await repairIssueLabels(issue)
282
+
283
+ assert.deepEqual(repaired.labels, ['area/web', 'source/member'])
284
+ assert.deepEqual(issue.labels, ['area/web', 'kind/bug-fix', 'bug-fix', 'source/member'])
285
+ assert.deepEqual(validateIssue(repaired), [])
286
+ assert.deepEqual(requests, [
287
+ {
288
+ url: 'https://api.github.com/repos/deepseek-harness/deepseek-harness/issues/42/labels/kind%2Fbug-fix',
289
+ method: 'DELETE',
290
+ },
291
+ {
292
+ url: 'https://api.github.com/repos/deepseek-harness/deepseek-harness/issues/42/labels/bug-fix',
293
+ method: 'DELETE',
294
+ },
295
+ ])
296
+ })
297
+
298
+ test('deletes a stale audit comment after repairing its only violation', async (t) => {
299
+ const previousToken = process.env.GH_TOKEN
300
+ process.env.GH_TOKEN = 'test-token'
301
+ t.after(() => {
302
+ if (previousToken === undefined) delete process.env.GH_TOKEN
303
+ else process.env.GH_TOKEN = previousToken
304
+ })
305
+ const requests = []
306
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
307
+ requests.push({ url, method: options.method ?? 'GET' })
308
+ if (url.endsWith('/issues/42')) {
309
+ return Response.json({
310
+ node_id: 'issue-id',
311
+ labels: [{ name: 'area/web' }, { name: 'kind/bug-fix' }],
312
+ type: { name: 'Bug' },
313
+ state: 'open',
314
+ state_reason: null,
315
+ })
316
+ }
317
+ if (url.endsWith('/graphql')) return Response.json({ data: projectGraphqlData() })
318
+ if (url.endsWith('/labels/kind%2Fbug-fix')) return Response.json([{ name: 'area/web' }])
319
+ if (url.endsWith('/issues/42/comments?per_page=100')) {
320
+ return Response.json([
321
+ {
322
+ id: 99,
323
+ user: { type: 'Bot' },
324
+ body: '<!-- dsh-issue-policy -->\nold audit',
325
+ },
326
+ ])
327
+ }
328
+ if (url.endsWith('/issues/comments/99')) return new Response(null, { status: 204 })
329
+ return Response.json({ message: 'unexpected request' }, { status: 500 })
330
+ })
331
+
332
+ assert.deepEqual(await auditIssue(42), [])
333
+ assert.deepEqual(
334
+ requests.map(({ url, method }) => ({ path: new URL(url).pathname + new URL(url).search, method })),
335
+ [
336
+ { path: '/repos/deepseek-harness/deepseek-harness/issues/42', method: 'GET' },
337
+ { path: '/graphql', method: 'POST' },
338
+ {
339
+ path: '/repos/deepseek-harness/deepseek-harness/issues/42/labels/kind%2Fbug-fix',
340
+ method: 'DELETE',
341
+ },
342
+ {
343
+ path: '/repos/deepseek-harness/deepseek-harness/issues/42/comments?per_page=100',
344
+ method: 'GET',
345
+ },
346
+ {
347
+ path: '/repos/deepseek-harness/deepseek-harness/issues/comments/99',
348
+ method: 'DELETE',
349
+ },
350
+ ],
351
+ )
352
+ })
353
+
354
+ test('keeps terminal Status aligned with the native close reason', () => {
355
+ assert.deepEqual(
356
+ validateIssue({ ...legalIssue, status: 'Done', state: 'closed', stateReason: 'completed' }),
357
+ [],
358
+ )
359
+ assert.deepEqual(
360
+ validateIssue({
361
+ ...legalIssue,
362
+ status: 'No action',
363
+ state: 'closed',
364
+ stateReason: 'not_planned',
365
+ }),
366
+ [],
367
+ )
368
+ assert.ok(validateIssue({ ...legalIssue, status: 'Done' }).includes('Done 必须对应 Completed 关闭原因'))
369
+ })
370
+
371
+ test('separates resolving and informational references', () => {
372
+ assert.deepEqual(
373
+ parseReferences({
374
+ body: 'Fixes #12\nRelated to #4\nRefs deepseekharness/dsh-test#7',
375
+ repository: 'deepseekharness/dsh-test',
376
+ }),
377
+ { all: [4, 7, 12], resolving: [12], related: [4, 7] },
378
+ )
379
+ })
380
+
381
+ test('converts PR creation timestamps to Shanghai Project dates', () => {
382
+ assert.equal(projectDate('2026-08-27T15:59:59Z', 'Asia/Shanghai'), '2026-08-27')
383
+ assert.equal(projectDate('2026-08-27T16:00:00Z', 'Asia/Shanghai'), '2026-08-28')
384
+ assert.throws(() => projectDate('invalid', 'Asia/Shanghai'), /无效的 PR 创建时间/)
385
+ })
386
+
387
+ test('initializes every referenced Issue only for a PR opened event', async () => {
388
+ const writes = []
389
+ const pull = {
390
+ createdAt: '2026-08-27T16:00:00Z',
391
+ references: { all: [4, 7, 12] },
392
+ }
393
+ const initialize = async (number, date) => writes.push({ number, date })
394
+
395
+ await initializePullRequestStartDates(pull, 'opened', initialize)
396
+ assert.deepEqual(writes, [
397
+ { number: 4, date: '2026-08-28' },
398
+ { number: 7, date: '2026-08-28' },
399
+ { number: 12, date: '2026-08-28' },
400
+ ])
401
+
402
+ for (const action of ['edited', 'synchronize', 'reopened']) {
403
+ await initializePullRequestStartDates(pull, action, initialize)
404
+ }
405
+ assert.equal(writes.length, 3)
406
+ })
407
+
408
+ test('reads Priority and Status from Project custom fields', async (t) => {
409
+ const previousGhToken = process.env.GH_TOKEN
410
+ const previousGithubToken = process.env.GITHUB_TOKEN
411
+ const previousProjectToken = process.env.PROJECT_TOKEN
412
+ delete process.env.GH_TOKEN
413
+ process.env.GITHUB_TOKEN = 'repository-token'
414
+ process.env.PROJECT_TOKEN = 'project-token'
415
+ t.after(() => {
416
+ if (previousGhToken === undefined) delete process.env.GH_TOKEN
417
+ else process.env.GH_TOKEN = previousGhToken
418
+ if (previousGithubToken === undefined) delete process.env.GITHUB_TOKEN
419
+ else process.env.GITHUB_TOKEN = previousGithubToken
420
+ if (previousProjectToken === undefined) delete process.env.PROJECT_TOKEN
421
+ else process.env.PROJECT_TOKEN = previousProjectToken
422
+ })
423
+ const urls = []
424
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
425
+ urls.push(url)
426
+ if (url.endsWith('/issues/42')) {
427
+ assert.equal(options.headers.Authorization, 'Bearer repository-token')
428
+ return Response.json({
429
+ node_id: 'issue-id',
430
+ title: 'Project metadata',
431
+ body: null,
432
+ assignees: [],
433
+ labels: [],
434
+ type: { name: 'Task' },
435
+ state: 'open',
436
+ state_reason: null,
437
+ })
438
+ }
439
+ assert.equal(url, 'https://api.github.com/graphql')
440
+ assert.equal(options.headers.Authorization, 'Bearer project-token')
441
+ return Response.json({ data: projectGraphqlData({ priority: 'P1' }) })
442
+ })
443
+
444
+ const issue = await issueSnapshot(42)
445
+
446
+ assert.equal(issue.priority, 'P1')
447
+ assert.equal(issue.status, 'Inbox')
448
+ assert.deepEqual(urls, [
449
+ 'https://api.github.com/repos/deepseek-harness/deepseek-harness/issues/42',
450
+ 'https://api.github.com/graphql',
451
+ ])
452
+ })
453
+
454
+ test('writes an empty Project Start Date with the configured field', async (t) => {
455
+ const requests = mockGraphql(t, (request) => {
456
+ if (request.query.includes('query(')) return projectGraphqlData()
457
+ return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'item-id' } } }
458
+ })
459
+
460
+ await initializeIssueStartDate(42, '2026-08-28')
461
+
462
+ assert.equal(requests.length, 2)
463
+ assert.match(requests[0].query, /isIssueField/)
464
+ assert.doesNotMatch(requests[0].query, /issueField\s*\{/)
465
+ assert.match(requests[0].query, /priorityValue: fieldValueByName/)
466
+ assert.equal(requests[0].variables.priorityField, 'Priority')
467
+ assert.match(requests[0].query, /ProjectV2ItemFieldDateValue/)
468
+ assert.match(requests[1].query, /updateProjectV2ItemFieldValue/)
469
+ assert.match(requests[1].query, /value: \{date: \$date\}/)
470
+ assert.deepEqual(requests[1].variables, {
471
+ projectId: 'project-id',
472
+ itemId: 'item-id',
473
+ fieldId: 'start-date-field-id',
474
+ date: '2026-08-28',
475
+ })
476
+ })
477
+
478
+ test('preserves an existing Project Start Date', async (t) => {
479
+ const requests = mockGraphql(t, () => projectGraphqlData({ startDate: '2026-08-01' }))
480
+
481
+ await initializeIssueStartDate(42, '2026-08-28')
482
+
483
+ assert.equal(requests.length, 1)
484
+ })
485
+
486
+ test('adds a referenced Issue to the Project before setting Start Date', async (t) => {
487
+ const requests = mockGraphql(t, (request) => {
488
+ if (request.query.includes('query(')) return projectGraphqlData({ projectItem: false })
489
+ if (request.query.includes('addProjectV2ItemById')) {
490
+ return { addProjectV2ItemById: { item: { id: 'new-item-id' } } }
491
+ }
492
+ return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'new-item-id' } } }
493
+ })
494
+
495
+ await initializeIssueStartDate(42, '2026-08-28')
496
+
497
+ assert.equal(requests.length, 3)
498
+ assert.deepEqual(requests[1].variables, { projectId: 'project-id', contentId: 'issue-id' })
499
+ assert.deepEqual(requests[2].variables, {
500
+ projectId: 'project-id',
501
+ itemId: 'new-item-id',
502
+ fieldId: 'start-date-field-id',
503
+ date: '2026-08-28',
504
+ })
505
+ })
506
+
507
+ test('rejects a missing, non-Date, or Issue-level Start Date field', async (t) => {
508
+ let response = projectGraphqlData({ startDateField: false })
509
+ const requests = mockGraphql(t, () => response)
510
+
511
+ await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Project 缺少 Start Date 字段/)
512
+ response = projectGraphqlData({ startDateType: 'TEXT' })
513
+ await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Start Date 字段必须为 Date/)
514
+ response = projectGraphqlData({ startDateIsIssueField: true })
515
+ await assert.rejects(
516
+ initializeIssueStartDate(42, '2026-08-28'),
517
+ /Start Date 字段必须为 Project Date 字段/,
518
+ )
519
+ assert.equal(requests.length, 3)
520
+ })
521
+
522
+ test('rejects a missing, non-select, or Issue-level Priority field', async (t) => {
523
+ let response = projectGraphqlData({ priorityField: false })
524
+ const requests = mockGraphql(t, () => response)
525
+
526
+ await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Project 缺少 Priority 字段/)
527
+ response = projectGraphqlData({ priorityType: 'TEXT' })
528
+ await assert.rejects(
529
+ initializeIssueStartDate(42, '2026-08-28'),
530
+ /Priority 字段必须为 Single Select/,
531
+ )
532
+ response = projectGraphqlData({ priorityIsIssueField: true })
533
+ await assert.rejects(
534
+ initializeIssueStartDate(42, '2026-08-28'),
535
+ /Priority 字段必须为 Project custom field/,
536
+ )
537
+ assert.equal(requests.length, 3)
538
+ })
539
+
540
+ test('does not treat pull request references as Issue associations', () => {
541
+ const references = {
542
+ all: [123, 1180, 1181],
543
+ resolving: [123, 1180],
544
+ related: [1181],
545
+ }
546
+ const issues = new Map([
547
+ [1180, {}],
548
+ [1181, {}],
549
+ ])
550
+
551
+ assert.deepEqual(retainIssueReferences(references, issues), {
552
+ all: [1180, 1181],
553
+ resolving: [1180],
554
+ related: [1181],
555
+ })
556
+ })
557
+
558
+ test('allows informational references without cross-object constraints', () => {
559
+ const errors = validatePullRequest({
560
+ isDraft: false,
561
+ authorType: 'User',
562
+ reviewRequestCount: 1,
563
+ reviewCount: 0,
564
+ labels: ['kind/cleanup', 'area/infra'],
565
+ references: { all: [4], resolving: [], related: [4] },
566
+ issues: new Map([[4, { type: 'Bug', priority: 'P0', labels: ['area/web'] }]]),
567
+ })
568
+ assert.deepEqual(errors, [])
569
+ })
570
+
571
+ test('enforces highest resolving Priority without Type or area synchronization', () => {
572
+ const pull = {
573
+ isDraft: false,
574
+ authorType: 'User',
575
+ reviewRequestCount: 0,
576
+ reviewCount: 1,
577
+ labels: ['kind/cleanup', 'p0', 'area/web'],
578
+ references: { all: [2, 3], resolving: [2, 3], related: [] },
579
+ issues: new Map([
580
+ [2, { type: 'Feature', priority: 'P2', labels: ['area/web'] }],
581
+ [3, { type: 'Bug', priority: 'P0', labels: ['area/session'] }],
582
+ ]),
583
+ }
584
+ assert.deepEqual(validatePullRequest(pull), [])
585
+ assert.ok(
586
+ validatePullRequest({ ...pull, labels: ['kind/cleanup', 'p2', 'area/web'] }).includes(
587
+ 'PR Priority 应为 p0',
588
+ ),
589
+ )
590
+ })
591
+
592
+ test('requires policy only after a human PR enters review', () => {
593
+ assert.equal(
594
+ requiresPullRequestPolicy({
595
+ isDraft: false,
596
+ authorType: 'User',
597
+ reviewRequestCount: 1,
598
+ reviewCount: 0,
599
+ }),
600
+ true,
601
+ )
602
+ assert.equal(
603
+ requiresPullRequestPolicy({
604
+ isDraft: false,
605
+ authorType: 'User',
606
+ reviewRequestCount: 0,
607
+ reviewCount: 0,
608
+ }),
609
+ false,
610
+ )
611
+ })
612
+
613
+ test('maps only explicit review handoffs to review status commands', () => {
614
+ assert.equal(
615
+ resolvingIssueStatusCommand('pull_request', {
616
+ action: 'review_requested',
617
+ }),
618
+ 'review-requested',
619
+ )
620
+ assert.equal(
621
+ resolvingIssueStatusCommand('pull_request_review', {
622
+ action: 'submitted',
623
+ review: { state: 'changes_requested' },
624
+ }),
625
+ 'changes-requested',
626
+ )
627
+ for (const state of ['approved', 'commented']) {
628
+ assert.equal(
629
+ resolvingIssueStatusCommand('pull_request_review', {
630
+ action: 'submitted',
631
+ review: { state },
632
+ }),
633
+ null,
634
+ )
635
+ }
636
+ assert.equal(
637
+ resolvingIssueStatusCommand('pull_request_review', {
638
+ action: 'dismissed',
639
+ review: { state: 'changes_requested' },
640
+ }),
641
+ null,
642
+ )
643
+ })
644
+
645
+ test('keeps PR opening, reopening, and body edits as implementation signals', () => {
646
+ for (const action of ['opened', 'reopened']) {
647
+ assert.equal(resolvingIssueStatusCommand('pull_request', { action }), 'implementation')
648
+ }
649
+ assert.equal(
650
+ resolvingIssueStatusCommand('pull_request', { action: 'edited', changes: { body: { from: '' } } }),
651
+ 'implementation',
652
+ )
653
+ for (const action of ['synchronize', 'labeled', 'unlabeled', 'edited']) {
654
+ assert.equal(resolvingIssueStatusCommand('pull_request', { action }), null)
655
+ }
656
+ assert.equal(
657
+ resolvingIssueStatusCommand('pull_request', { action: 'edited', changes: { title: { from: '' } } }),
658
+ null,
659
+ )
660
+ assert.equal(
661
+ resolvingIssueStatusCommand('pull_request', { action: 'review_request_removed' }),
662
+ null,
663
+ )
664
+ })
665
+
666
+ test('toggles automation-owned work on request changes and repeated review request', () => {
667
+ for (const status of ['Inbox', 'Backlog', 'Ready']) {
668
+ assert.equal(nextResolvingIssueStatus(status, 'implementation'), 'In progress')
669
+ assert.equal(nextResolvingIssueStatus(status, 'review-requested'), 'In review')
670
+ assert.equal(nextResolvingIssueStatus(status, 'changes-requested'), 'In progress')
671
+ }
672
+ let status = nextResolvingIssueStatus(
673
+ 'In review',
674
+ 'changes-requested',
675
+ 'dsh-issue-management',
676
+ )
677
+ assert.equal(status, 'In progress')
678
+ status = nextResolvingIssueStatus(status, 'review-requested')
679
+ assert.equal(status, 'In review')
680
+ })
681
+
682
+ test('preserves human review status and terminal Issues', () => {
683
+ assert.equal(nextResolvingIssueStatus('In progress', 'implementation'), null)
684
+ assert.equal(nextResolvingIssueStatus('In review', 'implementation'), null)
685
+ assert.equal(nextResolvingIssueStatus('In review', 'review-requested'), null)
686
+ assert.equal(nextResolvingIssueStatus('In review', 'changes-requested', 'tianyicui'), null)
687
+ assert.equal(nextResolvingIssueStatus('In review', 'changes-requested'), null)
688
+ assert.equal(nextResolvingIssueStatus('Done', 'review-requested'), null)
689
+ assert.equal(nextResolvingIssueStatus('No action', 'changes-requested'), null)
690
+ assert.equal(nextResolvingIssueStatus(null, 'review-requested'), null)
691
+ })
692
+
693
+ test('keeps lifecycle projection independent of PR metadata enforcement', () => {
694
+ const pull = {
695
+ isDraft: false,
696
+ authorType: 'User',
697
+ reviewRequestCount: 1,
698
+ reviewCount: 0,
699
+ labels: [],
700
+ references: { all: [2], resolving: [2], related: [] },
701
+ issues: new Map([[2, { priority: null }]]),
702
+ }
703
+
704
+ assert.ok(validatePullRequest(pull).length > 0)
705
+ assert.equal(nextResolvingIssueStatus('Inbox', 'review-requested'), 'In review')
706
+ })
707
+
708
+ test('exempts Draft, Bot, and App PRs', () => {
709
+ const invalid = {
710
+ isDraft: false,
711
+ labels: [],
712
+ references: { all: [], resolving: [], related: [] },
713
+ issues: new Map(),
714
+ reviewRequestCount: 1,
715
+ reviewCount: 0,
716
+ }
717
+ assert.deepEqual(validatePullRequest({ ...invalid, authorType: 'Bot' }), [])
718
+ assert.deepEqual(validatePullRequest({ ...invalid, authorType: 'App' }), [])
719
+ assert.deepEqual(validatePullRequest({ ...invalid, authorType: 'User', isDraft: true }), [])
720
+ assert.ok(validatePullRequest({ ...invalid, authorType: 'User' }).length > 0)
721
+ })
722
+
723
+ test('requires repository PR labels in the enforcement scope', () => {
724
+ const errors = validatePullRequest({
725
+ isDraft: false,
726
+ authorType: 'User',
727
+ reviewRequestCount: 1,
728
+ reviewCount: 0,
729
+ labels: [],
730
+ references: { all: [2], resolving: [], related: [2] },
731
+ issues: new Map([[2, { priority: null }]]),
732
+ })
733
+ assert.ok(errors.includes('PR 必须恰好有一个允许的 kind/*,当前为 0'))
734
+ assert.ok(errors.includes('PR 必须至少有一个 area/*'))
735
+ })
736
+
737
+ test('accepts exactly the canonical kinds with extensible areas', () => {
738
+ for (const kind of canonicalKinds) {
739
+ assert.deepEqual(validatePullRequest(reviewedPull([kind, 'area/future-domain'])), [], kind)
740
+ }
741
+ })
742
+
743
+ test('rejects multiple, unknown, legacy, and Issue-source PR labels', () => {
744
+ assert.ok(
745
+ validatePullRequest(
746
+ reviewedPull(['kind/feature', 'kind/doc', 'area/web']),
747
+ ).includes('PR ��须恰好有一个允许的 kind/*,当前为 2'),
748
+ )
749
+ assert.ok(
750
+ validatePullRequest(reviewedPull(['kind/experimental', 'area/web'])).includes(
751
+ 'PR 含不支持的 kind/*:kind/experimental',
752
+ ),
753
+ )
754
+ for (const label of legacyLabels) {
755
+ assert.ok(
756
+ validatePullRequest(reviewedPull(['kind/feature', 'area/web', label])).some((error) =>
757
+ error.startsWith('PR 含旧版标签:'),
758
+ ),
759
+ label,
760
+ )
761
+ }
762
+ assert.ok(
763
+ validatePullRequest(
764
+ reviewedPull(['kind/feature', 'area/web', 'source/internal-pr']),
765
+ ).includes('source/* 仅用于 Issue:source/internal-pr'),
766
+ )
767
+ })
768
+
769
+ const mockPolicyApi = (t, { pull = {}, requested = true, reviews = [], issues = {}, priority = 'P1', projectError = false } = {}) => {
770
+ const environment = ['GH_TOKEN', 'GITHUB_TOKEN', 'PROJECT_TOKEN', 'GITHUB_API_URL', 'GITHUB_OUTPUT']
771
+ const previous = new Map(environment.map((key) => [key, process.env[key]]))
772
+ const directory = mkdtempSync(join(tmpdir(), 'dsh-policy-'))
773
+ t.after(() => {
774
+ for (const [key, value] of previous) {
775
+ if (value === undefined) delete process.env[key]
776
+ else process.env[key] = value
777
+ }
778
+ rmSync(directory, { recursive: true, force: true })
779
+ })
780
+ for (const key of environment) delete process.env[key]
781
+ process.env.GITHUB_TOKEN = 'repository-token'
782
+ process.env.GITHUB_OUTPUT = join(directory, 'output')
783
+ const requests = []
784
+ const output = []
785
+ t.mock.method(process.stdout, 'write', (text) => { output.push(text); return true })
786
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
787
+ const path = new URL(url).pathname + new URL(url).search
788
+ requests.push(path)
789
+ if (path.endsWith('/pulls/10')) return Response.json({
790
+ draft: false, user: { type: 'User' }, body: 'Refs #2',
791
+ labels: [{ name: 'kind/cleanup' }, { name: 'area/infra' }], ...pull,
792
+ })
793
+ if (path.endsWith('/requested_reviewers')) {
794
+ return Response.json({ users: requested ? [{}] : [], teams: [] })
795
+ }
796
+ if (path.endsWith('/reviews?per_page=100')) return Response.json(reviews)
797
+ if (path === '/graphql') {
798
+ assert.equal(options.headers.Authorization, 'Bearer repository-token')
799
+ if (projectError) return Response.json({ errors: [{ message: 'Project access denied' }] })
800
+ return Response.json({ data: projectGraphqlData({ priority }) })
801
+ }
802
+ const number = Number(path.match(/\/issues\/(\d+)$/)?.[1])
803
+ assert.ok(Object.hasOwn(issues, number), 'Unexpected request: ' + path)
804
+ const issue = issues[number]
805
+ return Response.json(issue ?? { message: 'Not Found' }, { status: issue === null ? 404 : 200 })
806
+ })
807
+ return { requests, output, workflowOutput: () => readFileSync(process.env.GITHUB_OUTPUT, 'utf8') }
808
+ }
809
+
810
+ for (const [name, pull, requested, count] of [
811
+ ['draft', { draft: true }, true, 1],
812
+ ['Bot', { user: { type: 'Bot' } }, true, 1],
813
+ ['App', { user: { type: 'App' } }, true, 1],
814
+ ['not reviewed', {}, false, 3],
815
+ ]) {
816
+ test('reads no Issue or Project for a currently exempt ' + name + ' PR', async (t) => {
817
+ const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #999', ...pull }, requested })
818
+ const event = { pull_request: { number: 10, draft: false, user: { type: 'User' } } }
819
+ assert.deepEqual(await runPullRequestPreflight(event), { eligible: false, needsProject: false })
820
+ assert.equal(fixture.requests.length, count)
821
+ assert.equal(fixture.workflowOutput(), 'eligible=false\nexempt=true\nneeds-project=false\n')
822
+ await runPullRequestCheck(event)
823
+ assert.equal(fixture.requests.length, count * 2)
824
+ assert.ok(fixture.output.every((text) => text.includes('Issue policy exempt')))
825
+ })
826
+ }
827
+
828
+ test('validates informational Issues and ignores PR numbers without Project reads', async (t) => {
829
+ const fixture = mockPolicyApi(t, { pull: { body: 'Refs #2; Fixes #3' }, issues: { 2: {}, 3: { pull_request: {} } } })
830
+ const event = { pull_request: { number: 10, draft: true, body: 'Fixes #999' } }
831
+ assert.deepEqual(await runPullRequestPreflight(event), { eligible: true, needsProject: false })
832
+ assert.equal(fixture.requests.length, 5)
833
+ assert.equal(fixture.workflowOutput(), 'eligible=true\nexempt=false\nneeds-project=false\n')
834
+ await runPullRequestCheck(event)
835
+ assert.equal(fixture.requests.length, 10)
836
+ assert.ok(!fixture.requests.includes('/graphql'))
837
+ })
838
+
839
+ test('requires a real Issue and explains why stacked PR references do not qualify', async (t) => {
840
+ const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #3' }, issues: { 3: { pull_request: {} } } })
841
+ await assert.rejects(runPullRequestCheck({ pull_request: { number: 10 } }), /Issue policy 未通过/)
842
+ assert.equal(fixture.requests.length, 4)
843
+ assert.match(fixture.output.join(''), /PR 编号(包括堆叠依赖 PR)不算 Issue 引用/)
844
+ })
845
+
846
+ test('fetches Project Priority only for resolving Issues and enforces mismatch', async (t) => {
847
+ const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #2; Refs #4; Fixes #3' }, issues: { 2: {}, 4: {}, 3: { pull_request: {} } } })
848
+ const event = { pull_request: { number: 10 } }
849
+ assert.deepEqual(await runPullRequestPreflight(event), { eligible: true, needsProject: true })
850
+ assert.equal(fixture.requests.length, 6)
851
+ assert.equal(fixture.workflowOutput(), 'eligible=true\nexempt=false\nneeds-project=true\n')
852
+ assert.ok(!fixture.requests.includes('/graphql'))
853
+ await assert.rejects(runPullRequestCheck(event), /Issue policy 未通过/)
854
+ assert.equal(fixture.requests.length, 13)
855
+ assert.equal(fixture.requests.filter((path) => path === '/graphql').length, 1)
856
+ assert.match(fixture.output.join(''), /PR Priority 应为 p1/)
857
+ })
858
+
859
+ test('enforces current metadata on title edits and prior reviews without requested reviewers', async (t) => {
860
+ const fixture = mockPolicyApi(t, { requested: false, reviews: [{}], pull: { labels: [] }, issues: { 2: {} } })
861
+ await assert.rejects(runPullRequestCheck({ action: 'edited', changes: { title: { from: 'old' } }, pull_request: { number: 10 } }), /Issue policy 未通过/)
862
+ assert.equal(fixture.requests.length, 4)
863
+ assert.match(fixture.output.join(''), /PR 必须至少有一个 area/)
864
+ })
865
+
866
+ test('fails closed on missing referenced numbers and unavailable Project access', async (t) => {
867
+ const fixture = mockPolicyApi(t, { pull: { body: 'Fixes #2' }, issues: { 2: null } })
868
+ await assert.rejects(runPullRequestPreflight({ pull_request: { number: 10 } }), /404/)
869
+ assert.equal(fixture.requests.length, 4)
870
+ })
871
+
872
+ test('fails closed when current resolving Issues need a Project token preflight did not mint', async (t) => {
873
+ const pull = { draft: true, body: 'Fixes #2' }
874
+ const fixture = mockPolicyApi(t, { pull, issues: { 2: {} }, projectError: true })
875
+ const event = { pull_request: { number: 10 } }
876
+ assert.deepEqual(await runPullRequestPreflight(event), { eligible: false, needsProject: false })
877
+ pull.draft = false
878
+ await assert.rejects(runPullRequestCheck(event), /Project access denied/)
879
+ assert.equal(fixture.requests.length, 6)
880
+ })
881
+
882
+ test('performs no lifecycle requests for removed signals or title-only edits', async (t) => {
883
+ const fixture = mockPolicyApi(t)
884
+ for (const action of ['synchronize', 'labeled', 'unlabeled']) {
885
+ await runLifecycle('pull_request', { action, pull_request: { number: 10 } })
886
+ }
887
+ await runLifecycle('pull_request', { action: 'edited', changes: { title: { from: '' } }, pull_request: { number: 10 } })
888
+ for (const state of ['approved', 'commented']) {
889
+ await runLifecycle('pull_request_review', { action: 'submitted', review: { state }, pull_request: { number: 10 } })
890
+ }
891
+ assert.deepEqual(fixture.requests, [])
892
+ })
893
+
894
+ test('keeps trusted preflight before token minting and required policy unconditional', () => {
895
+ const source = readFileSync(new URL('../workflows/issue-policy.yml', import.meta.url), 'utf8')
896
+ const job = source.slice(source.indexOf(' policy:'))
897
+ assert.ok(job.includes(' name: Issue policy'))
898
+ assert.ok(!job.slice(0, job.indexOf(' steps:')).includes(' if:'))
899
+ assert.ok(source.includes('types: [opened, edited, synchronize, reopened, labeled, unlabeled, ready_for_review, review_requested]'))
900
+ const steps = job.split(' - name: ').slice(1)
901
+ assert.equal(steps.length, 4)
902
+ assert.ok(steps[0].includes('ref: ${{ github.event.repository.default_branch }}'))
903
+ assert.ok(steps[0].includes('persist-credentials: false'))
904
+ assert.doesNotMatch(source, /pull_request\.head|pull_request_target/)
905
+ assert.ok(steps[1].includes('id: preflight'))
906
+ assert.ok(steps[1].includes('GITHUB_TOKEN: ${{ github.token }}'))
907
+ assert.ok(steps[1].includes('node .github/issue-management/policy.mjs pr-preflight'))
908
+ assert.ok(steps[1].includes('if [ -f .github/issue-management/selective-preflight.json ]; then'))
909
+ assert.doesNotMatch(steps[1], /secrets\.|PROJECT_TOKEN|if:/)
910
+ assert.ok(steps[2].includes("if: ${{ steps.preflight.outputs.needs-project == 'true' }}"))
911
+ assert.ok(steps[2].includes('permission-organization-projects: read'))
912
+ assert.ok(steps[3].includes('PROJECT_TOKEN: ${{ steps.app-token.outputs.token }}'))
913
+ assert.ok(steps[3].includes('run: node .github/issue-management/policy.mjs pr'))
914
+ assert.ok(steps[3].includes("if: ${{ steps.preflight.outputs.legacy-automated != 'true' }}"))
915
+ })
916
+
917
+ test('runs trusted rollout selection with absent and present capability markers', { skip: process.platform === 'win32' ? 'The policy workflow executes under hosted Ubuntu bash' : false }, (t) => {
918
+ const directory = mkdtempSync(join(tmpdir(), 'dsh-policy-rollout-'))
919
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
920
+ const source = readFileSync(new URL('../workflows/issue-policy.yml', import.meta.url), 'utf8')
921
+ const script = source.split(' run: |\n')[1].split(' - name: Create Project read token')[0]
922
+ .split('\n').map((line) => line.slice(10)).join('\n')
923
+ assert.deepEqual(JSON.parse(readFileSync(new URL('./selective-preflight.json', import.meta.url), 'utf8')), { version: 1 })
924
+ const cases = [
925
+ { name: 'legacy human draft', type: 'User', draft: true, marker: false, expected: 'legacy-automated=false\nneeds-project=true\n' },
926
+ { name: 'legacy human ready', type: 'User', draft: false, marker: false, expected: 'legacy-automated=false\nneeds-project=true\n' },
927
+ { name: 'legacy bot', type: 'Bot', marker: false, expected: 'legacy-automated=true\nneeds-project=false\n' },
928
+ { name: 'legacy app', type: 'App', marker: false, expected: 'legacy-automated=true\nneeds-project=false\n' },
929
+ { name: 'modern exempt', type: 'Bot', marker: true, expected: 'exempt=true\nneeds-project=false\n' },
930
+ { name: 'modern failure', type: 'User', marker: true, failure: true, expected: '' },
931
+ ]
932
+ for (const [index, fixture] of cases.entries()) {
933
+ const cwd = join(directory, String(index))
934
+ const policyDirectory = join(cwd, '.github', 'issue-management')
935
+ mkdirSync(policyDirectory, { recursive: true })
936
+ const eventPath = join(cwd, 'event.json')
937
+ const outputPath = join(cwd, 'output')
938
+ writeFileSync(eventPath, JSON.stringify({ pull_request: { user: { type: fixture.type }, draft: fixture.draft } }))
939
+ writeFileSync(outputPath, '')
940
+ if (fixture.marker) writeFileSync(join(policyDirectory, 'selective-preflight.json'), '{"version":1}\n')
941
+ writeFileSync(join(policyDirectory, 'policy.mjs'), fixture.marker && !fixture.failure
942
+ ? "import fs from 'node:fs'; if (process.argv[2] !== 'pr-preflight') throw Error('wrong command'); fs.appendFileSync(process.env.GITHUB_OUTPUT, 'exempt=true\\nneeds-project=false\\n')\n"
943
+ : "throw new Error('preflight unavailable or failed')\n")
944
+ const result = spawnSync('bash', ['--noprofile', '--norc', '-eo', 'pipefail', '-c', script], {
945
+ cwd,
946
+ env: { PATH: process.env.PATH, GITHUB_EVENT_PATH: eventPath, GITHUB_OUTPUT: outputPath },
947
+ encoding: 'utf8',
948
+ timeout: 30_000,
949
+ })
950
+ assert.equal(result.error, undefined, fixture.name)
951
+ assert.equal(result.signal, null, fixture.name)
952
+ assert.equal(result.status, fixture.failure ? 1 : 0, fixture.name + ': ' + result.stderr)
953
+ assert.equal(readFileSync(outputPath, 'utf8'), fixture.expected, fixture.name)
954
+ if (fixture.marker) assert.doesNotMatch(result.stdout, /preserving legacy/)
955
+ else assert.match(result.stdout, /preserving legacy policy enforcement/)
956
+ }
957
+ })
958
+
959
+ test('allocates lifecycle runners only for relevant reviews and PR body edits', () => {
960
+ const source = readFileSync(new URL('../workflows/issue-lifecycle.yml', import.meta.url), 'utf8')
961
+ const issues = source.split(' issues:')[1].split(' pull_request:')[0]
962
+ const pulls = source.split(' pull_request:')[1].split(' pull_request_review:')[0]
963
+ const actions = (block) => [...block.matchAll(/^ - (\w+)$/gm)].map((match) => match[1])
964
+ assert.deepEqual(actions(issues), ['opened', 'edited', 'labeled', 'unlabeled', 'closed', 'reopened', 'typed', 'untyped', 'field_added', 'field_removed'])
965
+ assert.deepEqual(actions(pulls), ['opened', 'edited', 'reopened', 'review_requested'])
966
+ const job = source.slice(source.indexOf(' lifecycle:'))
967
+ const beforeSteps = job.slice(0, job.indexOf(' steps:'))
968
+ assert.ok(beforeSteps.includes(' if: >-'))
969
+ assert.ok(beforeSteps.includes("(github.event_name != 'pull_request_review' || github.event.review.state == 'changes_requested') &&"))
970
+ assert.ok(beforeSteps.includes("(github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.body != null)"))
971
+ assert.ok(source.includes('ref: ${{ github.event.repository.default_branch }}'))
972
+ assert.ok(source.includes('persist-credentials: false'))
973
+ })
974
+
975
+ test('keeps REST headers, null responses, and transport errors unchanged', async (t) => {
976
+ mockPolicyApi(t)
977
+ process.env.GH_TOKEN = 'preferred-token'
978
+ process.env.PROJECT_TOKEN = 'project-token'
979
+ process.env.GITHUB_API_URL = 'https://github.example/api/v3'
980
+ const requests = []
981
+ const responses = [
982
+ Response.json({ ok: true }),
983
+ new Response(null, { status: 204 }),
984
+ new Response('missing', { status: 404 }),
985
+ new Response('denied', { status: 403 }),
986
+ Response.json({ errors: [{ message: 'first' }, { message: 'second' }] }),
987
+ ]
988
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
989
+ requests.push({ url, options })
990
+ return responses.shift()
991
+ })
992
+ assert.deepEqual(await api('/example'), { ok: true })
993
+ assert.deepEqual(requests[0], {
994
+ url: 'https://github.example/api/v3/example',
995
+ options: { headers: {
996
+ Accept: 'application/vnd.github+json',
997
+ Authorization: 'Bearer preferred-token',
998
+ 'X-GitHub-Api-Version': '2026-03-10',
999
+ 'User-Agent': 'dsh-issue-policy',
1000
+ } },
1001
+ })
1002
+ assert.equal(await api('/empty'), null)
1003
+ assert.equal(await api('/missing', { allow404: true }), null)
1004
+ await assert.rejects(api('/denied', { method: 'PATCH' }), { message: 'PATCH /denied: 403 denied' })
1005
+ await assert.rejects(graphql('query { viewer { login } }', {}), { message: 'first; second' })
1006
+ assert.equal(requests[4].options.headers.Authorization, 'Bearer project-token')
1007
+ assert.equal(requests[4].options.method, 'POST')
1008
+ assert.equal(requests[4].options.body, JSON.stringify({ query: 'query { viewer { login } }', variables: {} }))
1009
+ assert.equal(requests.length, 5)
1010
+ })
1011
+
1012
+ test('reads policy snapshots in reference order and only resolving Project priorities', async (t) => {
1013
+ const fixture = mockPolicyApi(t, {
1014
+ pull: { body: 'Refs #4; Fixes #3; Fixes #2' },
1015
+ issues: { 2: {}, 3: { pull_request: {} }, 4: {} },
1016
+ })
1017
+ assert.deepEqual(await pullRequestSnapshot(10), {
1018
+ number: 10,
1019
+ isDraft: false,
1020
+ authorType: 'User',
1021
+ reviewRequestCount: 1,
1022
+ reviewCount: 0,
1023
+ labels: ['kind/cleanup', 'area/infra'],
1024
+ references: { all: [2, 4], resolving: [2], related: [4] },
1025
+ issues: new Map([[2, { priority: 'P1' }], [4, { priority: null }]]),
1026
+ })
1027
+ const repo = '/repos/deepseek-harness/deepseek-harness'
1028
+ assert.deepEqual(fixture.requests, [
1029
+ repo + '/pulls/10',
1030
+ repo + '/pulls/10/requested_reviewers',
1031
+ repo + '/pulls/10/reviews?per_page=100',
1032
+ repo + '/issues/2',
1033
+ repo + '/issues/3',
1034
+ repo + '/issues/4',
1035
+ '/graphql',
1036
+ ])
1037
+ assert.deepEqual(fixture.output, [])
1038
+ })
1039
+
1040
+ test('reads lifecycle references for draft Bot PRs without review or Project requests', async (t) => {
1041
+ const fixture = mockPolicyApi(t, {
1042
+ pull: { draft: true, user: { type: 'Bot' }, body: 'Fixes #2; Refs #4', created_at: '2026-08-27T16:00:00Z' },
1043
+ issues: { 2: {}, 4: {} },
1044
+ })
1045
+ assert.deepEqual(await lifecyclePullRequestSnapshot(10), {
1046
+ number: 10,
1047
+ references: { all: [2, 4], resolving: [2], related: [4] },
1048
+ issues: new Map([[2, { priority: null }], [4, { priority: null }]]),
1049
+ createdAt: '2026-08-27T16:00:00Z',
1050
+ })
1051
+ const repo = '/repos/deepseek-harness/deepseek-harness'
1052
+ assert.deepEqual(fixture.requests, [repo + '/pulls/10', repo + '/issues/2', repo + '/issues/4'])
1053
+ assert.deepEqual(fixture.output, [])
1054
+ })
1055
+
1056
+ test('allows missing Priority only when resolving Issues are also unprioritized', () => {
1057
+ const pull = {
1058
+ isDraft: false,
1059
+ authorType: 'User',
1060
+ reviewRequestCount: 1,
1061
+ reviewCount: 0,
1062
+ labels: ['kind/feature', 'area/web'],
1063
+ references: { all: [2], resolving: [2], related: [] },
1064
+ issues: new Map([[2, { priority: null }]]),
1065
+ }
1066
+ assert.deepEqual(validatePullRequest(pull), [])
1067
+ assert.ok(
1068
+ validatePullRequest({ ...pull, issues: new Map([[2, { priority: 'P2' }]]) }).includes(
1069
+ 'PR Priority 应为 p2',
1070
+ ),
1071
+ )
1072
+ assert.ok(
1073
+ validatePullRequest({ ...pull, labels: [...pull.labels, 'p2'] }).includes(
1074
+ '有 Priority 的解决型 PR 要求每个被解决 Issue 都设置 Priority',
1075
+ ),
1076
+ )
1077
+ })
.github/issue-management/pull-request.mjs ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Read-only PR snapshots and policy preflight/check workflow entry points. */
2
+
3
+ import fs from 'node:fs'
4
+ import process from 'node:process'
5
+
6
+ import config from './config.json' with { type: 'json' }
7
+ import { api, projectContext } from './github.mjs'
8
+ import {
9
+ parseReferences,
10
+ retainIssueReferences,
11
+ requiresPullRequestPolicy,
12
+ validatePullRequest,
13
+ } from './rules.mjs'
14
+
15
+ /**
16
+ * Resolve all same-repository body references with REST, excluding pull-request numbers.
17
+ * @param {number} number Pull-request number.
18
+ * @param {{body?: string}} pull Current REST pull-request data.
19
+ * @returns {Promise<object>} Issue-only references and placeholder priorities; never reads Project data.
20
+ */
21
+ export async function resolvingReferencesSnapshot(number, pull) {
22
+ const references = parseReferences({
23
+ body: pull.body ?? '',
24
+ repository: `${config.organization}/${config.repository}`,
25
+ })
26
+ const issues = new Map()
27
+ for (const issueNumber of references.all) {
28
+ const issue = await api(
29
+ `/repos/${config.organization}/${config.repository}/issues/${issueNumber}`,
30
+ )
31
+ if (!issue.pull_request) issues.set(issueNumber, { priority: null })
32
+ }
33
+ return {
34
+ number,
35
+ references: retainIssueReferences(references, issues),
36
+ issues,
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Read current PR policy inputs, skipping references for exempt PRs.
42
+ * @param {number} number Pull-request number.
43
+ * @param {boolean} includeProject Read Project Priority for resolving Issues when true.
44
+ * @returns {Promise<object>} Policy snapshot; rejects any failed read and performs no writes.
45
+ */
46
+ export async function pullRequestSnapshot(number, includeProject = true) {
47
+ const pull = await api(`/repos/${config.organization}/${config.repository}/pulls/${number}`)
48
+ const snapshot = {
49
+ number,
50
+ isDraft: pull.draft,
51
+ authorType: pull.user?.type ?? 'User',
52
+ reviewRequestCount: 0,
53
+ reviewCount: 0,
54
+ labels: pull.labels.map((label) => label.name),
55
+ references: { all: [], resolving: [], related: [] },
56
+ issues: new Map(),
57
+ }
58
+ if (snapshot.isDraft || ['Bot', 'App'].includes(snapshot.authorType)) return snapshot
59
+ const [reviewRequests, reviews] = await Promise.all([
60
+ api(`/repos/${config.organization}/${config.repository}/pulls/${number}/requested_reviewers`),
61
+ api(`/repos/${config.organization}/${config.repository}/pulls/${number}/reviews?per_page=100`),
62
+ ])
63
+ snapshot.reviewRequestCount = reviewRequests.users.length + reviewRequests.teams.length
64
+ snapshot.reviewCount = reviews.length
65
+ if (!requiresPullRequestPolicy(snapshot)) return snapshot
66
+ Object.assign(snapshot, await resolvingReferencesSnapshot(number, pull))
67
+ if (includeProject) {
68
+ for (const issueNumber of snapshot.references.resolving) {
69
+ const context = await projectContext(issueNumber)
70
+ snapshot.issues.get(issueNumber).priority = context.item?.priorityValue?.name ?? null
71
+ }
72
+ }
73
+ return snapshot
74
+ }
75
+
76
+ /**
77
+ * Read PR creation time and Issue references without review eligibility gating.
78
+ * @param {number} number Pull-request number.
79
+ * @returns {Promise<object>} Lifecycle snapshot without Project reads or writes.
80
+ */
81
+ export async function lifecyclePullRequestSnapshot(number) {
82
+ const pull = await api(`/repos/${config.organization}/${config.repository}/pulls/${number}`)
83
+ return {
84
+ ...(await resolvingReferencesSnapshot(number, pull)),
85
+ createdAt: pull.created_at,
86
+ }
87
+ }
88
+
89
+ const EXEMPT_MESSAGE =
90
+ 'Issue policy exempt:当前 PR 不在强制范围(Draft、Bot/App 或尚无 review request/review)。\n'
91
+
92
+ /**
93
+ * Determine current policy eligibility and Project access needs without Project credentials.
94
+ * @param {{pull_request: {number: number}}} event GitHub event identifying the PR.
95
+ * @returns {Promise<{eligible: boolean, needsProject: boolean}>} Trusted workflow decisions.
96
+ */
97
+ export async function runPullRequestPreflight(event) {
98
+ const pull = await pullRequestSnapshot(event.pull_request.number, false)
99
+ const eligible = requiresPullRequestPolicy(pull)
100
+ const needsProject = eligible && pull.references.resolving.length > 0
101
+ if (process.env.GITHUB_OUTPUT) {
102
+ fs.appendFileSync(
103
+ process.env.GITHUB_OUTPUT,
104
+ `eligible=${eligible}\nexempt=${!eligible}\nneeds-project=${needsProject}\n`,
105
+ )
106
+ }
107
+ process.stdout.write(eligible ? 'Issue policy applicable;执行完整校验。\n' : EXEMPT_MESSAGE)
108
+ return { eligible, needsProject }
109
+ }
110
+
111
+ /**
112
+ * Enforce all PR rules against current GitHub state, independently of preflight.
113
+ * @param {{pull_request: {number: number}}} event GitHub event identifying the PR.
114
+ * @returns {Promise<void>} Resolves on success or exemption; rejects policy failures.
115
+ */
116
+ export async function runPullRequestCheck(event) {
117
+ const pull = await pullRequestSnapshot(event.pull_request.number)
118
+ const errors = validatePullRequest(pull)
119
+ if (errors.length > 0) {
120
+ for (const error of errors) process.stdout.write(`::error::${error}\n`)
121
+ throw new Error(`Issue policy 未通过,共 ${errors.length} 项`)
122
+ }
123
+ process.stdout.write(
124
+ requiresPullRequestPolicy(pull) ? 'Issue policy 通过。\n' : EXEMPT_MESSAGE,
125
+ )
126
+ }
.github/issue-management/rules.mjs ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Pure Issue/PR validation, reference parsing, lifecycle decisions, and Project dates. */
2
+
3
+ import config from './config.json' with { type: 'json' }
4
+
5
+ const TYPES = new Set(['Idea', 'Feature', 'Bug', 'Research', 'Task'])
6
+ const PRIORITIES = ['p0', 'p1', 'p2', 'p3']
7
+ const PR_KINDS = new Set([
8
+ 'kind/feature',
9
+ 'kind/bug-fix',
10
+ 'kind/doc',
11
+ 'kind/testing',
12
+ 'kind/cleanup',
13
+ 'kind/dependency',
14
+ ])
15
+ // Retired label aliases stay reserved so they cannot be recreated.
16
+ const LEGACY_LABELS = new Set([
17
+ 'kind/bug',
18
+ 'kind/documentation',
19
+ 'feature',
20
+ 'bug-fix',
21
+ 'doc',
22
+ 'cleanup',
23
+ 'testing',
24
+ 'dependencies',
25
+ 'ci',
26
+ 'cli',
27
+ 'llm',
28
+ 'web-search',
29
+ ])
30
+ const TERMINAL_STATUSES = new Set(['Done', 'No action'])
31
+ const ACTIVE_STATUS_ORDER = config.statuses.filter((status) => !TERMINAL_STATUSES.has(status))
32
+ const IMPLEMENTATION_PULL_REQUEST_ACTIONS = new Set([
33
+ 'opened',
34
+ 'edited',
35
+ 'reopened',
36
+ ])
37
+
38
+ for (const status of ['In progress', 'In review']) {
39
+ if (!ACTIVE_STATUS_ORDER.includes(status)) throw new Error(`config.statuses 缺少 ${status}`)
40
+ }
41
+ if (typeof config.lifecycleActor !== 'string' || !config.lifecycleActor) {
42
+ throw new Error('config.lifecycleActor 未设置')
43
+ }
44
+ if (typeof config.priorityField !== 'string' || !config.priorityField) {
45
+ throw new Error('config.priorityField 未设置')
46
+ }
47
+ if (typeof config.startDateField !== 'string' || !config.startDateField) {
48
+ throw new Error('config.startDateField 未设置')
49
+ }
50
+ if (typeof config.projectTimeZone !== 'string' || !config.projectTimeZone) {
51
+ throw new Error('config.projectTimeZone 未设置')
52
+ }
53
+ Intl.DateTimeFormat('en-US', { timeZone: config.projectTimeZone })
54
+
55
+ /**
56
+ * Decide whether the human-review policy applies to a PR.
57
+ * @param {{isDraft: boolean, authorType: string, reviewRequestCount: number, reviewCount: number}} input PR state.
58
+ * @returns {boolean} Whether the PR policy is mandatory.
59
+ */
60
+ export function requiresPullRequestPolicy({
61
+ isDraft,
62
+ authorType,
63
+ reviewRequestCount,
64
+ reviewCount,
65
+ }) {
66
+ const automated = authorType === 'Bot' || authorType === 'App'
67
+ return !isDraft && !automated && (reviewRequestCount > 0 || reviewCount > 0)
68
+ }
69
+
70
+ /**
71
+ * Translate a repository event into one resolving-Issue lifecycle command.
72
+ * @param {string} eventName GitHub event name.
73
+ * @param {{action?: string, changes?: {body?: object}, review?: {state?: string}}} event GitHub event payload.
74
+ * @returns {'implementation'|'review-requested'|'changes-requested'|null} Lifecycle command.
75
+ */
76
+ export function resolvingIssueStatusCommand(eventName, event) {
77
+ if (eventName === 'pull_request') {
78
+ if (event.action === 'edited' && !event.changes?.body) return null
79
+ if (event.action === 'review_requested') return 'review-requested'
80
+ return IMPLEMENTATION_PULL_REQUEST_ACTIONS.has(event.action) ? 'implementation' : null
81
+ }
82
+ if (
83
+ eventName === 'pull_request_review' &&
84
+ event.action === 'submitted' &&
85
+ event.review?.state?.toLowerCase() === 'changes_requested'
86
+ ) {
87
+ return 'changes-requested'
88
+ }
89
+ return null
90
+ }
91
+
92
+ /**
93
+ * Plan one event-directed resolving-Issue status transition.
94
+ * @param {string|null} currentStatus Current Project status.
95
+ * @param {'implementation'|'review-requested'|'changes-requested'} command Lifecycle command.
96
+ * @param {string|null} currentStatusActor Actor that last set the current Project status.
97
+ * @returns {string|null} Status to write, or null when no permitted transition exists.
98
+ */
99
+ export function nextResolvingIssueStatus(currentStatus, command, currentStatusActor = null) {
100
+ let target
101
+ if (command === 'review-requested') target = 'In review'
102
+ else if (command === 'implementation' || command === 'changes-requested') target = 'In progress'
103
+ else throw new Error(`未知 lifecycle command:${command}`)
104
+
105
+ const currentIndex = ACTIVE_STATUS_ORDER.indexOf(currentStatus)
106
+ const targetIndex = ACTIVE_STATUS_ORDER.indexOf(target)
107
+ if (
108
+ command === 'changes-requested' &&
109
+ currentStatus === 'In review' &&
110
+ currentStatusActor === config.lifecycleActor
111
+ ) {
112
+ return target
113
+ }
114
+ return currentIndex >= 0 && currentIndex < targetIndex ? target : null
115
+ }
116
+
117
+ /**
118
+ * Convert a GitHub timestamp to a Project date in one configured time zone.
119
+ * @param {string} timestamp ISO timestamp.
120
+ * @param {string} timeZone IANA time-zone name.
121
+ * @returns {string} Calendar date in YYYY-MM-DD form.
122
+ */
123
+ export function projectDate(timestamp, timeZone = config.projectTimeZone) {
124
+ const instant = new Date(timestamp)
125
+ if (Number.isNaN(instant.getTime())) throw new Error(`无效的 PR 创建时间:${timestamp}`)
126
+ const parts = Object.fromEntries(
127
+ new Intl.DateTimeFormat('en-US', {
128
+ timeZone,
129
+ year: 'numeric',
130
+ month: '2-digit',
131
+ day: '2-digit',
132
+ })
133
+ .formatToParts(instant)
134
+ .filter((part) => part.type !== 'literal')
135
+ .map((part) => [part.type, part.value]),
136
+ )
137
+ return `${parts.year}-${parts.month}-${parts.day}`
138
+ }
139
+
140
+ function stripIgnoredMarkdown(body) {
141
+ const lines = body.replace(/<!--[\s\S]*?-->/g, '').split(/\r?\n/)
142
+ const kept = []
143
+ let fence = null
144
+ for (const line of lines) {
145
+ const marker = line.match(/^\s*([\u0060~]{3,})/)
146
+ if (marker) {
147
+ if (fence === null) fence = marker[1][0]
148
+ else if (marker[1][0] === fence) fence = null
149
+ continue
150
+ }
151
+ if (fence === null) kept.push(line)
152
+ }
153
+ return kept.join('\n').replace(/\u0060[^\u0060]*\u0060/g, ' ')
154
+ }
155
+
156
+ /**
157
+ * Parse same-repository resolving and informational references.
158
+ * @param {{body: string, repository: string}} input PR body and repository.
159
+ * @returns {{all: number[], resolving: number[], related: number[]}} References.
160
+ */
161
+ export function parseReferences({ body, repository }) {
162
+ const source = stripIgnoredMarkdown(body)
163
+ const expected = repository.toLowerCase()
164
+ const all = new Set()
165
+ const resolving = new Set()
166
+ const reference =
167
+ /(?:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#|#)(\d+)|https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/issues\/(\d+)/gi
168
+ const closing =
169
+ /\b(?:close(?:s|d)?|fix(?:es|ed)?|resolve(?:s|d)?)\s*:?\s+(?:(?:([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#|#)(\d+)|https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/issues\/(\d+))/gi
170
+
171
+ for (const match of source.matchAll(reference)) {
172
+ const explicit = (match[1] ?? match[3] ?? '').toLowerCase()
173
+ const number = Number(match[2] ?? match[4])
174
+ if (!explicit || explicit === expected) all.add(number)
175
+ }
176
+ for (const match of source.matchAll(closing)) {
177
+ const explicit = (match[1] ?? match[3] ?? '').toLowerCase()
178
+ const number = Number(match[2] ?? match[4])
179
+ if (!explicit || explicit === expected) {
180
+ all.add(number)
181
+ resolving.add(number)
182
+ }
183
+ }
184
+ return {
185
+ all: [...all].sort((left, right) => left - right),
186
+ resolving: [...resolving].sort((left, right) => left - right),
187
+ related: [...all].filter((number) => !resolving.has(number)).sort((a, b) => a - b),
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Retain only references that resolve to Issues rather than pull requests.
193
+ * @param {{all: number[], resolving: number[], related: number[]}} references Parsed references.
194
+ * @param {Map<number, unknown>} issues Resolved same-repository Issues.
195
+ * @returns {{all: number[], resolving: number[], related: number[]}} Issue-only references.
196
+ */
197
+ export function retainIssueReferences(references, issues) {
198
+ return {
199
+ all: references.all.filter((number) => issues.has(number)),
200
+ resolving: references.resolving.filter((number) => issues.has(number)),
201
+ related: references.related.filter((number) => issues.has(number)),
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Validate one Issue with its Project status.
207
+ * @param {{labels: string[], type: string|null, priority: string|null, status: string|null, state: string, stateReason: string|null}} issue Issue snapshot.
208
+ * @returns {string[]} Validation errors.
209
+ */
210
+ export function validateIssue(issue) {
211
+ const errors = []
212
+ const status = issue.status
213
+ const invalidLabels = issue.labels.filter(isInvalidIssueLabel)
214
+
215
+ if (invalidLabels.length > 0) {
216
+ errors.push(`Issue 不得使用 PR kind 或旧版标签:${invalidLabels.join(', ')}`)
217
+ }
218
+ if (!TYPES.has(issue.type ?? '')) errors.push('Type 必须是五种原生英文 Type 之一')
219
+ if (!status || !config.statuses.includes(status)) errors.push('Issue 必须在 Project 中且具有合法 Status')
220
+ if (issue.priority !== null && !PRIORITIES.includes(issue.priority.toLowerCase())) {
221
+ errors.push('Priority 必须为空或为 P0–P3')
222
+ }
223
+ if (status === 'Done' && (issue.state !== 'closed' || issue.stateReason !== 'completed')) {
224
+ errors.push('Done 必须对应 Completed 关闭原因')
225
+ }
226
+ if (
227
+ status === 'No action' &&
228
+ (issue.state !== 'closed' || issue.stateReason !== 'not_planned')
229
+ ) {
230
+ errors.push('No action 必须对应 Not planned 关闭原因')
231
+ }
232
+ if (!['Done', 'No action'].includes(status ?? '') && issue.state !== 'open') {
233
+ errors.push(`${status} 必须对应开放 Issue`)
234
+ }
235
+ return errors
236
+ }
237
+
238
+ /**
239
+ * Identify PR kinds and retired aliases that cannot label an Issue.
240
+ * @param {string} label Label name.
241
+ * @returns {boolean} Whether the label is invalid for Issues.
242
+ */
243
+ export function isInvalidIssueLabel(label) {
244
+ return label.startsWith('kind/') || LEGACY_LABELS.has(label)
245
+ }
246
+
247
+ /**
248
+ * Validate PR metadata and its referenced Issues.
249
+ * @param {{authorType: string, labels: string[], references: ReturnType<typeof parseReferences>, issues: Map<number, {priority: string|null}>}} input PR snapshot.
250
+ * @returns {string[]} Validation errors.
251
+ */
252
+ export function validatePullRequest(input) {
253
+ if (!requiresPullRequestPolicy(input)) return []
254
+ const errors = []
255
+ const kinds = input.labels.filter((label) => PR_KINDS.has(label))
256
+ const unknownKinds = input.labels.filter(
257
+ (label) => label.startsWith('kind/') && !PR_KINDS.has(label) && !LEGACY_LABELS.has(label),
258
+ )
259
+ const legacyLabels = input.labels.filter((label) => LEGACY_LABELS.has(label))
260
+ const sourceLabels = input.labels.filter((label) => label.startsWith('source/'))
261
+ const priorities = input.labels.filter((label) => PRIORITIES.includes(label))
262
+ const areas = input.labels.filter((label) => label.startsWith('area/'))
263
+
264
+ if (input.references.all.length === 0) {
265
+ errors.push('PR 正文必须引用至少一个同仓库 Issue;PR 编号(包括堆叠依赖 PR)不算 Issue 引用')
266
+ }
267
+ if (kinds.length !== 1) {
268
+ errors.push(`PR 必须恰好有一个允许的 kind/*,当前为 ${kinds.length}`)
269
+ }
270
+ if (unknownKinds.length > 0) {
271
+ errors.push(`PR 含不支持的 kind/*:${unknownKinds.join(', ')}`)
272
+ }
273
+ if (legacyLabels.length > 0) errors.push(`PR 含旧版标签:${legacyLabels.join(', ')}`)
274
+ if (sourceLabels.length > 0) errors.push(`source/* 仅用于 Issue:${sourceLabels.join(', ')}`)
275
+ if (priorities.length > 1) errors.push(`PR 最多有一个 p0–p3,当前为 ${priorities.length}`)
276
+ if (areas.length === 0) errors.push('PR 必须至少有一个 area/*')
277
+ for (const number of input.references.all) {
278
+ if (!input.issues.has(number)) errors.push(`#${number} 不是同仓库 Issue`)
279
+ }
280
+
281
+ const resolving = input.references.resolving
282
+ .map((number) => [number, input.issues.get(number)])
283
+ .filter((entry) => entry[1])
284
+ if (resolving.length === 0) return errors
285
+
286
+ const issuePriorities = resolving
287
+ .map(([, issue]) => issue.priority?.toLowerCase())
288
+ .filter((priority) => PRIORITIES.includes(priority))
289
+ if (priorities.length === 0 && issuePriorities.length > 0) {
290
+ const highest = issuePriorities.sort(
291
+ (left, right) => PRIORITIES.indexOf(left) - PRIORITIES.indexOf(right),
292
+ )[0]
293
+ errors.push(`PR Priority 应为 ${highest}`)
294
+ } else if (priorities.length === 1 && issuePriorities.length !== resolving.length) {
295
+ errors.push('有 Priority 的解决型 PR 要求每个被解决 Issue 都设置 Priority')
296
+ } else if (priorities.length === 1) {
297
+ const highest = issuePriorities.sort(
298
+ (left, right) => PRIORITIES.indexOf(left) - PRIORITIES.indexOf(right),
299
+ )[0]
300
+ if (priorities[0] !== highest) errors.push(`PR Priority 应为 ${highest}`)
301
+ }
302
+ return errors
303
+ }
.github/issue-management/selective-preflight.json ADDED
@@ -0,0 +1 @@
 
 
1
+ { "version": 1 }
.github/preview-sizing/README.i18n.yaml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write .github/preview-sizing/README.md
5
+ README.md: 142854e582523eb1ed48924a73fbe29ea6164bf6
6
+ README.zh.md: a71325189dc7966df87e14bbb591af3c76a3d498
.github/preview-sizing/README.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PR preview runner sizing
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ ## Summary
6
+
7
+ The [preview workflow](../workflows/build-preview-cloudflare.yml) builds pull-request previews on standard GitHub-hosted `ubuntu-24.04`. Runner sizing compares complete job cost, not price per minute or core count alone.
8
+
9
+ ## Table of Contents
10
+
11
+ - [Comparison requirements](#comparison-requirements)
12
+ - [Publication semantics](#publication-semantics)
13
+ - [Dev Note](#dev-note)
14
+
15
+ <a id="comparison-requirements"></a>
16
+
17
+ ## Comparison requirements
18
+
19
+ A sizing experiment holds checkout SHA, lockfile, Node and pnpm versions, workspace build, and preview/VFS packing commands constant. Each runner starts without build outputs. Cold installs do not restore dependency caches; pnpm bootstrap files may already exist. Warm installs restore the same exact cache without prefix fallback. Record the actual runner image, CPU, RAM, disk, cache outcome, phase duration, exit status, and peak memory. GNU time maximum RSS reports a process maximum, not simultaneous aggregate memory across the build process tree.
20
+
21
+ Calculate estimated gross compute as the sum of each completed job’s elapsed minutes rounded upward, multiplied by that runner’s rate. Include setup, cache restoration, cleanup, failures, and measurement-upload overhead. Report seed jobs separately. Queue delay is a latency observation, not executed job time. These estimates are not invoice totals; standard-runner included minutes and storage are separate.
22
+
23
+ A build-only benchmark does not deploy, access Cloudflare credentials, or post pull-request comments. Its cost does not establish complete preview publication cost. Confirm the selected runner through the actual preview workflow before treating deployment latency and protected-image delivery as verified.
24
+
25
+ <a id="publication-semantics"></a>
26
+
27
+ ## Publication semantics
28
+
29
+ Runner selection does not alter pull-request events, per-PR cancellation, immutable installation, restore-only dependency caching, full workspace build, preview packing, sourcemap removal, or the preview page copied to the deployment root. Cloudflare uploads only the built site to the PR branch alias. The protected-image check requires HTTP 200, no transport content encoding, and gzip magic bytes; the URL comment remains idempotent. Dependabot and other PR authors remain on GitHub-hosted machines.
30
+
31
+ <a id="dev-note"></a>
32
+
33
+ ## Dev Note
34
+
35
+ The [runner decision](../../.agents/notes/implemented/process/2026-09-06-preview-hosted-runner-sizing.md) records measurements, cost estimates, and image/CPU variation. The build-only experiment does not verify production deployment.
.github/preview-sizing/README.zh.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PR 预览运行器规格
2
+
3
+ [English](README.md) | 中文
4
+
5
+ ## 摘要
6
+
7
+ [预览工作流](../workflows/build-preview-cloudflare.yml) 在标准 GitHub 托管 `ubuntu-24.04` 上构建 PR(Pull Request)预览。运行器规格选择比较完整作业成本,而非仅比较每分钟价格或核心数。
8
+
9
+ ## 目录
10
+
11
+ - [比较要求](#comparison-requirements)
12
+ - [发布语义](#publication-semantics)
13
+ - [开发备注](#dev-note)
14
+
15
+ <a id="comparison-requirements"></a>
16
+
17
+ ## 比较要求
18
+
19
+ 规格实验保持检出 SHA、锁文件、Node 与 pnpm 版本、工作区构建以及预览/VFS 打包命令一致。每个运行器启动时均无构建产物。冷安装不恢复依赖缓存,但 pnpm 引导安装文件可能已存在;热安装恢复同一个精确缓存,不使用前缀回退。记录实际运行器镜像、CPU、内存、磁盘、缓存结果、各阶段耗时、退出状态与内存峰值。GNU time 最大 RSS 表示进程最大值,而非构建进程树同时占用的内存总量。
20
+
21
+ 估算总计算费用时,将每个已完成作业的运行分钟数向上取整,乘以对应运行器费率后求和。纳入设置、缓存恢复、清理、失败及测量数据上传的开销。单独报告缓存预热作业。排队延迟属于延迟观测,不属于作业执行时间。这些估算不是账单总额;标准运行器的套餐内分钟数及存储另行计算。
22
+
23
+ 仅构建的基准测试不部署、不访问 Cloudflare 凭据,也不发布 PR 评论。其成本不能证明完整预览发布成本。在将部署延迟与受保护镜像交付视为已验证之前,须通过实际预览工作流确认所选运行器。
24
+
25
+ <a id="publication-semantics"></a>
26
+
27
+ ## 发布语义
28
+
29
+ 运行器选择不改变 PR 事件、按 PR 取消、不可变安装、只恢复的依赖缓存、完整工作区构建、预览打包、sourcemap 删除,以及复制到部署根目录的预览页面。Cloudflare 仅将构建站点上传至 PR 分支别名。受保护镜像检查要求 HTTP 200、无传输内容编码及 gzip 魔数字节;URL 评论保持幂等。Dependabot 与其他 PR 作者仍使用 GitHub 托管机器。
30
+
31
+ <a id="dev-note"></a>
32
+
33
+ ## 开发备注
34
+
35
+ [运行器决策](../../.agents/notes/implemented/process/2026-09-06-preview-hosted-runner-sizing.zh.md) 记录测量、成本估算及镜像/CPU 差异。仅构建实验不验证生产部署。
.github/review-ownership/README.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pull-request approval policy
2
+
3
+ ## Summary
4
+
5
+ The [`weighted-approval` workflow](../workflows/weighted-approval.yml) publishes an approval score for branch rules. Reviewer selection and review requests remain manual.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Approval scoring](#approval-scoring)
10
+ - [Security](#security)
11
+ - [Verification](#verification)
12
+ - [Dev Note](#dev-note)
13
+
14
+ <a id="approval-scoring"></a>
15
+
16
+ ## Approval scoring
17
+
18
+ The weighted approval workflow exposes two pull-request checks. The `weighted approval publisher` Actions job reports whether evaluation and status publication completed, while the `weighted approval` commit status carries the approval decision on the pull request head. Branch rules must require only the commit status with GitHub Actions as its expected source; a context-only requirement can accept a same-named status from another integration. A completed evaluation returns `pending` below two approval points, while the pull request is a draft, or while a write-capable reviewer has an effective `CHANGES_REQUESTED` review; the blocker keeps the status pending even when counted approvals reach the threshold. It returns `success` only when the threshold is met, the pull request is ready, and no such blocker exists. If evaluation fails, the publisher writes an `error` status.
19
+
20
+ Reviewers whose calculated base repository permission is `write` or `admin` count. The [approval policy](approval-policy.json) gives `@07akioni`, `@imccyu`, `@tianyicui`, `@tianyicui-bot`, `@turtle1999`, and `@turtle2099` two points each; every other write-capable reviewer gets one point. The pull-request author and reviewers without write permission do not count.
21
+
22
+ Each reviewer contributes only the current `APPROVED` or `CHANGES_REQUESTED` decision that GitHub returns. A `DISMISSED` record clears that reviewer's standing decision, including earlier approvals. Comment-only and pending records do not replace a decision. Reviews from deleted accounts and reviewers without current repository access do not count. The workflow does not invalidate an approval by its review commit; the repository's native pull-request rules own stale-review and latest-push requirements.
23
+
24
+ The publisher runs when a pull request opens, synchronizes, reopens, becomes ready, or becomes a draft. Review submissions, edits, and dismissals run the no-permission [`weighted-approval-review-event` workflow](../workflows/weighted-approval-review-event.yml); its validated run title supplies the pull-request number to the default-branch publisher. The publisher validates the current head, fetches every review, and resolves current repository permission before publishing the status. Permission changes take effect on the next subscribed pull-request or review event.
25
+
26
+ <a id="security"></a>
27
+
28
+ ## Security
29
+
30
+ The status-writing job checks out only the repository default branch. It does not check out or execute pull-request code and does not use repository secrets. The review-event workflow has no `GITHUB_TOKEN` permissions and passes only a decimal pull-request number in its run title. The publisher accepts only successful `pull_request_review` runs from the review-event workflow file, identified by `workflow_run.path`; GitHub can populate `workflow_run.name` with the expanded run title. The publisher rejects an invalid run title and a number that does not resolve to the workflow run's current pull-request head. Pull-request reviews are treated as API data and escaped in logs.
31
+
32
+ Approval policy changes take effect only after they merge into the default branch. This prevents an untrusted pull request from changing the program or policy for its own run.
33
+
34
+ <a id="verification"></a>
35
+
36
+ ## Verification
37
+
38
+ Run `pnpm run test:approval-policy` for policy parsing, effective review decisions, review-event validation, pagination, permission filtering, weighted scoring, blockers, drafts, status publication, and API failures. [Workflow tests](../../scripts/ci-workflow.spec.ts) pin the trusted checkout, no-permission review handoff, permissions, events, and commands. The repository gate graph runs the approval policy and workflow tests in CI.
39
+
40
+ <a id="dev-note"></a>
41
+
42
+ ## Dev Note
43
+
44
+ None.
.github/review-ownership/approval-policy.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "requiredPoints": 2,
3
+ "defaultPoints": 1,
4
+ "reviewerPoints": {
5
+ "07akioni": 2,
6
+ "imccyu": 2,
7
+ "tianyicui": 2,
8
+ "tianyicui-bot": 2,
9
+ "turtle1999": 2,
10
+ "turtle2099": 2
11
+ }
12
+ }
.github/review-ownership/check-approval.mjs ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync } from 'node:fs'
4
+ import process from 'node:process'
5
+ import { pathToFileURL } from 'node:url'
6
+
7
+ const API_VERSION = '2026-03-10'
8
+ const MAX_PULL_REQUEST_REVIEWS = 3_000
9
+ const PAGE_SIZE = 100
10
+ const STATUS_CONTEXT = 'weighted approval'
11
+ const WRITABLE_PERMISSIONS = new Set(['admin', 'write'])
12
+ const REVIEW_STATES = new Set(['APPROVED', 'CHANGES_REQUESTED', 'COMMENTED', 'DISMISSED', 'PENDING'])
13
+ const LOGIN = /^[A-Za-z0-9-]+(?:\[bot\])?$/u
14
+
15
+ class GitHubApiError extends Error {
16
+ constructor(message, status) {
17
+ super(message)
18
+ this.name = 'GitHubApiError'
19
+ this.status = status
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Parse the approval score policy.
25
+ * @param {string} source Approval policy JSON.
26
+ * @returns {{requiredPoints: number, defaultPoints: number, reviewerPoints: Map<string, number>}} Validated policy.
27
+ */
28
+ export function parseApprovalPolicy(source) {
29
+ const value = JSON.parse(source)
30
+ if (!isRecord(value)) throw new Error('approval policy must be an object')
31
+ const fields = Object.keys(value).sort()
32
+ if (fields.join(',') !== 'defaultPoints,requiredPoints,reviewerPoints') {
33
+ throw new Error('approval policy must contain only defaultPoints, requiredPoints, and reviewerPoints')
34
+ }
35
+ const requiredPoints = positiveInteger(value.requiredPoints, 'requiredPoints')
36
+ const defaultPoints = positiveInteger(value.defaultPoints, 'defaultPoints')
37
+ if (!isRecord(value.reviewerPoints)) throw new Error('reviewerPoints must be an object')
38
+ const reviewerPoints = new Map()
39
+ for (const [login, pointsValue] of Object.entries(value.reviewerPoints)) {
40
+ validateLogin(login, 'approval policy reviewer')
41
+ const key = login.toLowerCase()
42
+ if (reviewerPoints.has(key)) throw new Error(`duplicate approval policy reviewer @${login}`)
43
+ reviewerPoints.set(key, positiveInteger(pointsValue, `reviewerPoints.${login}`))
44
+ }
45
+ return { requiredPoints, defaultPoints, reviewerPoints }
46
+ }
47
+
48
+ /**
49
+ * Select each reviewer's current approval or change-request decision.
50
+ * @param {unknown[]} reviews Pull-request review records in GitHub's chronological order.
51
+ * @returns {Array<{login: string, state: 'APPROVED' | 'CHANGES_REQUESTED'}>} Effective review decisions.
52
+ */
53
+ export function effectiveReviewDecisions(reviews) {
54
+ const decisions = new Map()
55
+ for (const review of reviews) {
56
+ if (!isRecord(review)) throw new Error('pull-request review is not an object')
57
+ if (review.user === null) continue
58
+ if (!isRecord(review.user) || typeof review.user.login !== 'string') {
59
+ throw new Error('pull-request review has no reviewer login')
60
+ }
61
+ const login = validateLogin(review.user.login, 'pull-request reviewer')
62
+ if (typeof review.state !== 'string' || !REVIEW_STATES.has(review.state.toUpperCase())) {
63
+ throw new Error(`pull-request review by @${login} has an invalid state`)
64
+ }
65
+ const state = review.state.toUpperCase()
66
+ const key = login.toLowerCase()
67
+ if (state === 'DISMISSED') {
68
+ decisions.delete(key)
69
+ } else if (state === 'APPROVED' || state === 'CHANGES_REQUESTED') {
70
+ decisions.set(key, { login, state })
71
+ }
72
+ }
73
+ return [...decisions.values()]
74
+ }
75
+
76
+ /**
77
+ * Create a repository-scoped GitHub JSON API caller.
78
+ * @param {{token: string, apiUrl?: string, fetchImpl?: typeof fetch}} options API dependencies.
79
+ * @returns {(path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>} API caller.
80
+ */
81
+ export function createGitHubApi({ token, apiUrl = 'https://api.github.com', fetchImpl = globalThis.fetch }) {
82
+ if (!token) throw new Error('GITHUB_TOKEN is not set')
83
+ if (typeof fetchImpl !== 'function') throw new Error('fetch is unavailable')
84
+ const root = apiUrl.replace(/\/+$/u, '')
85
+ return async (path, { method = 'GET', body } = {}) => {
86
+ const response = await fetchImpl(`${root}${path}`, {
87
+ method,
88
+ headers: {
89
+ Accept: 'application/vnd.github+json',
90
+ Authorization: `Bearer ${token}`,
91
+ 'Content-Type': 'application/json',
92
+ 'User-Agent': 'deepseek-harness-weighted-approval',
93
+ 'X-GitHub-Api-Version': API_VERSION,
94
+ },
95
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
96
+ })
97
+ if (!response.ok) {
98
+ const responseBody = await response.text()
99
+ throw new GitHubApiError(
100
+ `GitHub API ${method} ${path} returned ${response.status}: ${JSON.stringify(responseBody)}`,
101
+ response.status,
102
+ )
103
+ }
104
+ if (response.status === 204) return undefined
105
+ return response.json()
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Fetch every pull-request review or fail before scoring a partial list.
111
+ * @param {(path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>} api GitHub API caller.
112
+ * @param {string} repository Owner/name repository identifier.
113
+ * @param {number} pullNumber Pull-request number.
114
+ * @returns {Promise<unknown[]>} Complete review list within the supported limit.
115
+ */
116
+ export async function listPullRequestReviews(api, repository, pullNumber) {
117
+ const reviews = []
118
+ for (let page = 1; ; page++) {
119
+ const response = await api(`/repos/${repository}/pulls/${pullNumber}/reviews?per_page=${PAGE_SIZE}&page=${page}`)
120
+ if (!Array.isArray(response)) throw new Error('pull-request reviews response is not an array')
121
+ reviews.push(...response)
122
+ if (response.length < PAGE_SIZE) return reviews
123
+ if (reviews.length >= MAX_PULL_REQUEST_REVIEWS) {
124
+ throw new Error(`pull-request reviews exceed ${MAX_PULL_REQUEST_REVIEWS} records`)
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Evaluate approval points from current reviews and repository permissions.
131
+ * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>}} options Runtime inputs.
132
+ * @returns {Promise<{pull: {repository: string, number: number, headSha: string}, state: 'pending' | 'success', description: string, points: number, requiredPoints: number, approvals: Array<{login: string, points: number}>, blockers: string[], ignoredReviewers: string[]}>} Approval decision and status payload fields.
133
+ */
134
+ export async function evaluateApproval({ event, policySource, api }) {
135
+ const pull = pullRequestFromEvent(event)
136
+ const policy = parseApprovalPolicy(policySource)
137
+ if (pull.draft) {
138
+ return approvalResult(pull, policy.requiredPoints, [], [], [], 'pending', 'draft pull request')
139
+ }
140
+
141
+ const reviews = await listPullRequestReviews(api, pull.repository, pull.number)
142
+ const decisions = effectiveReviewDecisions(reviews)
143
+ .filter(({ login }) => login.toLowerCase() !== pull.author.toLowerCase())
144
+ const permissions = []
145
+ for (const { login, state } of decisions) {
146
+ permissions.push({ login, state, permission: await reviewerPermission(api, pull.repository, login) })
147
+ }
148
+ const approvals = []
149
+ const blockers = []
150
+ const ignoredReviewers = []
151
+ for (const { login, state, permission } of permissions) {
152
+ if (!WRITABLE_PERMISSIONS.has(permission)) {
153
+ ignoredReviewers.push(login)
154
+ } else if (state === 'CHANGES_REQUESTED') {
155
+ blockers.push(login)
156
+ } else {
157
+ approvals.push({
158
+ login,
159
+ points: policy.reviewerPoints.get(login.toLowerCase()) ?? policy.defaultPoints,
160
+ })
161
+ }
162
+ }
163
+ approvals.sort((left, right) => left.login.localeCompare(right.login, 'en'))
164
+ blockers.sort((left, right) => left.localeCompare(right, 'en'))
165
+ ignoredReviewers.sort((left, right) => left.localeCompare(right, 'en'))
166
+ const points = approvals.reduce((total, approval) => {
167
+ const next = total + approval.points
168
+ if (!Number.isSafeInteger(next)) throw new Error('approval points exceed the safe integer range')
169
+ return next
170
+ }, 0)
171
+ if (blockers.length > 0) {
172
+ return approvalResult(pull, policy.requiredPoints, approvals, blockers, ignoredReviewers, 'pending',
173
+ `${blockers.length} blocking change request${blockers.length === 1 ? '' : 's'}`)
174
+ }
175
+ const state = points >= policy.requiredPoints ? 'success' : 'pending'
176
+ return approvalResult(
177
+ pull,
178
+ policy.requiredPoints,
179
+ approvals,
180
+ blockers,
181
+ ignoredReviewers,
182
+ state,
183
+ `${points}/${policy.requiredPoints} approval points`,
184
+ )
185
+ }
186
+
187
+ /**
188
+ * Evaluate and publish the required commit status, publishing an error status when evaluation fails.
189
+ * @param {{event: unknown, policySource: string, api: (path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>, runUrl: string, write?: (line: string) => void}} options Runtime inputs.
190
+ * @returns {Promise<Awaited<ReturnType<typeof evaluateApproval>>>} Published approval decision.
191
+ */
192
+ export async function runApprovalCheck({ event, policySource, api, runUrl, write = line => process.stdout.write(`${line}\n`) }) {
193
+ const pull = pullRequestFromEvent(event)
194
+ let result
195
+ try {
196
+ result = await evaluateApproval({ event, policySource, api })
197
+ } catch (error) {
198
+ await publishStatus(api, pull, 'error', 'Approval evaluation failed.', runUrl)
199
+ throw error
200
+ }
201
+ write(`Approval score: ${result.points}/${result.requiredPoints}.`)
202
+ writeList(write, 'Counted approvals', result.approvals.map(({ login, points }) => `@${login}: ${points}`))
203
+ writeList(write, 'Blocking change requests', result.blockers.map(login => `@${login}`))
204
+ writeList(write, 'Ignored reviewers without write access', result.ignoredReviewers.map(login => `@${login}`))
205
+ await publishStatus(api, pull, result.state, result.description, runUrl)
206
+ write(`Published ${JSON.stringify(STATUS_CONTEXT)} status ${JSON.stringify(result.state)}.`)
207
+ return result
208
+ }
209
+
210
+ /**
211
+ * Resolve the reviewed pull request from a completed run of the review-event workflow file.
212
+ * @param {{event: unknown, api: (path: string, options?: {method?: string, body?: unknown}) => Promise<unknown>}} options Trusted workflow inputs.
213
+ * @returns {Promise<Record<string, unknown> | null>} Event with a current pull request, or null after the pull-request head changes.
214
+ */
215
+ export async function approvalEventFromWorkflowRun({ event, api }) {
216
+ const repository = repositoryFromEvent(event)
217
+ // GitHub can expand run-name into name; the file path identifies the source workflow.
218
+ if (!isRecord(event.workflow_run)
219
+ || event.workflow_run.path !== '.github/workflows/weighted-approval-review-event.yml'
220
+ || event.workflow_run.event !== 'pull_request_review' || event.workflow_run.conclusion !== 'success') {
221
+ throw new Error('event has no successful weighted approval review workflow run')
222
+ }
223
+ const expectedHeadSha = validateHeadSha(event.workflow_run.head_sha, 'workflow run')
224
+ const pullNumber = parsePullNumber(event.workflow_run.display_title)
225
+ if (!Array.isArray(event.workflow_run.pull_requests)) {
226
+ throw new Error('workflow run has no pull_requests array')
227
+ }
228
+ if (event.workflow_run.pull_requests.length > 0
229
+ && !event.workflow_run.pull_requests.some(pull => isRecord(pull) && pull.number === pullNumber)) {
230
+ throw new Error(`workflow run is not associated with pull request #${pullNumber}`)
231
+ }
232
+ const pull = await api(`/repos/${repository}/pulls/${pullNumber}`)
233
+ if (!isRecord(pull) || !isRecord(pull.head)) throw new Error(`pull request #${pullNumber} response is invalid`)
234
+ if (pull.head.sha !== expectedHeadSha) return null
235
+ return { ...event, pull_request: pull }
236
+ }
237
+
238
+ function approvalResult(pull, requiredPoints, approvals, blockers, ignoredReviewers, state, detail) {
239
+ return {
240
+ pull: { repository: pull.repository, number: pull.number, headSha: pull.headSha },
241
+ state,
242
+ description: `${detail}.`,
243
+ points: approvals.reduce((total, approval) => total + approval.points, 0),
244
+ requiredPoints,
245
+ approvals,
246
+ blockers,
247
+ ignoredReviewers,
248
+ }
249
+ }
250
+
251
+ async function reviewerPermission(api, repository, login) {
252
+ let response
253
+ try {
254
+ response = await api(`/repos/${repository}/collaborators/${encodeURIComponent(login)}/permission`)
255
+ } catch (error) {
256
+ if (error instanceof GitHubApiError && error.status === 404) return 'none'
257
+ throw error
258
+ }
259
+ if (!isRecord(response) || typeof response.permission !== 'string') {
260
+ throw new Error(`collaborator permission response for @${login} has no permission`)
261
+ }
262
+ return response.permission.toLowerCase()
263
+ }
264
+
265
+ async function publishStatus(api, pull, state, description, runUrl) {
266
+ if (!/^https:\/\/[^\s]+$/u.test(runUrl)) throw new Error('workflow run URL must use HTTPS')
267
+ if (description.length > 140) throw new Error('commit status description exceeds 140 characters')
268
+ await api(`/repos/${pull.repository}/statuses/${pull.headSha}`, {
269
+ method: 'POST',
270
+ body: {
271
+ state,
272
+ context: STATUS_CONTEXT,
273
+ description,
274
+ target_url: runUrl,
275
+ },
276
+ })
277
+ }
278
+
279
+ function pullRequestFromEvent(event) {
280
+ const repository = repositoryFromEvent(event)
281
+ if (!isRecord(event.pull_request) || !isRecord(event.pull_request.user)
282
+ || !isRecord(event.pull_request.head)) {
283
+ throw new Error('event has no pull_request')
284
+ }
285
+ const pull = event.pull_request
286
+ if (!Number.isSafeInteger(pull.number) || pull.number <= 0) throw new Error('pull request has no valid number')
287
+ if (typeof pull.draft !== 'boolean') throw new Error('pull request has no draft flag')
288
+ const author = validateLogin(pull.user.login, 'pull-request author')
289
+ const headSha = validateHeadSha(pull.head.sha, 'pull request')
290
+ return {
291
+ repository,
292
+ number: pull.number,
293
+ draft: pull.draft,
294
+ author,
295
+ headSha,
296
+ }
297
+ }
298
+
299
+ function repositoryFromEvent(event) {
300
+ if (!isRecord(event) || !isRecord(event.repository) || typeof event.repository.full_name !== 'string'
301
+ || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(event.repository.full_name)) {
302
+ throw new Error('event has no valid repository.full_name')
303
+ }
304
+ return event.repository.full_name
305
+ }
306
+
307
+ function validateHeadSha(value, subject) {
308
+ if (typeof value !== 'string' || !/^[0-9a-f]{40}$/u.test(value)) {
309
+ throw new Error(`${subject} has no valid head SHA`)
310
+ }
311
+ return value
312
+ }
313
+
314
+ function parsePullNumber(source) {
315
+ if (typeof source !== 'string') throw new Error('review event has no valid run title')
316
+ const match = /^weighted-approval-review-event:([1-9][0-9]*)$/u.exec(source)
317
+ if (!match) throw new Error('review event has no valid run title')
318
+ const pullNumber = Number(match[1])
319
+ if (!Number.isSafeInteger(pullNumber)) throw new Error('review event pull request number is not a safe integer')
320
+ return pullNumber
321
+ }
322
+
323
+ function positiveInteger(value, field) {
324
+ if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer`)
325
+ return value
326
+ }
327
+
328
+ function validateLogin(value, subject) {
329
+ if (typeof value !== 'string' || !LOGIN.test(value)) throw new Error(`${subject} has an invalid login`)
330
+ return value
331
+ }
332
+
333
+ function writeList(write, title, entries) {
334
+ write(`${title}:`)
335
+ if (entries.length === 0) write('- (none)')
336
+ else for (const entry of entries) write(`- ${entry}`)
337
+ }
338
+
339
+ function isRecord(value) {
340
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
341
+ }
342
+
343
+ async function main() {
344
+ const eventPath = process.env.GITHUB_EVENT_PATH
345
+ if (!eventPath) throw new Error('GITHUB_EVENT_PATH is not set')
346
+ let event = JSON.parse(readFileSync(eventPath, 'utf8'))
347
+ const policySource = readFileSync(new URL('approval-policy.json', import.meta.url), 'utf8')
348
+ const api = createGitHubApi({
349
+ token: process.env.GITHUB_TOKEN ?? '',
350
+ apiUrl: process.env.GITHUB_API_URL,
351
+ })
352
+ if (isRecord(event) && isRecord(event.workflow_run)) {
353
+ const resolved = await approvalEventFromWorkflowRun({
354
+ event,
355
+ api,
356
+ })
357
+ if (resolved === null) {
358
+ process.stdout.write('Skipped a review event for a superseded pull-request head.\n')
359
+ return
360
+ }
361
+ event = resolved
362
+ }
363
+ await runApprovalCheck({
364
+ event,
365
+ policySource,
366
+ api,
367
+ runUrl: process.env.GITHUB_RUN_URL ?? '',
368
+ })
369
+ }
370
+
371
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
372
+ main().catch((error) => {
373
+ process.stderr.write(`weighted approval failed: ${error instanceof Error ? error.message : String(error)}\n`)
374
+ process.exitCode = 1
375
+ })
376
+ }
.github/review-ownership/check-approval.test.mjs ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from 'node:assert/strict'
2
+ import { readFileSync } from 'node:fs'
3
+ import test from 'node:test'
4
+
5
+ import {
6
+ approvalEventFromWorkflowRun,
7
+ createGitHubApi,
8
+ effectiveReviewDecisions,
9
+ evaluateApproval,
10
+ listPullRequestReviews,
11
+ parseApprovalPolicy,
12
+ runApprovalCheck,
13
+ } from './check-approval.mjs'
14
+
15
+ const policySource = readFileSync(new URL('approval-policy.json', import.meta.url), 'utf8')
16
+ const HEAD_SHA = '1234567890abcdef1234567890abcdef12345678'
17
+
18
+ const pullRequestEvent = ({ author = 'author', draft = false } = {}) => ({
19
+ repository: { full_name: 'deepseek-harness/deepseek-harness' },
20
+ pull_request: {
21
+ number: 42,
22
+ draft,
23
+ user: { login: author },
24
+ head: { sha: HEAD_SHA },
25
+ },
26
+ })
27
+
28
+ const review = (login, state) => ({ user: { login }, state })
29
+
30
+ test('loads the repository approval score policy', () => {
31
+ const policy = parseApprovalPolicy(policySource)
32
+ assert.equal(policy.requiredPoints, 2)
33
+ assert.equal(policy.defaultPoints, 1)
34
+ assert.deepEqual([...policy.reviewerPoints], [
35
+ ['07akioni', 2],
36
+ ['imccyu', 2],
37
+ ['tianyicui', 2],
38
+ ['tianyicui-bot', 2],
39
+ ['turtle1999', 2],
40
+ ['turtle2099', 2],
41
+ ])
42
+ })
43
+
44
+ test('rejects invalid approval score policies', () => {
45
+ for (const [source, message] of [
46
+ ['[]', /must be an object/u],
47
+ ['{"requiredPoints":0,"defaultPoints":1,"reviewerPoints":{}}', /requiredPoints/u],
48
+ ['{"requiredPoints":2,"defaultPoints":0,"reviewerPoints":{}}', /defaultPoints/u],
49
+ ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":[]}', /reviewerPoints must be an object/u],
50
+ ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{},"typo":2}', /contain only/u],
51
+ ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{"bad login":2}}', /invalid login/u],
52
+ ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{"User":2,"user":2}}', /duplicate/u],
53
+ ['{"requiredPoints":2,"defaultPoints":1,"reviewerPoints":{"user":-1}}', /positive integer/u],
54
+ ]) {
55
+ assert.throws(() => parseApprovalPolicy(source), message)
56
+ }
57
+ })
58
+
59
+ test('uses each reviewer current decision and clears it on dismissal', () => {
60
+ assert.deepEqual(effectiveReviewDecisions([
61
+ review('first', 'APPROVED'),
62
+ review('first', 'APPROVED'),
63
+ review('first', 'COMMENTED'),
64
+ review('first', 'DISMISSED'),
65
+ review('second', 'CHANGES_REQUESTED'),
66
+ review('second', 'APPROVED'),
67
+ review('third', 'APPROVED'),
68
+ review('third', 'CHANGES_REQUESTED'),
69
+ review('dismissed', 'DISMISSED'),
70
+ { user: null, state: 'APPROVED' },
71
+ ]), [
72
+ { login: 'second', state: 'APPROVED' },
73
+ { login: 'third', state: 'CHANGES_REQUESTED' },
74
+ ])
75
+ })
76
+
77
+ test('resolves a review workflow run to the current pull request and rejects stale heads', async () => {
78
+ const workflowRunEvent = {
79
+ repository: { full_name: 'deepseek-harness/deepseek-harness' },
80
+ workflow_run: {
81
+ name: 'weighted-approval-review-event:42',
82
+ path: '.github/workflows/weighted-approval-review-event.yml',
83
+ event: 'pull_request_review',
84
+ conclusion: 'success',
85
+ head_sha: HEAD_SHA,
86
+ display_title: 'weighted-approval-review-event:42',
87
+ pull_requests: [],
88
+ },
89
+ }
90
+ const current = await approvalEventFromWorkflowRun({
91
+ event: workflowRunEvent,
92
+ api: async path => {
93
+ assert.equal(path, '/repos/deepseek-harness/deepseek-harness/pulls/42')
94
+ return pullRequestEvent().pull_request
95
+ },
96
+ })
97
+ assert.equal(current.pull_request.number, 42)
98
+
99
+ for (const invalidRun of [
100
+ { path: '.github/workflows/other.yml' },
101
+ { path: undefined },
102
+ { event: 'push' },
103
+ { conclusion: 'failure' },
104
+ ]) {
105
+ await assert.rejects(approvalEventFromWorkflowRun({
106
+ event: {
107
+ ...workflowRunEvent,
108
+ workflow_run: { ...workflowRunEvent.workflow_run, ...invalidRun },
109
+ },
110
+ api: async () => { throw new Error('invalid source must not call GitHub') },
111
+ }), /successful weighted approval review workflow run/u)
112
+ }
113
+
114
+ assert.equal(await approvalEventFromWorkflowRun({
115
+ event: workflowRunEvent,
116
+ api: async () => ({
117
+ ...pullRequestEvent().pull_request,
118
+ head: { sha: 'abcdef1234567890abcdef1234567890abcdef12' },
119
+ }),
120
+ }), null)
121
+ await assert.rejects(approvalEventFromWorkflowRun({
122
+ event: {
123
+ ...workflowRunEvent,
124
+ workflow_run: { ...workflowRunEvent.workflow_run, display_title: '../42' },
125
+ },
126
+ api: async () => { throw new Error('invalid number must not call GitHub') },
127
+ }), /valid run title/u)
128
+ })
129
+
130
+ test('fetches every pull-request review and rejects an unbounded history', async () => {
131
+ let calls = 0
132
+ const reviews = await listPullRequestReviews(async () => {
133
+ calls++
134
+ return calls === 1 ? Array.from({ length: 100 }, () => review('user', 'COMMENTED')) : []
135
+ }, 'owner/repo', 42)
136
+ assert.equal(reviews.length, 100)
137
+ assert.equal(calls, 2)
138
+
139
+ calls = 0
140
+ await assert.rejects(listPullRequestReviews(async () => {
141
+ calls++
142
+ return Array.from({ length: 100 }, () => review('user', 'COMMENTED'))
143
+ }, 'owner/repo', 42), /exceed 3000/u)
144
+ assert.equal(calls, 30)
145
+ })
146
+
147
+ test('accepts one two-point approval from a write-capable reviewer', async () => {
148
+ const calls = []
149
+ const result = await evaluateApproval({
150
+ event: pullRequestEvent(),
151
+ policySource,
152
+ api: async (path) => {
153
+ calls.push(path)
154
+ if (path.includes('/reviews?')) return [review('07akioni', 'APPROVED')]
155
+ if (path.includes('/collaborators/07akioni/permission')) return { permission: 'write' }
156
+ throw new Error(`unexpected API path ${path}`)
157
+ },
158
+ })
159
+ assert.equal(result.state, 'success')
160
+ assert.equal(result.points, 2)
161
+ assert.deepEqual(result.approvals, [{ login: '07akioni', points: 2 }])
162
+ assert.equal(calls.length, 2)
163
+ })
164
+
165
+ test('accepts two one-point approvals and ignores reviews without write access', async () => {
166
+ const result = await evaluateApproval({
167
+ event: pullRequestEvent(),
168
+ policySource,
169
+ api: async (path) => {
170
+ if (path.includes('/reviews?')) {
171
+ return [
172
+ review('reader', 'APPROVED'),
173
+ review('writer-b', 'APPROVED'),
174
+ review('writer-a', 'APPROVED'),
175
+ ]
176
+ }
177
+ if (path.includes('/collaborators/reader/permission')) return { permission: 'read' }
178
+ if (path.includes('/collaborators/writer-a/permission')) return { permission: 'admin' }
179
+ if (path.includes('/collaborators/writer-b/permission')) return { permission: 'write' }
180
+ throw new Error(`unexpected API path ${path}`)
181
+ },
182
+ })
183
+ assert.equal(result.state, 'success')
184
+ assert.equal(result.points, 2)
185
+ assert.deepEqual(result.approvals, [
186
+ { login: 'writer-a', points: 1 },
187
+ { login: 'writer-b', points: 1 },
188
+ ])
189
+ assert.deepEqual(result.ignoredReviewers, ['reader'])
190
+ })
191
+
192
+ test('keeps one one-point approval pending without failing the status', async () => {
193
+ const result = await evaluateApproval({
194
+ event: pullRequestEvent(),
195
+ policySource,
196
+ api: async (path) => {
197
+ if (path.includes('/reviews?')) return [review('writer', 'APPROVED')]
198
+ if (path.includes('/collaborators/writer/permission')) return { permission: 'write' }
199
+ throw new Error(`unexpected API path ${path}`)
200
+ },
201
+ })
202
+ assert.equal(result.state, 'pending')
203
+ assert.equal(result.points, 1)
204
+ })
205
+
206
+ test('ignores a reviewer whose collaborator permission lookup returns 404', async () => {
207
+ const api = createGitHubApi({
208
+ token: 'secret',
209
+ fetchImpl: async (url) => {
210
+ if (url.includes('/reviews?')) {
211
+ return new Response(JSON.stringify([review('former-writer', 'APPROVED')]), {
212
+ status: 200,
213
+ headers: { 'Content-Type': 'application/json' },
214
+ })
215
+ }
216
+ if (url.includes('/collaborators/former-writer/permission')) return new Response('Not Found', { status: 404 })
217
+ throw new Error(`unexpected API URL ${url}`)
218
+ },
219
+ })
220
+ const result = await evaluateApproval({ event: pullRequestEvent(), policySource, api })
221
+ assert.equal(result.state, 'pending')
222
+ assert.deepEqual(result.ignoredReviewers, ['former-writer'])
223
+ })
224
+
225
+ test('keeps the status pending on a write-capable change request while ignoring the author and read-only reviewers', async () => {
226
+ const statuses = []
227
+ const result = await runApprovalCheck({
228
+ event: pullRequestEvent({ author: 'author' }),
229
+ policySource,
230
+ runUrl: 'https://github.example/actions/runs/1',
231
+ api: async (path, options = {}) => {
232
+ if (path.includes('/reviews?')) {
233
+ return [
234
+ review('turtle1999', 'APPROVED'),
235
+ review('blocker', 'CHANGES_REQUESTED'),
236
+ review('reader', 'CHANGES_REQUESTED'),
237
+ review('author', 'CHANGES_REQUESTED'),
238
+ ]
239
+ }
240
+ if (path.includes('/collaborators/turtle1999/permission')) return { permission: 'admin' }
241
+ if (path.includes('/collaborators/blocker/permission')) return { permission: 'write' }
242
+ if (path.includes('/collaborators/reader/permission')) return { permission: 'read' }
243
+ if (path.includes('/statuses/')) {
244
+ statuses.push(options.body)
245
+ return {}
246
+ }
247
+ throw new Error(`unexpected API path ${path}`)
248
+ },
249
+ write: () => {},
250
+ })
251
+ assert.equal(result.state, 'pending')
252
+ assert.equal(result.description, '1 blocking change request.')
253
+ assert.equal(result.points, 2)
254
+ assert.deepEqual(result.blockers, ['blocker'])
255
+ assert.deepEqual(result.ignoredReviewers, ['reader'])
256
+ assert.deepEqual(statuses, [{
257
+ state: 'pending',
258
+ context: 'weighted approval',
259
+ description: '1 blocking change request.',
260
+ target_url: 'https://github.example/actions/runs/1',
261
+ }])
262
+ })
263
+
264
+ test('keeps drafts pending without reading reviews', async () => {
265
+ const result = await evaluateApproval({
266
+ event: pullRequestEvent({ draft: true }),
267
+ policySource,
268
+ api: async () => { throw new Error('draft evaluation must not call GitHub') },
269
+ })
270
+ assert.equal(result.state, 'pending')
271
+ assert.equal(result.points, 0)
272
+ assert.match(result.description, /draft pull request/u)
273
+ })
274
+
275
+ test('publishes the required status and replaces stale success with error on evaluation failure', async () => {
276
+ const calls = []
277
+ const output = []
278
+ const result = await runApprovalCheck({
279
+ event: pullRequestEvent(),
280
+ policySource,
281
+ runUrl: 'https://github.example/actions/runs/1',
282
+ api: async (path, options = {}) => {
283
+ calls.push({ path, options })
284
+ if (path.includes('/reviews?')) return [review('turtle2099', 'APPROVED')]
285
+ if (path.includes('/collaborators/turtle2099/permission')) return { permission: 'write' }
286
+ if (path.includes('/statuses/')) return {}
287
+ throw new Error(`unexpected API path ${path}`)
288
+ },
289
+ write: line => output.push(line),
290
+ })
291
+ assert.equal(result.state, 'success')
292
+ assert.deepEqual(calls.at(-1), {
293
+ path: `/repos/deepseek-harness/deepseek-harness/statuses/${HEAD_SHA}`,
294
+ options: {
295
+ method: 'POST',
296
+ body: {
297
+ state: 'success',
298
+ context: 'weighted approval',
299
+ description: '2/2 approval points.',
300
+ target_url: 'https://github.example/actions/runs/1',
301
+ },
302
+ },
303
+ })
304
+ assert.equal(output[0], 'Approval score: 2/2.')
305
+
306
+ const failures = []
307
+ await assert.rejects(runApprovalCheck({
308
+ event: pullRequestEvent(),
309
+ policySource,
310
+ runUrl: 'https://github.example/actions/runs/2',
311
+ api: async (path, options = {}) => {
312
+ if (path.includes('/reviews?')) throw new Error('reviews unavailable')
313
+ if (path.includes('/statuses/')) {
314
+ failures.push({ path, options })
315
+ return {}
316
+ }
317
+ throw new Error(`unexpected API path ${path}`)
318
+ },
319
+ write: () => {},
320
+ }), /reviews unavailable/u)
321
+ assert.equal(failures[0].options.body.state, 'error')
322
+ assert.equal(failures[0].options.body.description, 'Approval evaluation failed.')
323
+ })
324
+
325
+ test('sends authenticated JSON and escapes an API error body', async () => {
326
+ const requests = []
327
+ const api = createGitHubApi({
328
+ token: 'secret',
329
+ apiUrl: 'https://github.example/api/v3/',
330
+ fetchImpl: async (url, options) => {
331
+ requests.push({ url, options })
332
+ return new Response(JSON.stringify({ ok: true }), {
333
+ status: 200,
334
+ headers: { 'Content-Type': 'application/json' },
335
+ })
336
+ },
337
+ })
338
+ assert.deepEqual(await api('/repos/owner/repo', { method: 'POST', body: { value: 1 } }), { ok: true })
339
+ assert.equal(requests[0].url, 'https://github.example/api/v3/repos/owner/repo')
340
+ assert.equal(requests[0].options.headers.Authorization, 'Bearer secret')
341
+ assert.equal(requests[0].options.body, '{"value":1}')
342
+
343
+ const failing = createGitHubApi({
344
+ token: 'secret',
345
+ fetchImpl: async () => new Response('::error::untrusted\nbody', { status: 422 }),
346
+ })
347
+ await assert.rejects(failing('/failure'), /"::error::untrusted\\nbody"/u)
348
+ })
.github/workflows/build-exe-for-python-sdk.yml ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build single-exe
2
+
3
+ # Native builds for the release targets; see
4
+ # .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.
5
+ # A full target run retains one SDK wheel and five runtime wheels; subset
6
+ # dispatch retains the SDK wheel and selected runtime wheels. Bare executables
7
+ # and source closures are test inputs. Run manually or call it from the Python
8
+ # release workflow. There is no `pull_request` trigger: a label trigger would
9
+ # list gray skipped checks on every unrelated PR label event. Checkout uses the
10
+ # triggering ref, so dispatch needs no separate ref input.
11
+ on:
12
+ workflow_call:
13
+ inputs:
14
+ targets:
15
+ description: Comma-separated pkg targets to build; empty builds all five.
16
+ type: string
17
+ required: false
18
+ default: ''
19
+ release:
20
+ description: Run as the native builder for the Python release workflow.
21
+ type: boolean
22
+ required: false
23
+ default: false
24
+ ci:
25
+ description: Run Python runtime CI validation for the selected targets.
26
+ type: boolean
27
+ required: false
28
+ default: false
29
+ secrets:
30
+ DEEPSEEK_API_KEY_EXTERNAL:
31
+ description: Real DeepSeek API key for trusted installed-wheel pull-request tests.
32
+ required: false
33
+ workflow_dispatch:
34
+ inputs:
35
+ targets:
36
+ description: >-
37
+ Comma-separated pkg targets to build. Any subset of:
38
+ node24-linux-x64, node24-linux-arm64, node24-macos-arm64,
39
+ node24-macos-x64, node24-win-x64. Empty builds all five.
40
+ type: string
41
+ required: false
42
+ default: ''
43
+
44
+ concurrency:
45
+ # Keep the called workflow distinct from its caller's concurrency group;
46
+ # github.workflow identifies the caller inside a reusable workflow and keeps
47
+ # an ordinary CI run from cancelling a full release validation on the same ref.
48
+ group: build-single-exe-${{ github.workflow }}-${{ github.ref }}
49
+ # Release-owned builds are part of an intentional publication transaction.
50
+ cancel-in-progress: ${{ !inputs.release }}
51
+
52
+ permissions:
53
+ contents: read
54
+
55
+ env:
56
+ # CI runs must never report to the production telemetry endpoint baked
57
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
58
+ DSH_TELEMETRY_DISABLED: '1'
59
+
60
+ jobs:
61
+ # Job-level conditions cannot inspect `matrix`, so validate target names and
62
+ # construct the matrix before the dependent jobs.
63
+ plan:
64
+ name: plan targets
65
+ if: inputs.ci || inputs.release || github.event_name == 'workflow_dispatch'
66
+ runs-on: >-
67
+ ${{ inputs.ci && !inputs.release && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
68
+ && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }}
69
+ timeout-minutes: 5
70
+ outputs:
71
+ matrix: ${{ steps.plan.outputs.matrix }}
72
+ version: ${{ steps.version.outputs.version }}
73
+ repository-version: ${{ steps.version.outputs.repository-version }}
74
+ steps:
75
+ - uses: actions/checkout@v6
76
+
77
+ - name: Resolve repository version
78
+ id: version
79
+ run: |
80
+ set -euo pipefail
81
+ python3 - <<'PY' >> "$GITHUB_OUTPUT"
82
+ import runpy
83
+
84
+ release = runpy.run_path("scripts/build-python-release.py")
85
+ repository_version = release["repository_version"]()
86
+ wheel_version = release["pep440_version"](repository_version)
87
+ print(f"repository-version={repository_version}")
88
+ print(f"version={wheel_version}")
89
+ PY
90
+
91
+ - name: Compute matrix from targets input
92
+ id: plan
93
+ env:
94
+ # Blank dispatch inputs build all targets.
95
+ TARGETS: ${{ inputs.targets || 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-macos-x64,node24-win-x64' }}
96
+ run: |
97
+ set -euo pipefail
98
+ matrix='[]'
99
+ IFS=',' read -r -a targets <<< "$TARGETS"
100
+ for raw in "${targets[@]}"; do
101
+ t="$(echo "$raw" | xargs)" # trim surrounding whitespace
102
+ [ -z "$t" ] && continue
103
+ # Native-only: hosted arm64 Linux uses ubuntu-24.04-arm, while
104
+ # macos-latest is Apple Silicon; macos-15-intel is native x64.
105
+ case "$t" in
106
+ node24-linux-x64) runner=ubuntu-latest ;;
107
+ node24-linux-arm64) runner=ubuntu-24.04-arm ;;
108
+ node24-macos-arm64) runner=macos-latest ;;
109
+ node24-macos-x64) runner=macos-15-intel ;;
110
+ node24-win-x64) runner=windows-2025 ;;
111
+ *)
112
+ echo "::error::Unknown target '$t'. Supported: node24-linux-x64, node24-linux-arm64, node24-macos-arm64, node24-macos-x64, node24-win-x64."
113
+ exit 1
114
+ ;;
115
+ esac
116
+ matrix="$(jq -c --arg target "$t" --arg runner "$runner" '. + [{target: $target, runner: $runner}]' <<< "$matrix")"
117
+ done
118
+ if [ "$matrix" = '[]' ]; then
119
+ echo "::error::The targets input selected nothing to build."
120
+ exit 1
121
+ fi
122
+ echo "Matrix: $matrix"
123
+ echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
124
+
125
+ sdk-wheel:
126
+ needs: plan
127
+ name: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
128
+ runs-on: >-
129
+ ${{ inputs.ci && !inputs.release && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
130
+ && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }}
131
+ timeout-minutes: 5
132
+ steps:
133
+ - uses: actions/checkout@v6
134
+
135
+ - uses: actions/setup-python@v6.3.0
136
+ with:
137
+ python-version: '3.10'
138
+
139
+ - name: Install Python build tooling
140
+ run: python -m pip install uv==0.11.23
141
+
142
+ - name: Build release-shaped SDK wheel
143
+ run: >-
144
+ python scripts/build-python-release.py
145
+ --package sdk
146
+ --output-dir dist-python
147
+
148
+ - uses: actions/upload-artifact@v7
149
+ with:
150
+ name: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
151
+ path: dist-python/deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
152
+ if-no-files-found: error
153
+ retention-days: 7
154
+
155
+ build:
156
+ needs: [plan, sdk-wheel]
157
+ name: ${{ matrix.target }}
158
+ runs-on: >-
159
+ ${{ inputs.ci && !inputs.release && matrix.target == 'node24-linux-x64'
160
+ && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
161
+ || inputs.ci && !inputs.release && matrix.target == 'node24-win-x64'
162
+ && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025'
163
+ || matrix.runner }}
164
+ timeout-minutes: 45
165
+ strategy:
166
+ fail-fast: false
167
+ matrix:
168
+ include: ${{ fromJSON(needs.plan.outputs.matrix) }}
169
+ steps:
170
+ - uses: actions/checkout@v6
171
+ with:
172
+ persist-credentials: false
173
+
174
+ - uses: pnpm/action-setup@v4
175
+ with:
176
+ dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
177
+
178
+ - name: Enable Windows Developer Mode (symlink support)
179
+ if: runner.os == 'Windows'
180
+ shell: pwsh
181
+ run: >-
182
+ reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
183
+ /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
184
+
185
+ # setup-node's built-in pnpm store cache keys on platform AND arch, so
186
+ # the Linux architectures sharing runner.os stay on separate caches.
187
+ - uses: actions/setup-node@v6
188
+ with:
189
+ node-version: 24
190
+ cache: pnpm
191
+
192
+ - uses: actions/setup-python@v6.3.0
193
+ with:
194
+ python-version: '3.10'
195
+
196
+ - name: Install Python build tooling
197
+ run: python -m pip install uv==0.11.23
198
+
199
+ # Cache pkg's target Node binary; lockfile changes roll the
200
+ # exact key while the restore prefix can seed its replacement.
201
+ - uses: actions/cache@v4
202
+ with:
203
+ path: ~/.pkg-cache
204
+ key: pkg-fetch-${{ matrix.target }}-${{ hashFiles('pnpm-lock.yaml') }}
205
+ restore-keys: |
206
+ pkg-fetch-${{ matrix.target }}-
207
+
208
+ - name: Install (immutable)
209
+ # node-gyp fetches Node headers from nodejs.org during install; that
210
+ # endpoint stalls intermittently (observed 10 s connect timeouts).
211
+ # Bounded retries mirror the wine lane's transfer policy without a
212
+ # mirror, since these installs also resolve native addons.
213
+ shell: bash
214
+ run: |
215
+ for attempt in 1 2 3; do
216
+ if pnpm install --frozen-lockfile; then exit 0; fi
217
+ [ "$attempt" -lt 3 ] && sleep 10
218
+ done
219
+ exit 1
220
+
221
+ - name: Rebuild Linux node-pty against manylinux 2.28
222
+ if: runner.os == 'Linux'
223
+ env:
224
+ RUNNER_ARCH: ${{ runner.arch }}
225
+ run: |
226
+ set -euo pipefail
227
+ case "$RUNNER_ARCH" in
228
+ X64) image=quay.io/pypa/manylinux_2_28_x86_64 ;;
229
+ ARM64) image=quay.io/pypa/manylinux_2_28_aarch64 ;;
230
+ *) echo "::error::Unsupported Linux runner architecture $RUNNER_ARCH"; exit 1 ;;
231
+ esac
232
+ addon_dir="$(realpath packages/subprocess/subprocess-local/node_modules/node-pty)"
233
+ pnpm_setup_root="$(realpath "$(dirname "$(dirname "$PNPM_HOME")")")"
234
+ (cd "$addon_dir" && npm_config_build_from_source=true pnpm run install)
235
+ addon="$addon_dir/build/Release/pty.node"
236
+ [ -f "$addon_dir/build/Makefile" ] || {
237
+ echo "::error::node-pty install did not generate $addon_dir/build/Makefile"
238
+ exit 1
239
+ }
240
+ docker run --rm \
241
+ --user "$(id -u):$(id -g)" \
242
+ -v "$PWD:$PWD" \
243
+ -v "$HOME/.cache/node-gyp:$HOME/.cache/node-gyp:ro" \
244
+ -v "$pnpm_setup_root:$pnpm_setup_root:ro" \
245
+ -w "$addon_dir" \
246
+ "$image" \
247
+ bash -euxo pipefail -c \
248
+ 'rm -rf build/Release && make -C build -j2 BUILDTYPE=Release'
249
+ [ -f "$addon" ] || { echo "::error::$addon missing after manylinux rebuild"; exit 1; }
250
+ readelf --version-info "$addon" | tee node-pty-glibc-versions.txt
251
+ maximum="$(sed -n 's/.*Name: GLIBC_\([0-9.]*\).*/\1/p' node-pty-glibc-versions.txt | sort -V | tail -1)"
252
+ [ -n "$maximum" ] || { echo "::error::No GLIBC requirements found in $addon"; exit 1; }
253
+ dpkg --compare-versions "$maximum" le 2.28 || {
254
+ echo "::error::node-pty addon requires GLIBC_$maximum but wheel claims manylinux_2_28"
255
+ exit 1
256
+ }
257
+
258
+ - name: Build single-exe
259
+ env:
260
+ DSH_BUILD_CLIENT_PROFILE: official
261
+ run: pnpm exec tsx scripts/build-exe-for-python-sdk.ts --targets=${{ matrix.target }}
262
+
263
+ - name: Resolve platform outputs (POSIX)
264
+ id: runtime-posix
265
+ if: runner.os != 'Windows'
266
+ env:
267
+ TARGET: ${{ matrix.target }}
268
+ VERSION: ${{ needs.plan.outputs.version }}
269
+ run: |
270
+ set -euo pipefail
271
+ platform="${TARGET#node24-}"
272
+ exe="$PWD/dist-exe/deepseek-harness-sdk-runtime-$platform"
273
+ case "$platform" in
274
+ linux-x64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl ;;
275
+ linux-arm64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_aarch64.whl ;;
276
+ macos-arm64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_arm64.whl ;;
277
+ macos-x64) wheel=deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_x86_64.whl ;;
278
+ *) echo "::error::Unsupported runtime platform $platform"; exit 1 ;;
279
+ esac
280
+ [ -x "$exe" ] || { echo "::error::$exe missing or not executable"; exit 1; }
281
+ echo "platform=$platform" >> "$GITHUB_OUTPUT"
282
+ echo "exe=$exe" >> "$GITHUB_OUTPUT"
283
+ echo "wheel=$wheel" >> "$GITHUB_OUTPUT"
284
+
285
+ - name: Resolve platform outputs (Windows)
286
+ id: runtime-windows
287
+ if: runner.os == 'Windows'
288
+ shell: pwsh
289
+ env:
290
+ TARGET: ${{ matrix.target }}
291
+ VERSION: ${{ needs.plan.outputs.version }}
292
+ run: |
293
+ if ($env:TARGET -ne 'node24-win-x64') { throw "Unsupported runtime target $env:TARGET" }
294
+ $platform = 'win-x64'
295
+ $exe = Join-Path $PWD 'dist-exe\deepseek-harness-sdk-runtime-win-x64.exe'
296
+ $wheel = "deepseek_harness_runtime_bin-$env:VERSION-py3-none-win_amd64.whl"
297
+ if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) { throw "Runtime executable is missing at $exe" }
298
+ "platform=$platform" >> $env:GITHUB_OUTPUT
299
+ "exe=$exe" >> $env:GITHUB_OUTPUT
300
+ "wheel=$wheel" >> $env:GITHUB_OUTPUT
301
+
302
+ - name: Build release-shaped runtime wheel
303
+ run: >-
304
+ python scripts/build-python-release.py
305
+ --package runtime
306
+ --platform "${{ steps.runtime-posix.outputs.platform || steps.runtime-windows.outputs.platform }}"
307
+ --runtime-exe "${{ steps.runtime-posix.outputs.exe || steps.runtime-windows.outputs.exe }}"
308
+ --output-dir dist-python
309
+
310
+ - uses: actions/download-artifact@v8
311
+ with:
312
+ name: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
313
+ path: dist-python
314
+
315
+ - name: Install local SDK and runtime wheels into a clean venv (POSIX)
316
+ id: smoke-venv-posix
317
+ if: runner.os != 'Windows'
318
+ env:
319
+ RUNTIME_WHEEL: ${{ steps.runtime-posix.outputs.wheel }}
320
+ SDK_WHEEL: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
321
+ run: |
322
+ set -euo pipefail
323
+ venv="$(python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-smoke-"))')"
324
+ python -m venv "$venv"
325
+ smoke_python="$venv/bin/python"
326
+ "$smoke_python" -m pip install \
327
+ "dist-python/$SDK_WHEEL" \
328
+ "dist-python/$RUNTIME_WHEEL"
329
+ echo "python=$smoke_python" >> "$GITHUB_OUTPUT"
330
+
331
+ - name: Install local SDK and runtime wheels into a clean venv (Windows)
332
+ id: smoke-venv-windows
333
+ if: runner.os == 'Windows'
334
+ shell: pwsh
335
+ env:
336
+ RUNTIME_WHEEL: ${{ steps.runtime-windows.outputs.wheel }}
337
+ SDK_WHEEL: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
338
+ run: |
339
+ $venv = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-smoke-"))').Trim()
340
+ python -m venv $venv
341
+ $smokePython = Join-Path $venv 'Scripts\python.exe'
342
+ & $smokePython -m pip install "dist-python/$env:SDK_WHEEL" "dist-python/$env:RUNTIME_WHEEL"
343
+ if ($LASTEXITCODE -ne 0) { throw "Wheel installation failed with exit code $LASTEXITCODE" }
344
+ "python=$smokePython" >> $env:GITHUB_OUTPUT
345
+
346
+ - name: Run installed-wheel keyless black-box tests (POSIX)
347
+ if: runner.os != 'Windows'
348
+ run: |
349
+ set -euo pipefail
350
+ blackbox_root="$(python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-"))')"
351
+ cd "$blackbox_root"
352
+ env -u PYTHONPATH -u DSH_RUNTIME_MODE \
353
+ "${{ steps.smoke-venv-posix.outputs.python }}" \
354
+ "$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \
355
+ --scenario all \
356
+ --installed-wheel
357
+
358
+ - name: Run installed-wheel keyless black-box tests (Windows)
359
+ if: runner.os == 'Windows'
360
+ shell: pwsh
361
+ run: |
362
+ $blackboxRoot = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-"))').Trim()
363
+ Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue
364
+ Remove-Item Env:DSH_RUNTIME_MODE -ErrorAction SilentlyContinue
365
+ Push-Location $blackboxRoot
366
+ try {
367
+ & "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario all --installed-wheel
368
+ if ($LASTEXITCODE -ne 0) { throw "Installed-wheel black-box failed with exit code $LASTEXITCODE" }
369
+ } finally {
370
+ Pop-Location
371
+ }
372
+
373
+ - name: Preflight installed-wheel real API test (POSIX)
374
+ if: >-
375
+ inputs.ci
376
+ && runner.os != 'Windows'
377
+ && (github.event_name != 'pull_request'
378
+ || !(github.event.pull_request.head.repo.fork
379
+ || github.event.pull_request.user.login == 'dependabot[bot]'))
380
+ env:
381
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
382
+ run: |
383
+ set -euo pipefail
384
+ if [ -z "${DEEPSEEK_API_KEY:-}" ]; then
385
+ echo "::error::DEEPSEEK_API_KEY_EXTERNAL is empty; the installed-wheel real API test cannot self-skip."
386
+ exit 1
387
+ fi
388
+
389
+ - name: Preflight installed-wheel real API test (Windows)
390
+ if: >-
391
+ inputs.ci
392
+ && runner.os == 'Windows'
393
+ && (github.event_name != 'pull_request'
394
+ || !(github.event.pull_request.head.repo.fork
395
+ || github.event.pull_request.user.login == 'dependabot[bot]'))
396
+ shell: pwsh
397
+ env:
398
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
399
+ run: |
400
+ if ([string]::IsNullOrWhiteSpace($env:DEEPSEEK_API_KEY)) {
401
+ throw 'DEEPSEEK_API_KEY_EXTERNAL is empty; the installed-wheel real API test cannot self-skip.'
402
+ }
403
+
404
+ - name: Run installed-wheel real API black-box test (POSIX)
405
+ if: >-
406
+ inputs.ci
407
+ && runner.os != 'Windows'
408
+ && (github.event_name != 'pull_request'
409
+ || !(github.event.pull_request.head.repo.fork
410
+ || github.event.pull_request.user.login == 'dependabot[bot]'))
411
+ env:
412
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
413
+ DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic
414
+ run: |
415
+ set -euo pipefail
416
+ blackbox_root="$(python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-live-"))')"
417
+ cd "$blackbox_root"
418
+ env -u PYTHONPATH -u DSH_RUNTIME_MODE \
419
+ "${{ steps.smoke-venv-posix.outputs.python }}" \
420
+ "$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \
421
+ --scenario sdk-live \
422
+ --installed-wheel
423
+
424
+ - name: Run installed-wheel real API black-box test (Windows)
425
+ if: >-
426
+ inputs.ci
427
+ && runner.os == 'Windows'
428
+ && (github.event_name != 'pull_request'
429
+ || !(github.event.pull_request.head.repo.fork
430
+ || github.event.pull_request.user.login == 'dependabot[bot]'))
431
+ shell: pwsh
432
+ env:
433
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
434
+ DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic
435
+ run: |
436
+ $blackboxRoot = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-blackbox-live-"))').Trim()
437
+ Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue
438
+ Remove-Item Env:DSH_RUNTIME_MODE -ErrorAction SilentlyContinue
439
+ Push-Location $blackboxRoot
440
+ try {
441
+ & "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario sdk-live --installed-wheel
442
+ if ($LASTEXITCODE -ne 0) { throw "Installed-wheel live API smoke failed with exit code $LASTEXITCODE" }
443
+ } finally {
444
+ Pop-Location
445
+ }
446
+
447
+ - name: Check Linux GLIBC requirements
448
+ if: runner.os == 'Linux'
449
+ run: |
450
+ set -euo pipefail
451
+ readelf --version-info "${{ steps.runtime-posix.outputs.exe }}" | tee glibc-versions.txt
452
+ maximum="$(sed -n 's/.*Name: GLIBC_\([0-9.]*\).*/\1/p' glibc-versions.txt | sort -V | tail -1)"
453
+ [ -n "$maximum" ] || { echo "::error::No GLIBC requirements found"; exit 1; }
454
+ dpkg --compare-versions "$maximum" le 2.28 || {
455
+ echo "::error::Executable requires GLIBC_$maximum but wheel claims manylinux_2_28"
456
+ exit 1
457
+ }
458
+
459
+ - name: Check macOS payload architecture and deployment target
460
+ if: runner.os == 'macOS'
461
+ env:
462
+ EXE: ${{ steps.runtime-posix.outputs.exe }}
463
+ PLATFORM: ${{ steps.runtime-posix.outputs.platform }}
464
+ run: |
465
+ set -euo pipefail
466
+ case "$PLATFORM" in
467
+ macos-arm64) macho_arch=arm64 ;;
468
+ macos-x64) macho_arch=x86_64 ;;
469
+ *) echo "::error::Unsupported macOS platform $PLATFORM"; exit 1 ;;
470
+ esac
471
+ for payload in "$EXE" "$EXE-rg" "$EXE-spawn-helper"; do
472
+ lipo "$payload" -verify_arch "$macho_arch"
473
+ done
474
+ python3 scripts/check-macos-deployment-target.py \
475
+ --platform "$PLATFORM" "$EXE" "$EXE-rg" "$EXE-spawn-helper"
476
+
477
+ - name: Run wheel in a manylinux 2.28 container
478
+ if: runner.os == 'Linux'
479
+ env:
480
+ RUNNER_ARCH: ${{ runner.arch }}
481
+ RUNTIME_WHEEL: ${{ steps.runtime-posix.outputs.wheel }}
482
+ SDK_WHEEL: deepseek_harness_sdk-${{ needs.plan.outputs.version }}-py3-none-any.whl
483
+ run: |
484
+ set -euo pipefail
485
+ case "$RUNNER_ARCH" in
486
+ X64) image=quay.io/pypa/manylinux_2_28_x86_64 ;;
487
+ ARM64) image=quay.io/pypa/manylinux_2_28_aarch64 ;;
488
+ *) echo "::error::Unsupported Linux runner architecture $RUNNER_ARCH"; exit 1 ;;
489
+ esac
490
+ docker run --rm -e RUNTIME_WHEEL -e SDK_WHEEL -e DSH_TELEMETRY_DISABLED -v "$PWD:/work" -w /work "$image" bash -euxo pipefail -c '
491
+ /opt/python/cp310-cp310/bin/python -m venv /tmp/dsh-sdk
492
+ /tmp/dsh-sdk/bin/python -m pip install "/work/dist-python/$SDK_WHEEL" "/work/dist-python/$RUNTIME_WHEEL"
493
+ mkdir -p /tmp/dsh-sdk-manylinux-smoke
494
+ cd /tmp/dsh-sdk-manylinux-smoke
495
+ env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-default --installed-wheel
496
+ env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-mcp --installed-wheel
497
+ '
498
+
499
+ - uses: actions/upload-artifact@v7
500
+ with:
501
+ name: ${{ steps.runtime-posix.outputs.wheel || steps.runtime-windows.outputs.wheel }}
502
+ path: dist-python/${{ steps.runtime-posix.outputs.wheel || steps.runtime-windows.outputs.wheel }}
503
+ if-no-files-found: error
504
+ retention-days: 7
.github/workflows/build-preview-cloudflare.yml ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build PR preview
2
+
3
+ # Every push to a pull request publishes that pull request's preview to
4
+ # Cloudflare Pages under its own branch alias, behind Cloudflare Access. The
5
+ # upload carries build products only: the workflow never grants the deployment
6
+ # platform access to this repository's sources.
7
+
8
+ on:
9
+ pull_request:
10
+ types: [opened, synchronize, reopened]
11
+
12
+ # Within one pull request the newest build wins. Across pull requests there is
13
+ # nothing to serialize: each uploads to its own branch alias, so two deployments
14
+ # never contend for the same URL.
15
+ concurrency:
16
+ group: build-preview-cloudflare-${{ github.event.pull_request.number }}
17
+ cancel-in-progress: true
18
+
19
+ permissions:
20
+ contents: read
21
+ pull-requests: write
22
+
23
+ env:
24
+ PRIMARY_NODE_VERSION: '24'
25
+ # Cloudflare Pages project receiving the upload. Its preview deployments are
26
+ # the surface the Access application protects; the project's production branch
27
+ # is deliberately a name no deployment uses, so no unprotected URL exists.
28
+ CF_PROJECT: dsh-build-preview
29
+ # CI runs must never report to the production telemetry endpoint baked into
30
+ # apps/cli/cordis.yml (AppCLIEntry disables the row when set).
31
+ DSH_TELEMETRY_DISABLED: '1'
32
+
33
+ jobs:
34
+ preview:
35
+ runs-on: ubuntu-24.04
36
+ name: cloudflare pages preview
37
+ steps:
38
+ - uses: actions/checkout@v6
39
+ with:
40
+ persist-credentials: false
41
+
42
+ - uses: pnpm/action-setup@v4
43
+ with:
44
+ dest: ${{ runner.temp }}/setup-pnpm
45
+
46
+ - uses: actions/setup-node@v6
47
+ with:
48
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
49
+
50
+ - name: Configure pnpm store path
51
+ id: pnpm-store
52
+ run: |
53
+ store_root="$HOME/.local/share/pnpm/store"
54
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
55
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
56
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
57
+
58
+ # Read-only: the preview lane consumes the default-branch cache without
59
+ # putting cache upload on its own path.
60
+ - uses: actions/cache/restore@v4
61
+ with:
62
+ path: ${{ steps.pnpm-store.outputs.path }}
63
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
64
+ restore-keys: |
65
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
66
+
67
+ - name: Install (immutable)
68
+ run: pnpm install --frozen-lockfile
69
+
70
+ # apps/web consumes workspace packages as built lib products, and
71
+ # build:preview packs the image through the packer's installed bin
72
+ # (lib/bin.js), so neither half exists before the full build runs.
73
+ - name: Build workspace
74
+ run: pnpm run build
75
+
76
+ - name: Build the preview page and pack the VFS image
77
+ env:
78
+ DSH_CLIENT_TITLE: DSH preview pr-${{ github.event.pull_request.number }}
79
+ run: pnpm --filter @deepseek-ai/dsh-web-frontend run build:preview
80
+
81
+ # Sourcemaps carry complete sources and stay off the deployment platform.
82
+ # index.html is the served page, which cannot boot without a host
83
+ # injecting window.__DSH_BOOT__; replacing it with the worker page makes
84
+ # the deployment root the usable entry instead of a page that never boots.
85
+ - name: Shape the upload
86
+ run: |
87
+ find apps/web/dist -name '*.map' -delete
88
+ cp apps/web/dist/preview.html apps/web/dist/index.html
89
+
90
+ - name: Upload to Cloudflare Pages
91
+ env:
92
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
93
+ CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
94
+ run: |
95
+ npx --yes wrangler@4 pages deploy apps/web/dist \
96
+ --project-name "$CF_PROJECT" \
97
+ --branch "pr-${{ github.event.pull_request.number }}" \
98
+ --commit-dirty=true
99
+
100
+ # The image is what a worker boot fails on first and least visibly, so the
101
+ # run only passes once the protected URL serves it as gzip bytes. Three
102
+ # facts are asserted, each with its own failure meaning:
103
+ # 200 Access admitted the request; a 302 means the
104
+ # Access policy is missing its Service Auth rule
105
+ # for this token
106
+ # no content-encoding the platform did not claim transport
107
+ # compression, which would make the browser
108
+ # decode the body and leave the worker's
109
+ # DecompressionStream inflating a plain tar
110
+ # gzip magic 1f 8b the bytes really are the gzip member the
111
+ # packer wrote
112
+ # Accept-Encoding is sent because a browser sends it; the assertion is
113
+ # about what the platform does with a body that is already compressed.
114
+ - name: Verify the protected deployment serves the image
115
+ env:
116
+ CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }}
117
+ CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }}
118
+ run: |
119
+ url="https://pr-${{ github.event.pull_request.number }}.${CF_PROJECT}.pages.dev"
120
+ image="$url/preview/vfs-image.tar.gz"
121
+ code=000
122
+ for attempt in 1 2 3 4 5; do
123
+ code=$(curl -sS -o image.bin -D headers.txt -w '%{http_code}' \
124
+ -H 'Accept-Encoding: gzip' \
125
+ -H "CF-Access-Client-Id: $CF_ACCESS_CLIENT_ID" \
126
+ -H "CF-Access-Client-Secret: $CF_ACCESS_CLIENT_SECRET" \
127
+ "$image" || echo 000)
128
+ echo "attempt $attempt: HTTP $code"
129
+ if [ "$code" = "200" ]; then break; fi
130
+ sleep 10
131
+ done
132
+ if [ "$code" != "200" ]; then
133
+ echo "the protected image URL answered $code, not 200"
134
+ head -20 headers.txt
135
+ exit 1
136
+ fi
137
+ if grep -qi '^content-encoding:' headers.txt; then
138
+ echo "the platform declared transport compression on an already-compressed image:"
139
+ grep -i '^content-encoding:' headers.txt
140
+ exit 1
141
+ fi
142
+ magic=$(head -c 2 image.bin | od -An -tx1 | tr -d ' \n')
143
+ if [ "$magic" != "1f8b" ]; then
144
+ echo "image does not start with the gzip magic number: $magic"
145
+ exit 1
146
+ fi
147
+ echo "image served as $(wc -c < image.bin) gzip bytes"
148
+
149
+ # The alias URL follows from the pull request number, so it is stable
150
+ # across redeploys and worth stating once. The marker makes the comment
151
+ # idempotent: a pull request opened before this workflow existed never
152
+ # sees an `opened` event, and every later push must not restate the URL.
153
+ - name: Comment the preview URL
154
+ env:
155
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
156
+ PR: ${{ github.event.pull_request.number }}
157
+ run: |
158
+ marker='<!-- dsh-preview-url -->'
159
+ existing=$(gh pr view "$PR" --json comments \
160
+ --jq "[.comments[] | select(.body | contains(\"$marker\")) | .url] | first // empty")
161
+ if [ -n "$existing" ]; then
162
+ echo "preview URL already commented: $existing"
163
+ exit 0
164
+ fi
165
+ # The marker sits on its own line: markdown renders no link on a
166
+ # line that opens with a raw HTML comment.
167
+ printf '%s\n\n%s\n' \
168
+ "$marker" \
169
+ "[Preview for #$PR](https://pr-$PR.${CF_PROJECT}.pages.dev) (requires Cloudflare Access sign-in)" \
170
+ | gh pr comment "$PR" --body-file -
.github/workflows/ci-master.yml ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI master
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ workflow_dispatch:
7
+ inputs:
8
+ suite:
9
+ description: Manual CI suite to run
10
+ required: true
11
+ default: larger-runner-benchmark
12
+ type: choice
13
+ options:
14
+ - larger-runner-benchmark
15
+ - consolidated-runner-benchmark
16
+
17
+ # New master pushes and manual runs replace obsolete checks in this workflow/ref.
18
+ # Standby drills share cancellation; use completed runs as readiness evidence.
19
+ concurrency:
20
+ group: ${{ github.workflow }}-${{ github.ref }}
21
+ cancel-in-progress: true
22
+
23
+ permissions:
24
+ contents: read
25
+
26
+ env:
27
+ PRIMARY_NODE_VERSION: '24'
28
+ # CI runs must never report to the production telemetry endpoint baked
29
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
30
+ DSH_TELEMETRY_DISABLED: '1'
31
+
32
+ jobs:
33
+ # These native runtime carriers are post-merge checks; release keeps all targets.
34
+ python-runtime:
35
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
36
+ name: python runtime / macOS and Linux ARM64
37
+ uses: ./.github/workflows/build-exe-for-python-sdk.yml
38
+ with:
39
+ targets: node24-linux-arm64,node24-macos-arm64,node24-macos-x64
40
+ ci: true
41
+ secrets:
42
+ DEEPSEEK_API_KEY_EXTERNAL: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
43
+
44
+ # Wine runs once here, independently of the native serial standby aggregates.
45
+ windows:
46
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
47
+ runs-on: ubuntu-latest
48
+ name: windows node 24 / wine
49
+ timeout-minutes: 15
50
+ steps:
51
+ - uses: actions/checkout@v6
52
+ with:
53
+ persist-credentials: false
54
+
55
+ - uses: pnpm/action-setup@v4
56
+ with:
57
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
58
+
59
+ - uses: actions/setup-node@v6
60
+ with:
61
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
62
+
63
+ - name: Configure pnpm store path
64
+ id: pnpm-store
65
+ run: |
66
+ store_root="$HOME/.local/share/pnpm/store"
67
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
68
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
69
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
70
+
71
+ - uses: actions/cache/restore@v4
72
+ with:
73
+ path: ${{ steps.pnpm-store.outputs.path }}
74
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
75
+ restore-keys: |
76
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
77
+
78
+ # Master CI restores and seeds the image-specific Wine dependency cache.
79
+ - name: Compose Wine apt cache key
80
+ id: wine-cache-key
81
+ run: echo "key=wine-debs-${ImageOS:-linux}-${ImageVersion:-v0}" >> "$GITHUB_OUTPUT"
82
+
83
+ - uses: actions/cache@v4
84
+ with:
85
+ path: ~/wine-debs
86
+ key: ${{ steps.wine-cache-key.outputs.key }}
87
+
88
+ # Runner provisioning only — a developer machine installs Wine through
89
+ # its own package manager; the gate script assumes a wine binary and
90
+ # fails loud without one. Wine from the apt cache when present; else
91
+ # download the full dependency closure once and keep it for the next
92
+ # run. The `wine` dispatcher package (not bare `wine64`) is what puts a
93
+ # binary on PATH.
94
+ - name: Install Wine
95
+ run: |
96
+ if compgen -G "$HOME/wine-debs/*.deb" > /dev/null; then
97
+ # The restored archive is the full --download-only closure of
98
+ # `wine` for this runner image, so installing the .debs directly
99
+ # with dpkg needs no repository access. apt-get would instead
100
+ # re-download the same 100+ MB closure from the mirror, which has
101
+ # stalled the job past its budget on a degraded runner network.
102
+ # If the archive cannot satisfy the closure, fall back to the apt
103
+ # network install.
104
+ if ! sudo DEBIAN_FRONTEND=noninteractive dpkg -i "$HOME"/wine-debs/*.deb; then
105
+ sudo DEBIAN_FRONTEND=noninteractive dpkg --configure -a || true
106
+ sudo apt-get install -y --no-install-recommends "$HOME"/wine-debs/*.deb
107
+ fi
108
+ else
109
+ sudo apt-get update
110
+ sudo apt-get install -y --no-install-recommends --download-only wine
111
+ mkdir -p "$HOME/wine-debs"
112
+ cp /var/cache/apt/archives/*.deb "$HOME/wine-debs/" 2>/dev/null || true
113
+ sudo apt-get install -y --no-install-recommends wine
114
+ fi
115
+
116
+ - name: Run the Wine Windows gates
117
+ run: bash scripts/wine-windows-gates.sh
118
+
119
+ - name: Shut down wineserver
120
+ if: always()
121
+ run: wineserver -k 2>/dev/null || true
122
+
123
+ # Hot-standby drill for the in-house self-hosted pool: every master move
124
+ # re-runs the complete unsharded aggregate on the persistent 64-core VM,
125
+ # continuously proving that environment can take over a required lane if
126
+ # the hosted pools degrade (the switch is then setting the writer-manageable
127
+ # DSH_CI_FAILOVER_LINUX variable — see the failover runbook, no merge required).
128
+ # Push-triggered, so this lane always executes the base branch's own
129
+ # workflow definition. This workflow never listens to pull_request, so the
130
+ # drill does not appear in PR checks. No cache steps because the VM's
131
+ # persistent pnpm store and tool caches make them redundant (and saving here
132
+ # would poison the hosted cache namespace with self-hosted paths).
133
+ serial-linux-selfhosted:
134
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
135
+ name: serial / linux (self-hosted standby)
136
+ runs-on: [self-hosted, linux, x64, vm-backup]
137
+ steps:
138
+ # DSH_ARCHIVE_BASE_REF below compares the frozen-archive gate against
139
+ # github.event.before, so full history is required: depth 2 would miss it
140
+ # on multi-commit or force pushes; full fetch is cheap here because
141
+ # checkout resolves against the VM's local mirror.
142
+ - uses: actions/checkout@v6
143
+ with:
144
+ fetch-depth: 0
145
+
146
+ # Redirect the Node compile cache (enabled by pnpm and TypeScript) off
147
+ # the root partition's /tmp before the first pnpm call in this lane —
148
+ # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md.
149
+ - name: Redirect Node compile cache to runner temp
150
+ run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
151
+
152
+ - uses: pnpm/action-setup@v4
153
+ with:
154
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
155
+
156
+ - uses: actions/setup-node@v6
157
+ with:
158
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
159
+
160
+ - name: Configure persistent pnpm store
161
+ run: echo "PNPM_CONFIG_STORE_DIR=$HOME/.local/share/pnpm/store" >> "$GITHUB_ENV"
162
+
163
+ - name: Install (immutable)
164
+ run: pnpm install --frozen-lockfile
165
+
166
+ # The persistent VM image owns Playwright's Linux system packages; this
167
+ # step also proves that browser provisioning remains usable for failover.
168
+ - name: Install Playwright Chromium
169
+ run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install chromium
170
+
171
+ - name: Prepare bubblewrap (unrestrict userns)
172
+ run: bash scripts/prepare-ci-bubblewrap.sh
173
+
174
+ - name: Run complete unsharded primary Node CI serially
175
+ env:
176
+ DSH_ARCHIVE_BASE_REF: ${{ github.event.before }}
177
+ DSH_COVERAGE_MAX_WORKERS: '1'
178
+ DSH_E2E_MAX_WORKERS: '1'
179
+ DSH_GATE_CONCURRENCY: '1'
180
+ DSH_OXLINT_THREADS: '1'
181
+ DSH_PUBLINT_CONCURRENCY: '1'
182
+ DSH_SNAPSHOT_MAX_CONCURRENCY: '1'
183
+ run: pnpm run check:ci:linux-primary
184
+
185
+ # TODO(hosted-serial-ci): Re-enable the one remaining disabled hosted serial
186
+ # reference job (serial-macos) before release. Re-enabling serial-macos does
187
+ # not restore a Linux hosted-cache producer: decide whether to add a master
188
+ # seeder or remove the restore-only steps if cold starts become a concern.
189
+ serial-macos:
190
+ if: false
191
+ name: serial / macos
192
+ runs-on: macos-latest
193
+ steps:
194
+ - uses: actions/checkout@v6
195
+
196
+ - uses: pnpm/action-setup@v4
197
+ with:
198
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
199
+
200
+ - uses: actions/setup-node@v6
201
+ with:
202
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
203
+
204
+ - name: Install (immutable)
205
+ run: pnpm install --frozen-lockfile
206
+
207
+ - name: Run complete unsharded primary Node CI serially
208
+ env:
209
+ DSH_COVERAGE_MAX_WORKERS: '1'
210
+ DSH_E2E_MAX_WORKERS: '1'
211
+ DSH_GATE_CONCURRENCY: '1'
212
+ DSH_PUBLINT_CONCURRENCY: '1'
213
+ DSH_SNAPSHOT_MAX_CONCURRENCY: '1'
214
+ run: pnpm run check:ci
215
+
216
+ # Hot-standby drill for the in-house self-hosted Windows pool: every master
217
+ # move re-runs the complete unsharded Windows gate inventory on the persistent
218
+ # VM, continuously proving that environment can take over the required
219
+ # `windows` lane if the hosted pool degrades (the switch is setting the
220
+ # writer-manageable DSH_CI_FAILOVER_WINDOWS variable — see the failover
221
+ # runbook, no merge required). Push-triggered, so this lane always executes
222
+ # the base branch's own workflow definition. This workflow never listens to
223
+ # pull_request, so the drill does not appear in PR checks. No cache steps
224
+ # because the VM's persistent pnpm store and tool caches make them redundant
225
+ # (and saving here would poison the hosted cache namespace with self-hosted
226
+ # paths).
227
+ serial-windows:
228
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
229
+ name: serial / windows (self-hosted standby)
230
+ runs-on: [self-hosted, dsh-win-ci, windows]
231
+ timeout-minutes: 120
232
+ steps:
233
+ - uses: actions/checkout@v6
234
+
235
+ - name: Enable Developer Mode (symlink support)
236
+ shell: pwsh
237
+ run: >-
238
+ reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
239
+ /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
240
+
241
+ - uses: pnpm/action-setup@v4
242
+ with:
243
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
244
+
245
+ - uses: actions/setup-node@v6
246
+ with:
247
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
248
+
249
+ - name: Configure persistent pnpm store
250
+ shell: pwsh
251
+ # The store must share the ReFS workspace volume for the clone
252
+ # import method below. Runner workspaces can reside on different drives.
253
+ run: |
254
+ $storeRoot = Join-Path ([IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE)) '.pnpm-store'
255
+ echo "PNPM_CONFIG_STORE_DIR=$storeRoot" >> $env:GITHUB_ENV
256
+
257
+ - name: Install (immutable)
258
+ shell: pwsh
259
+ # See 2026-08-30-windows-refs-store-block-clone-install for the
260
+ # ReFS block-clone rationale; use clone only on ReFS.
261
+ run: >-
262
+ $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':');
263
+ $fs = (Get-Volume -DriveLetter $drive).FileSystem;
264
+ if ($fs -eq 'ReFS') {
265
+ corepack pnpm install --frozen-lockfile --package-import-method=clone
266
+ } else {
267
+ pnpm install --frozen-lockfile
268
+ }
269
+
270
+ - name: Run complete unsharded Windows gate inventory serially
271
+ shell: pwsh
272
+ env:
273
+ DSH_COVERAGE_MAX_WORKERS: '1'
274
+ DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'
275
+ DSH_GATE_CONCURRENCY: '1'
276
+ DSH_PUBLINT_CONCURRENCY: '1'
277
+ run: pnpm run check:ci:windows-complete
278
+
279
+ # Manual, bounded comparison of the actual critical Linux and Windows lanes.
280
+ # The named pools are restricted at the organization level to this repository.
281
+ larger-runner-benchmark:
282
+ if: github.event_name == 'workflow_dispatch' && inputs.suite == 'larger-runner-benchmark'
283
+ # Default measures the repository's own fleet tiers; under the matching
284
+ # platform's blacksmith failover value the tiers Blacksmith offers (up to
285
+ # 32 vCPU) move onto their Blacksmith equivalents, while the 64/96-core
286
+ # rows keep the fleet labels because Blacksmith has no such tier.
287
+ runs-on: >-
288
+ ${{ (matrix.platform == 'linux' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
289
+ || matrix.platform == 'windows' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith')
290
+ && matrix.blacksmith
291
+ || matrix.runner }}
292
+ timeout-minutes: 15
293
+ strategy:
294
+ fail-fast: false
295
+ max-parallel: 12
296
+ matrix:
297
+ include:
298
+ - platform: linux
299
+ cores: '4'
300
+ runner: dsh-ubuntu-24-04-4core
301
+ blacksmith: blacksmith-4vcpu-ubuntu-2404
302
+ workload: typecheck
303
+ - platform: linux
304
+ cores: '8'
305
+ runner: dsh-ubuntu-24-04-8core
306
+ blacksmith: blacksmith-8vcpu-ubuntu-2404
307
+ workload: typecheck
308
+ - platform: linux
309
+ cores: '16'
310
+ runner: dsh-ubuntu-24-04-16core
311
+ blacksmith: blacksmith-16vcpu-ubuntu-2404
312
+ workload: typecheck
313
+ - platform: linux
314
+ cores: '32'
315
+ runner: dsh-ubuntu-24-04-32core
316
+ blacksmith: blacksmith-32vcpu-ubuntu-2404
317
+ workload: typecheck
318
+ - platform: linux
319
+ cores: '64'
320
+ runner: dsh-ubuntu-24-04-64core
321
+ blacksmith: ''
322
+ workload: typecheck
323
+ - platform: linux
324
+ cores: '96'
325
+ runner: dsh-ubuntu-24-04-96core
326
+ blacksmith: ''
327
+ workload: typecheck
328
+ - platform: windows
329
+ cores: '4'
330
+ runner: dsh-windows-2025-4core
331
+ blacksmith: blacksmith-4vcpu-windows-2025
332
+ workload: production-site
333
+ - platform: windows
334
+ cores: '8'
335
+ runner: dsh-windows-2025-8core
336
+ blacksmith: blacksmith-8vcpu-windows-2025
337
+ workload: production-site
338
+ - platform: windows
339
+ cores: '16'
340
+ runner: dsh-windows-2025-16core
341
+ blacksmith: blacksmith-16vcpu-windows-2025
342
+ workload: production-site
343
+ - platform: windows
344
+ cores: '32'
345
+ runner: dsh-windows-2025-32core
346
+ blacksmith: blacksmith-32vcpu-windows-2025
347
+ workload: production-site
348
+ - platform: windows
349
+ cores: '64'
350
+ runner: dsh-windows-2025-64core
351
+ blacksmith: ''
352
+ workload: production-site
353
+ - platform: windows
354
+ cores: '96'
355
+ runner: dsh-windows-2025-96core
356
+ blacksmith: ''
357
+ workload: production-site
358
+ steps:
359
+ - uses: actions/checkout@v6
360
+
361
+ - uses: pnpm/action-setup@v4
362
+ with:
363
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
364
+
365
+ # The benchmark's Windows lanes deliberately skip the store cache like
366
+ # the independent native Windows job; an empty input disables caching.
367
+ - uses: actions/setup-node@v6
368
+ with:
369
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
370
+ cache: ${{ matrix.platform == 'linux' && 'pnpm' || '' }}
371
+
372
+ - name: Report runner capacity
373
+ run: >-
374
+ node -e "const os = require('node:os');
375
+ console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length,
376
+ memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))"
377
+
378
+ - name: Install (immutable)
379
+ run: pnpm install --frozen-lockfile
380
+
381
+ - name: Run critical Linux typecheck lane
382
+ if: matrix.platform == 'linux'
383
+ run: pnpm run typecheck
384
+
385
+ - name: Run critical Windows production-site lane
386
+ if: matrix.platform == 'windows'
387
+ run: pnpm run docs:build
388
+
389
+ # Manual comparison of the intended low-fanout topology. Linux runs the
390
+ # complete unsharded primary aggregate with bounded in-runner parallelism;
391
+ # Windows runs both blocking build targets concurrently through run-gates.
392
+ consolidated-runner-benchmark:
393
+ if: github.event_name == 'workflow_dispatch' && inputs.suite == 'consolidated-runner-benchmark'
394
+ # Default measures the repository's own fleet tiers; under the matching
395
+ # platform's blacksmith failover value the tiers Blacksmith offers (up to
396
+ # 32 vCPU) move onto their Blacksmith equivalents, while the 64/96-core
397
+ # rows keep the fleet labels because Blacksmith has no such tier.
398
+ runs-on: >-
399
+ ${{ (matrix.platform == 'linux' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
400
+ || matrix.platform == 'windows' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith')
401
+ && matrix.blacksmith
402
+ || matrix.runner }}
403
+ timeout-minutes: 15
404
+ strategy:
405
+ fail-fast: false
406
+ max-parallel: 12
407
+ matrix:
408
+ include:
409
+ - platform: linux
410
+ cores: '4'
411
+ runner: dsh-ubuntu-24-04-4core
412
+ blacksmith: blacksmith-4vcpu-ubuntu-2404
413
+ workers: '4'
414
+ - platform: linux
415
+ cores: '8'
416
+ runner: dsh-ubuntu-24-04-8core
417
+ blacksmith: blacksmith-8vcpu-ubuntu-2404
418
+ workers: '8'
419
+ - platform: linux
420
+ cores: '16'
421
+ runner: dsh-ubuntu-24-04-16core
422
+ blacksmith: blacksmith-16vcpu-ubuntu-2404
423
+ workers: '16'
424
+ - platform: linux
425
+ cores: '32'
426
+ runner: dsh-ubuntu-24-04-32core
427
+ blacksmith: blacksmith-32vcpu-ubuntu-2404
428
+ workers: '32'
429
+ - platform: linux
430
+ cores: '64'
431
+ runner: dsh-ubuntu-24-04-64core
432
+ blacksmith: ''
433
+ workers: '32'
434
+ - platform: linux
435
+ cores: '96'
436
+ runner: dsh-ubuntu-24-04-96core
437
+ blacksmith: ''
438
+ workers: '32'
439
+ - platform: windows
440
+ cores: '4'
441
+ runner: dsh-windows-2025-4core
442
+ blacksmith: blacksmith-4vcpu-windows-2025
443
+ workers: '2'
444
+ - platform: windows
445
+ cores: '8'
446
+ runner: dsh-windows-2025-8core
447
+ blacksmith: blacksmith-8vcpu-windows-2025
448
+ workers: '2'
449
+ - platform: windows
450
+ cores: '16'
451
+ runner: dsh-windows-2025-16core
452
+ blacksmith: blacksmith-16vcpu-windows-2025
453
+ workers: '2'
454
+ - platform: windows
455
+ cores: '32'
456
+ runner: dsh-windows-2025-32core
457
+ blacksmith: blacksmith-32vcpu-windows-2025
458
+ workers: '2'
459
+ - platform: windows
460
+ cores: '64'
461
+ runner: dsh-windows-2025-64core
462
+ blacksmith: ''
463
+ workers: '2'
464
+ - platform: windows
465
+ cores: '96'
466
+ runner: dsh-windows-2025-96core
467
+ blacksmith: ''
468
+ workers: '2'
469
+ steps:
470
+ - uses: actions/checkout@v6
471
+
472
+ - uses: pnpm/action-setup@v4
473
+ with:
474
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
475
+
476
+ # Unlike the larger-runner suite, both platforms cache the store here:
477
+ # the consolidated topology measures cache mechanics as workload.
478
+ - uses: actions/setup-node@v6
479
+ with:
480
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
481
+ cache: pnpm
482
+
483
+ - name: Report runner capacity
484
+ run: >-
485
+ node -e "const os = require('node:os');
486
+ console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length,
487
+ memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))"
488
+
489
+ - name: Install and prepare Linux
490
+ if: matrix.platform == 'linux'
491
+ run: |
492
+ pnpm install --frozen-lockfile &
493
+ install_pid=$!
494
+ bash scripts/prepare-ci-bubblewrap.sh &
495
+ sandbox_pid=$!
496
+ install_status=0
497
+ wait "$install_pid" || install_status=$?
498
+ sandbox_status=0
499
+ wait "$sandbox_pid" || sandbox_status=$?
500
+ if (( install_status != 0 )); then exit "$install_status"; fi
501
+ exit "$sandbox_status"
502
+
503
+ - name: Install (immutable)
504
+ if: matrix.platform == 'windows'
505
+ shell: pwsh
506
+ run: pnpm install --frozen-lockfile
507
+
508
+ - name: Run complete unsharded primary Node CI concurrently
509
+ if: matrix.platform == 'linux'
510
+ env:
511
+ DSH_COVERAGE_MAX_WORKERS: ${{ matrix.workers }}
512
+ DSH_GATE_CONCURRENCY: ${{ matrix.workers }}
513
+ DSH_OXLINT_THREADS: ${{ matrix.workers }}
514
+ DSH_PUBLINT_CONCURRENCY: ${{ matrix.workers }}
515
+ DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ matrix.workers }}
516
+ run: pnpm run check:ci
517
+
518
+ - name: Run blocking Windows builds concurrently
519
+ if: matrix.platform == 'windows'
520
+ shell: pwsh
521
+ env:
522
+ DSH_GATE_CONCURRENCY: ${{ matrix.workers }}
523
+ run: pnpm run check:ci:windows-blocking
.github/workflows/ci.yml ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ permissions:
6
+ contents: read
7
+
8
+ env:
9
+ PRIMARY_NODE_VERSION: '24'
10
+ # CI runs must never report to the production telemetry endpoint baked
11
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
12
+ DSH_TELEMETRY_DISABLED: '1'
13
+
14
+ # Cancel a superseded pull-request run on a new push so a fresh head does not
15
+ # queue a second full 9-job run behind a stale one (paid enterprise runners
16
+ # would otherwise stack with no auto-cancellation).
17
+ concurrency:
18
+ group: ${{ github.workflow }}-${{ github.ref }}
19
+ cancel-in-progress: true
20
+
21
+ jobs:
22
+
23
+ # Three enterprise jobs isolate coverage, static analysis, and the
24
+ # build-backed consumer tail. The consumer job owns the only Linux build so
25
+ # all three jobs enter runner allocation independently.
26
+ #
27
+ # FAILOVER (Linux): each Linux enterprise job resolves its pool through the
28
+ # DSH_CI_FAILOVER_LINUX repository variable. Unset (normal), the expressions
29
+ # pick the hosted enterprise pools below. Setting the variable to
30
+ # 'selfhosted' (repo Settings → Actions → Variables; writer-manageable
31
+ # repository state — not PR-editable, no merge required) retargets all
32
+ # three onto the in-house
33
+ # vm-backup pool and re-running the failed jobs is the entire switch —
34
+ # see .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md.
35
+ # Setting the variable to 'blacksmith' instead routes the same jobs onto
36
+ # Blacksmith's hosted runners at the matching vCPU size (see
37
+ # .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md). The
38
+ # in-house pool's readiness is re-proven on every master push by the
39
+ # serial-linux-selfhosted standby lane in ci-master.yml. The Windows failover
40
+ # switch is the separate DSH_CI_FAILOVER_WINDOWS variable on the windows-native
41
+ # job below.
42
+ node-24:
43
+ if: github.event_name == 'pull_request'
44
+ runs-on: >-
45
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
46
+ || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
47
+ && github.event.pull_request.user.login != 'dependabot[bot]'
48
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
49
+ || 'dsh-ubuntu-24-04-16core' }}
50
+ name: node 24 / static
51
+ env:
52
+ DSH_GATE_CONCURRENCY: '8'
53
+ # Stop the aggregate at the first blocking gate failure so a red run
54
+ # does not keep burning enterprise runner time on the remaining gates.
55
+ DSH_GATE_FAIL_FAST: '1'
56
+ steps:
57
+ # Runner cleanup owns tool caches and fixtures, including cancelled runs.
58
+ - name: Use runner-owned temporary storage
59
+ run: |
60
+ echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
61
+
62
+ # Fetch complete history so the archive gate can read the trusted PR base from a reused shallow checkout.
63
+ - uses: actions/checkout@v6
64
+ with:
65
+ fetch-depth: 0
66
+ persist-credentials: false
67
+
68
+ # Redirect the Node compile cache (enabled by pnpm and TypeScript) off
69
+ # the root partition's /tmp before the first pnpm call in this lane —
70
+ # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md.
71
+ - name: Redirect Node compile cache to runner temp
72
+ run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
73
+
74
+ - uses: pnpm/action-setup@v4
75
+ with:
76
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
77
+
78
+ - uses: actions/setup-node@v6
79
+ with:
80
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
81
+
82
+ - name: Configure pnpm store path
83
+ id: pnpm-store
84
+ run: |
85
+ store_root="$HOME/.local/share/pnpm/store"
86
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
87
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
88
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
89
+
90
+ # Pull requests consume the default-branch cache but do not put cache
91
+ # compression and upload on the paid latency-critical path. Skipped
92
+ # under failover — see the coverage lane's identical rationale.
93
+ - uses: actions/cache/restore@v4
94
+ if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
95
+ with:
96
+ path: ${{ steps.pnpm-store.outputs.path }}
97
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
98
+ restore-keys: |
99
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
100
+
101
+ - name: Install (immutable)
102
+ run: pnpm install --frozen-lockfile
103
+
104
+ - name: Run static gates
105
+ env:
106
+ DSH_ARCHIVE_BASE_REF: ${{ github.event.pull_request.base.sha }}
107
+ run: pnpm run check:ci:static
108
+
109
+ node-24-coverage:
110
+ if: github.event_name == 'pull_request'
111
+ runs-on: >-
112
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
113
+ || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
114
+ && github.event.pull_request.user.login != 'dependabot[bot]'
115
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
116
+ || 'dsh-ubuntu-24-04-16core' }}
117
+ name: node 24 / coverage
118
+ env:
119
+ # Partitioning replaces the instrumented share; this budget gives the
120
+ # exempt-heavy gate two workers on both hosted and failover runners.
121
+ DSH_COVERAGE_MAX_WORKERS: '6'
122
+ DSH_COVERAGE_PARTITIONS: '4'
123
+ DSH_GATE_CONCURRENCY: '3'
124
+ # Managed-scope teardown cases run past the default per-test budget when
125
+ # this lane's partitions, workers, and sibling gates share one host: the
126
+ # disposal cases in subprocess-local and bash-sandbox exceeded 5000ms on
127
+ # the hosted image (run 34449848541) while the same commit stayed inside
128
+ # the budget on the in-house pool; the lane is green with this value
129
+ # (run 34457655892). The Windows coverage lane grants the same budget for
130
+ # the same reason.
131
+ DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'
132
+ # A gate failure aborts the sibling gate instead of waiting out its
133
+ # multi-minute instrumented run.
134
+ DSH_GATE_FAIL_FAST: '1'
135
+ steps:
136
+ # Runner cleanup owns tool caches and fixtures, including cancelled runs.
137
+ - name: Use runner-owned temporary storage
138
+ run: |
139
+ echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
140
+
141
+ - uses: actions/checkout@v6
142
+ with:
143
+ persist-credentials: false
144
+
145
+ # Redirect the Node compile cache (enabled by pnpm and TypeScript) off
146
+ # the root partition's /tmp before the first pnpm call in this lane —
147
+ # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md.
148
+ - name: Redirect Node compile cache to runner temp
149
+ run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
150
+
151
+ - uses: pnpm/action-setup@v4
152
+ with:
153
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
154
+
155
+ - uses: actions/setup-node@v6
156
+ with:
157
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
158
+
159
+ - name: Configure pnpm store path
160
+ id: pnpm-store
161
+ run: |
162
+ store_root="$HOME/.local/share/pnpm/store"
163
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
164
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
165
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
166
+
167
+ # Self-hosted runners reuse the shared persistent pnpm store.
168
+ # Hosted runners restore the remote cache into their ephemeral store.
169
+ - uses: actions/cache/restore@v4
170
+ if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
171
+ with:
172
+ path: ${{ steps.pnpm-store.outputs.path }}
173
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
174
+ restore-keys: |
175
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
176
+
177
+ - name: Install dependencies and prepare bubblewrap
178
+ run: |
179
+ pnpm install --frozen-lockfile &
180
+ install_pid=$!
181
+ bash scripts/prepare-ci-bubblewrap.sh &
182
+ sandbox_pid=$!
183
+ install_status=0
184
+ wait "$install_pid" || install_status=$?
185
+ sandbox_status=0
186
+ wait "$sandbox_pid" || sandbox_status=$?
187
+ if (( install_status != 0 )); then exit "$install_status"; fi
188
+ exit "$sandbox_status"
189
+
190
+ - name: Run exhaustive coverage
191
+ run: pnpm run check:ci:coverage
192
+
193
+ node-24-bench:
194
+ if: github.event_name == 'pull_request'
195
+ runs-on: ubuntu-24.04
196
+ name: node 24 / benchmarks
197
+ # Wall-clock budgets need an otherwise idle runner, so this job runs the
198
+ # benchmark lane alone instead of joining a concurrent gate aggregate.
199
+ timeout-minutes: 15
200
+ steps:
201
+ - uses: actions/checkout@v6
202
+ with:
203
+ persist-credentials: false
204
+
205
+ - uses: pnpm/action-setup@v4
206
+ with:
207
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
208
+
209
+ - uses: actions/setup-node@v6
210
+ with:
211
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
212
+
213
+ - name: Configure pnpm store path
214
+ id: pnpm-store
215
+ run: |
216
+ store_root="$HOME/.local/share/pnpm/store"
217
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
218
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
219
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
220
+
221
+ - uses: actions/cache/restore@v4
222
+ with:
223
+ path: ${{ steps.pnpm-store.outputs.path }}
224
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
225
+ restore-keys: |
226
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
227
+
228
+ - name: Install (immutable)
229
+ run: pnpm install --frozen-lockfile
230
+
231
+ - name: Install benchmark browser and hosted dependencies
232
+ run: pnpm --filter @deepseek-ai/dsh-benchmarks exec playwright install --with-deps chromium
233
+
234
+ - name: Run performance benchmarks
235
+ env:
236
+ DSH_GATE_VERBOSE: '1'
237
+ run: pnpm run check:ci:bench
238
+
239
+ node-24-consumers:
240
+ if: github.event_name == 'pull_request'
241
+ runs-on: >-
242
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404'
243
+ || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
244
+ && github.event.pull_request.user.login != 'dependabot[bot]'
245
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
246
+ || 'dsh-ubuntu-24-04-16core' }}
247
+ name: node 24 / snapshots and artifacts
248
+ env:
249
+ DSH_GATE_CONCURRENCY: '10'
250
+ DSH_NODE_COMPAT_SKIP_TYPECHECK: '1'
251
+ DSH_OXLINT_THREADS: '8'
252
+ DSH_PUBLINT_CONCURRENCY: '8'
253
+ DSH_WEB_SNAPSHOT_WORKERS: '6'
254
+ # A failing gate aborts its running siblings: a failing build stops the
255
+ # independent Node compatibility smoke, and a failing reader (e.g.
256
+ # publint) stops the remaining artifact consumers.
257
+ DSH_GATE_FAIL_FAST: '1'
258
+ # Failover halves snapshot concurrency for the shared 64-core VM.
259
+ DSH_SNAPSHOT_MAX_CONCURRENCY: ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && '12' || '32' }}
260
+ steps:
261
+ # Runner cleanup owns tool caches and fixtures, including cancelled runs.
262
+ - name: Use runner-owned temporary storage
263
+ run: |
264
+ echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
265
+ echo "PLAYWRIGHT_BROWSERS_PATH=${RUNNER_TEMP%/*}/ms-playwright" >> "$GITHUB_ENV"
266
+
267
+ - uses: actions/checkout@v6
268
+ with:
269
+ persist-credentials: false
270
+
271
+ # Redirect the Node compile cache (enabled by pnpm and TypeScript) off
272
+ # the root partition's /tmp before the first pnpm call in this lane —
273
+ # see .agents/notes/implemented/process/2026-08-28-ci-node-compile-cache-data-disk.md.
274
+ - name: Redirect Node compile cache to runner temp
275
+ run: echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
276
+
277
+ - uses: pnpm/action-setup@v4
278
+ with:
279
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
280
+
281
+ - uses: actions/setup-node@v6
282
+ with:
283
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
284
+
285
+ - name: Configure pnpm store path
286
+ id: pnpm-store
287
+ run: |
288
+ store_root="$HOME/.local/share/pnpm/store"
289
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
290
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
291
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
292
+
293
+ # Pull requests restore the pnpm store and Playwright caches without paying
294
+ # compression and upload on the required path. No master job saves these
295
+ # hosted cache keys, so each restore-keys fallback hits the matching archived
296
+ # entry until it evicts, after which the store is cold. Self-hosted runners
297
+ # reuse the shared persistent store instead of restoring the remote archive.
298
+ - uses: actions/cache/restore@v4
299
+ if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
300
+ with:
301
+ path: ${{ steps.pnpm-store.outputs.path }}
302
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
303
+ restore-keys: |
304
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
305
+
306
+ # Self-hosted runners retain their own browser cache between jobs.
307
+ - uses: actions/cache/restore@v4
308
+ if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
309
+ with:
310
+ path: ${{ env.PLAYWRIGHT_BROWSERS_PATH }}
311
+ key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
312
+ restore-keys: |
313
+ ${{ runner.os }}-playwright-
314
+
315
+ - name: Install dependencies and prepare bubblewrap
316
+ run: |
317
+ pnpm install --frozen-lockfile &
318
+ install_pid=$!
319
+ bash scripts/prepare-ci-bubblewrap.sh &
320
+ sandbox_pid=$!
321
+ install_status=0
322
+ wait "$install_pid" || install_status=$?
323
+ sandbox_status=0
324
+ wait "$sandbox_pid" || sandbox_status=$?
325
+ if (( install_status != 0 )); then exit "$install_status"; fi
326
+ exit "$sandbox_status"
327
+
328
+ # Blacksmith's Ubuntu HTTP archive endpoints can be unreachable while HTTPS works.
329
+ - name: Use HTTPS for Ubuntu archives on Blacksmith
330
+ if: vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
331
+ run: |
332
+ sudo python3 - <<'PY'
333
+ from pathlib import Path
334
+ import re
335
+
336
+ apt = Path('/etc/apt')
337
+ sources = [apt / 'sources.list', apt / 'blacksmith-ubuntu-mirrors.txt',
338
+ *(apt / 'sources.list.d').glob('*.list'),
339
+ *(apt / 'sources.list.d').glob('*.sources')]
340
+ for source in sources:
341
+ if source.is_file():
342
+ source.write_text(re.sub(
343
+ r'http://((?:[a-z]{2}\.)?archive\.ubuntu\.com|security\.ubuntu\.com)/',
344
+ r'https://\1/', source.read_text()))
345
+ PY
346
+
347
+ - name: Install Playwright Chromium and hosted dependencies
348
+ if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
349
+ run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install --with-deps chromium
350
+
351
+ # The persistent VM image owns Playwright's Linux system packages; do
352
+ # not mutate the shared host with apt on every failover run.
353
+ - name: Install Playwright Chromium on the failover VM
354
+ if: vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]'
355
+ run: pnpm --filter @deepseek-ai/dsh-web-frontend exec playwright install chromium
356
+
357
+ - name: Run compatibility, snapshot, and artifact gates
358
+ run: pnpm run check:ci:consumers
359
+
360
+
361
+ node-compat:
362
+ if: github.event_name == 'pull_request'
363
+ # Under the selfhosted leg this job admits only repository-owned PR code
364
+ # to the persistent shared VM; the blacksmith branch targets ephemeral
365
+ # runners and carries none of those predicates.
366
+ runs-on: >-
367
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
368
+ || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
369
+ && github.event.pull_request.head.repo.full_name == github.repository
370
+ && github.event.pull_request.head.repo.fork == false
371
+ && github.event.pull_request.user.login != 'dependabot[bot]'
372
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
373
+ || matrix.runner }}
374
+ name: ${{ matrix.name }}
375
+ env:
376
+ DSH_GATE_CONCURRENCY: ${{ matrix.gate_concurrency }}
377
+ DSH_NODE_COMPAT_SKIP_TYPECHECK: '1'
378
+ # A failed smoke aborts the remaining compatibility gates instead of
379
+ # letting the build-backed legs run against an already-red aggregate.
380
+ DSH_GATE_FAIL_FAST: '1'
381
+ strategy:
382
+ fail-fast: false
383
+ matrix:
384
+ include:
385
+ - node: '22.19'
386
+ name: node 22.19
387
+ runner: ubuntu-latest
388
+ gate_concurrency: '1'
389
+ # Pinned inside 24.0-24.11.1: those releases carry the v1 internal
390
+ # loader while reporting major 24, and every other job tracks the
391
+ # latest 24, which is v2. A bare `24` here would retest that same v2.
392
+ - node: '24.9'
393
+ name: node 24.9
394
+ runner: ubuntu-latest
395
+ gate_concurrency: '1'
396
+ - node: 26
397
+ name: node 26
398
+ runner: ubuntu-latest
399
+ gate_concurrency: '1'
400
+ steps:
401
+ - uses: actions/checkout@v6
402
+ with:
403
+ persist-credentials: false
404
+
405
+ # Shared hosts keep version installs and generated caches inside runner temp.
406
+ - name: Isolate compatibility caches
407
+ if: runner.environment == 'self-hosted'
408
+ run: |
409
+ echo "NODE_COMPILE_CACHE=$RUNNER_TEMP/node-compile-cache" >> "$GITHUB_ENV"
410
+ echo "npm_config_devdir=$RUNNER_TEMP/node-gyp" >> "$GITHUB_ENV"
411
+ echo "PNPM_CONFIG_STORE_DIR=$HOME/.local/share/pnpm/store" >> "$GITHUB_ENV"
412
+
413
+ - uses: pnpm/action-setup@v4
414
+ with:
415
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}
416
+
417
+ - uses: actions/setup-node@v6
418
+ env:
419
+ # The runner overwrites RUNNER_* step env before starting JavaScript actions.
420
+ NODE_OPTIONS: ${{ runner.environment == 'self-hosted' && '--import=./scripts/ci-compatible-toolcache.mjs' || '' }}
421
+ with:
422
+ node-version: ${{ matrix.node }}
423
+ cache: ${{ runner.environment == 'github-hosted' && 'pnpm' || '' }}
424
+ package-manager-cache: false
425
+
426
+ - name: Verify isolated Node installation
427
+ if: runner.environment == 'self-hosted'
428
+ run: |
429
+ node_path=$(node -p process.execPath)
430
+ echo "Node executable: $node_path"
431
+ case "$node_path" in
432
+ "$RUNNER_TEMP/node-compat-toolcache/"*) ;;
433
+ *) echo "::error::Node compatibility installation is outside runner temp"; exit 1 ;;
434
+ esac
435
+
436
+ - name: Install (immutable)
437
+ run: pnpm install --frozen-lockfile
438
+
439
+ - name: Prepare bubblewrap (unrestrict userns)
440
+ run: bash scripts/prepare-ci-bubblewrap.sh
441
+
442
+ - name: Run compatibility smokes
443
+ env:
444
+ DSH_BUILD_CLIENT_PROFILE: official
445
+ run: pnpm run check:node-compat
446
+
447
+ # Kept out of the gate aggregate: the shape a Node release carries only
448
+ # changes with the Node version, so this belongs to the version matrix
449
+ # rather than to every commit's checks.
450
+ - name: Check Loader internal shape detection
451
+ run: pnpm exec vitest run packages/boot/app-boot/tests/loader-shape.compat.spec.ts
452
+
453
+ python-sdk:
454
+ if: github.event_name == 'pull_request'
455
+ runs-on: ubuntu-latest
456
+ name: python 3.10 / keyless SDK
457
+ steps:
458
+ - uses: actions/checkout@v6
459
+
460
+ - uses: actions/setup-python@v6.3.0
461
+ with:
462
+ python-version: '3.10'
463
+ cache: pip
464
+
465
+ - name: Install uv
466
+ run: python -m pip install uv==0.11.23
467
+
468
+ - name: Run complete keyless Python suite
469
+ run: uv run --python 3.10 --group test --project python/sdk pytest
470
+
471
+ # The reusable builder owns each published executable, wheel, clean-install,
472
+ # keyless black-box, and trusted real-API path. Linux/Windows x64 block PRs;
473
+ # Linux ARM64 and both macOS architectures run in ci-master.yml.
474
+ python-runtime:
475
+ if: github.event_name == 'pull_request'
476
+ name: python runtime / release-shaped matrix
477
+ uses: ./.github/workflows/build-exe-for-python-sdk.yml
478
+ with:
479
+ targets: node24-linux-x64,node24-win-x64
480
+ ci: true
481
+ secrets:
482
+ DEEPSEEK_API_KEY_EXTERNAL: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
483
+
484
+ # Every pull request also gets real Windows-kernel signals. The former
485
+ # monolithic windows-native job is split into smaller jobs so one slow
486
+ # coverage gate does not hold up build/static results, while the total
487
+ # per-job process count stays lower. Observational checks are non-blocking.
488
+ # Dependabot PRs are excluded from the self-hosted pool and stay queued for
489
+ # the hosted runner.
490
+ windows-build:
491
+ if: github.event_name == 'pull_request'
492
+ runs-on: >-
493
+ ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025'
494
+ || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted'
495
+ && github.event.pull_request.user.login != 'dependabot[bot]'
496
+ && fromJSON('["self-hosted", "dsh-win-ci", "windows"]')
497
+ || 'dsh-windows-2025-16core' }}
498
+ name: windows node 24 / build
499
+ timeout-minutes: 60
500
+ env:
501
+ # A failing build or site aborts the sibling gate on the same runner.
502
+ DSH_GATE_FAIL_FAST: '1'
503
+ steps:
504
+ - uses: actions/checkout@v6
505
+ with:
506
+ persist-credentials: false
507
+ - name: Enable Developer Mode (symlink support)
508
+ shell: pwsh
509
+ run: >-
510
+ reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
511
+ /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
512
+ - uses: pnpm/action-setup@v4
513
+ with:
514
+ dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
515
+ - uses: actions/setup-node@v6
516
+ with:
517
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
518
+ - name: Install (immutable)
519
+ shell: pwsh
520
+ # See 2026-08-30-windows-refs-store-block-clone-install for the
521
+ # ReFS block-clone rationale; detect the workspace filesystem and
522
+ # pass --package-import-method=clone only on ReFS.
523
+ run: >-
524
+ $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':');
525
+ $fs = (Get-Volume -DriveLetter $drive).FileSystem;
526
+ if ($fs -eq 'ReFS') {
527
+ corepack pnpm install --frozen-lockfile --package-import-method=clone
528
+ } else {
529
+ pnpm install --frozen-lockfile
530
+ }
531
+ - name: Run blocking Windows builds
532
+ shell: pwsh
533
+ run: pnpm run check:ci:windows-blocking
534
+
535
+ windows-coverage:
536
+ if: github.event_name == 'pull_request'
537
+ runs-on: >-
538
+ ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025'
539
+ || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted'
540
+ && github.event.pull_request.user.login != 'dependabot[bot]'
541
+ && fromJSON('["self-hosted", "dsh-win-ci", "windows"]')
542
+ || 'dsh-windows-2025-16core' }}
543
+ name: windows node 24 / coverage
544
+ timeout-minutes: 120
545
+ env:
546
+ DSH_COVERAGE_MAX_WORKERS: '6'
547
+ DSH_COVERAGE_PARTITIONS: '4'
548
+ DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'
549
+ DSH_GATE_CONCURRENCY: '3'
550
+ # A gate failure aborts the sibling gate instead of waiting out its
551
+ # multi-minute instrumented run.
552
+ DSH_GATE_FAIL_FAST: '1'
553
+ steps:
554
+ - uses: actions/checkout@v6
555
+ with:
556
+ persist-credentials: false
557
+ # Checkout removes the gitignored duration history, so restore it from
558
+ # the GitHub cache before coverage and save the updated one afterwards.
559
+ # The coordinator then weights partitions by measured durations on the
560
+ # second run instead of degrading to a file-count split. GitHub cache
561
+ # entries are immutable, so the save key is unique per run and the
562
+ # restore matches the newest entry through the stable prefix.
563
+ - name: Restore coverage duration history
564
+ uses: actions/cache/restore@v4
565
+ with:
566
+ path: .coverage-times.json
567
+ key: coverage-times-${{ github.run_id }}
568
+ restore-keys: |
569
+ coverage-times-
570
+ - name: Enable Developer Mode (symlink support)
571
+ shell: pwsh
572
+ run: >-
573
+ reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
574
+ /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
575
+ - uses: pnpm/action-setup@v4
576
+ with:
577
+ dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
578
+ - uses: actions/setup-node@v6
579
+ with:
580
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
581
+ - name: Install (immutable)
582
+ shell: pwsh
583
+ # See 2026-08-30-windows-refs-store-block-clone-install for the
584
+ # ReFS block-clone rationale; detect the workspace filesystem and
585
+ # pass --package-import-method=clone only on ReFS.
586
+ run: >-
587
+ $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':');
588
+ $fs = (Get-Volume -DriveLetter $drive).FileSystem;
589
+ if ($fs -eq 'ReFS') {
590
+ corepack pnpm install --frozen-lockfile --package-import-method=clone
591
+ } else {
592
+ pnpm install --frozen-lockfile
593
+ }
594
+ # No build before coverage, matching the Linux lane: workspace imports
595
+ # resolve to src through the tsconfig paths map, and the lib-consuming
596
+ # suites (webworker-packer image-loadable, webworker-runtime
597
+ # transform-corpus, client ui-trajectory client-bundle) self-skip on
598
+ # unbuilt checkouts.
599
+ - name: Run Windows coverage
600
+ shell: pwsh
601
+ run: pnpm run check:ci:coverage
602
+ - name: Save coverage duration history
603
+ # Coverage flakes must not prevent the cache from building; the
604
+ # measured durations remain useful even when a partition failed. The
605
+ # per-run key keeps every save a fresh immutable cache entry.
606
+ if: ${{ !cancelled() }}
607
+ uses: actions/cache/save@v4
608
+ with:
609
+ path: .coverage-times.json
610
+ key: coverage-times-${{ github.run_id }}
611
+
612
+ windows-native-tests:
613
+ if: github.event_name == 'pull_request'
614
+ runs-on: >-
615
+ ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025'
616
+ || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted'
617
+ && github.event.pull_request.user.login != 'dependabot[bot]'
618
+ && fromJSON('["self-hosted", "dsh-win-ci", "windows"]')
619
+ || 'dsh-windows-2025-16core' }}
620
+ name: windows node 24 / native tests
621
+ timeout-minutes: 60
622
+ steps:
623
+ - uses: actions/checkout@v6
624
+ with:
625
+ persist-credentials: false
626
+ - name: Enable Developer Mode (symlink support)
627
+ shell: pwsh
628
+ run: >-
629
+ reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
630
+ /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
631
+ - uses: pnpm/action-setup@v4
632
+ with:
633
+ dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
634
+ - uses: actions/setup-node@v6
635
+ with:
636
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
637
+ - name: Install (immutable)
638
+ shell: pwsh
639
+ # See 2026-08-30-windows-refs-store-block-clone-install for the
640
+ # ReFS block-clone rationale; detect the workspace filesystem and
641
+ # pass --package-import-method=clone only on ReFS.
642
+ run: >-
643
+ $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':');
644
+ $fs = (Get-Volume -DriveLetter $drive).FileSystem;
645
+ if ($fs -eq 'ReFS') {
646
+ corepack pnpm install --frozen-lockfile --package-import-method=clone
647
+ } else {
648
+ pnpm install --frozen-lockfile
649
+ }
650
+ - name: Run Windows-specific native tests
651
+ shell: pwsh
652
+ run: >-
653
+ pnpm exec vitest run
654
+ --no-file-parallelism
655
+ --testTimeout 90000
656
+ packages/shell/tool-pwsh/tests/loader.spec.ts
657
+ packages/workflow/workflow-ptc/tests/workflow-ptc.spec.ts
658
+ packages/workflow/tool-ralph/tests/integration.spec.ts
659
+ packages/subprocess/subprocess-local/tests/process-exit.spec.ts
660
+
661
+ windows-observational:
662
+ if: github.event_name == 'pull_request'
663
+ continue-on-error: true
664
+ runs-on: >-
665
+ ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025'
666
+ || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted'
667
+ && github.event.pull_request.user.login != 'dependabot[bot]'
668
+ && fromJSON('["self-hosted", "dsh-win-ci", "windows"]')
669
+ || 'dsh-windows-2025-16core' }}
670
+ name: windows node 24 / observational
671
+ timeout-minutes: 60
672
+ env:
673
+ DSH_PUBLINT_CONCURRENCY: '8'
674
+ steps:
675
+ - uses: actions/checkout@v6
676
+ with:
677
+ persist-credentials: false
678
+ - name: Enable Developer Mode (symlink support)
679
+ shell: pwsh
680
+ run: >-
681
+ reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\AppModelUnlock"
682
+ /t REG_DWORD /f /v "AllowDevelopmentWithoutDevLicense" /d "1"
683
+ - uses: pnpm/action-setup@v4
684
+ with:
685
+ dest: ${{ runner.temp }}/setup-pnpm-js-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
686
+ - uses: actions/setup-node@v6
687
+ with:
688
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
689
+ - name: Install (immutable)
690
+ shell: pwsh
691
+ # See 2026-08-30-windows-refs-store-block-clone-install for the
692
+ # ReFS block-clone rationale; detect the workspace filesystem and
693
+ # pass --package-import-method=clone only on ReFS.
694
+ run: >-
695
+ $drive = (Split-Path -Qualifier $env:GITHUB_WORKSPACE).TrimEnd(':');
696
+ $fs = (Get-Volume -DriveLetter $drive).FileSystem;
697
+ if ($fs -eq 'ReFS') {
698
+ corepack pnpm install --frozen-lockfile --package-import-method=clone
699
+ } else {
700
+ pnpm install --frozen-lockfile
701
+ }
702
+ - name: Run Windows observational gates
703
+ shell: pwsh
704
+ run: pnpm run check:ci:windows-observational
705
+
706
+ # Single stable required check for branch protection: require "all checks
707
+ # passed" instead of enumerating matrix legs whose names change as lanes and
708
+ # node versions evolve. Every blocking job in THIS workflow must be listed in
709
+ # `needs`. Native Windows build and process checks are required; Wine and
710
+ # the deferred Python runtime targets live in ci-master.yml and do not
711
+ # participate in this PR verdict. `needs` cannot cross workflow files.
712
+ # An explicit status function runs the verdict after failed/skipped needs
713
+ # without keeping a cancelled workflow alive for an obsolete verdict.
714
+ all-checks-passed:
715
+ name: all checks passed
716
+ # This bookkeeping-only verdict must not depend on custom-pool
717
+ # provisioning — and under Linux failover it follows the same selector as
718
+ # the worker jobs it aggregates, so a standard-hosted outage cannot strand
719
+ # the branch-protection verdict either. It retargets with the Linux switch
720
+ # (DSH_CI_FAILOVER_LINUX), not the Windows one, because it aggregates the
721
+ # required Linux workers and runs on the vm-backup pool. Under the
722
+ # 'blacksmith' value the verdict shares Blacksmith's pool with its workers
723
+ # through the same selector, so a Blacksmith outage strands both together —
724
+ # the accepted consequence of the explicit opt-in switch.
725
+ runs-on: >-
726
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
727
+ || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
728
+ && github.event.pull_request.user.login != 'dependabot[bot]'
729
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
730
+ || 'ubuntu-latest' }}
731
+ needs: [node-24, node-24-coverage, node-24-bench, node-24-consumers, node-compat, python-sdk, python-runtime, windows-build, windows-native-tests]
732
+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}
733
+ steps:
734
+ - name: Fail if any needed job did not succeed
735
+ if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped')
736
+ run: |
737
+ echo "::error::Needed job results: ${{ join(needs.*.result, ', ') }}"
738
+ exit 1
739
+ - name: All checks passed
740
+ run: echo "All needed jobs succeeded (${{ join(needs.*.result, ', ') }})"
.github/workflows/docs-pages.yml ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Publish the documentation website to GitHub Pages. This workflow is manual-only
2
+ # (workflow_dispatch) and intentionally does not listen to pull_request or push:
3
+ # the site presents a released snapshot, so publication is an explicit act from a
4
+ # dsh-v* tag and must never appear as a PR check. `release:verify` rejects every
5
+ # other ref, and the github-pages environment repeats that restriction as a
6
+ # deployment tag policy with required reviewers.
7
+ #
8
+ # The build signal does not depend on this workflow. Every pull request builds
9
+ # the production site through `check:ci:static`, and ci-master.yml builds it
10
+ # again on master.
11
+ name: Deploy documentation
12
+
13
+ on:
14
+ workflow_dispatch:
15
+
16
+ concurrency:
17
+ group: github-pages
18
+ cancel-in-progress: false
19
+
20
+ permissions:
21
+ contents: read
22
+
23
+ env:
24
+ PRIMARY_NODE_VERSION: '24'
25
+ # Projected source links target the public repository, whose history can
26
+ # differ from this workflow's source repository. This stays on master rather
27
+ # than following the dispatched tag: that repository advances only to each
28
+ # release commit, so its master never carries unreleased work, and it retains
29
+ # only the most recent tags — following the tag would leave every projected
30
+ # source link on an older deploy unresolvable.
31
+ DOCS_REPOSITORY_REF: master
32
+ # CI runs must never report to the production telemetry endpoint baked
33
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
34
+ DSH_TELEMETRY_DISABLED: '1'
35
+
36
+ jobs:
37
+ build:
38
+ runs-on: ubuntu-latest
39
+ permissions:
40
+ contents: read
41
+ pages: read
42
+ steps:
43
+ # Complete history: the release scripts read tags.
44
+ - uses: actions/checkout@v6
45
+ with:
46
+ fetch-depth: 0
47
+ persist-credentials: false
48
+
49
+ - uses: pnpm/action-setup@v4
50
+
51
+ - uses: actions/setup-node@v6
52
+ with:
53
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
54
+ cache: pnpm
55
+
56
+ - name: Install (immutable)
57
+ run: pnpm install --frozen-lockfile
58
+
59
+ # One definition of "released" for the site and the npm sequence: this
60
+ # rejects every ref that is not a dsh-v* tag naming the version this tree
61
+ # carries.
62
+ - name: Verify release version
63
+ env:
64
+ RELEASE_PUBLISH: 'true'
65
+ run: pnpm run release:verify --family dsh
66
+
67
+ - name: Configure Pages
68
+ id: pages
69
+ uses: actions/configure-pages@v6
70
+
71
+ - name: Verify and build documentation
72
+ env:
73
+ DOCS_BASE: ${{ steps.pages.outputs.base_path }}/
74
+ run: pnpm run doc-sync
75
+
76
+ - name: Upload Pages artifact
77
+ uses: actions/upload-pages-artifact@v5
78
+ with:
79
+ path: website/.dist
80
+
81
+ deploy:
82
+ needs: build
83
+ runs-on: ubuntu-latest
84
+ permissions:
85
+ pages: write
86
+ id-token: write
87
+ environment:
88
+ name: github-pages
89
+ url: ${{ steps.deployment.outputs.page_url }}
90
+ steps:
91
+ - name: Deploy to GitHub Pages
92
+ id: deployment
93
+ uses: actions/deploy-pages@v5
.github/workflows/e2e.yml ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: E2E (real DeepSeek API)
2
+
3
+ # Real-API end-to-end suite (`pnpm run test:e2e`). Unlike ci.yml this job
4
+ # consumes the DEEPSEEK_API_KEY_EXTERNAL secret (mapped to the env var
5
+ # DEEPSEEK_API_KEY the tests read) and hits the external API at
6
+ # https://api.deepseek.com/anthropic (DEEPSEEK_BASE_URL is pinned explicitly so a
7
+ # stray repo-root .env can't redirect the run).
8
+ #
9
+ # pull_request IS a trigger, but GitHub withholds repo secrets from BOTH forked
10
+ # PRs and Dependabot PRs (the latter are same-repo, fork==false, but still
11
+ # keyless). The job-level `if:` below skips the whole job for those untrusted
12
+ # PRs. The Dependabot test keys on the PR AUTHOR (pull_request.user.login), not
13
+ # github.actor (the run trigger) — a maintainer reopening a Dependabot PR would
14
+ # make github.actor human while the PR is still keyless. When the job runs, the
15
+ # secret is expected, so the preflight hard-fails if it's missing (a missing
16
+ # secret would otherwise make the self-skipping suite report a false green). A
17
+ # job skipped by a job-level `if:` reports as a SUCCESSFUL check, so this
18
+ # workflow is safe to use as a required status check if desired.
19
+ #
20
+ # SECURITY — NEVER change this trigger to `pull_request_target`. `pull_request`
21
+ # checks out and runs the PR's HEAD code WITHOUT secrets for forks, which is what
22
+ # keeps an untrusted fork from exfiltrating the key. `pull_request_target` runs
23
+ # in the BASE repo's context WITH secrets while still able to check out untrusted
24
+ # fork code — a textbook key-leak vector, especially once this repo is public.
25
+ # The fork/secret model and its public-repo implications are recorded in
26
+ # .agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md.
27
+ #
28
+ # Note: scheduled triggers are auto-disabled after 60 days of repo inactivity;
29
+ # push/pull_request/workflow_dispatch act as backstops.
30
+ on:
31
+ workflow_dispatch:
32
+ push:
33
+ branches: [main, master]
34
+ pull_request:
35
+ schedule:
36
+ # 00:17 UTC nightly = 08:17 Asia/Shanghai — off the top-of-hour cron stampede.
37
+ - cron: '17 0 * * *'
38
+
39
+ # Keep only the newest validation in each workflow/ref, including master
40
+ # pushes, nightly runs, and manual dispatches.
41
+ concurrency:
42
+ group: ${{ github.workflow }}-${{ github.ref }}
43
+ cancel-in-progress: true
44
+
45
+ # Least privilege: this job only reads the repo to run tests.
46
+ permissions:
47
+ contents: read
48
+
49
+ env:
50
+ # CI runs must never report to the production telemetry endpoint baked
51
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
52
+ DSH_TELEMETRY_DISABLED: '1'
53
+
54
+ jobs:
55
+ e2e:
56
+ runs-on: >-
57
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
58
+ && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-latest' }}
59
+ name: e2e
60
+ # Run on every trusted event. Skip untrusted PRs (forks + Dependabot) where
61
+ # the secret is withheld — they would otherwise hard-fail the preflight.
62
+ if: >-
63
+ github.event_name != 'pull_request'
64
+ || !(github.event.pull_request.head.repo.fork || github.event.pull_request.user.login == 'dependabot[bot]')
65
+ # Profile e2e files can each own several complete dsh subprocess trees, so
66
+ # four file workers preserve process/PTY headroom. Tests retain 120s/test
67
+ # and retry 2; 45m still bounds retry storms against a slow API.
68
+ timeout-minutes: 45
69
+ steps:
70
+ - uses: actions/checkout@v6
71
+
72
+ - uses: pnpm/action-setup@v4
73
+
74
+ - uses: actions/setup-node@v6
75
+ with:
76
+ node-version: 24
77
+ cache: pnpm
78
+
79
+ - name: Install (immutable)
80
+ run: pnpm install --frozen-lockfile
81
+
82
+ # The with-key escalation e2e self-skips without a usable runner. Prepare
83
+ # bwrap so trusted CI exercises it; the functional probe remains the
84
+ # authority on whether the runner can use the sandbox.
85
+ - name: Prepare bubblewrap (unrestrict userns)
86
+ run: bash scripts/prepare-ci-bubblewrap.sh
87
+
88
+ # Guard against a false green: the e2e suites self-skip when the key is
89
+ # absent, so a missing/misconfigured secret would otherwise pass as
90
+ # "all skipped". This job only runs on trusted events (the `if:` above
91
+ # excludes keyless PRs), so the secret MUST be present — fail loudly if not.
92
+ - name: Preflight (require DEEPSEEK_API_KEY)
93
+ env:
94
+ # Repo secret DEEPSEEK_API_KEY_EXTERNAL holds the external-API key;
95
+ # the tests read process.env.DEEPSEEK_API_KEY, so map it across here.
96
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
97
+ run: |
98
+ set -euo pipefail
99
+ if [ -z "${DEEPSEEK_API_KEY:-}" ]; then
100
+ echo "::error::DEEPSEEK_API_KEY is empty. The e2e suite would self-skip and"
101
+ echo "::error::report a false green. Configure the repo secret DEEPSEEK_API_KEY_EXTERNAL."
102
+ exit 1
103
+ fi
104
+ echo "DEEPSEEK_API_KEY present."
105
+
106
+ # The e2e suites boot the example bins in `lib` mode (DSH_EXAMPLE_MODE=lib):
107
+ # the built artifact under plain Node, resolving plugins through real package
108
+ # exports — the shape a real consumer runs. That requires a prior build.
109
+ - name: Build (lib for the e2e example bins)
110
+ run: pnpm run build:official
111
+
112
+ # Real-API end-to-end tests only. The keyless gates (lint/typecheck/
113
+ # coverage/snapshot/etc.) already run in ci.yml (pull requests) and
114
+ # ci-master.yml (master push standby).
115
+ # DEEPSEEK_BASE_URL is pinned to the external API; the secret is scoped to
116
+ # this step (and preflight) only — never exposed to checkout/setup/install.
117
+ - name: E2E tests (real DeepSeek API)
118
+ env:
119
+ DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }}
120
+ DEEPSEEK_BASE_URL: https://api.deepseek.com/anthropic
121
+ DSH_E2E_MAX_WORKERS: 4
122
+ DSH_EXAMPLE_MODE: lib
123
+ run: pnpm run test:e2e
.github/workflows/expected-filenames.yml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Expected filenames
2
+
3
+ on:
4
+ pull_request:
5
+ paths:
6
+ - '*[gG][oO][lL][dD][eE][nN]*'
7
+ - '**/*[gG][oO][lL][dD][eE][nN]*'
8
+ - '!vendor/**'
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ env:
14
+ # CI runs must never report to the production telemetry endpoint baked
15
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
16
+ DSH_TELEMETRY_DISABLED: '1'
17
+
18
+ jobs:
19
+ expected-filenames:
20
+ name: no golden filenames
21
+ runs-on: >-
22
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404'
23
+ || 'ubuntu-latest' }}
24
+ steps:
25
+ - uses: actions/checkout@v6
26
+
27
+ - name: Check tracked filenames
28
+ run: scripts/check-expected-filenames.sh
.github/workflows/issue-lifecycle.yml ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Issue lifecycle
2
+
3
+ on:
4
+ issues:
5
+ types:
6
+ - opened
7
+ - edited
8
+ - labeled
9
+ - unlabeled
10
+ - closed
11
+ - reopened
12
+ - typed
13
+ - untyped
14
+ - field_added
15
+ - field_removed
16
+ pull_request:
17
+ types:
18
+ - opened
19
+ - edited
20
+ - reopened
21
+ - review_requested
22
+ pull_request_review:
23
+ types:
24
+ - submitted
25
+
26
+ permissions:
27
+ contents: read
28
+
29
+ concurrency:
30
+ group: issue-lifecycle-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}
31
+ cancel-in-progress: false
32
+
33
+ jobs:
34
+ lifecycle:
35
+ name: Issue lifecycle
36
+ if: >-
37
+ (github.event_name != 'pull_request_review' || github.event.review.state == 'changes_requested') &&
38
+ (github.event_name != 'pull_request' || github.event.action != 'edited' || github.event.changes.body != null)
39
+ runs-on: ubuntu-latest
40
+ steps:
41
+ - name: Check out trusted policy
42
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
43
+ with:
44
+ ref: ${{ github.event.repository.default_branch }}
45
+ persist-credentials: false
46
+ - name: Create project token
47
+ id: app-token
48
+ uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1
49
+ with:
50
+ client-id: ${{ vars.DSH_ISSUE_APP_CLIENT_ID }}
51
+ private-key: ${{ secrets.DSH_ISSUE_APP_PRIVATE_KEY }}
52
+ owner: deepseek-harness
53
+ repositories: deepseek-harness
54
+ - name: Handle repository event
55
+ env:
56
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
57
+ run: node .github/issue-management/policy.mjs lifecycle
.github/workflows/issue-policy.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Issue policy
2
+
3
+ on:
4
+ pull_request:
5
+ types: [opened, edited, synchronize, reopened, labeled, unlabeled, ready_for_review, review_requested]
6
+ pull_request_review:
7
+ types: [submitted]
8
+
9
+ permissions:
10
+ contents: read
11
+ issues: read
12
+ pull-requests: read
13
+
14
+ jobs:
15
+ policy:
16
+ name: Issue policy
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - name: Check out trusted policy
20
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
21
+ with:
22
+ ref: ${{ github.event.repository.default_branch }}
23
+ persist-credentials: false
24
+ - name: Determine policy eligibility
25
+ id: preflight
26
+ env:
27
+ GITHUB_TOKEN: ${{ github.token }}
28
+ shell: bash
29
+ run: |
30
+ if [ -f .github/issue-management/selective-preflight.json ]; then
31
+ node .github/issue-management/policy.mjs pr-preflight
32
+ else
33
+ node --input-type=module <<'NODE'
34
+ import fs from 'node:fs'
35
+ const event = JSON.parse(fs.readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8'))
36
+ const automated = ['Bot', 'App'].includes(event.pull_request.user.type)
37
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `legacy-automated=${automated}\nneeds-project=${!automated}\n`)
38
+ console.log('Trusted policy has no selective preflight; preserving legacy policy enforcement.')
39
+ NODE
40
+ fi
41
+ - name: Create Project read token
42
+ id: app-token
43
+ if: ${{ steps.preflight.outputs.needs-project == 'true' }}
44
+ uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1
45
+ with:
46
+ client-id: ${{ vars.DSH_ISSUE_APP_CLIENT_ID }}
47
+ private-key: ${{ secrets.DSH_ISSUE_APP_PRIVATE_KEY }}
48
+ owner: deepseek-harness
49
+ repositories: deepseek-harness
50
+ permission-issues: read
51
+ permission-organization-projects: read
52
+ # Re-read current state even after an exempt preflight; never replace a failure with an edit skip.
53
+ - name: Validate pull request
54
+ if: ${{ steps.preflight.outputs.legacy-automated != 'true' }}
55
+ env:
56
+ GITHUB_TOKEN: ${{ github.token }}
57
+ PROJECT_TOKEN: ${{ steps.app-token.outputs.token }}
58
+ run: node .github/issue-management/policy.mjs pr
.github/workflows/node-addon-system-release.yml ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build and publish the @deepseek-ai/node-addon-system package family from the
2
+ # harness source of record. Rehearsal and publication consume the same packed
3
+ # tarballs; each native binary is built on its matching architecture.
4
+ name: Node Addon System Release
5
+
6
+ on:
7
+ workflow_dispatch:
8
+ inputs:
9
+ publish:
10
+ description: Publish packed tarballs to npm. Must run from a node-addon-system-v* tag.
11
+ required: true
12
+ type: boolean
13
+ default: false
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ concurrency:
19
+ # Stable/prerelease dist-tags are shared registry state; serialize release
20
+ # runs so two versions cannot race the final tag assignment.
21
+ group: ${{ github.workflow }}
22
+ cancel-in-progress: false
23
+
24
+ defaults:
25
+ run:
26
+ working-directory: native/system
27
+
28
+ jobs:
29
+ matrix:
30
+ name: Matrix
31
+ runs-on: ubuntu-24.04
32
+ outputs:
33
+ prebuilds: ${{ steps.matrix.outputs.prebuilds }}
34
+ steps:
35
+ - uses: actions/checkout@v4
36
+
37
+ - id: matrix
38
+ run: echo "prebuilds=$(node ./scripts/github-matrix.mjs release-prebuild)" >> "$GITHUB_OUTPUT"
39
+
40
+ build-prebuilds:
41
+ name: ${{ matrix.package }}
42
+ needs: matrix
43
+ runs-on: ${{ matrix.runner }}
44
+ strategy:
45
+ fail-fast: false
46
+ matrix: ${{ fromJson(needs.matrix.outputs.prebuilds) }}
47
+ steps:
48
+ - uses: actions/checkout@v4
49
+
50
+ - uses: pnpm/action-setup@v4
51
+ with:
52
+ package_json_file: package.json
53
+
54
+ - uses: actions/setup-node@v4
55
+ with:
56
+ node-version: 24
57
+ cache: pnpm
58
+ cache-dependency-path: pnpm-lock.yaml
59
+
60
+ - name: Install dependencies
61
+ run: pnpm install --filter @deepseek-ai/node-addon-system-workspace... --frozen-lockfile
62
+
63
+ - name: Install musl toolchain
64
+ if: runner.os == 'Linux'
65
+ run: |
66
+ sudo apt-get update -q
67
+ sudo apt-get install -yq musl-tools
68
+
69
+ - name: Build native binaries
70
+ run: pnpm build:native
71
+
72
+ - name: Verify binary metadata
73
+ run: node ./scripts/verify-launcher-binary.mjs ${{ matrix.dir }}
74
+
75
+ - name: Verify the built entry and flock
76
+ run: |
77
+ pnpm build:ts
78
+ pnpm build:test-oracle
79
+ pnpm test:flock
80
+ pnpm test:packaging
81
+
82
+ - name: Upload prebuild artifact
83
+ uses: actions/upload-artifact@v4
84
+ with:
85
+ name: ${{ matrix.artifact }}
86
+ path: native/system/${{ matrix.dir }}/bin/**
87
+ if-no-files-found: error
88
+ retention-days: 7
89
+
90
+ pack:
91
+ name: Pack npm tarballs
92
+ needs: build-prebuilds
93
+ runs-on: ubuntu-24.04
94
+ steps:
95
+ - uses: actions/checkout@v4
96
+
97
+ - uses: pnpm/action-setup@v4
98
+ with:
99
+ package_json_file: package.json
100
+
101
+ - uses: actions/setup-node@v4
102
+ with:
103
+ node-version: 24
104
+ cache: pnpm
105
+ cache-dependency-path: pnpm-lock.yaml
106
+
107
+ - name: Install dependencies
108
+ run: pnpm install --filter @deepseek-ai/node-addon-system-workspace... --frozen-lockfile
109
+
110
+ - name: Build TypeScript
111
+ run: pnpm build:ts
112
+
113
+ - name: Verify release version
114
+ run: node ./scripts/verify-release.mjs
115
+ env:
116
+ RELEASE_PUBLISH: ${{ inputs.publish }}
117
+
118
+ - name: Download prebuild artifacts
119
+ uses: actions/download-artifact@v4
120
+ with:
121
+ pattern: prebuild-*
122
+ path: native/system/.release/prebuild-artifacts
123
+
124
+ - name: Assemble and verify prebuilds
125
+ run: node ./scripts/assemble-prebuilds.mjs .release/prebuild-artifacts
126
+
127
+ - name: Verify release payload
128
+ run: node ./scripts/verify-release.mjs --prebuilds
129
+ env:
130
+ RELEASE_PUBLISH: ${{ inputs.publish }}
131
+
132
+ - name: Pack release tarballs
133
+ run: node ./scripts/pack-release.mjs dist/npm
134
+
135
+ - name: Verify packed install
136
+ run: node ./scripts/verify-packed-install.mjs dist/npm
137
+ env:
138
+ NALR_REQUIRE_LANDLOCK: 1
139
+
140
+ - name: Upload npm tarballs
141
+ uses: actions/upload-artifact@v4
142
+ with:
143
+ name: npm-tarballs
144
+ path: native/system/dist/npm/*
145
+ if-no-files-found: error
146
+ retention-days: 7
147
+
148
+ publish:
149
+ name: Publish to npm
150
+ if: inputs.publish
151
+ needs: pack
152
+ runs-on: ubuntu-24.04
153
+ environment: npm-publish
154
+ permissions:
155
+ contents: read
156
+ id-token: write
157
+ steps:
158
+ # The publish script is the only repository file this job needs, and it
159
+ # imports nothing outside Node's builtins, so there is no install step.
160
+ - uses: actions/checkout@v4
161
+ with:
162
+ persist-credentials: false
163
+
164
+ - uses: actions/setup-node@v4
165
+ with:
166
+ node-version: 24
167
+ registry-url: https://registry.npmjs.org
168
+
169
+ - name: Download npm tarballs
170
+ uses: actions/download-artifact@v4
171
+ with:
172
+ name: npm-tarballs
173
+ path: native/system/dist/npm
174
+
175
+ - name: Configure npm token fallback
176
+ env:
177
+ NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
178
+ run: |
179
+ if [[ -n "$NPM_TOKEN" ]]; then
180
+ echo "NODE_AUTH_TOKEN=$NPM_TOKEN" >> "$GITHUB_ENV"
181
+ fi
182
+
183
+ - name: Publish tarballs
184
+ # Publication is decided per package against the registry, so re-running
185
+ # this job over the same artifact skips what already landed instead of
186
+ # failing on it. A bare `npm publish` loop could not be retried: the
187
+ # registry answers a repeat of an existing version permanently.
188
+ run: node ./scripts/publish-release.mjs dist/npm
.github/workflows/node-addon-system.yml ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CI for the node-addon-system packages under native/system. A separate
2
+ # workflow from ci.yml keeps the native OS/architecture matrix independent of
3
+ # the harness Node matrix. Each platform job builds once and tests those bytes
4
+ # under every supported Node release. Release assembly and publication use the
5
+ # companion Node Addon System Release workflow.
6
+ name: Node Addon System
7
+
8
+ on:
9
+ pull_request:
10
+ paths:
11
+ - '.github/workflows/node-addon-system.yml'
12
+ - '.github/workflows/node-addon-system-release.yml'
13
+ - 'native/system/**'
14
+ - 'package.json'
15
+ - 'pnpm-lock.yaml'
16
+ - 'pnpm-workspace.yaml'
17
+ push:
18
+ branches: [master]
19
+ paths:
20
+ - '.github/workflows/node-addon-system.yml'
21
+ - '.github/workflows/node-addon-system-release.yml'
22
+ - 'native/system/**'
23
+ - 'package.json'
24
+ - 'pnpm-lock.yaml'
25
+ - 'pnpm-workspace.yaml'
26
+ workflow_dispatch:
27
+
28
+ concurrency:
29
+ group: ${{ github.workflow }}-${{ github.ref }}
30
+ cancel-in-progress: true
31
+
32
+ permissions:
33
+ contents: read
34
+
35
+ env:
36
+ # CI runs must never report to the production telemetry endpoint baked
37
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
38
+ DSH_TELEMETRY_DISABLED: '1'
39
+
40
+ defaults:
41
+ run:
42
+ working-directory: native/system
43
+
44
+ jobs:
45
+ matrix:
46
+ name: Matrix
47
+ runs-on: ubuntu-24.04
48
+ outputs:
49
+ ci: ${{ steps.matrix.outputs.ci }}
50
+ steps:
51
+ - uses: actions/checkout@v4
52
+
53
+ - id: matrix
54
+ run: echo "ci=$(node ./scripts/github-matrix.mjs ci)" >> "$GITHUB_OUTPUT"
55
+
56
+ native:
57
+ name: ${{ matrix.platform }}
58
+ needs: matrix
59
+ runs-on: ${{ matrix.runner }}
60
+ strategy:
61
+ fail-fast: false
62
+ matrix: ${{ fromJson(needs.matrix.outputs.ci) }}
63
+ steps:
64
+ - uses: actions/checkout@v4
65
+
66
+ - uses: pnpm/action-setup@v4
67
+ with:
68
+ package_json_file: package.json
69
+
70
+ - uses: actions/setup-node@v4
71
+ with:
72
+ node-version: 24
73
+ cache: pnpm
74
+ cache-dependency-path: pnpm-lock.yaml
75
+
76
+ - name: Install dependencies
77
+ run: pnpm install --filter @deepseek-ai/node-addon-system-workspace... --frozen-lockfile
78
+
79
+ - name: Install musl toolchain
80
+ if: runner.os == 'Linux'
81
+ run: |
82
+ sudo apt-get update -q
83
+ sudo apt-get install -yq musl-tools
84
+
85
+ - name: Build TypeScript
86
+ run: pnpm build:ts
87
+
88
+ - name: Typecheck
89
+ run: pnpm typecheck
90
+
91
+ - name: Build native binaries (this architecture is the builder of record)
92
+ run: pnpm build:native
93
+
94
+ - name: Entry tests (keyless)
95
+ run: node ./test/entry.test.js
96
+
97
+ # NALR_REQUIRE_LANDLOCK: a self-skip on the very platform that exists to
98
+ # prove enforcement would be a false green, so an unenforcing kernel
99
+ # fails the leg instead of skipping.
100
+ - name: Launcher tests (real kernel enforcement)
101
+ if: runner.os == 'Linux'
102
+ run: node ./test/launcher.test.js
103
+ env:
104
+ NALR_REQUIRE_LANDLOCK: 1
105
+
106
+ - name: Pack rehearsal (pack → install → confine, this platform only)
107
+ run: |
108
+ node ./scripts/pack-release.mjs .release/npm --current-platform-only
109
+ node ./scripts/verify-packed-install.mjs .release/npm --current-platform-only
110
+ env:
111
+ NALR_REQUIRE_LANDLOCK: ${{ runner.os == 'Linux' && '1' || '0' }}
112
+
113
+ - name: Verify platform payload rules (Node 24)
114
+ run: pnpm test:packaging
115
+
116
+ - name: Flock behavior (Node 24, built addon)
117
+ run: |
118
+ pnpm build:test-oracle
119
+ pnpm test:flock
120
+
121
+ - name: Test the same musl addon on Node 24 without a compiler
122
+ if: runner.os == 'Linux'
123
+ run: >-
124
+ docker run --rm -v "$PWD:$PWD" -w "$PWD"
125
+ node:24-alpine
126
+ node --test ./test/flock.test.js ./test/package-matrix.test.js
127
+
128
+ - uses: actions/setup-node@v4
129
+ with:
130
+ node-version: 20
131
+
132
+ - name: Test the same binaries on Node 20
133
+ run: node --test ./test/flock.test.js ./test/package-matrix.test.js
134
+
135
+ - name: Test the same musl addon on Node 20 without a compiler
136
+ if: runner.os == 'Linux'
137
+ run: >-
138
+ docker run --rm -v "$PWD:$PWD" -w "$PWD"
139
+ node:20-alpine
140
+ node --test ./test/flock.test.js ./test/package-matrix.test.js
141
+
142
+ - uses: actions/setup-node@v4
143
+ with:
144
+ node-version: 22
145
+
146
+ - name: Test the same binaries on Node 22
147
+ run: node --test ./test/flock.test.js ./test/package-matrix.test.js
148
+
149
+ - name: Test the same musl addon on Node 22 without a compiler
150
+ if: runner.os == 'Linux'
151
+ run: >-
152
+ docker run --rm -v "$PWD:$PWD" -w "$PWD"
153
+ node:22-alpine
154
+ node --test ./test/flock.test.js ./test/package-matrix.test.js
155
+
156
+ - uses: actions/setup-node@v4
157
+ with:
158
+ node-version: 26
159
+
160
+ - name: Test the same binaries on Node 26
161
+ run: node --test ./test/flock.test.js ./test/package-matrix.test.js
162
+
163
+ - name: Test the same musl addon on Node 26 without a compiler
164
+ if: runner.os == 'Linux'
165
+ run: >-
166
+ docker run --rm -v "$PWD:$PWD" -w "$PWD"
167
+ node:26-alpine
168
+ node --test ./test/flock.test.js ./test/package-matrix.test.js
.github/workflows/pi-ai-provider-e2e.yml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: E2E (pi-ai Azure OpenAI and Anthropic)
2
+
3
+ # This suite spends tokens against two external providers and is intentionally
4
+ # opt-in. It has no push, pull_request, schedule, or workflow_call trigger.
5
+ on:
6
+ workflow_dispatch:
7
+ inputs:
8
+ azure_openai_model:
9
+ description: Azure OpenAI model from pi-ai's installed catalog
10
+ required: true
11
+ default: gpt-5.5
12
+ type: string
13
+ anthropic_model:
14
+ description: Anthropic model from pi-ai's installed catalog
15
+ required: true
16
+ default: claude-opus-4-8
17
+ type: string
18
+
19
+ permissions:
20
+ contents: read
21
+
22
+ env:
23
+ # CI runs must never report to the production telemetry endpoint baked
24
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
25
+ DSH_TELEMETRY_DISABLED: '1'
26
+
27
+ jobs:
28
+ e2e:
29
+ runs-on: ubuntu-latest
30
+ name: Azure OpenAI Responses + Anthropic Messages
31
+ timeout-minutes: 20
32
+ steps:
33
+ - uses: actions/checkout@v6
34
+
35
+ - uses: pnpm/action-setup@v4
36
+
37
+ - uses: actions/setup-node@v6
38
+ with:
39
+ node-version: 24
40
+ cache: pnpm
41
+
42
+ - name: Install (immutable)
43
+ run: pnpm install --frozen-lockfile
44
+
45
+ # The tests self-skip locally when a credential is absent. A manually
46
+ # dispatched CI run must fail instead of reporting an all-skipped green.
47
+ - name: Preflight (require provider API keys)
48
+ env:
49
+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY_EXTERNAL }}
50
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY_EXTERNAL }}
51
+ run: |
52
+ set -euo pipefail
53
+ missing=0
54
+ for name in AZURE_OPENAI_API_KEY ANTHROPIC_API_KEY; do
55
+ if [ -z "${!name:-}" ]; then
56
+ echo "::error::${name} is empty. Configure the corresponding *_EXTERNAL repository secret."
57
+ missing=1
58
+ fi
59
+ done
60
+ exit "$missing"
61
+
62
+ - name: E2E tests (real Azure OpenAI and Anthropic APIs)
63
+ env:
64
+ AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY_EXTERNAL }}
65
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY_EXTERNAL }}
66
+ DSH_PI_AI_OPENAI_MODEL: ${{ inputs.azure_openai_model }}
67
+ DSH_PI_AI_OPENAI_BASE_URL: https://openai-routerhub-resource.services.ai.azure.com/api/projects/openai/openai/v1
68
+ DSH_PI_AI_ANTHROPIC_MODEL: ${{ inputs.anthropic_model }}
69
+ DSH_E2E_MAX_WORKERS: 2
70
+ run: >-
71
+ pnpm exec vitest run --config vitest.e2e.config.ts
72
+ packages/llm/llm-pi-ai/tests/provider-apis.e2e.ts
.github/workflows/python-release.yml ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Release (Python)
2
+
3
+ # A manual run with publish=false builds and validates the complete release
4
+ # without registry credentials. Publication is accepted only from a manual run
5
+ # on the matching python-v* tag when the private publisher-repository identity
6
+ # and public-PyPI switch are configured.
7
+ on:
8
+ workflow_dispatch:
9
+ inputs:
10
+ publish:
11
+ description: Publish the validated wheels to public PyPI. Must run from a python-v* tag.
12
+ required: true
13
+ type: boolean
14
+ default: false
15
+
16
+ permissions:
17
+ contents: read
18
+
19
+ concurrency:
20
+ # Public runs stay globally serialized across tags. Dry runs remain isolated
21
+ # by ref so they do not block an intentional publication.
22
+ group: ${{ github.event_name == 'workflow_dispatch' && inputs.publish && 'python-publication' || format('{0}-{1}', github.workflow, github.ref) }}
23
+ cancel-in-progress: false
24
+
25
+ jobs:
26
+ build:
27
+ name: Build six wheels
28
+ uses: ./.github/workflows/build-exe-for-python-sdk.yml
29
+ with:
30
+ targets: node24-linux-x64,node24-linux-arm64,node24-macos-arm64,node24-macos-x64,node24-win-x64
31
+ release: true
32
+
33
+ python-compat:
34
+ name: Python ${{ matrix.python }} / installed SDK
35
+ needs: build
36
+ runs-on: ubuntu-latest
37
+ timeout-minutes: 10
38
+ strategy:
39
+ fail-fast: false
40
+ matrix:
41
+ python: ['3.10', '3.14']
42
+ steps:
43
+ - uses: actions/checkout@v6
44
+ with:
45
+ persist-credentials: false
46
+
47
+ - uses: actions/setup-python@v6.3.0
48
+ with:
49
+ python-version: ${{ matrix.python }}
50
+
51
+ - uses: actions/download-artifact@v8
52
+ with:
53
+ pattern: deepseek_harness_*
54
+ path: dist
55
+ merge-multiple: true
56
+
57
+ - name: Resolve installed wheel version
58
+ id: compatibility-version
59
+ run: |
60
+ python - <<'PY' >> "$GITHUB_OUTPUT"
61
+ import runpy
62
+
63
+ release = runpy.run_path("scripts/build-python-release.py")
64
+ repository_version = release["repository_version"]()
65
+ print(f"version={release['pep440_version'](repository_version)}")
66
+ PY
67
+
68
+ - name: Install local release wheels and run the public entry path
69
+ env:
70
+ VERSION: ${{ steps.compatibility-version.outputs.version }}
71
+ run: |
72
+ python -m pip install \
73
+ "dist/deepseek_harness_sdk-$VERSION-py3-none-any.whl" \
74
+ "dist/deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl"
75
+ python scripts/smoke-python-runtime.py --scenario sdk-default
76
+ python scripts/smoke-python-runtime.py --scenario sdk-mcp
77
+
78
+ validate:
79
+ name: Validate release candidate
80
+ needs: [build, python-compat]
81
+ runs-on: ubuntu-latest
82
+ timeout-minutes: 10
83
+ outputs:
84
+ version: ${{ steps.version.outputs.version }}
85
+ steps:
86
+ - uses: actions/checkout@v6
87
+ with:
88
+ persist-credentials: false
89
+
90
+ - uses: actions/setup-python@v6.3.0
91
+ with:
92
+ python-version: '3.10'
93
+
94
+ - name: Resolve release version
95
+ id: version
96
+ run: |
97
+ python3 - <<'PY' >> "$GITHUB_OUTPUT"
98
+ import runpy
99
+
100
+ release = runpy.run_path("scripts/build-python-release.py")
101
+ repository_version = release["repository_version"]()
102
+ wheel_version = release["pep440_version"](repository_version)
103
+ print(f"repository-version={repository_version}")
104
+ print(f"version={wheel_version}")
105
+ PY
106
+
107
+ - name: Authorize publication request
108
+ env:
109
+ PUBLISH: ${{ github.event_name == 'workflow_dispatch' && inputs.publish }}
110
+ PUBLIC_PYPI_RELEASE_ENABLED: ${{ vars.PUBLIC_PYPI_RELEASE_ENABLED }}
111
+ PYPI_PUBLISHER_REPOSITORY: ${{ vars.PYPI_PUBLISHER_REPOSITORY }}
112
+ REPOSITORY: ${{ github.repository }}
113
+ REF_NAME: ${{ github.ref_name }}
114
+ REF_TYPE: ${{ github.ref_type }}
115
+ REPOSITORY_VERSION: ${{ steps.version.outputs.repository-version }}
116
+ run: |
117
+ set -euo pipefail
118
+ if [ "$PUBLISH" = true ]; then
119
+ [ -n "$PYPI_PUBLISHER_REPOSITORY" ] || {
120
+ echo "::error::Set the repository variable PYPI_PUBLISHER_REPOSITORY before publication."
121
+ exit 1
122
+ }
123
+ [ "$REPOSITORY" = "$PYPI_PUBLISHER_REPOSITORY" ] || {
124
+ echo "::error::This repository is not the configured PyPI publisher repository."
125
+ exit 1
126
+ }
127
+ [ "$PUBLIC_PYPI_RELEASE_ENABLED" = true ] || {
128
+ echo "::error::Set PUBLIC_PYPI_RELEASE_ENABLED=true before public publication."
129
+ exit 1
130
+ }
131
+ [ "$REF_TYPE" = tag ] && [ "$REF_NAME" = "python-v$REPOSITORY_VERSION" ] || {
132
+ echo "::error::Publication must run from tag python-v$REPOSITORY_VERSION."
133
+ exit 1
134
+ }
135
+ fi
136
+
137
+ - uses: actions/download-artifact@v8
138
+ with:
139
+ pattern: deepseek_harness_*
140
+ path: dist
141
+ merge-multiple: true
142
+
143
+ - name: Check release contents
144
+ env:
145
+ VERSION: ${{ steps.version.outputs.version }}
146
+ run: |
147
+ set -euo pipefail
148
+ expected="$(mktemp)"
149
+ actual="$(mktemp)"
150
+ printf '%s\n' \
151
+ "deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_arm64.whl" \
152
+ "deepseek_harness_runtime_bin-$VERSION-py3-none-macosx_14_0_x86_64.whl" \
153
+ "deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_aarch64.whl" \
154
+ "deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl" \
155
+ "deepseek_harness_runtime_bin-$VERSION-py3-none-win_amd64.whl" \
156
+ "deepseek_harness_sdk-$VERSION-py3-none-any.whl" > "$expected"
157
+ find dist -maxdepth 1 -type f -name '*.whl' -exec basename {} \; | sort > "$actual"
158
+ diff -u "$expected" "$actual"
159
+ while IFS= read -r wheel; do
160
+ size="$(stat -c '%s' "dist/$wheel")"
161
+ [ "$size" -lt 100000000 ] || {
162
+ echo "::error::$wheel is $size bytes; public PyPI accepts at most 100000000 bytes by default."
163
+ exit 1
164
+ }
165
+ done < "$actual"
166
+
167
+ - name: Validate package metadata
168
+ run: |
169
+ python -m pip install twine==6.2.0
170
+ python -m twine check dist/*.whl
171
+
172
+ - name: Record artifact hashes
173
+ run: |
174
+ cd dist
175
+ sha256sum *.whl | sort -k2 > SHA256SUMS
176
+ cat SHA256SUMS
177
+
178
+ - uses: actions/upload-artifact@v7
179
+ with:
180
+ name: python-release-${{ steps.version.outputs.version }}
181
+ path: dist/*
182
+ if-no-files-found: error
183
+ retention-days: 7
184
+
185
+ publish-runtime:
186
+ name: Publish runtime wheels to public PyPI
187
+ if: github.event_name == 'workflow_dispatch' && inputs.publish
188
+ needs: validate
189
+ runs-on: ubuntu-latest
190
+ timeout-minutes: 10
191
+ environment: pypi-runtime
192
+ permissions:
193
+ contents: read
194
+ id-token: write
195
+ steps:
196
+ - uses: actions/download-artifact@v8
197
+ with:
198
+ name: python-release-${{ needs.validate.outputs.version }}
199
+ path: dist
200
+
201
+ - name: Verify release artifact hashes
202
+ run: cd dist && sha256sum -c SHA256SUMS
203
+
204
+ - name: Select runtime wheels
205
+ run: |
206
+ mkdir -p dist/runtime
207
+ mv dist/deepseek_harness_runtime_bin-*.whl dist/runtime/
208
+
209
+ - name: Publish runtime wheels
210
+ uses: pypa/gh-action-pypi-publish@release/v1
211
+ with:
212
+ packages-dir: dist/runtime/
213
+ # Public attestations reveal the private publisher repository. OIDC
214
+ # authentication remains enabled without uploading that repository identity.
215
+ attestations: false
216
+
217
+ # Keep the SDK in a dependent job. If its upload fails after the immutable
218
+ # runtime files arrive, "re-run failed jobs" resumes here without attempting
219
+ # to overwrite the runtime release.
220
+ publish-sdk:
221
+ name: Publish SDK wheel to public PyPI
222
+ if: github.event_name == 'workflow_dispatch' && inputs.publish
223
+ needs: [validate, publish-runtime]
224
+ runs-on: ubuntu-latest
225
+ timeout-minutes: 10
226
+ environment: pypi
227
+ permissions:
228
+ contents: read
229
+ id-token: write
230
+ steps:
231
+ - uses: actions/download-artifact@v8
232
+ with:
233
+ name: python-release-${{ needs.validate.outputs.version }}
234
+ path: dist
235
+
236
+ - name: Verify release artifact hashes
237
+ run: cd dist && sha256sum -c SHA256SUMS
238
+
239
+ - name: Select SDK wheel
240
+ run: |
241
+ mkdir -p dist/sdk
242
+ mv dist/deepseek_harness_sdk-*.whl dist/sdk/
243
+
244
+ - name: Publish SDK wheel
245
+ uses: pypa/gh-action-pypi-publish@release/v1
246
+ with:
247
+ packages-dir: dist/sdk/
248
+ attestations: false
.github/workflows/release-publish.yml ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Publish the dsh release sequence to npm. This workflow is manual-only
2
+ # (workflow_dispatch) and intentionally does not listen to pull_request or push:
3
+ # publication must always be an explicit, reviewed act from a dsh-v* tag, and it
4
+ # must never appear as a PR check. It repacks the current tree before publishing
5
+ # so the bytes uploaded are exactly what this dispatch produced.
6
+ name: Release publish (dsh)
7
+
8
+ on:
9
+ workflow_dispatch:
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ env:
15
+ PRIMARY_NODE_VERSION: '24'
16
+ DSH_TELEMETRY_DISABLED: '1'
17
+
18
+ jobs:
19
+ pack:
20
+ name: Pack npm tarballs
21
+ runs-on: ubuntu-24.04
22
+ steps:
23
+ # Complete history: the release scripts read tags.
24
+ - uses: actions/checkout@v6
25
+ with:
26
+ fetch-depth: 0
27
+ persist-credentials: false
28
+
29
+ - uses: pnpm/action-setup@v4
30
+ with:
31
+ dest: ${{ runner.temp }}/setup-pnpm
32
+
33
+ - uses: actions/setup-node@v6
34
+ with:
35
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
36
+
37
+ - name: Configure pnpm store path
38
+ id: pnpm-store
39
+ run: |
40
+ store_root="$HOME/.local/share/pnpm/store"
41
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
42
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
43
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
44
+
45
+ - uses: actions/cache/restore@v4
46
+ with:
47
+ path: ${{ steps.pnpm-store.outputs.path }}
48
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
49
+ restore-keys: |
50
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
51
+
52
+ - name: Install (immutable)
53
+ run: pnpm install --frozen-lockfile
54
+
55
+ - name: Verify release version
56
+ env:
57
+ RELEASE_PUBLISH: 'true'
58
+ run: pnpm run release:verify --family dsh
59
+
60
+ - name: Build
61
+ run: pnpm run build:official
62
+
63
+ - name: Pack release tarballs
64
+ run: pnpm run release:pack --family dsh --out dist/npm
65
+
66
+ # The harness packages declare the vendored framework as a peer, and this
67
+ # verification must not depend on the registry already carrying matching
68
+ # versions — one pull request may bump both families before either
69
+ # publishes — so it installs that family's pack output too. Only dist/npm
70
+ # is published.
71
+ - name: Pack the vendored framework for verification
72
+ run: pnpm run release:pack --family vendor --out dist/npm-vendor
73
+
74
+ # dsh-sandbox-local declares the Landlock entry as a runtime dependency, so
75
+ # the verification needs its tarball. Its platform packages stay out: they
76
+ # are optional, and building them needs a musl toolchain per architecture.
77
+ - name: Pack the Landlock entry for verification
78
+ run: |
79
+ pnpm --dir native/system run build:ts
80
+ pnpm --dir native/system/packages/entry pack --pack-destination "$PWD/dist/npm-landlock"
81
+
82
+ - name: Verify packed install
83
+ run: pnpm run release:verify-packed-install --family dsh --from dist/npm --from dist/npm-vendor --from dist/npm-landlock
84
+
85
+ - uses: actions/upload-artifact@v4
86
+ with:
87
+ name: dsh-npm-tarballs
88
+ path: dist/npm/*
89
+ if-no-files-found: error
90
+ retention-days: 7
91
+
92
+ publish:
93
+ name: Publish to npm
94
+ needs: pack
95
+ runs-on: ubuntu-24.04
96
+ # Required reviewers and the allowed tags live on the environment; this is
97
+ # the only job in the sequence that can write to the registry.
98
+ environment: npm-publish
99
+ concurrency:
100
+ group: Release-publish
101
+ cancel-in-progress: false
102
+ permissions:
103
+ contents: read
104
+ steps:
105
+ # Checkout and install carry the release scripts only. There is no build
106
+ # step: publication uploads the bytes the pack job produced.
107
+ - uses: actions/checkout@v6
108
+ with:
109
+ persist-credentials: false
110
+
111
+ - uses: pnpm/action-setup@v4
112
+ with:
113
+ dest: ${{ runner.temp }}/setup-pnpm
114
+
115
+ - uses: actions/setup-node@v6
116
+ with:
117
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
118
+ registry-url: https://registry.npmjs.org
119
+
120
+ - name: Install (immutable, no package scripts)
121
+ run: pnpm install --frozen-lockfile --ignore-scripts
122
+
123
+ - uses: actions/download-artifact@v4
124
+ with:
125
+ name: dsh-npm-tarballs
126
+ path: dist/npm
127
+
128
+ - name: Publish tarballs
129
+ env:
130
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
131
+ run: pnpm run release:publish --family dsh --from dist/npm
.github/workflows/release-vendor-publish.yml ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Publish the vendored framework sequence to npm. This workflow is manual-only
2
+ # (workflow_dispatch) and intentionally does not listen to pull_request or push:
3
+ # publication must always be an explicit, reviewed act from a vendor-* tag, and
4
+ # it must never appear as a PR check. It repacks the current tree before
5
+ # publishing so the bytes uploaded are exactly what this dispatch produced.
6
+ name: Release publish (vendor)
7
+
8
+ on:
9
+ workflow_dispatch:
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ env:
15
+ PRIMARY_NODE_VERSION: '24'
16
+ DSH_TELEMETRY_DISABLED: '1'
17
+
18
+ jobs:
19
+ pack:
20
+ name: Pack npm tarballs
21
+ runs-on: ubuntu-24.04
22
+ steps:
23
+ # Complete history: the release scripts read tags.
24
+ - uses: actions/checkout@v6
25
+ with:
26
+ fetch-depth: 0
27
+ persist-credentials: false
28
+
29
+ - uses: pnpm/action-setup@v4
30
+ with:
31
+ dest: ${{ runner.temp }}/setup-pnpm
32
+
33
+ - uses: actions/setup-node@v6
34
+ with:
35
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
36
+
37
+ - name: Configure pnpm store path
38
+ id: pnpm-store
39
+ run: |
40
+ store_root="$HOME/.local/share/pnpm/store"
41
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
42
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
43
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
44
+
45
+ - uses: actions/cache/restore@v4
46
+ with:
47
+ path: ${{ steps.pnpm-store.outputs.path }}
48
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
49
+ restore-keys: |
50
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
51
+
52
+ - name: Install (immutable)
53
+ run: pnpm install --frozen-lockfile
54
+
55
+ - name: Verify release version
56
+ env:
57
+ RELEASE_PUBLISH: 'true'
58
+ run: pnpm run release:verify --family vendor
59
+
60
+ # The vendored packages publish their own sources and build outputs; the
61
+ # host build produces what their manifests select.
62
+ - name: Build
63
+ run: pnpm run build:lib:host
64
+
65
+ - name: Pack release tarballs
66
+ run: pnpm run release:pack --family vendor --out dist/npm-vendor
67
+
68
+ - name: Verify packed install
69
+ run: pnpm run release:verify-packed-install --family vendor --from dist/npm-vendor
70
+
71
+ - uses: actions/upload-artifact@v4
72
+ with:
73
+ name: vendor-npm-tarballs
74
+ path: dist/npm-vendor/*
75
+ if-no-files-found: error
76
+ retention-days: 7
77
+
78
+ publish:
79
+ name: Publish to npm
80
+ needs: pack
81
+ runs-on: ubuntu-24.04
82
+ environment: npm-publish
83
+ concurrency:
84
+ group: Release-publish
85
+ cancel-in-progress: false
86
+ permissions:
87
+ contents: read
88
+ steps:
89
+ # Checkout and install carry the release scripts only; no build step.
90
+ - uses: actions/checkout@v6
91
+ with:
92
+ persist-credentials: false
93
+
94
+ - uses: pnpm/action-setup@v4
95
+ with:
96
+ dest: ${{ runner.temp }}/setup-pnpm
97
+
98
+ - uses: actions/setup-node@v6
99
+ with:
100
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
101
+ registry-url: https://registry.npmjs.org
102
+
103
+ - name: Install (immutable, no package scripts)
104
+ run: pnpm install --frozen-lockfile --ignore-scripts
105
+
106
+ - uses: actions/download-artifact@v4
107
+ with:
108
+ name: vendor-npm-tarballs
109
+ path: dist/npm-vendor
110
+
111
+ - name: Publish tarballs
112
+ env:
113
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
114
+ run: pnpm run release:publish --family vendor --from dist/npm-vendor
.github/workflows/release-vendor.yml ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pack the vendored framework sequence: the nine rescoped Cordis packages under
2
+ # vendor/, each on its own version line. This sequence releases independently of
3
+ # dsh and of the native packages.
4
+ #
5
+ # Pack runs without credentials on every pull request and master push.
6
+ # Publication is a manual workflow_dispatch of release-vendor-publish.yml from a
7
+ # vendor-* tag; a vendor release can carry several versions, so each package has
8
+ # its own tag.
9
+ name: Release (vendor)
10
+
11
+ on:
12
+ pull_request:
13
+ push:
14
+ branches: [master]
15
+ workflow_dispatch:
16
+
17
+ permissions:
18
+ contents: read
19
+
20
+ concurrency:
21
+ # Pack runs per ref so concurrent pull requests never displace each other.
22
+ group: ${{ github.workflow }}-${{ github.ref }}
23
+ cancel-in-progress: true
24
+
25
+ env:
26
+ PRIMARY_NODE_VERSION: '24'
27
+ DSH_TELEMETRY_DISABLED: '1'
28
+
29
+ jobs:
30
+ pack:
31
+ name: Pack npm tarballs
32
+ # Persistent runners accept only trusted, credential-free rehearsals.
33
+ runs-on: >-
34
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
35
+ && github.repository == 'deepseek-harness/deepseek-harness'
36
+ && github.actor != 'dependabot[bot]'
37
+ && ((github.event_name == 'push' && github.ref == 'refs/heads/master')
38
+ || (github.event_name == 'pull_request'
39
+ && github.event.pull_request.head.repo.full_name == github.repository
40
+ && github.event.pull_request.head.repo.fork == false
41
+ && github.event.pull_request.user.login != 'dependabot[bot]'))
42
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
43
+ || 'ubuntu-24.04' }}
44
+ steps:
45
+ # Complete history: the release scripts read tags.
46
+ - uses: actions/checkout@v6
47
+ with:
48
+ fetch-depth: 0
49
+ persist-credentials: false
50
+ clean: true
51
+
52
+ - name: Configure runner-private caches
53
+ run: |
54
+ echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
55
+ echo "npm_config_devdir=${{ runner.temp }}/node-gyp" >> "$GITHUB_ENV"
56
+ echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
57
+
58
+ - uses: pnpm/action-setup@v4
59
+ with:
60
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
61
+
62
+ - uses: actions/setup-node@v6
63
+ with:
64
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
65
+ package-manager-cache: false
66
+
67
+ - name: Configure pnpm store path
68
+ id: pnpm-store
69
+ run: |
70
+ store_root="$HOME/.local/share/pnpm/store"
71
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
72
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
73
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
74
+
75
+ - uses: actions/cache/restore@v4
76
+ if: runner.environment == 'github-hosted'
77
+ with:
78
+ path: ${{ steps.pnpm-store.outputs.path }}
79
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
80
+ restore-keys: |
81
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
82
+
83
+ - name: Install (immutable)
84
+ run: pnpm install --frozen-lockfile
85
+
86
+ - name: Verify release version
87
+ run: pnpm run release:verify --family vendor
88
+
89
+ # The vendored packages publish their own sources and build outputs; the
90
+ # host build produces what their manifests select.
91
+ - name: Build
92
+ run: pnpm run build:lib:host
93
+
94
+ # Concurrency here is rehearsal-only: the credentialed publish workflows
95
+ # invoke release:pack without the flag and keep the strictly serial path.
96
+ - name: Pack release tarballs
97
+ run: pnpm run release:pack --family vendor --out dist/npm-vendor --concurrency 8
98
+
99
+ - name: Verify packed install
100
+ run: pnpm run release:verify-packed-install --family vendor --from dist/npm-vendor
101
+
102
+ - uses: actions/upload-artifact@v4
103
+ with:
104
+ name: vendor-npm-tarballs
105
+ path: dist/npm-vendor/*
106
+ if-no-files-found: error
107
+ retention-days: 7
.github/workflows/release.yml ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pack the dsh release sequence: every package under packages/ plus the apps/
2
+ # entries, all on one version. The vendored framework and the native packages are
3
+ # separate sequences with their own workflows and version lines.
4
+ #
5
+ # Pack and dependency-layout verification run without credentials on every pull
6
+ # request and master push. Publication is a manual workflow_dispatch of
7
+ # release-publish.yml from a dsh-v* tag.
8
+ name: Release (dsh)
9
+
10
+ on:
11
+ pull_request:
12
+ push:
13
+ branches: [master]
14
+ workflow_dispatch:
15
+
16
+ permissions:
17
+ contents: read
18
+
19
+ concurrency:
20
+ # Pack runs per ref so concurrent pull requests never displace each other.
21
+ group: ${{ github.workflow }}-${{ github.ref }}
22
+ cancel-in-progress: true
23
+
24
+ env:
25
+ PRIMARY_NODE_VERSION: '24'
26
+ DSH_TELEMETRY_DISABLED: '1'
27
+
28
+ jobs:
29
+ dependencies:
30
+ name: Dependency layout
31
+ # Persistent runners accept only trusted, credential-free rehearsals.
32
+ runs-on: >-
33
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
34
+ && github.repository == 'deepseek-harness/deepseek-harness'
35
+ && github.actor != 'dependabot[bot]'
36
+ && ((github.event_name == 'push' && github.ref == 'refs/heads/master')
37
+ || (github.event_name == 'pull_request'
38
+ && github.event.pull_request.head.repo.full_name == github.repository
39
+ && github.event.pull_request.head.repo.fork == false
40
+ && github.event.pull_request.user.login != 'dependabot[bot]'))
41
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
42
+ || 'ubuntu-24.04' }}
43
+ steps:
44
+ - uses: actions/checkout@v6
45
+ with:
46
+ persist-credentials: false
47
+ clean: true
48
+
49
+ - name: Configure runner-private caches
50
+ run: |
51
+ echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
52
+ echo "npm_config_devdir=${{ runner.temp }}/node-gyp" >> "$GITHUB_ENV"
53
+ echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
54
+
55
+ - uses: pnpm/action-setup@v4
56
+ with:
57
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
58
+
59
+ - uses: actions/setup-node@v6
60
+ with:
61
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
62
+ package-manager-cache: false
63
+
64
+ - name: Configure pnpm store path
65
+ id: pnpm-store
66
+ run: |
67
+ store_root="$HOME/.local/share/pnpm/store"
68
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
69
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
70
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
71
+
72
+ - uses: actions/cache/restore@v4
73
+ if: runner.environment == 'github-hosted'
74
+ with:
75
+ path: ${{ steps.pnpm-store.outputs.path }}
76
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
77
+ restore-keys: |
78
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
79
+
80
+ - name: Install (immutable)
81
+ run: pnpm install --frozen-lockfile
82
+
83
+ - name: Verify dependency policy
84
+ run: pnpm run verify-package-dependencies
85
+
86
+ - name: Verify npm install layout
87
+ run: pnpm run verify-npm-install-layout
88
+
89
+ pack:
90
+ name: Pack npm tarballs
91
+ # Persistent runners accept only trusted, credential-free rehearsals.
92
+ runs-on: >-
93
+ ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted'
94
+ && github.repository == 'deepseek-harness/deepseek-harness'
95
+ && github.actor != 'dependabot[bot]'
96
+ && ((github.event_name == 'push' && github.ref == 'refs/heads/master')
97
+ || (github.event_name == 'pull_request'
98
+ && github.event.pull_request.head.repo.full_name == github.repository
99
+ && github.event.pull_request.head.repo.fork == false
100
+ && github.event.pull_request.user.login != 'dependabot[bot]'))
101
+ && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]')
102
+ || 'ubuntu-24.04' }}
103
+ steps:
104
+ # Complete history: the release scripts read tags.
105
+ - uses: actions/checkout@v6
106
+ with:
107
+ fetch-depth: 0
108
+ persist-credentials: false
109
+ clean: true
110
+
111
+ - name: Configure runner-private caches
112
+ run: |
113
+ echo "NODE_COMPILE_CACHE=${{ runner.temp }}/node-compile-cache" >> "$GITHUB_ENV"
114
+ echo "npm_config_devdir=${{ runner.temp }}/node-gyp" >> "$GITHUB_ENV"
115
+ echo "TMPDIR=${{ runner.temp }}" >> "$GITHUB_ENV"
116
+
117
+ - uses: pnpm/action-setup@v4
118
+ with:
119
+ dest: ${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
120
+
121
+ - uses: actions/setup-node@v6
122
+ with:
123
+ node-version: ${{ env.PRIMARY_NODE_VERSION }}
124
+ package-manager-cache: false
125
+
126
+ - name: Configure pnpm store path
127
+ id: pnpm-store
128
+ run: |
129
+ store_root="$HOME/.local/share/pnpm/store"
130
+ echo "PNPM_CONFIG_STORE_DIR=$store_root" >> "$GITHUB_ENV"
131
+ store_path=$(PNPM_CONFIG_STORE_DIR="$store_root" pnpm store path --silent)
132
+ echo "path=$store_path" >> "$GITHUB_OUTPUT"
133
+
134
+ - uses: actions/cache/restore@v4
135
+ if: runner.environment == 'github-hosted'
136
+ with:
137
+ path: ${{ steps.pnpm-store.outputs.path }}
138
+ key: ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
139
+ restore-keys: |
140
+ ${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
141
+
142
+ - name: Install (immutable)
143
+ run: pnpm install --frozen-lockfile
144
+
145
+ - name: Verify release version
146
+ run: pnpm run release:verify --family dsh
147
+
148
+ - name: Build
149
+ run: pnpm run build:official
150
+
151
+ # Concurrency here is rehearsal-only: the credentialed publish workflows
152
+ # invoke release:pack without the flag and keep the strictly serial path.
153
+ - name: Pack release tarballs
154
+ run: pnpm run release:pack --family dsh --out dist/npm --concurrency 8
155
+
156
+ # The harness packages declare the vendored framework as a peer, and this
157
+ # verification must not depend on the registry already carrying matching
158
+ # versions — one pull request may bump both families before either
159
+ # publishes — so it installs that family's pack output too. Only dist/npm
160
+ # is published.
161
+ - name: Pack the vendored framework for verification
162
+ run: pnpm run release:pack --family vendor --out dist/npm-vendor --concurrency 8
163
+
164
+ # dsh-sandbox-local declares the Landlock entry as a runtime dependency, so
165
+ # the verification needs its tarball. Its platform packages stay out: they
166
+ # are optional, and building them needs a musl toolchain per architecture.
167
+ - name: Pack the Landlock entry for verification
168
+ run: |
169
+ pnpm --dir native/system run build:ts
170
+ pnpm --dir native/system/packages/entry pack --pack-destination "$PWD/dist/npm-landlock"
171
+
172
+ - name: Verify packed install
173
+ run: pnpm run release:verify-packed-install --family dsh --from dist/npm --from dist/npm-vendor --from dist/npm-landlock
174
+
175
+ - uses: actions/upload-artifact@v4
176
+ with:
177
+ name: dsh-npm-tarballs
178
+ path: dist/npm/*
179
+ if-no-files-found: error
180
+ retention-days: 7
.github/workflows/sandbox.yml ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sandbox CI: the keyless real-kernel confinement proofs. This master-only
2
+ # reference stays outside the pull-request verdict; rationale lives in
3
+ # .agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md.
4
+ # A separate workflow from ci.yml because the axis is different — these jobs
5
+ # fan out over OS×runner (kernel capabilities), not node versions. The Landlock
6
+ # launcher is built from native/system on each Landlock leg and installed
7
+ # from the same tarballs the main-repository release workflow publishes.
8
+ name: Sandbox
9
+
10
+ on:
11
+ push:
12
+ branches: [master]
13
+
14
+ concurrency:
15
+ group: ${{ github.workflow }}-${{ github.ref }}
16
+ cancel-in-progress: true
17
+
18
+ permissions:
19
+ contents: read
20
+
21
+ env:
22
+ # CI runs must never report to the production telemetry endpoint baked
23
+ # into apps/cli/cordis.yml (AppCLIEntry disables the row when set).
24
+ DSH_TELEMETRY_DISABLED: '1'
25
+
26
+ jobs:
27
+ # Keyless real-kernel sandbox proofs (sandbox Agent Note § Testing): each ladder
28
+ # rung is only provable on a host where it enforces, so this job fans out
29
+ # an OS×runner matrix — bwrap and Landlock on Linux (separate legs: the
30
+ # Landlock files force the bwrap rung off, so each leg proves exactly one
31
+ # rung; Landlock twice, once per architecture, each confining through the
32
+ # locally built launcher), Seatbelt on macOS (sandbox-exec ships with
33
+ # the OS). One node
34
+ # version only: kernel confinement does not vary by node, and ci.yml's
35
+ # node matrix already covers the node axis.
36
+ #
37
+ # The e2e files self-skip where their runner is absent, so a leg that lost
38
+ # its runner (no bwrap, kernel without Landlock, macOS without
39
+ # sandbox-exec) would otherwise pass as a false green — the same trap
40
+ # e2e.yml's key preflight guards against. Each leg therefore asserts BOTH
41
+ # its platform files actually ran: `Test Files 2 passed (2)`, no skips.
42
+ sandbox-e2e:
43
+ strategy:
44
+ fail-fast: false
45
+ matrix:
46
+ include:
47
+ # Only the bwrap leg has a Blacksmith equivalent: the earlier
48
+ # migration dispatch runs measured that Blacksmith's Linux images do
49
+ # not enforce Landlock (the run-guard would turn the leg red) and
50
+ # its macOS image is unverified, so those legs stay on GitHub's
51
+ # images under every failover value — see
52
+ # .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md.
53
+ - os: ubuntu-latest
54
+ runner: bwrap
55
+ - os: ubuntu-24.04
56
+ runner: landlock
57
+ - os: ubuntu-24.04-arm
58
+ runner: landlock
59
+ - os: macos-latest
60
+ runner: seatbelt
61
+ name: sandbox e2e (${{ matrix.runner }}, ${{ matrix.os }})
62
+ runs-on: >-
63
+ ${{ matrix.runner == 'bwrap' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
64
+ && 'blacksmith-4vcpu-ubuntu-2404'
65
+ || matrix.os }}
66
+ timeout-minutes: 20
67
+ steps:
68
+ - uses: actions/checkout@v6
69
+
70
+ - uses: pnpm/action-setup@v4
71
+
72
+ - uses: actions/setup-node@v6
73
+ with:
74
+ node-version: 24
75
+
76
+ - name: Install (immutable)
77
+ run: pnpm install --frozen-lockfile
78
+
79
+ # The bwrap rung needs bubblewrap on PATH and unprivileged user
80
+ # namespaces. Ubuntu 24.04 gates the latter behind an AppArmor knob;
81
+ # lift it best-effort — on images where the knob is absent the
82
+ # functional probe (and the run-guard below) is the arbiter anyway.
83
+ - name: Install bubblewrap (unrestrict userns)
84
+ if: matrix.runner == 'bwrap'
85
+ run: |
86
+ sudo apt-get update -q
87
+ sudo apt-get install -yq bubblewrap
88
+ sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 \
89
+ || echo "apparmor userns knob absent — the functional probe decides"
90
+
91
+ - name: Build Landlock launcher for this architecture
92
+ if: matrix.runner == 'landlock'
93
+ run: |
94
+ sudo apt-get update -q
95
+ sudo apt-get install -yq musl-tools
96
+ pnpm --dir native/system run build:ts
97
+ pnpm --dir native/system run build:native
98
+
99
+ # The unit suite runs on ubuntu in `checks`; this is the one darwin leg
100
+ # in the workflow, so run it here too — the platform-dependent unit
101
+ # expectations (Seatbelt path canonicalization: /tmp IS /private/tmp)
102
+ # take their darwin branch only on this runner.
103
+ - name: Unit tests (darwin parity)
104
+ if: matrix.runner == 'seatbelt'
105
+ run: pnpm run test
106
+
107
+ - name: Sandbox e2e (real kernel confinement, world-verified)
108
+ # NO_COLOR: vitest force-enables ANSI color under GITHUB_ACTIONS even
109
+ # without a TTY, which would thread escape codes through the summary
110
+ # line the run-guard greps.
111
+ env:
112
+ NO_COLOR: 1
113
+ run: |
114
+ set -u +e -o pipefail
115
+ out=$(pnpm exec vitest run --config vitest.e2e.config.ts \
116
+ packages/sandbox/sandbox-local/tests/${{ matrix.runner }}.e2e.ts \
117
+ packages/shell/bash-sandbox/tests/${{ matrix.runner }}.e2e.ts 2>&1); status=$?
118
+ echo "$out"
119
+ [ "$status" -eq 0 ]
120
+ # Both platform files must have RUN — a self-skip (runner missing on
121
+ # the very platform that exists to prove it) is a failure, not a pass.
122
+ echo "$out" | grep -qE 'Test Files[[:space:]]+2 passed \(2\)'
123
+
124
+ # Publish-path rehearsal, Landlock legs only. Build the launcher on its
125
+ # native architecture, then install the local native and harness tarballs
126
+ # together so registry state cannot mask source/package drift.
127
+ - name: Build packages for the pack rehearsal
128
+ if: matrix.runner == 'landlock'
129
+ run: pnpm run build:official
130
+
131
+ - name: Packed-distribution e2e (pack → install → confine)
132
+ if: matrix.runner == 'landlock'
133
+ env:
134
+ NO_COLOR: 1
135
+ run: |
136
+ set -u +e -o pipefail
137
+ out=$(pnpm exec vitest run --config vitest.e2e.config.ts \
138
+ packages/sandbox/sandbox-local/tests/packed-install.e2e.ts 2>&1); status=$?
139
+ echo "$out"
140
+ [ "$status" -eq 0 ]
141
+ echo "$out" | grep -qE 'Test Files[[:space:]]+1 passed \(1\)'
.github/workflows/weighted-approval-review-event.yml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: weighted-approval-review-event
2
+ run-name: weighted-approval-review-event:${{ github.event.pull_request.number }}
3
+
4
+ on:
5
+ pull_request_review:
6
+ types: [submitted, edited, dismissed]
7
+
8
+ permissions: {}
9
+
10
+ jobs:
11
+ record-review-event:
12
+ name: record weighted approval review event
13
+ runs-on: ubuntu-latest
14
+ timeout-minutes: 2
15
+ steps:
16
+ - name: Record review event
17
+ run: echo 'Recorded a weighted approval review event.'
.github/workflows/weighted-approval.yml ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: weighted-approval
2
+
3
+ on:
4
+ pull_request_target:
5
+ types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]
6
+ workflow_run:
7
+ workflows: [weighted-approval-review-event]
8
+ types: [completed]
9
+
10
+ permissions:
11
+ contents: read
12
+ pull-requests: read
13
+ statuses: write
14
+
15
+ concurrency:
16
+ group: weighted-approval-${{ github.event.pull_request.number || github.event.workflow_run.head_sha }}
17
+ cancel-in-progress: false
18
+
19
+ jobs:
20
+ publish-status:
21
+ if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success'
22
+ name: weighted approval publisher
23
+ runs-on: ubuntu-latest
24
+ timeout-minutes: 5
25
+ steps:
26
+ # SECURITY: the status-writing job executes policy from the trusted default
27
+ # branch and reads pull-request reviews only as API data.
28
+ - name: Check out trusted approval policy
29
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
30
+ with:
31
+ ref: ${{ github.event.repository.default_branch }}
32
+ persist-credentials: false
33
+ - name: Publish weighted approval status
34
+ env:
35
+ GITHUB_TOKEN: ${{ github.token }}
36
+ GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
37
+ run: node .github/review-ownership/check-approval.mjs
apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"type":"session","version":3,"id":"{{sessionId}}","createdAt":0,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0}
2
+ {"type":"turn/start","data":{"turn":1}}
3
+ {"type":"step/start","data":{"turn":1,"step":1}}
4
+ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
5
+ {"type":"user/message","data":{"content":[{"type":"text","text":"Perform one side-effecting remote mutation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
6
+ {"type":"assistant/message","data":{"turn":1,"step":1,"stream":[],"message":{"role":"assistant","content":[{"type":"tool-call","id":"unknown-outcome-call","name":"write_remote","arguments":"{\"value\":1}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
7
+ {"type":"tool/call","data":{"turn":1,"step":1,"callId":"unknown-outcome-call","name":"write_remote","arguments":"{\"value\":1}"}}
8
+ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"id":"interrupted-tool-result-unknown-outcome-call-6","role":"user","source":{"kind":"tool","callId":"unknown-outcome-call"},"content":[{"type":"tool-result","toolCallId":"unknown-outcome-call","isError":true,"content":[{"type":"text","text":"The tool call was interrupted after it was recorded, but no result was durably recorded. Its outcome is unknown. Decide whether to retry from the tool semantics: retry only if the operation is read-only or idempotent; if it may have side effects, first verify external state or ask the user. Do not retry blindly."}]}]},"error":{"name":"ToolOutcomeUnknownError","code":"TOOL_OUTCOME_UNKNOWN"}},"surfaceOp":"append","sourceEventSeqs":[5]}
9
+ {"type":"step/end","data":{"turn":1,"step":1}}
10
+ {"type":"turn/end","data":{"turn":1,"reason":{"kind":"interrupted"}}}
11
+ {"type":"session/end-seed","data":{}}
12
+ {"type":"permission/preset","data":{"preset":"workspace-write"}}
13
+ {"type":"sandbox/mode","data":{"mode":"workspace-write"}}
14
+ {"type":"approval/policy","data":{"policy":"ask"}}
15
+ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}}
16
+ {"type":"turn/start","data":{"turn":2}}
17
+ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
18
+ {"type":"step/start","data":{"turn":2,"step":1}}
19
+ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
20
+ {"type":"user/message","data":{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
21
+ {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
22
+ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
23
+ {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
24
+ {"type":"session/title","data":{"title":"Perform one side-effecting remote mutati","messageSeqs":[3],"source":{"kind":"fallback"}}}
25
+ {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"I will verify the external state before deciding whether to retry the side-effecting operation."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["I will verify the external state before deciding whether to retry the side-effecting operation."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"I will verify the external state before deciding whether to retry the side-effecting operation."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}
26
+ {"type":"step/end","data":{"turn":2,"step":1}}
27
+ {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}}
apps/web/tests/expected/agent-preset-authoring/copy-dialog.expected.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - dialog "复制预设 · 复制自 极简模式":
2
+ - heading "复制预设 · 复制自 极简模式" [level=2]
3
+ - button "关闭":
4
+ - img
5
+ - paragraph: 整个预设会在本机复制一份。标识符将成为目录名,事后无法更改;其余内容之后直接在预设自己的文件里编辑。
6
+ - text: 标识符
7
+ - textbox "标识符":
8
+ - /placeholder: my-agent
9
+ - text: 名称
10
+ - textbox "名称":
11
+ - /placeholder: 选择器中显示的名字,缺省用标识符
12
+ - alert: 请填写标识符。
13
+ - button "取消"
14
+ - button "创建" [disabled]
apps/web/tests/expected/agent-preset-authoring/created.expected.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - dialog "设置":
2
+ - navigation:
3
+ - text: 设置
4
+ - button "通用设置":
5
+ - img
6
+ - text: 通用设置
7
+ - button "模型":
8
+ - img
9
+ - text: 模型
10
+ - button "插件":
11
+ - img
12
+ - text: 插件
13
+ - button "Agent 预设":
14
+ - img
15
+ - text: Agent 预设
16
+ - button "已归档会话":
17
+ - img
18
+ - text: 已归档会话
19
+ - button "打开配置文件"
20
+ - button "关闭":
21
+ - img
22
+ - text: 关闭
23
+ - heading "Agent 预设" [level=2]
24
+ - paragraph: 预设即一个会话的 Agent 所运行的插件组装 —— 它的工具、提示词与能力。复制一份既有预设改成自己的,或用「创造模式」让 Agent 帮你创建。
25
+ - text: 允许切换agent模式 beta
26
+ - paragraph: 开启后,新任务可选择标准、PTC、创造、极简及自定义模式;关闭后统一使用默认模式(默认为标准模式,可自定义)。仅影响新任务。
27
+ - switch "允许切换agent模式" [checked]
28
+ - heading "内置" [level=3]
29
+ - list:
30
+ - listitem:
31
+ - 'button "新任务默认: 标准模式" [disabled] [pressed]':
32
+ - text: 标准模式 内置 新任务默认 功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。
33
+ - code: standard
34
+ - 'button "查看: 标准模式"':
35
+ - img
36
+ - text: 查看
37
+ - 'button "复制: 标准模式"':
38
+ - img
39
+ - text: 复制
40
+ - listitem:
41
+ - 'button "设为默认: PTC 模式"':
42
+ - text: PTC 模式 内置 功能完整的编码 Agent,但默认不提供 workflow 工具;其他工具通过 PTC 模式 SDK 呈现,让模型用一个 TypeScript 程序组合多步操作。
43
+ - code: ptc
44
+ - 'button "查看: PTC 模式"':
45
+ - img
46
+ - text: 查看
47
+ - 'button "复制: PTC 模式"':
48
+ - img
49
+ - text: 复制
50
+ - listitem:
51
+ - 'button "设为默认: 极简模式"':
52
+ - text: 极简模式 内置 仅提供持久 shell 的单工具编码 Agent。
53
+ - code: minimal
54
+ - 'button "查看: 极简模式"':
55
+ - img
56
+ - text: 查看
57
+ - 'button "复制: 极简模式"':
58
+ - img
59
+ - text: 复制
60
+ - listitem:
61
+ - 'button "设为默认: 创造模式"':
62
+ - text: 创造模式 内置 用于创建自定义 Agent preset:具备标准模式的全部能力,并提供运行时检查、插件实验和 preset 创作指导。
63
+ - code: cordis
64
+ - 'button "查看: 创造模式"':
65
+ - img
66
+ - text: 查看
67
+ - 'button "复制: 创造模式"':
68
+ - img
69
+ - text: 复制
70
+ - heading "自定义" [level=3]
71
+ - list:
72
+ - listitem:
73
+ - 'button "设为默认: 我的模式"':
74
+ - text: 我的模式 自定义 仅提供持久 shell 的单工具编码 Agent。
75
+ - code: my-agent
76
+ - 'button "查看路径: 我的模式"':
77
+ - img
78
+ - text: 查看路径
79
+ - 'button "复制: 我的模式"':
80
+ - img
81
+ - text: 复制
82
+ - 'button "删除: 我的模式"':
83
+ - img
84
+ - text: 删除
85
+ - paragraph:
86
+ - text: 预设文件:
87
+ - code: {{presetRoot}}/my-agent
88
+ - button "用「创造模式」创作自定义预设":
89
+ - img
90
+ - text: 用「创造模式」创作自定义预设
apps/web/tests/expected/agent-preset-authoring/damaged.expected.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - dialog "设置":
2
+ - navigation:
3
+ - text: 设置
4
+ - button "通用设置":
5
+ - img
6
+ - text: 通用设置
7
+ - button "模型":
8
+ - img
9
+ - text: 模型
10
+ - button "插件":
11
+ - img
12
+ - text: 插件
13
+ - button "Agent 预设":
14
+ - img
15
+ - text: Agent 预设
16
+ - button "已归档会话":
17
+ - img
18
+ - text: 已归档会话
19
+ - button "打开配置文件"
20
+ - button "关闭":
21
+ - img
22
+ - text: 关闭
23
+ - heading "Agent 预设" [level=2]
24
+ - paragraph: 预设即一个会话的 Agent 所运行的插件组装 —— 它的工具、提示词与能力。复制一份既有预设改成自己的,或用「创造模式」让 Agent 帮你创建。
25
+ - text: 允许切换agent模式 beta
26
+ - paragraph: 开启后,新任务可选择标准、PTC、创造、极简及自定义模式;关闭后统一使用默认模式(默认为标准模式,可自定义)。仅影响新任务。
27
+ - switch "允许切换agent模式" [checked]
28
+ - heading "内置" [level=3]
29
+ - list:
30
+ - listitem:
31
+ - 'button "新任务默认: 标准模式" [disabled] [pressed]':
32
+ - text: 标准模式 内置 新任务默认 功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。
33
+ - code: standard
34
+ - 'button "查看: 标准模式"':
35
+ - img
36
+ - text: 查看
37
+ - 'button "复制: 标准模式"':
38
+ - img
39
+ - text: 复制
40
+ - listitem:
41
+ - 'button "设为默认: PTC 模式"':
42
+ - text: PTC 模式 内置 功能完整的编码 Agent,但默认不提供 workflow 工具;其他工具通过 PTC 模式 SDK 呈现,让模型用一个 TypeScript 程序组合多步操作。
43
+ - code: ptc
44
+ - 'button "查看: PTC 模式"':
45
+ - img
46
+ - text: 查看
47
+ - 'button "复制: PTC 模式"':
48
+ - img
49
+ - text: 复制
50
+ - listitem:
51
+ - 'button "设为默认: 极简模式"':
52
+ - text: 极简模式 内置 仅提供持久 shell 的单工具编码 Agent。
53
+ - code: minimal
54
+ - 'button "查看: 极简模式"':
55
+ - img
56
+ - text: 查看
57
+ - 'button "复制: 极简模式"':
58
+ - img
59
+ - text: 复制
60
+ - listitem:
61
+ - 'button "设为默认: 创造模式"':
62
+ - text: 创造模式 内置 用于创建自定义 Agent preset:具备标准模式的全部能力,并提供运行时检查、插件实验和 preset 创作指导。
63
+ - code: cordis
64
+ - 'button "查看: 创造模式"':
65
+ - img
66
+ - text: 查看
67
+ - 'button "复制: 创造模式"':
68
+ - img
69
+ - text: 复制
70
+ - heading "自定义" [level=3]
71
+ - list:
72
+ - listitem:
73
+ - 'button "加载失败: broken-yaml" [disabled]':
74
+ - text: broken-yaml 加载失败 自定义 暂无描述。
75
+ - alert: "the composition is not valid YAML: unexpected end of the stream within a flow collection (3:1)"
76
+ - code: broken-yaml
77
+ - 'button "查看路径: broken-yaml"':
78
+ - img
79
+ - text: 查看路径
80
+ - 'button "复制: broken-yaml" [disabled]':
81
+ - img
82
+ - text: 预设加载失败,不能复制
83
+ - 'button "删除: broken-yaml"':
84
+ - img
85
+ - text: 删除
86
+ - listitem:
87
+ - 'button "加载失败: 幽灵预设" [disabled]':
88
+ - text: 幽灵预设 加载失败 自定义 composition 已被手动删除。
89
+ - alert: the composition file agent.cordis.yml is missing — the directory still occupies the id; delete it or restore the file
90
+ - code: ghost
91
+ - 'button "查看路径: 幽灵预设"':
92
+ - img
93
+ - text: 查看路径
94
+ - 'button "复制: 幽灵预设" [disabled]':
95
+ - img
96
+ - text: 预设加载失败,不能复制
97
+ - 'button "删除: 幽灵预设"':
98
+ - img
99
+ - text: 删除
100
+ - button "用「创造模式」创作自定义预设":
101
+ - img
102
+ - text: 用「创造模式」创作自定义预设
apps/web/tests/expected/agent-preset-authoring/section.expected.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - dialog "设置":
2
+ - navigation:
3
+ - text: 设置
4
+ - button "通用设置":
5
+ - img
6
+ - text: 通用设置
7
+ - button "模型":
8
+ - img
9
+ - text: 模型
10
+ - button "插件":
11
+ - img
12
+ - text: 插件
13
+ - button "Agent 预设":
14
+ - img
15
+ - text: Agent 预设
16
+ - button "已归档会话":
17
+ - img
18
+ - text: 已归档会话
19
+ - button "打开配置文件"
20
+ - button "关闭":
21
+ - img
22
+ - text: 关闭
23
+ - heading "Agent 预设" [level=2]
24
+ - paragraph: 预设即一个会话的 Agent 所运行的插件组装 —— 它的工具、提示词与能力。复制一份既有预设改成自己的,或用「创造模式」让 Agent 帮你创建。
25
+ - text: 允许切换agent模式 beta
26
+ - paragraph: 开启后,新任务可选择标准、PTC、创造、极简及自定义模式;关闭后统一使用默认模式(默认为标准模式,可自定义)。仅影响新任务。
27
+ - switch "允许切换agent模式" [checked]
28
+ - heading "内置" [level=3]
29
+ - list:
30
+ - listitem:
31
+ - 'button "新任务默认: 标准模式" [disabled] [pressed]':
32
+ - text: 标准模式 内置 新任务默认 功能完整的编码 Agent,支持文件编辑、Shell、文件与网页检索、Skills、计划、目标、子代理和工作流。
33
+ - code: standard
34
+ - 'button "查看: 标准模式"':
35
+ - img
36
+ - text: 查看
37
+ - 'button "复制: 标准模式"':
38
+ - img
39
+ - text: 复制
40
+ - listitem:
41
+ - 'button "设为默认: PTC 模式"':
42
+ - text: PTC 模式 内置 功能完整的编码 Agent,但默认不提供 workflow 工具;其他工具通过 PTC 模式 SDK 呈现,让模型用一个 TypeScript 程序组合多步操作。
43
+ - code: ptc
44
+ - 'button "查看: PTC 模式"':
45
+ - img
46
+ - text: 查看
47
+ - 'button "复制: PTC 模式"':
48
+ - img
49
+ - text: 复制
50
+ - listitem:
51
+ - 'button "设为默认: 极简模式"':
52
+ - text: 极简模式 内置 仅提供持久 shell 的单工具编码 Agent。
53
+ - code: minimal
54
+ - 'button "查看: 极简模式"':
55
+ - img
56
+ - text: 查看
57
+ - 'button "复制: 极简模式"':
58
+ - img
59
+ - text: 复制
60
+ - listitem:
61
+ - 'button "设为默认: 创造模式"':
62
+ - text: 创造模式 内置 用于创建自定义 Agent preset:具备标准模式的全部能力,并提供运行时检查、插件实验和 preset 创作指导。
63
+ - code: cordis
64
+ - 'button "查看: 创造模式"':
65
+ - img
66
+ - text: 查看
67
+ - 'button "复制: 创造模式"':
68
+ - img
69
+ - text: 复制
70
+ - heading "自定义" [level=3]
71
+ - button "用「创造模式」创作自定义预设":
72
+ - img
73
+ - text: 用「创造模式」创作自定义预设
apps/web/tests/expected/agent-preset-selection/header.expected.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - navigation "Session hierarchy":
2
+ - button "Seeded turn" [disabled]
3
+ - text: /
4
+ - button "1 subagent":
5
+ - text: 1 subagent
6
+ - img
7
+ - img
8
+ - text: Minimal mode
9
+ - button "More actions":
10
+ - img
11
+ - button "Open right sidebar":
12
+ - img
apps/web/tests/expected/agent-preset-selection/hero.expected.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ - button "Choose workspace":
2
+ - img
3
+ - text: workspace
4
+ - img
5
+ - button "Standard mode":
6
+ - img
7
+ - text: Standard mode
8
+ - img
apps/web/tests/expected/agent-preset-selection/menu.expected.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ - menu:
2
+ - menuitem "Standard mode Full coding agent with file editing, shell, file and web search, skills, planning, goals, subagents, and workflows.":
3
+ - text: Standard mode Full coding agent with file editing, shell, file and web search, skills, planning, goals, subagents, and workflows.
4
+ - img
5
+ - menuitem "PTC mode Full coding agent without the workflow tool; other tools are exposed through the PTC mode SDK so the model can combine multi-step operations in one TypeScript program."
6
+ - menuitem "Minimal mode Single-tool coding agent with a persistent shell."
7
+ - menuitem "Creator mode Built for creating custom agent presets, with all Standard mode capabilities plus runtime inspection, plugin experiments, and preset-authoring guidance."
8
+ - menuitem "Refusing mode Resolves, then refuses to start."