bailinghub 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/.dockerignore +6 -0
  2. package/.npmignore +6 -0
  3. package/CONTRIBUTING.md +4 -0
  4. package/GOVERNANCE.md +9 -0
  5. package/README.en.md +7 -6
  6. package/README.md +7 -6
  7. package/SECURITY.md +8 -2
  8. package/THIRD_PARTY_NOTICES.md +17 -17
  9. package/docker-compose.images.yml +2 -2
  10. package/docs/CHANGELOG.en.md +11 -1
  11. package/docs/CHANGELOG.md +11 -1
  12. package/docs/COMPATIBILITY.en.md +4 -0
  13. package/docs/IMPLEMENTATION_STATUS.en.md +73 -0
  14. package/docs/IMPLEMENTATION_STATUS.md +73 -0
  15. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  16. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  17. package/docs/KERNEL_HOST_API.en.md +18 -0
  18. package/docs/KERNEL_HOST_API.md +18 -0
  19. package/docs/README.en.md +3 -0
  20. package/docs/README.md +3 -0
  21. package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
  22. package/docs/RELEASE_NOTES_NEXT.md +3 -3
  23. package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
  24. package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
  25. package/docs/UPGRADE_v0.9.1.en.md +39 -0
  26. package/docs/UPGRADE_v0.9.1.md +39 -0
  27. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
  28. package/package.json +5 -4
  29. package/scripts/check-doc-links.mjs +2 -0
  30. package/scripts/check-image-tags.sh +1 -1
  31. package/scripts/check-release-consistency.test.mjs +2 -2
  32. package/scripts/dependency-audit.mjs +134 -0
  33. package/scripts/dependency-audit.test.mjs +125 -0
  34. package/scripts/install.sh +1 -1
  35. package/scripts/osps-results.py +114 -0
  36. package/scripts/publish-images.sh +1 -1
  37. package/scripts/release-audit.mjs +1 -0
  38. package/scripts/verify-github-repo.mjs +1 -0
  39. package/security/dependency-audit-exceptions.json +192 -0
  40. package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
  41. package/src/app/kernel.ts +10 -0
  42. package/src/modules/usage/background-work.test.ts +144 -0
  43. package/src/modules/usage/background-work.ts +50 -0
  44. package/src/modules/usage/billing-repository.ts +6 -4
  45. package/src/modules/usage/model-gateway.ts +10 -3
  46. package/src/modules/usage/model-tool-gateway.mysql.test.ts +1 -1
  47. package/src/modules/usage/pricing.ts +3 -2
  48. package/src/modules/usage/repository.ts +2 -0
  49. package/src/modules/usage/test-harness.ts +2 -1
  50. package/web/console/assets/{Accounts-DnddhY6t.js → Accounts-DKhw_QLr.js} +1 -1
  51. package/web/console/assets/{AgentClients-VInbD7JS.js → AgentClients-CM4_5HaA.js} +1 -1
  52. package/web/console/assets/{AgentTasks-B-1XklBg.js → AgentTasks-CkQgZTU5.js} +1 -1
  53. package/web/console/assets/{Approvals-34qUPHf0.js → Approvals-B9O9TkbO.js} +1 -1
  54. package/web/console/assets/{Audit-BbVgkSm2.js → Audit-2vDC1SPu.js} +1 -1
  55. package/web/console/assets/{BrandLockup-DgscF28e.js → BrandLockup-BgASiRSE.js} +1 -1
  56. package/web/console/assets/{Channels-Bp-yuk8d.js → Channels-A-GvkNBt.js} +1 -1
  57. package/web/console/assets/{ChatEntries-C9Ft60TS.js → ChatEntries-BLxymI67.js} +1 -1
  58. package/web/console/assets/{Clients-NPldD-DD.js → Clients-DeNlmvS6.js} +1 -1
  59. package/web/console/assets/{Cost-DZcuB-EB.js → Cost-CBq_L4Kz.js} +1 -1
  60. package/web/console/assets/{Credentials-RTT7N6zl.js → Credentials-DmtbctNj.js} +1 -1
  61. package/web/console/assets/{Diagnostics-_LeK8cce.js → Diagnostics-BbcRDiA-.js} +1 -1
  62. package/web/console/assets/{Executors-Bi7H8rIm.js → Executors-gGgmQrDt.js} +1 -1
  63. package/web/console/assets/{HelpTip-BfyWrxCE.js → HelpTip-Dtdt2tKR.js} +1 -1
  64. package/web/console/assets/{Kb-BHamz8NP.js → Kb-lgY6OXUz.js} +2 -2
  65. package/web/console/assets/{Login-C1rJR-6w.js → Login-DA6BASZd.js} +1 -1
  66. package/web/console/assets/{Projects-BRA4a48v.js → Projects-DEbmB_sT.js} +1 -1
  67. package/web/console/assets/{Routes-CTC7U-fQ.js → Routes-qS6LLoyS.js} +1 -1
  68. package/web/console/assets/{Runs-B_fa_BlD.js → Runs-DG-VLRSc.js} +1 -1
  69. package/web/console/assets/{Setup-C1_d0mFy.js → Setup-DEpVF5uw.js} +1 -1
  70. package/web/console/assets/{Shell-CHEV6RGC.js → Shell-DgoPgK1E.js} +1 -1
  71. package/web/console/assets/{StorageBuckets-DlG3ojhA.js → StorageBuckets-DJtNN769.js} +1 -1
  72. package/web/console/assets/{SystemSettings-DYo2gg6d.js → SystemSettings-0DEUgeTR.js} +1 -1
  73. package/web/console/assets/{SystemStatus-DKCoUZlq.js → SystemStatus-CR1phiPE.js} +1 -1
  74. package/web/console/assets/{Targets-CdkG6BPR.js → Targets-D65l-IMB.js} +1 -1
  75. package/web/console/assets/{Tools-DVpCt0ox.js → Tools-DqtrINrN.js} +1 -1
  76. package/web/console/assets/{Usage-DWCpLugC.js → Usage-B5njXNjx.js} +1 -1
  77. package/web/console/assets/{UsageAccess-B_Xq7ARW.js → UsageAccess-ChnB4pjb.js} +1 -1
  78. package/web/console/assets/{UsageHelp-t5ZG_f-e.js → UsageHelp-BBKIvbQ5.js} +1 -1
  79. package/web/console/assets/{index-C6W4LWVV.js → index-65JiiUr4.js} +1 -1
  80. package/web/console/assets/{index-H1kfa0Mj.js → index-sLKrJd_p.js} +2 -2
  81. package/web/console/assets/{request-DLsP1_ot.js → request-BpaimqEb.js} +1 -1
  82. package/web/console/assets/{schema-BLOHvAJQ.js → schema-D0Z4kFCZ.js} +1 -1
  83. package/web/console/assets/{util-CGVh2Jvr.js → util-DZYfJ5Zo.js} +1 -1
  84. package/web/console/assets/{vendor-element-BD089KxE.js → vendor-element-8cVcdt5T.js} +1 -1
  85. package/web/console/assets/{vendor-mammoth-Bv-CZhmH.js → vendor-mammoth-CnDA23N0.js} +1 -1
  86. package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
  87. package/web/console/index.html +3 -3
  88. package/web-admin/package-lock.json +83 -85
  89. package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
