@sanqianx/ai-coding-workflow 0.1.2 → 0.2.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/docs/contract.md +19 -1
- package/package.json +1 -1
- package/src/bin.js +8 -6
- package/src/checks.js +31 -11
- package/src/consumer.js +10 -3
- package/src/domain.js +51 -1
- package/src/identity.js +1 -0
- package/src/review-native.js +396 -0
- package/src/server.js +403 -31
- package/src/snapshots.js +81 -20
- package/src/store.js +22 -0
- package/src/tasks.js +582 -27
package/docs/contract.md
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
|
|
24
24
|
| 方法与路径 | 语义 |
|
|
25
25
|
| --- | --- |
|
|
26
|
-
| `GET /capabilities` | 版本化能力开关(team/tasks/bridgeConsumer/reviews/checks/memberMemory/digests/internalEndpoints),未交付能力必须显式 false |
|
|
26
|
+
| `GET /capabilities` | 版本化能力开关(team/tasks/bridgeConsumer/reviews/checks/projectRepoBinding/memberMemory/digests/internalEndpoints),未交付能力必须显式 false |
|
|
27
27
|
| `GET /team` | 默认团队读取:`{team\|null, memberCount, status:'empty'\|'ready'}` |
|
|
28
28
|
| `POST /team` | 幂等创建(requestId、members、projectSettings)。members 可以传任意非空成员列表,省略时使用开发与 Review 两个模板成员。同 ID 重试复用原结果 |
|
|
29
29
|
| `PATCH /team` | CAS 改名(expectedRevision) |
|
|
@@ -32,6 +32,24 @@
|
|
|
32
32
|
| `GET/PUT /projects/:id/settings` | 项目启用与检查配置;autoDispatch、externalNotifications 默认关闭 |
|
|
33
33
|
| `GET /overview` | 有界投影(revision、team、members 汇总、projects、tasks 真实计数) |
|
|
34
34
|
| `POST /internal/context-bindings/validate` | **仅受信服务**(`X-KB-Runtime-Token`/Bearer = `KB_WORKFLOW_RUNTIME_TOKEN`);W4 前恒答 501 UNSUPPORTED,调用方必须按"无成员内容"处理 |
|
|
35
|
+
| `GET/POST /internal/project-roots` | **仅受信服务**。受信 `projectId → canonicalGitRoot` 映射注册(M0-A);POST 校验路径必须已是 Git 根,重复注册同一根幂等 |
|
|
36
|
+
|
|
37
|
+
### Review 作业与验收证据(M0-B)
|
|
38
|
+
|
|
39
|
+
- `POST /workflow-tasks/:id/reviews` **原子保留一个 review 作业并立即返回 202 `{reviewJobId, status, snapshotId, poll}`**;确定性检查在存储事务之外执行。结果一律从 `GET /review-jobs/:reviewJobId` 读取(返回 `{job, receipts, task}`,执行令牌永不出服务端)。同一 `requestId` 重试复用同一作业。
|
|
40
|
+
- 作业完成前在持久化事务内重新核对:占有令牌(外部令牌 403 FORBIDDEN)、任务 `acceptanceRevision`(被修改 → 作业 `stale`)、快照 id(工作树移动 → 作业 `stale`)。失效结果保留诊断,不应用任何收据。
|
|
41
|
+
- 快照覆盖 HEAD 一致(真实 Git blob 哈希比对)、修改、**删除**与显式包含的未跟踪文件,按 POSIX 路径确定性排序;包含文件缺失、不可读、路径越界、符号链接/junction 指向仓外均返回明确错误(`snapshot-*` reason),绝不静默跳过。
|
|
42
|
+
- 验收项可选 `requiredEvidence: [{ toolId }]`(工具 ∈ {eslint, knip})。自动项满足条件:其**每一个**具名工具都有一条 pass、complete、属于本任务、匹配当前快照 + 验收版本 + 策略的收据。跨任务收据(403)、未具名工具收据(保持 pending)一律不满足。
|
|
43
|
+
- **旧验收项重定义(PATCH acceptance)必须显式给出 requiredEvidence**——不按标题猜测检查工具;缺省验收定义仍可读,历史已交付记录保留。旧自动项重审后如实回到 pending,等待重定义。
|
|
44
|
+
- `done` 只经 `evaluateDelivery` 产生:不满足项、失效证据、未清整改清单、显式 blocked/cancelled、过期豁免都会阻止交付并给出可整改原因;人工/模型确认的授权入口尚未建立前,`satisfied` 对 manual/model_review 项返回 501 UNSUPPORTED(保持待确认),记录在案的人工确认可用带理由与有效期的豁免(waive)表达。
|
|
45
|
+
- 检查器只接受本仓锁定安装的真实 CLI 入口(eslint `bin/eslint.js`、knip `bin/knip.js`),以真实退出码、JSON 报告形态(含 knip ≥5 的 `{files, issues}` 形态)与可执行版本裁决;未知工具、未安装、超时、截断永不构成通过。
|
|
46
|
+
|
|
47
|
+
### 仓库绑定(M0-A)
|
|
48
|
+
|
|
49
|
+
- 任务在创建事务内绑定其 Git 根:绑定根只来自受信来源(受信内部端点、`createWorkflowServer({ projectRoots })` 或 `<dataDir>/workflow/projects.json`);客户端提交的 `repoPath` 只作匹配提示,必须落在绑定根之内,永远不能建立信任。
|
|
50
|
+
- 真实路径与 Git 根必须一致(realpath + `git rev-parse --show-toplevel` 双重核对);同名仓、目录不符返回 403 `FORBIDDEN`(`reason: 'repo-mismatch'`)。
|
|
51
|
+
- 无受信映射时任务如实标记 `repoBinding.status='unbound'`,其后的 review 请求在子进程启动前失败(400,`reason: 'repo-unbound'`)——未经授权的调用永远到不了检查器。
|
|
52
|
+
- Review 请求可携带受信 `canonicalGitRoot`(仅 runtime token 调用方有效)即时绑定;重复绑定同一根幂等。`resume` 保持只读,重绑会话通过既有 `session-bindings` 显式提交。
|
|
35
53
|
|
|
36
54
|
### shell 侧代理(shell 仓库实现,此处仅声明契约)
|
|
37
55
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanqianx/ai-coding-workflow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
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
5
|
"license": "Apache-2.0",
|
|
6
6
|
"publishConfig": {
|
package/src/bin.js
CHANGED
|
@@ -36,13 +36,17 @@ async function main() {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
const runtime = createWorkflowServer({ dataDir, managed: process.env.KB_WORKFLOW_MANAGED === '1', runtimeToken: process.env.KB_WORKFLOW_RUNTIME_TOKEN });
|
|
39
|
-
const {
|
|
40
|
-
|
|
39
|
+
const { consumer } = runtime;
|
|
40
|
+
// Bind ONCE. The historical second server.listen(port, host) here crashed
|
|
41
|
+
// the real CLI gate with ERR_SERVER_ALREADY_LISTEN; everything below uses
|
|
42
|
+
// the address this call resolved (so --port 0 reports the real port).
|
|
43
|
+
const bound = await runtime.listen(port, host);
|
|
44
|
+
const { port: boundPort, host: boundHost } = bound;
|
|
41
45
|
// Register the independent consumer with a wake-up URL once the port is
|
|
42
46
|
// bound, then run the startup drain (register + catch-up). Failures are
|
|
43
47
|
// logged, never fatal: the module keeps serving tasks offline.
|
|
44
48
|
if (process.env.KB_EVENT_BRIDGE_URL) {
|
|
45
|
-
const notifyUrl = `http://127.0.0.1:${
|
|
49
|
+
const notifyUrl = `http://127.0.0.1:${boundPort}/api/internal/bridge-notify`;
|
|
46
50
|
try {
|
|
47
51
|
await consumer.drain({ register: true, notifyUrl });
|
|
48
52
|
console.log(`[ai-coding-workflow] bridge consumer registered (${consumer.name}), notify ${notifyUrl}`);
|
|
@@ -59,9 +63,7 @@ async function main() {
|
|
|
59
63
|
};
|
|
60
64
|
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, stop);
|
|
61
65
|
process.on('message', message => { if (message?.type === 'kb:shutdown') stop(); });
|
|
62
|
-
|
|
63
|
-
console.log(`[ai-coding-workflow] listening on http://${host}:${port} (data: ${dataDir})`);
|
|
64
|
-
});
|
|
66
|
+
console.log(`[ai-coding-workflow] listening on http://${boundHost}:${boundPort} (data: ${dataDir})`);
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
main().catch(error => { console.error(`[ai-coding-workflow] ${error.code || 'START_FAILED'}: ${error.message}`); process.exitCode = 1; });
|
package/src/checks.js
CHANGED
|
@@ -25,6 +25,11 @@ function eslintBinPath() {
|
|
|
25
25
|
return fs.existsSync(candidate) ? candidate : null;
|
|
26
26
|
}
|
|
27
27
|
function knipEntry() {
|
|
28
|
+
// The require.resolve('knip') main entry is the library barrel — running
|
|
29
|
+
// it with --version prints nothing and the probe reports "missing". The
|
|
30
|
+
// real CLI entry is bin/knip.js (same pattern as eslint's bin).
|
|
31
|
+
const bin = path.join(__dirname, '..', 'node_modules', 'knip', 'bin', 'knip.js');
|
|
32
|
+
if (fs.existsSync(bin)) return bin;
|
|
28
33
|
try { return require.resolve('knip'); } catch { return null; }
|
|
29
34
|
}
|
|
30
35
|
|
|
@@ -116,15 +121,30 @@ const knipAdapter = {
|
|
|
116
121
|
try { payload = JSON.parse(result.stdout); }
|
|
117
122
|
catch { return { findings: [], completeness: 'unparsed', message: 'knip 输出不是合法 JSON' }; }
|
|
118
123
|
const findings = [];
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
124
|
+
// knip ≥5 JSON reporter: { files: ["src/unused.js", ...], issues: [
|
|
125
|
+
// { file, exports: [{ name, line, col }], dependencies: [], ... } ] }
|
|
126
|
+
// (older builds printed grouped { files: [{ displayName, issues }] } —
|
|
127
|
+
// keep reading that shape too so a version bump cannot silently unparse).
|
|
128
|
+
for (const entry of payload.files || []) {
|
|
129
|
+
const file = typeof entry === 'string' ? entry : (entry.file || entry.name || '');
|
|
130
|
+
if (!file) continue;
|
|
131
|
+
findings.push({ toolId: 'knip', ruleId: 'knip/unused-file', file: String(file).split(':')[0], line: null, column: null, severity: 'warning', message: `unused file: ${file}`.slice(0, 300) });
|
|
132
|
+
}
|
|
133
|
+
const issueGroups = Array.isArray(payload.issues) ? payload.issues : Object.values(payload.issues || {});
|
|
134
|
+
for (const group of issueGroups) {
|
|
135
|
+
if (typeof group === 'string') continue;
|
|
136
|
+
const file = String(group.file || '').split(':')[0];
|
|
137
|
+
for (const [kind, list] of Object.entries(group)) {
|
|
138
|
+
if (!Array.isArray(list) || ['dependencies', 'devDependencies', 'optionalPeerDependencies', 'unlisted', 'binaries', 'unresolved'].includes(kind)) continue;
|
|
139
|
+
for (const issue of list) {
|
|
140
|
+
const name = typeof issue === 'string' ? issue : (issue.name || issue.identifier || '');
|
|
141
|
+
const line = typeof issue === 'object' && issue ? (issue.line ?? null) : null;
|
|
142
|
+
const col = typeof issue === 'object' && issue ? (issue.col ?? null) : null;
|
|
143
|
+
findings.push({
|
|
144
|
+
toolId: 'knip', ruleId: `knip/${kind}`, file: file || null, line, column: col,
|
|
145
|
+
severity: 'warning', message: `${kind}: ${name}`.slice(0, 300),
|
|
146
|
+
});
|
|
147
|
+
}
|
|
128
148
|
}
|
|
129
149
|
}
|
|
130
150
|
return { findings, completeness: 'complete' };
|
|
@@ -141,8 +161,8 @@ const ADAPTERS = { eslint: eslintAdapter, knip: knipAdapter };
|
|
|
141
161
|
* success — a missing tool, error, timeout or unparsed output is recorded as
|
|
142
162
|
* such and can never be a pass.
|
|
143
163
|
*/
|
|
144
|
-
async function runChecks(repoPath, { tools = ['eslint'], policyHash = 'policy:none', acceptanceRevision = 1, config = {}, snapshot: providedSnapshot } = {}) {
|
|
145
|
-
const snapshot = providedSnapshot || captureSnapshot(repoPath, {});
|
|
164
|
+
async function runChecks(repoPath, { tools = ['eslint'], policyHash = 'policy:none', acceptanceRevision = 1, config = {}, included, snapshot: providedSnapshot } = {}) {
|
|
165
|
+
const snapshot = providedSnapshot || captureSnapshot(repoPath, { included });
|
|
146
166
|
const receipts = [];
|
|
147
167
|
for (const toolId of tools) {
|
|
148
168
|
const adapter = ADAPTERS[toolId];
|
package/src/consumer.js
CHANGED
|
@@ -61,20 +61,26 @@ class WorkflowConsumer {
|
|
|
61
61
|
this.drainPromise = null;
|
|
62
62
|
this.stopped = false;
|
|
63
63
|
this.lastDrain = null;
|
|
64
|
+
// The wake-up callback URL the Bridge should call (M0-C). First setter
|
|
65
|
+
// wins and EVERY registration carries it — a later notify-triggered
|
|
66
|
+
// drain re-registers and must never overwrite the callback back to
|
|
67
|
+
// "none", or the Bridge silently stops waking this module.
|
|
68
|
+
this.notifyUrl = null;
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
/** One drain pass over every journal. Returns per-journal stats. */
|
|
67
|
-
async drain({ register = true } = {}) {
|
|
72
|
+
async drain({ register = true, notifyUrl } = {}) {
|
|
68
73
|
if (this.drainPromise) return this.drainPromise;
|
|
74
|
+
if (notifyUrl && !this.notifyUrl) this.notifyUrl = String(notifyUrl);
|
|
69
75
|
this.drainPromise = this._drain({ register }).finally(() => { this.drainPromise = null; });
|
|
70
76
|
return this.drainPromise;
|
|
71
77
|
}
|
|
72
78
|
|
|
73
|
-
async _drain({ register
|
|
79
|
+
async _drain({ register } = {}) {
|
|
74
80
|
const stats = [];
|
|
75
81
|
if (register) {
|
|
76
82
|
const meta = { module: 'ai-coding-workflow' };
|
|
77
|
-
if (notifyUrl) meta.notifyUrl = notifyUrl;
|
|
83
|
+
if (this.notifyUrl) meta.notifyUrl = this.notifyUrl;
|
|
78
84
|
try { await this.bridge.registerConsumer(this.name, meta); }
|
|
79
85
|
catch (error) { this.logger.warn('workflow.consumer.register_failed', error.message, {}); }
|
|
80
86
|
}
|
|
@@ -210,6 +216,7 @@ class WorkflowConsumer {
|
|
|
210
216
|
return {
|
|
211
217
|
consumer: this.name,
|
|
212
218
|
bridgeUrl: this.bridge.url || null,
|
|
219
|
+
notifyUrl: this.notifyUrl || null,
|
|
213
220
|
running: Boolean(this.drainPromise),
|
|
214
221
|
stopped: this.stopped,
|
|
215
222
|
lastDrain: this.lastDrain,
|
package/src/domain.js
CHANGED
|
@@ -159,6 +159,22 @@ function normalizeProjectSettings(projectId, settings) {
|
|
|
159
159
|
externalNotifications: Boolean(settings && settings.externalNotifications), // default OFF
|
|
160
160
|
historyBackfill: Boolean(settings && settings.historyBackfill), // full-history replay, default OFF
|
|
161
161
|
checkConfig: (settings && settings.checkConfig) || null,
|
|
162
|
+
// M2-A leader planning (opt-in): the member that may be asked to plan,
|
|
163
|
+
// plus a bounded budget. Absent => plain tasks run the M1 path with
|
|
164
|
+
// ZERO leader involvement, exactly as before.
|
|
165
|
+
leaderMemberId: (settings && settings.leaderMemberId) || null,
|
|
166
|
+
leaderBudget: (settings && settings.leaderBudget && typeof settings.leaderBudget === 'object')
|
|
167
|
+
? {
|
|
168
|
+
maxPlansPerDay: Number(settings.leaderBudget.maxPlansPerDay) || 5,
|
|
169
|
+
maxPlanRunsPerTask: Number(settings.leaderBudget.maxPlanRunsPerTask) || 2,
|
|
170
|
+
}
|
|
171
|
+
: null,
|
|
172
|
+
// P2a team dispatch (opt-in, requires autoDispatch): the developer
|
|
173
|
+
// members the project allows to be dispatched work items, and the
|
|
174
|
+
// reviewer member whose driver/model must match the TRUSTED reviewer
|
|
175
|
+
// runtime config for model reviews of this project's tasks.
|
|
176
|
+
developerMemberIds: Array.isArray(settings && settings.developerMemberIds) ? [...new Set(settings.developerMemberIds.map(String))] : [],
|
|
177
|
+
reviewerMemberId: (settings && settings.reviewerMemberId) || null,
|
|
162
178
|
updatedAt: new Date().toISOString(),
|
|
163
179
|
revision: 1,
|
|
164
180
|
};
|
|
@@ -166,7 +182,10 @@ function normalizeProjectSettings(projectId, settings) {
|
|
|
166
182
|
|
|
167
183
|
function putProjectSettings(state, projectId, settings) {
|
|
168
184
|
const existing = state.projects[projectId];
|
|
169
|
-
|
|
185
|
+
// M2-A compatibility: MERGE over the existing record instead of rebuilding
|
|
186
|
+
// it. An old client PUTting only the fields it knows must never wipe the
|
|
187
|
+
// leader configuration (or any newer field) it does not send.
|
|
188
|
+
const normalized = normalizeProjectSettings(projectId, { ...(existing || {}), ...(settings || {}) });
|
|
170
189
|
if (existing) {
|
|
171
190
|
if (settings && settings.expectedRevision !== undefined && settings.expectedRevision !== null && Number(settings.expectedRevision) !== existing.revision) {
|
|
172
191
|
throw new WorkflowError('STALE_REVISION', 'Project settings changed while you were editing.', { currentRevision: existing.revision });
|
|
@@ -174,6 +193,37 @@ function putProjectSettings(state, projectId, settings) {
|
|
|
174
193
|
normalized.revision = existing.revision + 1;
|
|
175
194
|
normalized.createdAt = existing.createdAt;
|
|
176
195
|
}
|
|
196
|
+
// Leader validation: a named leader must be an existing, ENABLED member
|
|
197
|
+
// of this team — unknown or disabled members leave a visible blocker.
|
|
198
|
+
if (normalized.leaderMemberId) {
|
|
199
|
+
const leader = state.members[normalized.leaderMemberId];
|
|
200
|
+
if (!leader) throw new WorkflowError('VALIDATION', `leaderMemberId does not reference a known member.`, { projectId, leaderMemberId: normalized.leaderMemberId, reason: 'leader-member-unknown' });
|
|
201
|
+
if (!leader.enabled) throw new WorkflowError('VALIDATION', `leaderMemberId references a disabled member.`, { projectId, leaderMemberId: normalized.leaderMemberId, reason: 'leader-member-disabled' });
|
|
202
|
+
} else {
|
|
203
|
+
normalized.leaderMemberId = null;
|
|
204
|
+
normalized.leaderBudget = null;
|
|
205
|
+
}
|
|
206
|
+
// P2a: dispatchable developer members must exist, be ENABLED and carry the
|
|
207
|
+
// developer role (the role the execution engine is allowed to drive).
|
|
208
|
+
normalized.developerMemberIds = (normalized.developerMemberIds || []).filter(id => {
|
|
209
|
+
const member = state.members[id];
|
|
210
|
+
if (!member) throw new WorkflowError('VALIDATION', `developerMemberIds references unknown member ${id}.`, { projectId, memberId: id, reason: 'developer-member-unknown' });
|
|
211
|
+
if (!member.enabled) throw new WorkflowError('VALIDATION', `developerMemberIds references disabled member ${id}.`, { projectId, memberId: id, reason: 'developer-member-disabled' });
|
|
212
|
+
if (member.role !== 'developer') throw new WorkflowError('VALIDATION', `developerMemberIds requires developer-role members; ${id} is ${member.role}.`, { projectId, memberId: id, reason: 'developer-role-mismatch' });
|
|
213
|
+
return true;
|
|
214
|
+
});
|
|
215
|
+
// P2a: a project reviewer must be an enabled reviewer-role member. Its
|
|
216
|
+
// driver/model matching against the TRUSTED reviewer runtime config is
|
|
217
|
+
// checked where that config lives (server dispatch); here we pin the
|
|
218
|
+
// role/enabled shape so misconfiguration fails at save time.
|
|
219
|
+
if (normalized.reviewerMemberId) {
|
|
220
|
+
const reviewer = state.members[normalized.reviewerMemberId];
|
|
221
|
+
if (!reviewer) throw new WorkflowError('VALIDATION', `reviewerMemberId does not reference a known member.`, { projectId, reviewerMemberId: normalized.reviewerMemberId, reason: 'reviewer-member-unknown' });
|
|
222
|
+
if (!reviewer.enabled) throw new WorkflowError('VALIDATION', `reviewerMemberId references a disabled member.`, { projectId, reviewerMemberId: normalized.reviewerMemberId, reason: 'reviewer-member-disabled' });
|
|
223
|
+
if (reviewer.role !== 'reviewer') throw new WorkflowError('VALIDATION', `reviewerMemberId requires the reviewer role; ${normalized.reviewerMemberId} is ${reviewer.role}.`, { projectId, reviewerMemberId: normalized.reviewerMemberId, reason: 'reviewer-role-mismatch' });
|
|
224
|
+
} else {
|
|
225
|
+
normalized.reviewerMemberId = null;
|
|
226
|
+
}
|
|
177
227
|
state.projects[projectId] = normalized;
|
|
178
228
|
return normalized;
|
|
179
229
|
}
|
package/src/identity.js
CHANGED
|
@@ -20,6 +20,7 @@ const CAPABILITIES = {
|
|
|
20
20
|
bridgeConsumer: true, // independent Bridge journal consumer (W3)
|
|
21
21
|
reviews: false, // model review orchestration via Workbench (later slice of W5)
|
|
22
22
|
checks: true, // deterministic quality CLI runner (eslint/knip subprocess receipts)
|
|
23
|
+
projectRepoBinding: true, // trusted projectId → canonical Git root binding (M0-A)
|
|
23
24
|
memberMemory: true, // member binding validation for engine reads (W4)
|
|
24
25
|
digests: true, // daily digest + reminders, deterministic aggregation (W7)
|
|
25
26
|
internalEndpoints: true, // trusted-service validation endpoints (engine/workbench)
|