@sanqianx/ai-coding-workflow 0.0.0-stage → 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ https://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # ai-coding-workflow
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `project-knowledge` 模块家族的第五个模块:**独立工作流模块**。它拥有 AI 团队的业务主数据——默认团队、Agent 成员、跨项目业务任务、固定工作流、程序质量检查、Review 编排、交付判定、日报与提醒——并自带"AI 团队"页面。
4
+
5
+ ```text
6
+ 原生 Claude Code / Codex → Event Bridge journal → 独立工作流模块(本模块)
7
+ ├→ 确定性检查 runner(真实 CLI 子进程)
8
+ ├→ Workbench 受信执行(独立 Review)
9
+ └→ knowledge-engine(成员记忆绑定)
10
+ shell(project-knowledge)只做接线:/api/workflow/* 反代 + /workflow-ui/ 页面代理
11
+ ```
12
+
13
+ ## 运行
14
+
15
+ ```bash
16
+ npx ai-coding-workflow serve --data <独立目录> --host 127.0.0.1 --port 5810
17
+ ```
18
+
19
+ - Node ≥ 22,零 npm 运行依赖,CommonJS,默认只绑定 loopback。
20
+ - 所有测试/生命周期命令必须显式 `--data`;测试数据与任何真实安装隔离。
21
+
22
+ ## 开发
23
+
24
+ ```bash
25
+ npm test # 单元 + 存储 + API 合同
26
+ npm run test:contract # 冻结契约(identity、包白名单)
27
+ npm run test:integration# 真实服务重启/嵌入/穿越反例
28
+ npm run test:package # npm pack 白名单审计
29
+ ```
30
+
31
+ 仓库治理见 [AGENTS.md](AGENTS.md);对外接口契约见 [docs/contract.md](docs/contract.md)。
32
+
33
+ ## 边界(不可漂移)
34
+
35
+ - 团队/任务主数据只在本模块;不写入 shell、Workbench 或其他模块数据目录。
36
+ - 不保存供应商凭据(driverId/profileId 只是引用);不复制 knowledge-engine 记忆正文。
37
+ - 独立消费 Event Bridge journal:先持久化 inbox 再 ACK,不复用 engine 游标。
38
+ - 不用定时器、seed 数据或静态页面假装功能完成;能力开关(`/api/workflow/v1/capabilities`)如实反映交付状态。
@@ -0,0 +1,52 @@
1
+ # ai-coding-workflow 对外契约(v1)
2
+
3
+ 首版 `0.1.0`。本文是 shell(project-knowledge)与独立使用者编译依赖的冻结契约;任何破坏性变更须升版本并同步 shell。
4
+
5
+ ## 服务身份
6
+
7
+ | 项 | 值 |
8
+ | --- | --- |
9
+ | npm 包 | `@sanqianx/ai-coding-workflow` |
10
+ | 服务名(health.name) | `ai-coding-workflow` |
11
+ | CLI | `ai-coding-workflow serve --data <目录> --host 127.0.0.1 --port <端口>`(首选 5810) |
12
+ | 运行时 | Node ≥ 22,CommonJS,零 npm 运行依赖 |
13
+ | 数据 | `<dataDir>/workflow/state.json`(单聚合,原子替换,跨进程文件锁) |
14
+
15
+ ## 路由
16
+
17
+ ### 模块自有(独立启动直连;shell 探测用)
18
+
19
+ - `GET /api/health` → `{ok, name:'ai-coding-workflow', version, apiVersion:'v1', schema:'workflow-health/v1', capabilities, managed, uptimeSec, dataDir, time}`。shell 的 MODULE_IDENTITY 以 `name` + `apiVersion` 判定"本模块已在该端口运行"。
20
+ - `GET /`、`/app.js`、`/app.css` → AI 团队页(原生三件套)。`?embed=1&apiBase=/api/workflow` 进入嵌入形态:隐藏品牌栏,API 走传入基址。只接受同源 postMessage。
21
+
22
+ ### 业务 API 基址 `/api/workflow/v1`
23
+
24
+ | 方法与路径 | 语义 |
25
+ | --- | --- |
26
+ | `GET /capabilities` | 版本化能力开关(team/tasks/bridgeConsumer/reviews/checks/memberMemory/digests/internalEndpoints),未交付能力必须显式 false |
27
+ | `GET /team` | 默认团队读取:`{team\|null, memberCount, status:'empty'\|'ready'}` |
28
+ | `POST /team` | 幂等创建(requestId + memberDrafts + projectSettings);重复创建 409;重试同 ID 复用原结果 |
29
+ | `PATCH /team` | CAS 改名(expectedRevision) |
30
+ | `GET /members` / `POST /members` | 成员列表 / 新建(角色 developer\|reviewer;driverId/profileId/model 为引用,不存凭据) |
31
+ | `GET/PATCH /members/:id` | 读取 / CAS 更新与禁用(enabled=false 立即阻止新运行) |
32
+ | `GET/PUT /projects/:id/settings` | 项目启用与检查配置;autoDispatch、externalNotifications 默认关闭 |
33
+ | `GET /overview` | 有界投影(revision、team、members 汇总、projects、tasks 真实计数) |
34
+ | `POST /internal/context-bindings/validate` | **仅受信服务**(`X-KB-Runtime-Token`/Bearer = `KB_WORKFLOW_RUNTIME_TOKEN`);W4 前恒答 501 UNSUPPORTED,调用方必须按"无成员内容"处理 |
35
+
36
+ ### shell 侧代理(shell 仓库实现,此处仅声明契约)
37
+
38
+ - `/api/workflow/<rest>` → 本模块 `/api/workflow/v1/<rest>`(同源反代,`/internal/` 前缀对浏览器 403)。
39
+ - `/workflow-ui/<asset>` → 本模块 `/<asset>`(页面代理,仅 GET,拒绝编码分隔符与 `api`/`internal` 段)。
40
+
41
+ ## 写入合同
42
+
43
+ - 所有写请求携带 `requestId`(幂等键);更新携带 `expectedRevision`。
44
+ - 同 `requestId` 同载荷 → 复用原结果(200,`replayed:true`);同 `requestId` 不同载荷 → 409 `PAYLOAD_MISMATCH`;revision 过期 → 409 `STALE_REVISION`(details.currentRevision)。
45
+ - 错误码域:`VALIDATION`(400) `UNAUTHENTICATED`(401) `FORBIDDEN`(403) `NOT_FOUND`(404) `CONFLICT`(409) `STALE_REVISION`(409) `PAYLOAD_MISMATCH`(409) `UNSUPPORTED`(501) `UPSTREAM_UNAVAILABLE`(503) `EXECUTION_FAILED`(500) `DATA_CORRUPT`(500)。不回显凭据或供应商原始错误。
46
+
47
+ ## 存储与恢复合同
48
+
49
+ - 单聚合 JSON:schema `ai-coding-workflow/state/v1`;不支持的未来 schema 拒绝读取(DATA_CORRUPT),绝不静默重置。
50
+ - 原子替换(tmp+fsync+rename);跨进程单写者(pid/nonce 锁文件,死进程锁可打破)。
51
+ - `requests` 幂等表、事件 `inbox`、待发 `outbox`、journal `cursors` 与业务状态同文件同事务落盘;副作用只在 rename 之后发出,ack 后清除。
52
+ - 损坏文件保留到 `<dataDir>/workflow/corrupt/` 并报错。
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@sanqianx/ai-coding-workflow",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Independent workflow module for project-knowledge: AI team, cross-project business tasks, fixed workflow orchestration, deterministic quality checks, review coordination, delivery decisions, daily digests and reminders.",
5
+ "license": "Apache-2.0",
6
+ "publishConfig": {
7
+ "access": "public",
8
+ "registry": "https://registry.npmjs.org",
9
+ "provenance": false
10
+ },
11
+ "main": "src/server.js",
12
+ "bin": {
13
+ "ai-coding-workflow": "src/bin.js"
14
+ },
15
+ "engines": {
16
+ "node": ">=22"
17
+ },
18
+ "files": [
19
+ "src",
20
+ "ui/index.html",
21
+ "ui/app.js",
22
+ "ui/app.css",
23
+ "docs/contract.md",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/SanQianX/ai-coding-workflow.git"
30
+ },
31
+ "scripts": {
32
+ "start": "node src/bin.js serve",
33
+ "test": "node --test test/*.test.js",
34
+ "test:contract": "node --test test/contract/*.test.js",
35
+ "test:integration": "node --test test/integration/*.test.js",
36
+ "test:tools": "node --test test/tools/*.test.js",
37
+ "test:web": "node test/support/product-web-ui-test.js",
38
+ "test:real": "node --test test/real/*.test.js",
39
+ "test:package": "node test/support/package-audit-test.js"
40
+ },
41
+ "keywords": [
42
+ "project-knowledge",
43
+ "workflow",
44
+ "ai-team",
45
+ "task-management",
46
+ "quality-gates"
47
+ ],
48
+ "private": false,
49
+ "devDependencies": {
50
+ "eslint": "^9.39.4",
51
+ "knip": "^5.88.1"
52
+ }
53
+ }
package/src/bin.js ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { createWorkflowServer } = require('./server');
5
+
6
+ /**
7
+ * ai-coding-workflow CLI
8
+ *
9
+ * serve [--port 5810] [--host 127.0.0.1] [--data DIR]
10
+ * Start the workflow module (AI team page + /api/workflow/v1).
11
+ *
12
+ * The server binds to loopback by default. Tests must always pass an
13
+ * explicit --data directory so they never touch a real install's data.
14
+ */
15
+ async function main() {
16
+ const argv = process.argv.slice(2);
17
+ const command = argv[0];
18
+ const get = name => {
19
+ const i = argv.indexOf('--' + name);
20
+ return i >= 0 ? argv[i + 1] : undefined;
21
+ };
22
+
23
+ if (command !== 'serve') {
24
+ console.log('Usage: ai-coding-workflow serve [--port 5810] [--host 127.0.0.1] [--data DIR]');
25
+ process.exitCode = command ? 1 : 0;
26
+ return;
27
+ }
28
+
29
+ const port = Number(get('port') || process.env.AI_CODING_WORKFLOW_PORT || 5810);
30
+ const host = get('host') || process.env.AI_CODING_WORKFLOW_HOST || '127.0.0.1';
31
+ const dataDir = get('data') || process.env.AI_CODING_WORKFLOW_DATA;
32
+ if (!dataDir) {
33
+ console.error('[ai-coding-workflow] MISSING_DATA_DIR: an explicit --data directory is required.');
34
+ process.exitCode = 1;
35
+ return;
36
+ }
37
+
38
+ const runtime = createWorkflowServer({ dataDir, managed: process.env.KB_WORKFLOW_MANAGED === '1', runtimeToken: process.env.KB_WORKFLOW_RUNTIME_TOKEN });
39
+ const { server, consumer } = runtime;
40
+ await runtime.listen(port, host);
41
+ // Register the independent consumer with a wake-up URL once the port is
42
+ // bound, then run the startup drain (register + catch-up). Failures are
43
+ // logged, never fatal: the module keeps serving tasks offline.
44
+ if (process.env.KB_EVENT_BRIDGE_URL) {
45
+ const notifyUrl = `http://127.0.0.1:${port}/api/internal/bridge-notify`;
46
+ try {
47
+ await consumer.drain({ register: true, notifyUrl });
48
+ console.log(`[ai-coding-workflow] bridge consumer registered (${consumer.name}), notify ${notifyUrl}`);
49
+ } catch (error) {
50
+ console.error(`[ai-coding-workflow] bridge consumer startup drain failed: ${error.message}`);
51
+ }
52
+ }
53
+ let stopping = false;
54
+ const stop = async () => {
55
+ if (stopping) return; stopping = true;
56
+ try { await runtime.close(); process.exitCode = 0; }
57
+ catch (error) { console.error(`[ai-coding-workflow] ${error.code || 'SHUTDOWN_FAILED'}: ${error.message}`); process.exitCode = 1; }
58
+ if (process.connected) process.disconnect();
59
+ };
60
+ for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, stop);
61
+ process.on('message', message => { if (message?.type === 'kb:shutdown') stop(); });
62
+ server.listen(port, host, () => {
63
+ console.log(`[ai-coding-workflow] listening on http://${host}:${port} (data: ${dataDir})`);
64
+ });
65
+ }
66
+
67
+ main().catch(error => { console.error(`[ai-coding-workflow] ${error.code || 'START_FAILED'}: ${error.message}`); process.exitCode = 1; });
package/src/checks.js ADDED
@@ -0,0 +1,188 @@
1
+ 'use strict';
2
+
3
+ // Deterministic check runner (main plan §9.2/§9.3): real subprocesses,
4
+ // separated argv (shell:false), no auto-fix, honest execution status.
5
+ //
6
+ // Adapter contract per tool:
7
+ // probe() -> { available, version } (absent tool => receipt 'missing',
8
+ // which is NEVER a pass)
9
+ // buildArgs() -> argv[] for the fixed snapshot
10
+ // parse() -> { findings, completeness } from stdout/exit code
11
+ // Receipts carry the evidence key (snapshot+baseline+policy+toolchain+
12
+ // acceptanceRevision) so stale evidence cannot satisfy a new candidate.
13
+
14
+ const { spawn } = require('child_process');
15
+ const path = require('path');
16
+ const fs = require('fs');
17
+ const crypto = require('crypto');
18
+ const { captureSnapshot, evidenceKey } = require('./snapshots');
19
+
20
+ // eslint 9's package exports block require.resolve of the bin path; resolve
21
+ // it from this package's own node_modules layout instead. Absent dev install
22
+ // (production runtime package) simply means "tool missing".
23
+ function eslintBinPath() {
24
+ const candidate = path.join(__dirname, '..', 'node_modules', 'eslint', 'bin', 'eslint.js');
25
+ return fs.existsSync(candidate) ? candidate : null;
26
+ }
27
+ function knipEntry() {
28
+ try { return require.resolve('knip'); } catch { return null; }
29
+ }
30
+
31
+ const CHECK_TIMEOUT_MS = 120_000;
32
+
33
+ /** Run a fixed argv (no shell), bounded; classify exit/timeout/kill. */
34
+ function runProcess(cmd, args, { cwd, timeoutMs = CHECK_TIMEOUT_MS, env } = {}) {
35
+ return new Promise(resolve => {
36
+ const child = spawn(cmd, args, { cwd, env: { ...process.env, ...(env || {}) }, windowsHide: true, shell: false });
37
+ let stdout = '', stderr = '';
38
+ let settled = false;
39
+ const timer = setTimeout(() => { try { child.kill(); } catch {} }, timeoutMs);
40
+ const finish = result => { if (settled) return; settled = true; clearTimeout(timer); resolve(result); };
41
+ child.stdout.on('data', d => { stdout += d; if (stdout.length > 4 * 1024 * 1024) { try { child.kill(); } catch {} } });
42
+ child.stderr.on('data', d => { stderr += d; if (stderr.length > 1024 * 1024) { try { child.kill(); } catch {} } });
43
+ child.on('error', error => finish({ status: 'error', errorCode: error.code || 'SPAWN_ERROR', stdout, stderr }));
44
+ child.on('close', (code, signal) => finish({
45
+ status: code === null ? (signal ? 'killed' : 'error') : 'ok',
46
+ exitCode: code, signal: signal || null, stdout, stderr,
47
+ truncated: stdout.length >= 4 * 1024 * 1024,
48
+ }));
49
+ });
50
+ }
51
+
52
+ function nodeBin(script) { return process.execPath; }
53
+
54
+ // ---------- adapters ----------
55
+
56
+ const eslintAdapter = {
57
+ id: 'eslint',
58
+ async probe() {
59
+ let version = null;
60
+ try {
61
+ const bin = eslintBinPath();
62
+ const result = bin ? await runProcess(process.execPath, [bin, '--version'], { timeoutMs: 15_000 }) : { status: 'error' };
63
+ version = result.status === 'ok' ? (result.stdout || '').trim() : null;
64
+ } catch { version = null; }
65
+ return { available: Boolean(version), version, toolchainHash: crypto.createHash('sha256').update(version || 'missing').digest('hex').slice(0, 16) };
66
+ },
67
+ buildArgs({ configPath }) {
68
+ const entry = eslintBinPath();
69
+ if (!entry) return [];
70
+ const argv = [process.execPath, entry, '--format', 'json', '--no-fix'];
71
+ if (configPath) argv.push('--config', configPath);
72
+ argv.push('.');
73
+ return argv;
74
+ },
75
+ parse(result) {
76
+ if (result.status !== 'ok') return { findings: [], completeness: 'error', message: `eslint 执行失败(${result.errorCode || result.signal || result.exitCode})` };
77
+ let reports;
78
+ try { reports = JSON.parse(result.stdout); }
79
+ catch { return { findings: [], completeness: 'unparsed', message: 'eslint 输出不是合法 JSON' }; }
80
+ const findings = [];
81
+ for (const report of reports) {
82
+ for (const message of report.messages || []) {
83
+ findings.push({
84
+ toolId: 'eslint', ruleId: message.ruleId || 'parse-error',
85
+ file: report.filePath, line: message.line || null, column: message.column || null,
86
+ severity: message.severity === 2 ? 'error' : 'warning',
87
+ message: String(message.message || '').slice(0, 500),
88
+ });
89
+ }
90
+ }
91
+ return { findings, completeness: 'complete' };
92
+ },
93
+ };
94
+
95
+ const knipAdapter = {
96
+ id: 'knip',
97
+ async probe() {
98
+ let version = null;
99
+ try {
100
+ const knipMain = knipEntry();
101
+ const result = knipMain ? await runProcess(process.execPath, [knipMain, '--version'], { timeoutMs: 15_000 }) : { status: 'error' };
102
+ version = result.status === 'ok' ? (result.stdout || '').trim() : null;
103
+ } catch { version = null; }
104
+ return { available: Boolean(version), version, toolchainHash: crypto.createHash('sha256').update(version || 'missing').digest('hex').slice(0, 16) };
105
+ },
106
+ buildArgs({ configPath }) {
107
+ const knipMain = knipEntry();
108
+ if (!knipMain) return [];
109
+ const argv = [process.execPath, knipMain, '--reporter', 'json'];
110
+ if (configPath) argv.push('--config', configPath);
111
+ return argv;
112
+ },
113
+ parse(result) {
114
+ if (result.status !== 'ok') return { findings: [], completeness: 'error', message: `knip 执行失败(${result.errorCode || result.signal || result.exitCode})` };
115
+ let payload;
116
+ try { payload = JSON.parse(result.stdout); }
117
+ catch { return { findings: [], completeness: 'unparsed', message: 'knip 输出不是合法 JSON' }; }
118
+ const findings = [];
119
+ const counters = payload.counters || {};
120
+ for (const group of payload.files || []) {
121
+ const kind = group.displayName || group.id || 'unused';
122
+ for (const issue of group.issues || []) {
123
+ findings.push({
124
+ toolId: 'knip', ruleId: `knip/${kind}`,
125
+ file: (issue.file || issue.name || '').split(':')[0], line: null, column: null,
126
+ severity: 'warning', message: `${kind}: ${issue.name || issue.file || ''}`.slice(0, 300),
127
+ });
128
+ }
129
+ }
130
+ return { findings, completeness: 'complete' };
131
+ },
132
+ };
133
+
134
+ const ADAPTERS = { eslint: eslintAdapter, knip: knipAdapter };
135
+
136
+ // ---------- runner ----------
137
+
138
+ /**
139
+ * Run the configured checks for a repository snapshot and produce receipts.
140
+ * Receipts are pure records: the API layer persists them; nothing here fakes
141
+ * success — a missing tool, error, timeout or unparsed output is recorded as
142
+ * such and can never be a pass.
143
+ */
144
+ async function runChecks(repoPath, { tools = ['eslint'], policyHash = 'policy:none', acceptanceRevision = 1, config = {}, snapshot: providedSnapshot } = {}) {
145
+ const snapshot = providedSnapshot || captureSnapshot(repoPath, {});
146
+ const receipts = [];
147
+ for (const toolId of tools) {
148
+ const adapter = ADAPTERS[toolId];
149
+ if (!adapter) { receipts.push({ toolId, executionStatus: 'unsupported', verdict: 'not-run', findings: [], completeness: 'unsupported', message: `未知工具 ${toolId}` }); continue; }
150
+ const probe = await adapter.probe();
151
+ if (!probe.available) {
152
+ receipts.push({ toolId, executionStatus: 'missing', verdict: 'not-run', findings: [], completeness: 'missing', message: `${toolId} 未安装(这不构成通过)`, evidenceKey: null });
153
+ continue;
154
+ }
155
+ const argv = adapter.buildArgs(config[toolId] || {});
156
+ const startedAt = Date.now();
157
+ const result = await runProcess(argv[0], argv.slice(1), { cwd: repoPath });
158
+ const parsed = adapter.parse(result);
159
+ const errorFindings = parsed.findings.filter(f => f.severity === 'error').length;
160
+ const verdict = parsed.completeness !== 'complete' ? 'error'
161
+ : errorFindings > 0 ? 'fail'
162
+ : parsed.findings.length > 0 ? 'warn'
163
+ : 'pass';
164
+ receipts.push({
165
+ toolId,
166
+ toolVersion: probe.version,
167
+ executionStatus: result.status,
168
+ exitCode: result.exitCode ?? null,
169
+ durationMs: Date.now() - startedAt,
170
+ verdict,
171
+ findings: parsed.findings,
172
+ findingCount: parsed.findings.length,
173
+ errorCount: errorFindings,
174
+ completeness: parsed.completeness,
175
+ truncated: Boolean(result.truncated),
176
+ message: parsed.message || null,
177
+ snapshotId: snapshot.snapshotId,
178
+ policyHash,
179
+ toolchainHash: probe.toolchainHash,
180
+ acceptanceRevision,
181
+ evidenceKey: evidenceKey({ snapshotId: snapshot.snapshotId, baselineId: null, policyHash, toolchainHash: probe.toolchainHash, acceptanceRevision }),
182
+ receivedAt: new Date().toISOString(),
183
+ });
184
+ }
185
+ return { snapshot, receipts };
186
+ }
187
+
188
+ module.exports = { runChecks, runProcess, ADAPTERS };