@@ -7,7 +7,7 @@
7
7
  ## 验证范围
8
8
 
9
9
  - 验证对象:BailingHub 开源版 Docker demo;
10
- - 稳定基线:`v0.9.0`;
10
+ - 稳定基线:`v0.9.1`;
11
11
  - 数据范围:仓库自带的 demo 订单、工单、退款和故障工具;
12
12
  - 预计用时:镜像和依赖下载完成后约 20 分钟;
13
13
  - 不需要:真实大模型 Key、生产 API、生产凭据或真实业务数据。
@@ -32,7 +32,7 @@ curl -fsSL https://www.bailinghub.com/install.sh | sh
32
32
  cd "$HOME/bailinghub"
33
33
  ```
34
34
 
35
- 脚本默认拉取 `v0.9.0` 官方镜像,生成随机 Token 与后台密码,启动服务并自动运行基础体检。首次管理员只在数据库管理员表为空时创建;对同一持久化数据库进行重启、升级、容器重建或重新安装,不会覆盖已经修改的管理员密码。可选 `/metrics` 端点默认关闭,不影响基础验证。请保留终端输出中的版本、安装模式、耗时和“常用命令”,但不要把密码或 Token 写入反馈。新安装 Docker 后,当前非 root 会话通常仍需使用脚本打印的 `sudo docker compose ...` 命令;重新登录后 Docker 组权限才可能生效。
35
+ 脚本默认拉取 `v0.9.1` 官方镜像,生成随机 Token 与后台密码,启动服务并自动运行基础体检。首次管理员只在数据库管理员表为空时创建;对同一持久化数据库进行重启、升级、容器重建或重新安装,不会覆盖已经修改的管理员密码。可选 `/metrics` 端点默认关闭,不影响基础验证。请保留终端输出中的版本、安装模式、耗时和“常用命令”,但不要把密码或 Token 写入反馈。新安装 Docker 后,当前非 root 会话通常仍需使用脚本打印的 `sudo docker compose ...` 命令;重新登录后 Docker 组权限才可能生效。
36
36
 
37
37
  如果默认目录已被占用,请使用一个新的空目录,不要覆盖现有部署:
38
38
 
@@ -46,7 +46,7 @@ cd "$HOME/bailinghub-validation"
46
46
  ### 路径 B:本地源码复现
47
47
 
48
48
  ```bash
49
- git clone --depth 1 --branch v0.9.0 https://github.com/bailinghub/bailinghub.git
49
+ git clone --depth 1 --branch v0.9.1 https://github.com/bailinghub/bailinghub.git
50
50
  cd bailinghub
51
51
  git rev-parse HEAD
52
52
  export BAILING_TOKEN="$(openssl rand -hex 32)"
@@ -167,7 +167,7 @@ docker compose exec -T bailinghub npm run demo:e2e
167
167
  - [可信富内容渲染与聊天可靠性](RELEASE_NOTES_v0.1.15.md)。
168
168
  - [工具运行时收敛与语义检索韧性](RELEASE_NOTES_v0.1.16.md)。
169
169
  - [可组合 Core 与 Kernel Host API v1](RELEASE_NOTES_v0.3.0.md)。
170
- - [当前稳定版发布说明](RELEASE_NOTES_v0.9.0.md)。
170
+ - [当前稳定版发布说明](RELEASE_NOTES_v0.9.1.md)。
171
171
 
172
172
  扩展验证请在同一 Issue 模板中选择对应路径,并说明是否获得过维护者的直接帮助。
173
173
 
@@ -46,6 +46,24 @@ await kernel.close(30_000);
46
46
 
47
47
  Managed mode does not create a full timer set per Kernel. The host must call `tick()` fairly and call `close()` during eviction, upgrade, or process shutdown. The 0-600000 ms `close(drainMs)` budget covers initialization, in-flight maintenance/ticks, HTTP, InHub, and execution-queue drain; after drain, Core also clears Kernel-owned transient credential caches such as WeCom access tokens. A timeout preserves the original instance dependencies and reports an error, so the host can retry on that same instance or alert. New `initialize()` and `tick()` calls cannot reopen resources after closing begins.
48
48
 
49
+ ### Usage background drain: Core v0.9.1
50
+
51
+ [Core v0.9.1](RELEASE_NOTES_v0.9.1.en.md) adds usage background work to that close budget. **The formal v0.9.0 Tag does not contain this shutdown fix**. Each Kernel's `UsageRepository` owns a separate [background-work tracker](../src/modules/usage/background-work.ts), covering model-tool completion, settlement, response cleanup, pending-usage reconciliation, and reference-price refresh through persistence.
52
+
53
+ `close()` first blocks new Kernel HTTP admission and waits for accepted HTTP handlers, InHub, and execution queues to finish registering work. It then stops new model requests and maintenance/price refresh for that repository, and dynamically waits for accepted background work. An accepted model-tool completion may register a settlement child after drain starts; that child must also finish before resources close. Asynchronous model tools still promptly return the original pending state/HTTP 202. This revision does not make the first response wait for image-provider completion.
54
+
55
+ All stages share the original `drainMs` deadline rather than receiving a fresh full budget each. A usage-drain timeout reports an error, keeps the Kernel closing and its dependencies intact, and skips subsequent resource closure. The host can wait for the original work and retry `close()` on **the same instance**. A timeout never authorizes a fresh model dispatch or business write. Successful drain establishes that registered work has ended, not that every billing record is settled; failed work may retain durable pending/unknown evidence for later reconciliation. Diagnostics report fixed work categories without provider bodies or raw SQL errors.
56
+
57
+ The [tracker unit tests](../src/modules/usage/background-work.test.ts) check registration before execution, late children, stopped maintenance, timeout/retry, isolation between two owners, and failure cleanup/fixed-category diagnostics. Those two unit-test owners are not two actual Kernels or databases. The public [Kernel + MySQL lifecycle tests](../src/app/kernel-usage-lifecycle.mysql.test.ts) use actual Kernels, separate test schemas, and synthetic providers to assert:
58
+
59
+ - delayed model-tool completion, late settlement, real SQL-lock waits, resource preservation on timeouts, and same-instance retry;
60
+ - ordinary text-model delivery before asynchronous settlement, close waiting for that settlement, and standalone shutdown draining before exit;
61
+ - work/resource isolation between two Kernels using the same original request ID, one original dispatch, and one settlement-ledger record;
62
+ - response cleanup and usage reconciliation each independently blocking close, reference-price refresh through SQL persistence, and stopped new maintenance;
63
+ - settlement failure retaining the original result and durable pending evidence, later reconciliation without provider redispatch, and diagnostics excluding raw errors.
64
+
65
+ The database tests explicitly require `BAILING_USAGE_TEST_MYSQL=1`. Their existence, or a default run that skips them, does not establish a passing database run or live-provider, process-crash recovery, or production-host acceptance. See the [capability/evidence index](IMPLEMENTATION_STATUS.en.md) for the historical v0.9.0 limitation.
66
+
49
67
  Multiple Kernels may share `KernelExecutionQueueV1` as a process-wide concurrency ceiling. This v1 wrapper exposes only `run()` to the Host; admission, statistics, and drain for each Kernel-local queue remain Core-owned. All Kernels in one process currently need the same `display_tz` and `display_tz_label`.
50
68
 
51
69
  ## Artifact And Schema Upgrades
@@ -46,6 +46,24 @@ await kernel.close(30_000);
46
46
 
47
47
  `managed` 模式不为每个 Kernel 创建完整定时器组;宿主必须公平调用 `tick()`,并在淘汰、升级或进程退出时调用 `close()`。`close(drainMs)` 的 0~600000 毫秒时限覆盖初始化、在途维护/tick、HTTP、InHub 与执行队列排空;排空后还会清理 Kernel 自己的企微令牌等瞬时凭证缓存。超时会保留原实例依赖并报错,宿主应在同一实例上重试或告警。`close()` 开始后的新 `initialize()` / `tick()` 不会重开资源。
48
48
 
49
+ ### usage 后台工作排空:Core v0.9.1
50
+
51
+ [Core v0.9.1](RELEASE_NOTES_v0.9.1.md) 在上述关闭时限内增加 usage 后台工作等待;**正式 v0.9.0 Tag 不包含这项关闭修复**。每个 Kernel 所使用的 `UsageRepository` 拥有独立的 [后台工作登记器](../src/modules/usage/background-work.ts),记录模型工具完成、结算、响应清理、待结算 usage 核对,以及参考价格刷新到持久化结束的工作。
52
+
53
+ `close()` 先阻止新的 Kernel HTTP 接入,并等待已接纳的 HTTP、InHub 与执行队列结束登记;随后停止该 repository 的新模型请求及新维护/价格刷新,再动态等待已有后台工作。已接纳的模型工具完成可以在关闭等待开始后登记其结算子工作,该子工作也须结束后才允许关闭资源。异步模型工具仍先返回原请求的 pending/HTTP 202;此修订不会让首次响应等待图片供应商完成。
54
+
55
+ 所有阶段共用原 `drainMs` 时限,而不是为每类工作增加新的完整时限。usage 排空超时会报错,保持 Kernel 的关闭状态并保留其依赖,不调用后续资源关闭。宿主可以等待原工作结束,再对**同一实例**重试 `close()`;不能把超时当作重新派发模型请求或业务写入的许可。成功排空只说明已登记工作已结束,不保证所有账本记录已经 settled;失败工作可保留 durable pending/unknown 证据供后续核对。日志只报告固定工作类别,不附供应商正文或原始 SQL 错误。
56
+
57
+ [登记器单元测试](../src/modules/usage/background-work.test.ts) 检查先登记后启动、晚登记子工作、维护停止、超时重试、两个 owner 的隔离,以及失败清理/固定类别诊断;这些单测的两个 owner 不是两个实际 Kernel 或数据库。[Kernel + MySQL 生命周期测试](../src/app/kernel-usage-lifecycle.mysql.test.ts) 则使用实际 Kernel、独立测试 schema 和模拟供应商,公开断言覆盖:
58
+
59
+ - 延迟模型工具完成、晚登记结算、真实 SQL 锁等待、超时保留资源与同实例重试;
60
+ - 普通文本模型先返回结果、关闭仍等待异步结算,以及 standalone shutdown 排空后才退出;
61
+ - 两个 Kernel 使用同一原请求标识时的工作/资源隔离,原请求单次派发和单条结算记录;
62
+ - 响应清理和 usage 核对分别单独阻挡关闭,以及参考价格刷新到 SQL 持久化、新维护停止;
63
+ - 结算失败仍保留原结果及 durable pending,后续核对不重派供应商请求,诊断不输出原始错误。
64
+
65
+ 数据库入口由 `BAILING_USAGE_TEST_MYSQL=1` 显式启用。测试源码存在或默认运行时被跳过,不代表实际数据库测试通过,也不代表真实供应商、进程崩溃恢复或生产宿主已完成验收。正式 v0.9.0 的历史限制另见 [能力与证据索引](IMPLEMENTATION_STATUS.md)。
66
+
49
67
  多个 Kernel 可以共享 `KernelExecutionQueueV1` 作为进程级并发上限。这个 v1 包装只向宿主暴露 `run()`;每个 Kernel 内部队列的接入、统计和排空仍由 Core 自己管理。当前同进程实例必须使用相同的 `display_tz` / `display_tz_label`。
50
68
 
51
69
  ## 制品与数据库升级
package/docs/README.en.md CHANGED
@@ -6,6 +6,9 @@ This directory contains public documentation for the open-source BailingHub proj
6
6
 
7
7
  | Document | Purpose |
8
8
  |---|---|
9
+ | [IMPLEMENTATION_STATUS.en.md](IMPLEMENTATION_STATUS.en.md) · [Chinese](IMPLEMENTATION_STATUS.md) | Core ownership, formal releases versus main, public evidence, and uncovered scope. |
10
+ | [RELEASE_NOTES_v0.9.1.en.md](RELEASE_NOTES_v0.9.1.en.md) · [Chinese](RELEASE_NOTES_v0.9.1.md) | v0.9.1: asynchronous usage shutdown fix, public capability index, and general security governance. |
11
+ | [UPGRADE_v0.9.1.en.md](UPGRADE_v0.9.1.en.md) · [Chinese](UPGRADE_v0.9.1.md) | 0.9.0 patch upgrade, original requests, artifact manifests, and shutdown acceptance; no new SQL/APIs. |
9
12
  | [RELEASE_NOTES_v0.9.0.en.md](RELEASE_NOTES_v0.9.0.en.md) · [Chinese](RELEASE_NOTES_v0.9.0.md) | v0.9.0: optional model billing, shared allowances and image tools. |
10
13
  | [UPGRADE_v0.9.0.en.md](UPGRADE_v0.9.0.en.md) · [Chinese](UPGRADE_v0.9.0.md) | Upgrade from public 0.8.0, migrations 063/064 and optional host integration. |
11
14
  | [MODEL_BILLING.en.md](MODEL_BILLING.en.md) · [Chinese](MODEL_BILLING.md) | Models/tools, reference prices, asynchronous settlement, archive and allowance reset contract. |
package/docs/README.md CHANGED
@@ -8,6 +8,9 @@
8
8
 
9
9
  | 文档 | 用途 |
10
10
  |---|---|
11
+ | [IMPLEMENTATION_STATUS.md](IMPLEMENTATION_STATUS.md) · [English](IMPLEMENTATION_STATUS.en.md) | Core 能力归属、正式发行与主分支状态、公开证据和未覆盖范围。 |
12
+ | [RELEASE_NOTES_v0.9.1.md](RELEASE_NOTES_v0.9.1.md) · [English](RELEASE_NOTES_v0.9.1.en.md) | v0.9.1:异步 usage 关闭修复、公开能力索引与通用安全治理。 |
13
+ | [UPGRADE_v0.9.1.md](UPGRADE_v0.9.1.md) · [English](UPGRADE_v0.9.1.en.md) | 0.9.0 补丁升级、原请求核对、制品 manifest 与关闭验收;无新增 SQL/API。 |
11
14
  | [RELEASE_NOTES_v0.9.0.md](RELEASE_NOTES_v0.9.0.md) · [English](RELEASE_NOTES_v0.9.0.en.md) | v0.9.0:可选模型计费、统一套餐额度与文生图工具。 |
12
15
  | [UPGRADE_v0.9.0.md](UPGRADE_v0.9.0.md) · [English](UPGRADE_v0.9.0.en.md) | 从公开 0.8.0 升级、063/064 迁移及宿主按需接入。 |
13
16
  | [MODEL_BILLING.md](MODEL_BILLING.md) · [English](MODEL_BILLING.en.md) | 模型与工具、参考价格、异步结算、账户归档和额度重置契约。 |
@@ -1,5 +1,5 @@
1
- # Current release: Core 0.9.0
1
+ # Current release: Core 0.9.1
2
2
 
3
- Core 0.9.0 introduces an optional model billing gateway, shared USD plans, periodic allowances and text-to-image tools. Release pairing: SDK 0.7.0 / DSH 0.7.0.
3
+ Core 0.9.1 fixes asynchronous usage shutdown, adds a public capability/evidence index, and includes general security governance. No new APIs, SQL, plan rules, or client features are introduced. SDK 0.7.0 / DSH 0.7.0 remain unchanged.
4
4
 
5
- [Core 0.9.0 release notes](RELEASE_NOTES_v0.9.0.en.md) · [Upgrade guide](UPGRADE_v0.9.0.en.md) · [Billing contract](MODEL_BILLING.en.md) · [简体中文](RELEASE_NOTES_NEXT.md)
5
+ [Core 0.9.1 release notes](RELEASE_NOTES_v0.9.1.en.md) · [Upgrade guide](UPGRADE_v0.9.1.en.md) · [Billing contract](MODEL_BILLING.en.md) · [简体中文](RELEASE_NOTES_NEXT.md)
@@ -1,5 +1,5 @@
1
- # 当前版本:Core 0.9.0
1
+ # 当前版本:Core 0.9.1
2
2
 
3
- Core 0.9.0 提供可选模型计费网关、统一 USD 套餐、周期额度与文生图工具。配套为 SDK 0.7.0 / DSH 0.7.0。
3
+ Core 0.9.1 修复异步 usage 工作关闭等待,增加公开能力与证据索引,并纳入通用安全治理。没有新增 API、SQL、套餐或客户端功能;SDK 0.7.0 / DSH 0.7.0 不变。
4
4
 
5
- [Core 0.9.0 版本说明](RELEASE_NOTES_v0.9.0.md) · [升级指南](UPGRADE_v0.9.0.md) · [计费契约](MODEL_BILLING.md) · [English](RELEASE_NOTES_NEXT.en.md)
5
+ [Core 0.9.1 版本说明](RELEASE_NOTES_v0.9.1.md) · [升级指南](UPGRADE_v0.9.1.md) · [计费契约](MODEL_BILLING.md) · [English](RELEASE_NOTES_NEXT.en.md)
@@ -0,0 +1,38 @@
1
+ # v0.9.1: asynchronous model shutdown and public capability evidence
2
+
3
+ [中文版](RELEASE_NOTES_v0.9.1.md)
4
+
5
+ After an assistant requests an image, the Hub promptly returns the original request's pending state. Provider completion and usage settlement follow later. If a host evicts an instance, upgrades, or exits at that point, a finished HTTP request does not mean its background work is finished.
6
+
7
+ Core 0.9.1 fixes that shutdown boundary by waiting for the original instance's usage background work and subsequent settlement before closing resources. It also includes a public capability index and general security governance already on main. This is a patch release with **no new HTTP/API, SQL migration, plan rule, client feature, or SDK/DSH release**.
8
+
9
+ ## Shutdown fix
10
+
11
+ - Each `UsageRepository` separately registers model-tool completion, settlement after ordinary model responses, response cleanup, pending-usage reconciliation, and reference-price refresh through persistence.
12
+ - Kernel stops new HTTP admission and waits for foreground handlers, InHub, and execution queues to finish registering work. It then stops new usage work/maintenance and dynamically drains accepted completion and late settlement children before resource closure.
13
+ - All stages share the original `close(drainMs)` deadline. A usage-drain timeout preserves the original dependencies and closing state for same-instance retry; it does not redispatch a model request or business write.
14
+ - Image requests still promptly return HTTP 202. Ordinary text results also arrive before financial settlement. Original `operation_id` values, separate result/billing states, business authority, approvals, and unknown-outcome handling remain unchanged.
15
+ - Failed background work can retain durable pending/unknown evidence. Completed drain does not guarantee every record is settled or provide process-crash recovery or provider-task recovery.
16
+
17
+ The formal v0.9.0 close path did not explicitly register these usage continuations. Its Tag and existing artifacts remain unchanged; this fix does not rewrite their historical guarantees. See the [Kernel Host API](KERNEL_HOST_API.en.md) and [capability/evidence index](IMPLEMENTATION_STATUS.en.md).
18
+
19
+ ## Public documentation and general security governance
20
+
21
+ The new Chinese/English capability index separates Core, business-system, local-host, and independent-adapter responsibilities, release facts, public test/reproduction paths, and uncovered scope. Thread context, visible conversation audits, and complete user-level long-term memory remain distinct. Existing tests are not presented as production adoption.
22
+
23
+ This release also includes dependency auditing with explicit exception checks, pinned GitHub Actions sources and minimal permissions, dependency-update and repository scanning configuration, plus public security self-assessments and Security Insights metadata. Assessments/metadata are repository governance and excluded from npm runtime packages and Docker build contents. Their existence does not establish that every control passes or that no residual risks remain.
24
+
25
+ ## Upgrade impact
26
+
27
+ - Upgrading public Core 0.9.0 adds no SQL files and changes no existing migrations. Earlier versions still require their outstanding migrations; see the [upgrade guide](UPGRADE_v0.9.1.en.md).
28
+ - USD allowances, the uniform multiplier, periodic price/allowance, model catalogs, and business-governance contracts remain unchanged. This patch does not require new plan grants or replacement request IDs.
29
+ - Continue using **MCP / Agent Client SDK 0.7.0 and DSH 0.7.0**. Independent packages are not republished solely for this patch. Business declarations, signatures, authorization, and approval code need no patch-specific rewrite.
30
+ - Embedded hosts should read the new Core artifact's version and complete manifest, and continue using its public tick/close entry points. A Core artifact upgrade does not establish that hosts or clients have been upgraded, deployed, or accepted.
31
+
32
+ ## Validation scope
33
+
34
+ [Tracker unit tests](../src/modules/usage/background-work.test.ts) check registration/drain mechanisms. [Actual Kernel + MySQL lifecycle tests](../src/app/kernel-usage-lifecycle.mysql.test.ts) check real Kernels, database transactions, and HTTP/standalone shutdown wiring. They cover delayed completion, late settlement, SQL locks, same-instance retry, two-Kernel isolation, ordinary text asynchronous settlement, independent cleanup/reconciliation, price persistence, and failed settlement retaining original results without redispatch.
35
+
36
+ Database cases require `BAILING_USAGE_TEST_MYSQL=1` and their dedicated test MySQL; providers and business data are synthetic. Test source or skipped tests are not passing runs. Real providers, business APIs, and deployments require their own acceptance. This page makes no production-adoption, comprehensive model-quality, or complete failure-recovery claim.
37
+
38
+ [Upgrade guide](UPGRADE_v0.9.1.en.md) · [Changelog](CHANGELOG.en.md) · [Previous release](RELEASE_NOTES_v0.9.0.en.md)
@@ -0,0 +1,38 @@
1
+ # v0.9.1:异步模型工作关闭与公开能力证据
2
+
3
+ [English](RELEASE_NOTES_v0.9.1.en.md)
4
+
5
+ 业务助手请求生成图片后,中枢会先返回原请求的 pending 状态,供应商响应和用量结算随后完成。如果宿主此时淘汰实例、升级或退出进程,不能把 HTTP 请求已经结束当成后台工作也已结束。
6
+
7
+ Core 0.9.1 修复这一关闭边界:在关闭资源前,等待属于原实例的 usage 后台工作及其后续结算。它还纳入公开能力索引和此前主分支的通用安全治理。本版是补丁版本,**没有新增 HTTP/API、SQL 迁移、套餐规则、客户端功能或 SDK/DSH 发行**。
8
+
9
+ ## 关闭修复
10
+
11
+ - 每个 `UsageRepository` 独立登记模型工具完成、普通模型响应后的结算、响应清理、待结算 usage 核对,以及参考价格刷新到持久化结束的工作。
12
+ - Kernel 先停止新 HTTP 接入,等待前台、InHub 和执行队列完成登记,再停止新 usage 工作和维护;动态排空已接纳的完成及晚登记的结算子工作后才关闭资源。
13
+ - 所有阶段共用原 `close(drainMs)` 时限。usage 排空超时会保留原实例依赖和关闭状态,供宿主在同一实例重试;不因此重新派发模型或业务写入。
14
+ - 图片首次响应仍及时返回 HTTP 202;普通文本结果也不等待财务结算再交付。原 `operation_id`、结果/计费状态分离、业务权限、审批和未知结果处理不变。
15
+ - 失败后台工作仍可能留下 durable pending/unknown 证据。排空结束不保证所有记录已经 settled,也不提供进程崩溃恢复或供应商任务恢复保证。
16
+
17
+ 正式 v0.9.0 的关闭路径没有显式登记这些 usage continuation;该 Tag 和已有制品保持原样。修复不回写其历史保证。完整语义见 [Kernel Host API](KERNEL_HOST_API.md) 和 [能力与证据索引](IMPLEMENTATION_STATUS.md)。
18
+
19
+ ## 公开文档与通用安全治理
20
+
21
+ 新增中英能力与证据索引,分别说明 Core、业务系统、本地宿主和独立适配层的职责,以及发行事实、公开测试/复现路径和未覆盖范围。线程上下文、可见对话审计与完整用户级长期记忆分别说明,不把已有测试扩展为生产采用证明。
22
+
23
+ 本版同时纳入依赖审计与显式例外检查、固定 GitHub Actions 来源和最小权限、依赖更新及仓库安全扫描配置,以及公开安全自评和 Security Insights 元数据。自评/元数据属于仓库治理,排除在 npm 运行包和 Docker 构建内容之外;治理资料存在不意味着全部安全控制通过或没有残余风险。
24
+
25
+ ## 升级影响
26
+
27
+ - 从公开 Core 0.9.0 升级,没有新增 SQL 文件,不改变已有迁移内容。更早版本仍须应用其未执行迁移,见 [升级指南](UPGRADE_v0.9.1.md)。
28
+ - 原有 USD 额度、统一倍率、周期售价/额度、模型目录和业务治理契约保持。无需为本补丁重新开通套餐或改变原请求标识。
29
+ - 使用既有 **MCP / Agent Client SDK 0.7.0、DSH 0.7.0**;不机械重发独立包。业务后端的声明、验签、授权和审批代码无须为本补丁改写。
30
+ - 嵌入式宿主应读取新 Core 制品的版本及完整 manifest,并继续调用其公开 tick/close 入口。Core 制品升级不证明宿主或客户端已经升级、部署或验收。
31
+
32
+ ## 验证范围
33
+
34
+ [登记器单元测试](../src/modules/usage/background-work.test.ts) 与 [实际 Kernel + MySQL 生命周期测试](../src/app/kernel-usage-lifecycle.mysql.test.ts) 分别检查内部登记/排空机制和真实 Kernel、数据库事务、HTTP/standalone 关闭接线。后者覆盖延迟完成、晚结算、SQL 锁、同实例重试、双 Kernel 隔离、普通文本异步结算、单独清理/核对、价格持久化,以及失败保留原结果而不重派。
35
+
36
+ 数据库用例需 `BAILING_USAGE_TEST_MYSQL=1` 和其专用测试 MySQL;供应商及业务数据为合成数据。测试源码或被跳过的测试不等于通过记录;真实供应商、业务接口和部署仍各自验收。本页不声称生产采用、全量模型质量或完整故障恢复。
37
+
38
+ [升级指南](UPGRADE_v0.9.1.md) · [版本记录](CHANGELOG.md) · [上一版本](RELEASE_NOTES_v0.9.0.md)
@@ -0,0 +1,39 @@
1
+ # Core v0.9.1 patch upgrade guide
2
+
3
+ [中文版](UPGRADE_v0.9.1.md)
4
+
5
+ Upgrade public Core 0.9.0 to 0.9.1 to include usage background work in shutdown drain and receive the public capability index and general security-governance updates. There are no new APIs, SQL migrations, plan rules, or client features. MCP / Agent Client SDK and DSH remain at their existing 0.7.0 versions.
6
+
7
+ ## Preserve data and original calls
8
+
9
+ Retain databases, instance configuration/credentials, attachment storage, previous artifacts, and host session/original-call records. Stop new work for the target instance, coordinate writers sharing its state, and reconcile dispatched requests. Do not replace recovery with a new `operation_id`.
10
+
11
+ The 0.9.0 `close()` did not explicitly drain usage background continuations. A finished old-version HTTP request or a returned old `close()` does not establish that image completion, settlement, or price persistence has finished. Reconcile in-flight work using original requests before replacing artifacts.
12
+
13
+ ## Versions and database
14
+
15
+ - Use formal `v0.9.1` source, npm packages, or images. Verify the actual version, source Tag/commit, and artifact digest. Installer and prebuilt-image Compose defaults are updated to 0.9.1.
16
+ - Compared with 0.9.0, there are no new migrations, changes to existing SQL, table clears, or required plan/allowance resets. Earlier versions still apply all outstanding files through the official migrator; see the [0.9.0 upgrade guide](UPGRADE_v0.9.0.en.md).
17
+ - Embedded hosts recheck the complete `BAILINGHUB_CORE_ARTIFACT_V1` manifest. A version change changes artifact identity even when active SQL filenames/checksums are unchanged. Comparing only the latest migration is insufficient.
18
+ - This patch does not require SDK/DSH version bumps or changes to business declarations, signatures, permissions, or approvals.
19
+
20
+ ## Shutdown and acceptance
21
+
22
+ For an ordinary deployment, check `/health`, the console, and existing business smoke paths. Deployments using the usage gateway also check original request results, billing states, and allowance. A complete result is not necessarily settled billing.
23
+
24
+ Embedded hosts continue fair `tick()` calls and use `close(drainMs)` for eviction, upgrades, and shutdown. Within the original budget, 0.9.1 waits for model completion, settlement, cleanup/reconciliation, and price refresh. A **usage-drain-stage timeout** retains the original dependencies and closing state. Wait for original work and retry on the same instance or alert; do not forcibly close its database or treat timeout as permission to redispatch. This does not imply that every subsequent resource-close failure leaves all resources untouched.
25
+
26
+ Public regressions can be reproduced in a dedicated test environment:
27
+
28
+ ```bash
29
+ node --import tsx --test src/modules/usage/background-work.test.ts
30
+ BAILING_USAGE_TEST_MYSQL=1 node --import tsx --test src/app/kernel-usage-lifecycle.mysql.test.ts
31
+ ```
32
+
33
+ The database cases use the fixture's isolated test MySQL, synthetic providers, and synthetic data. Without that environment, or when cases are skipped, record database validation as unexecuted. The cases need no live model calls and do not replace live-provider or deployment acceptance. See the [Kernel Host API](KERNEL_HOST_API.en.md) and [capability index](IMPLEMENTATION_STATUS.en.md) for coverage and limitations.
34
+
35
+ ## Rollback boundary
36
+
37
+ No new schema is introduced, but returning to 0.9.0 removes the usage background-drain fix. Stop new work, retain original results, ledger, configuration, and rollback artifacts, and reconcile in-flight operations before deciding to roll back. Do not delete ledgers, replay original requests, or treat backup restoration as undoing later business effects.
38
+
39
+ [Release notes](RELEASE_NOTES_v0.9.1.en.md) · [Compatibility policy](COMPATIBILITY.en.md)
@@ -0,0 +1,39 @@
1
+ # Core v0.9.1 补丁升级指南
2
+
3
+ [English](UPGRADE_v0.9.1.en.md)
4
+
5
+ 从公开 Core 0.9.0 升级到 0.9.1,目标是补齐 usage 后台工作关闭等待,并取得公开能力索引与通用安全治理更新。没有新增 API、SQL、套餐规则或客户端功能;MCP / Agent Client SDK 与 DSH 继续使用既有 0.7.0。
6
+
7
+ ## 保留数据与原调用
8
+
9
+ 保留数据库、实例配置和凭据、附件存储、旧制品以及宿主的会话/原调用持久记录。停止目标实例的新工作,协调共享状态库的写入方,核对已经派发的原请求;不要通过新 `operation_id` 代替结果恢复。
10
+
11
+ 0.9.0 的 `close()` 没有显式排空 usage 后台 continuation。因此,升级前不能只凭旧版 HTTP 已结束或旧 `close()` 已返回,就认定图片完成、结算或价格写入已经结束。应按原请求核对在途工作,再替换制品。
12
+
13
+ ## 版本与数据库
14
+
15
+ - 使用正式 `v0.9.1` 源码、npm 包或镜像,核对实际版本、来源 Tag/提交和制品摘要;安装器与预构建镜像 Compose 的默认版本同步为 0.9.1。
16
+ - 相对 0.9.0 没有新增迁移,不修改已有 SQL,也不要求清表或重置套餐/额度。更早版本按正式迁移器应用其全部未执行文件,仍可参考 [0.9.0 升级指南](UPGRADE_v0.9.0.md)。
17
+ - 嵌入式宿主使用 `BAILINGHUB_CORE_ARTIFACT_V1` 重新核对完整制品 manifest。版本变更会改变 manifest 身份,即使活动 SQL 名称与摘要不变;不要只比较最后一个迁移文件。
18
+ - 本补丁不要求升级 SDK/DSH 的版本声明,也不改变业务后端的声明、验签、权限或审批。
19
+
20
+ ## 关闭与验收
21
+
22
+ 正常部署先验证 `/health`、控制台和原有业务 smoke。使用 usage 网关的部署另核对原请求结果、计费状态和额度,不把结果 complete 等同于已 settled。
23
+
24
+ 嵌入式宿主继续公平调用 `tick()`,在淘汰、升级或退出时调用 `close(drainMs)`。0.9.1 在原关闭预算内等待模型完成、结算、清理/核对和价格刷新。**usage 排空阶段超时**会保留原实例依赖和 closing 状态;等待原工作后,在同一实例重试或告警,不强行关闭其数据库,也不把超时解释为重派许可。该描述不扩大为任何资源关闭失败都能原封不动回退。
25
+
26
+ 可在专用测试环境复现公开回归:
27
+
28
+ ```bash
29
+ node --import tsx --test src/modules/usage/background-work.test.ts
30
+ BAILING_USAGE_TEST_MYSQL=1 node --import tsx --test src/app/kernel-usage-lifecycle.mysql.test.ts
31
+ ```
32
+
33
+ 数据库用例使用 fixture 要求的隔离测试 MySQL、合成供应商和数据。没有该环境或用例被跳过时,应明确记录数据库验证未执行;这些用例不需要真实模型调用,也不替代真实供应商或部署验收。完整覆盖与限制见 [Kernel Host API](KERNEL_HOST_API.md) 和 [能力索引](IMPLEMENTATION_STATUS.md)。
34
+
35
+ ## 回退边界
36
+
37
+ 本版没有新增 schema,但回退到 0.9.0 会重新失去 usage 后台关闭等待。先停止新工作并保留原结果、账本、配置和回滚制品,核对在途操作后再决定回退。不要删账本、重发原请求或把备份恢复当作撤销备份后业务效果的办法。
38
+
39
+ [版本说明](RELEASE_NOTES_v0.9.1.md) · [兼容策略](兼容性与升级.md)
@@ -1,5 +1,9 @@
1
1
  # 百灵中枢 · 兼容性与升级策略
2
2
 
3
+ ## Core 0.9.1 补丁升级
4
+
5
+ 相对 0.9.0 仅修复异步 usage 工作关闭等待并更新公开文档/通用安全治理,没有新增 API、SQL、套餐规则或客户端功能。SDK 0.7.0 / DSH 0.7.0 不变。旧版关闭返回不能证明 usage 后台工作已结束;替换制品前核对原请求,新版 usage 排空超时在原实例重试。见 [0.9.1 升级指南](UPGRADE_v0.9.1.md)。
6
+
3
7
  ## Core 0.9.0 配套升级
4
8
 
5
9
  Core 0.9.0 配套 SDK 0.7.0 / DSH 0.7.0,新增可选模型计费网关;本地宿主继续编排,既有业务权限、审批与原调用恢复保持。从公开 0.8.0 升级应用未执行的 063/064,保留真实数据,不需要清退测试结构。周期套餐的售价与额度独立,原开通快照和账本保留。启用模型套餐的宿主需要显式接入;只使用原业务工具的宿主不必开启计费。详见 [0.9.0 升级指南](UPGRADE_v0.9.0.md)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bailinghub",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Open-source ACC runtime and agent control plane for existing business systems.",
@@ -81,8 +81,8 @@
81
81
  "client-api:contract": "tsx scripts/client-api-contract-test.ts",
82
82
  "client-api:ecosystem:local": "node scripts/check-client-api-ecosystem.mjs --mode local",
83
83
  "client-api:ecosystem:clone": "node scripts/check-client-api-ecosystem.mjs --mode clone",
84
- "audit:deps": "npm audit --audit-level=low && npm --prefix web-admin audit --audit-level=low",
85
- "web-admin:check": "npm --prefix web-admin run build && npm --prefix web-admin audit --audit-level=low",
84
+ "audit:deps": "node scripts/dependency-audit.mjs",
85
+ "web-admin:check": "npm --prefix web-admin run build && node scripts/dependency-audit.mjs --scope web-admin",
86
86
  "oss:guard": "node scripts/oss-boundary-check.mjs",
87
87
  "oss:export": "node scripts/export-oss.mjs",
88
88
  "oss:verify": "node scripts/verify-oss-export.mjs",
@@ -104,7 +104,8 @@
104
104
  "sdk:test-runtime": "node scripts/sdk-runtime-test.mjs",
105
105
  "sdk:test-p1": "node scripts/sdk-p1-check.mjs",
106
106
  "sdk:pack": "COPYFILE_DISABLE=1 tar --no-xattrs -czf web/connect/bailing-connect-php.tgz -s '|^php|bailing-connect-php|' -C sdk php",
107
- "sdk:pack7": "COPYFILE_DISABLE=1 tar --no-xattrs -czf web/connect/bailing-connect-php7.tgz -s '|^php7|bailing-connect-php7|' -C sdk php7"
107
+ "sdk:pack7": "COPYFILE_DISABLE=1 tar --no-xattrs -czf web/connect/bailing-connect-php7.tgz -s '|^php7|bailing-connect-php7|' -C sdk php7",
108
+ "audit:deps:test": "node --test scripts/dependency-audit.test.mjs"
108
109
  },
109
110
  "dependencies": {
110
111
  "mammoth": "^1.12.0",
@@ -106,6 +106,8 @@ const englishCompanions = {
106
106
  'docs/RELEASE_NOTES_v0.8.0.md': 'docs/RELEASE_NOTES_v0.8.0.en.md',
107
107
  'docs/RELEASE_NOTES_v0.9.0.md': 'docs/RELEASE_NOTES_v0.9.0.en.md',
108
108
  'docs/UPGRADE_v0.9.0.md': 'docs/UPGRADE_v0.9.0.en.md',
109
+ 'docs/RELEASE_NOTES_v0.9.1.md': 'docs/RELEASE_NOTES_v0.9.1.en.md',
110
+ 'docs/UPGRADE_v0.9.1.md': 'docs/UPGRADE_v0.9.1.en.md',
109
111
  'docs/MODEL_BILLING.md': 'docs/MODEL_BILLING.en.md',
110
112
  'docs/PERIOD_ALLOWANCE_UPGRADE.md': 'docs/PERIOD_ALLOWANCE_UPGRADE.en.md',
111
113
  'docs/RELEASE_NOTES_v0.7.0.md': 'docs/RELEASE_NOTES_v0.7.0.en.md',
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.9.0"
12
+ [ -n "$TAG" ] || TAG="0.9.1"
13
13
  MYSQL_TAG="${BAILING_MYSQL_IMAGE_TAG:-8.4}"
14
14
  MYSQL_IMAGE="${BAILING_MYSQL_IMAGE:-$REGISTRY/$NAMESPACE/bailing-mysql:$MYSQL_TAG}"
15
15
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
@@ -38,8 +38,8 @@ function updateJson(root, relativePath, update) {
38
38
  test('current release surface is internally consistent', () => {
39
39
  const result = checkReleaseConsistency({ root: repoRoot });
40
40
  assert.deepEqual(result.findings, []);
41
- assert.equal(result.version, '0.9.0');
42
- assert.equal(result.stableVersion, '0.9.0');
41
+ assert.equal(result.version, '0.9.1');
42
+ assert.equal(result.stableVersion, '0.9.1');
43
43
  assert.equal(result.publishTag, 'latest');
44
44
  });
45
45
 
@@ -0,0 +1,134 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync, lstatSync } from 'node:fs';
3
+ import { resolve, relative, join } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { spawnSync } from 'node:child_process';
6
+
7
+ const affectedNames = ['mammoth', 'argparse', 'sprintf-js'];
8
+ const approvedAdvisory = 'https://github.com/advisories/GHSA-hp3w-g68c-fv3c';
9
+ const usagePattern = /\b(?:mammoth|argparse|sprintf-js)\b/i;
10
+ const levels = ['info', 'low', 'moderate', 'high', 'critical'];
11
+ const json = path => JSON.parse(readFileSync(path, 'utf8'));
12
+ const hash = source => createHash('sha256').update(source).digest('hex');
13
+ const stable = value => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item)
14
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
15
+
16
+ function reviewedRowsAreExact(rows) {
17
+ if (!rows || Array.isArray(rows) || typeof rows !== 'object' ||
18
+ stable(Object.keys(rows).sort()) !== stable([...affectedNames].sort())) return false;
19
+ const chain = { mammoth: ['argparse'], argparse: ['sprintf-js'] };
20
+ const effects = { mammoth: [], argparse: ['mammoth'], 'sprintf-js': ['argparse'] };
21
+ for (const name of affectedNames) {
22
+ const row = rows[name];
23
+ if (!row || row.name !== name || row.severity !== 'moderate' ||
24
+ stable(row.nodes) !== stable([`node_modules/${name}`]) ||
25
+ stable(row.effects) !== stable(effects[name])) return false;
26
+ if (name !== 'sprintf-js') {
27
+ if (stable(row.via) !== stable(chain[name])) return false;
28
+ } else {
29
+ if (!Array.isArray(row.via) || row.via.length !== 1) return false;
30
+ const advisory = row.via[0];
31
+ if (!advisory || typeof advisory !== 'object' || Array.isArray(advisory) ||
32
+ advisory.name !== name || advisory.dependency !== name ||
33
+ advisory.severity !== 'moderate' || advisory.url !== approvedAdvisory) return false;
34
+ }
35
+ }
36
+ return true;
37
+ }
38
+
39
+ export function dependencyState(lock) {
40
+ const versions = {}, references = [];
41
+ for (const [path, entry] of Object.entries(lock.packages ?? {})) {
42
+ if (affectedNames.some(name => path === `node_modules/${name}` || path.endsWith(`/node_modules/${name}`))) versions[path] = entry.version;
43
+ for (const kind of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
44
+ for (const [name, range] of Object.entries(entry[kind] ?? {})) {
45
+ if (affectedNames.includes(name)) references.push(`${path || '<root>'}|${kind}|${name}|${range}`);
46
+ }
47
+ }
48
+ }
49
+ return { versions, references: references.sort() };
50
+ }
51
+
52
+ export function collectUsage(root, scope) {
53
+ const inventory = {};
54
+ const directories = scope === 'core' ? ['src', 'scripts', '.github'] : ['web-admin/src', 'web-admin/scripts'];
55
+ const excluded = new Set(['scripts/dependency-audit.mjs', 'scripts/dependency-audit.test.mjs']);
56
+ function visit(path) {
57
+ const local = relative(root, path).replaceAll('\\', '/');
58
+ if (excluded.has(local)) return;
59
+ const stat = lstatSync(path);
60
+ if (stat.isSymbolicLink()) throw new Error(`Source symlink requires review: ${local}`);
61
+ if (stat.isDirectory()) {
62
+ for (const entry of readdirSync(path).sort()) visit(join(path, entry));
63
+ } else if (stat.isFile() && /\.(?:[cm]?js|[cm]?ts|jsx|tsx|vue|html|ya?ml|json|sh)$/.test(path)) {
64
+ const source = readFileSync(path);
65
+ if (usagePattern.test(source.toString('utf8'))) inventory[local] = hash(source);
66
+ }
67
+ }
68
+ for (const directory of directories) if (existsSync(join(root, directory))) visit(join(root, directory));
69
+ const manifestPath = scope === 'core' ? 'package.json' : 'web-admin/package.json';
70
+ const scripts = json(join(root, manifestPath)).scripts ?? {};
71
+ for (const [name, command] of Object.entries(scripts)) {
72
+ if (usagePattern.test(String(command))) inventory[`${manifestPath}#scripts.${name}`] = hash(String(command));
73
+ }
74
+ return inventory;
75
+ }
76
+
77
+ export function evaluateScope({ scope, audit, lock, usage, policy, now = new Date() }) {
78
+ const reasons = [], counts = Object.fromEntries(levels.map(level => [level, 0]));
79
+ const exception = policy.scopes?.[scope];
80
+ const from = Date.parse(policy.approvedFrom), until = Date.parse(policy.expiresAt), time = +now;
81
+ if (policy.version !== 1 || policy.owner !== 'Jingchuan Nie' || policy.advisory !== approvedAdvisory) reasons.push('Unknown exception policy');
82
+ if (![from, until, time].every(Number.isFinite) || until <= from || until - from > 30 * 86400000) reasons.push('Invalid exception period');
83
+ else if (time < from || time >= until) reasons.push('Exception is not active or has expired');
84
+ if (!exception) reasons.push(`Unknown scope: ${scope}`);
85
+ else if (!reviewedRowsAreExact(exception.knownAuditRows)) reasons.push('Exception policy must contain only the reviewed Mammoth/argparse/sprintf-js chain and advisory');
86
+ const rows = audit?.vulnerabilities;
87
+ if (audit?.auditReportVersion !== 2 || audit?.error || !rows || Array.isArray(rows) || typeof rows !== 'object') {
88
+ reasons.push('Invalid or failed npm audit response');
89
+ return { scope, pass: false, rawCounts: null, exceptedRows: 0, reasons };
90
+ }
91
+ let exceptedRows = 0;
92
+ for (const [name, row] of Object.entries(rows)) {
93
+ if (levels.includes(row.severity)) counts[row.severity]++;
94
+ else reasons.push(`Unknown vulnerability severity: ${name}`);
95
+ if (!exception?.knownAuditRows?.[name] || stable(row) !== stable(exception.knownAuditRows[name])) reasons.push(`Unreviewed vulnerability or changed advisory/dependency path: ${name}`);
96
+ else exceptedRows++;
97
+ }
98
+ counts.total = Object.keys(rows).length;
99
+ if (stable(counts) !== stable(audit.metadata?.vulnerabilities)) reasons.push('Audit counts do not match vulnerability rows');
100
+ if (exception) {
101
+ const state = dependencyState(lock);
102
+ if (stable(state.versions) !== stable(exception.packageVersions)) reasons.push('Reviewed dependency versions or installed locations changed');
103
+ if (stable(state.references) !== stable(exception.dependencyReferences)) reasons.push('New or changed dependency consumer/path requires review');
104
+ if (stable(usage) !== stable(exception.reviewedUsageFiles)) reasons.push('New/changed source or CLI usage requires review');
105
+ }
106
+ return { scope, pass: reasons.length === 0, rawCounts: counts, exceptedRows, unexceptedRows: counts.total - exceptedRows, exceptionExpiresAt: policy.expiresAt, reasons };
107
+ }
108
+
109
+ export function runScope(root, scope, policy) {
110
+ const directory = scope === 'core' ? root : join(root, 'web-admin');
111
+ const run = spawnSync('npm', ['audit', '--json'], { cwd: directory, encoding: 'utf8', timeout: 120000, maxBuffer: 8 * 1024 * 1024 });
112
+ if (run.error || run.signal || ![0, 1].includes(run.status)) throw new Error(`npm audit failed in ${scope}; exit=${run.status}`);
113
+ return evaluateScope({ scope, audit: JSON.parse(run.stdout), lock: json(join(directory, 'package-lock.json')), usage: collectUsage(root, scope), policy });
114
+ }
115
+
116
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
117
+ try {
118
+ const options = { root: process.cwd(), scope: 'all' };
119
+ for (let index = 2; index < process.argv.length; index += 2) {
120
+ const flag = process.argv[index], value = process.argv[index + 1];
121
+ if (!['--root', '--scope', '--policy'].includes(flag) || !value) throw new Error('Usage: dependency-audit.mjs [--root PATH] [--scope core|web-admin|all] [--policy PATH]');
122
+ options[flag.slice(2)] = value;
123
+ }
124
+ if (!['core', 'web-admin', 'all'].includes(options.scope)) throw new Error('Unknown scope');
125
+ const root = resolve(options.root), policy = json(options.policy ?? join(root, 'security/dependency-audit-exceptions.json'));
126
+ const scopes = options.scope === 'all' ? ['core', 'web-admin'] : [options.scope];
127
+ const results = scopes.map(scope => runScope(root, scope, policy));
128
+ console.log(JSON.stringify({ results, note: 'Raw findings remain open; an exact temporary exception is not a vulnerability fix.' }, null, 2));
129
+ process.exitCode = results.every(result => result.pass) ? 0 : 1;
130
+ } catch (error) {
131
+ console.error(`Dependency audit blocked: ${error.message}`);
132
+ process.exitCode = 1;
133
+ }
134
+ }