@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 +201 -0
- package/README.md +37 -2
- package/docs/contract.md +52 -0
- package/package.json +51 -4
- package/src/bin.js +67 -0
- package/src/checks.js +188 -0
- package/src/consumer.js +222 -0
- package/src/digests.js +103 -0
- package/src/domain.js +174 -0
- package/src/errors.js +43 -0
- package/src/identity.js +47 -0
- package/src/server.js +532 -0
- package/src/snapshots.js +84 -0
- package/src/store.js +257 -0
- package/src/tasks.js +395 -0
- package/ui/app.css +186 -0
- package/ui/app.js +541 -0
- package/ui/index.html +41 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// HTTP server for the workflow module. Node standard library only.
|
|
4
|
+
//
|
|
5
|
+
// Route map (runbook §2.3, main plan §11):
|
|
6
|
+
// GET /api/health identity probe (shell reuse detection)
|
|
7
|
+
// GET /api/workflow/v1/capabilities additive capability switches
|
|
8
|
+
// GET/POST /api/workflow/v1/team read / idempotent create of the default team
|
|
9
|
+
// PATCH /api/workflow/v1/team CAS rename
|
|
10
|
+
// GET/POST /api/workflow/v1/members list / create
|
|
11
|
+
// GET/PATCH /api/workflow/v1/members/:id read / CAS update + disable
|
|
12
|
+
// GET/PUT /api/workflow/v1/projects/:id/settings per-project enablement
|
|
13
|
+
// GET /api/workflow/v1/overview bounded projection for the shell home
|
|
14
|
+
// POST /api/internal/context-bindings/validate trusted-only (runtime token), W4 fills real validation
|
|
15
|
+
// GET / + /ui assets native page (standalone or embed=1)
|
|
16
|
+
//
|
|
17
|
+
// Browser-facing writes require same-origin (loopback default) and carry
|
|
18
|
+
// requestId + expectedRevision; the internal endpoints additionally require
|
|
19
|
+
// the KB_WORKFLOW_RUNTIME_TOKEN bearer and are stripped by the shell proxy.
|
|
20
|
+
|
|
21
|
+
const http = require('http');
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
const { URL } = require('url');
|
|
25
|
+
const { WorkflowError } = require('./errors');
|
|
26
|
+
const { WorkflowStore } = require('./store');
|
|
27
|
+
const domain = require('./domain');
|
|
28
|
+
const tasksDomain = require('./tasks');
|
|
29
|
+
const { WorkflowConsumer } = require('./consumer');
|
|
30
|
+
const { runChecks } = require('./checks');
|
|
31
|
+
const { buildDailyDigest, upsertReminder, reminderAction, localDay } = require('./digests');
|
|
32
|
+
const { healthBody, capabilitiesBody } = require('./identity');
|
|
33
|
+
|
|
34
|
+
function taskRepoPath(snapshot, taskId) {
|
|
35
|
+
const task = snapshot.tasks[taskId];
|
|
36
|
+
return task && task.sourceRefs && task.sourceRefs.repoPath ? task.sourceRefs.repoPath : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const UI_ROOT = path.join(__dirname, '..', 'ui');
|
|
40
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
41
|
+
const PROXY_HOP_HEADERS = ['x-forwarded-host', 'x-forwarded-for'];
|
|
42
|
+
|
|
43
|
+
function createWorkflowServer(options = {}) {
|
|
44
|
+
const store = options.store || new WorkflowStore(options.dataDir);
|
|
45
|
+
const runtimeToken = options.runtimeToken || process.env.KB_WORKFLOW_RUNTIME_TOKEN || null;
|
|
46
|
+
const startedAt = Date.now();
|
|
47
|
+
const state = { dataDir: options.dataDir || null, managed: Boolean(options.managed) };
|
|
48
|
+
// Independent Bridge consumer. Registering/draining is explicit (notify or
|
|
49
|
+
// admin call); constructing never starts network loops.
|
|
50
|
+
const bridgeUrl = options.bridgeUrl || process.env.KB_EVENT_BRIDGE_URL || '';
|
|
51
|
+
const consumer = new WorkflowConsumer({
|
|
52
|
+
store,
|
|
53
|
+
bridgeUrl,
|
|
54
|
+
consumerName: options.consumerName || `workflow:${options.storeId || 'default'}`,
|
|
55
|
+
logger: { info: () => {}, warn: () => {} },
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
function send(res, status, body, extraHeaders = {}) {
|
|
59
|
+
const payload = typeof body === 'string' ? body : JSON.stringify(body);
|
|
60
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...extraHeaders });
|
|
61
|
+
res.end(payload);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function isTrustedRequest(req) {
|
|
65
|
+
if (!runtimeToken) return false;
|
|
66
|
+
const header = req.headers['x-kb-runtime-token'] || '';
|
|
67
|
+
const auth = String(req.headers.authorization || '');
|
|
68
|
+
const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';
|
|
69
|
+
return header === runtimeToken || bearer === runtimeToken;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function readJsonBody(req) {
|
|
73
|
+
const chunks = [];
|
|
74
|
+
let size = 0;
|
|
75
|
+
for await (const chunk of req) {
|
|
76
|
+
size += chunk.length;
|
|
77
|
+
if (size > MAX_BODY_BYTES) throw new WorkflowError('VALIDATION', 'Request body too large.');
|
|
78
|
+
chunks.push(chunk);
|
|
79
|
+
}
|
|
80
|
+
if (!chunks.length) return {};
|
|
81
|
+
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
82
|
+
catch { throw new WorkflowError('VALIDATION', 'Request body must be valid JSON.'); }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function requireId(requestId) {
|
|
86
|
+
if (!requestId || typeof requestId !== 'string') throw new WorkflowError('VALIDATION', 'Write requests must carry a requestId.');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---------- API handlers ----------
|
|
90
|
+
|
|
91
|
+
async function handleTeam(method, search) {
|
|
92
|
+
if (method === 'GET') {
|
|
93
|
+
const snapshot = await store.read();
|
|
94
|
+
return { team: snapshot.team ? domain.publicTeam(snapshot.team) : null, memberCount: Object.keys(snapshot.members).length, status: snapshot.team ? 'ready' : 'empty' };
|
|
95
|
+
}
|
|
96
|
+
if (method === 'POST') {
|
|
97
|
+
// handled by caller with body
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
throw new WorkflowError('NOT_FOUND', 'Unsupported method for /team.');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function apiRoute(req, res, pathname, search) {
|
|
104
|
+
const method = req.method || 'GET';
|
|
105
|
+
const url = new URL(pathname + (search || ''), 'http://localhost');
|
|
106
|
+
|
|
107
|
+
if (pathname === '/api/health' && method === 'GET') {
|
|
108
|
+
return send(res, 200, healthBody({ uptimeSec: Math.floor((Date.now() - startedAt) / 1000), dataDir: state.dataDir, managed: state.managed }));
|
|
109
|
+
}
|
|
110
|
+
if (pathname === '/api/workflow/v1/capabilities' && method === 'GET') {
|
|
111
|
+
return send(res, 200, capabilitiesBody());
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (pathname === '/api/workflow/v1/team') {
|
|
115
|
+
if (method === 'GET') return send(res, 200, await handleTeam('GET'));
|
|
116
|
+
if (method === 'POST') {
|
|
117
|
+
const body = await readJsonBody(req);
|
|
118
|
+
requireId(body.requestId);
|
|
119
|
+
const { replayed, result, revision } = await store.mutate({
|
|
120
|
+
requestId: body.requestId,
|
|
121
|
+
payload: { op: 'createTeam', name: body.name, memberDrafts: body.members, projectSettings: body.projectSettings },
|
|
122
|
+
op: snapshot => domain.createTeam(snapshot, { name: body.name, memberDrafts: body.members, projectSettings: body.projectSettings }),
|
|
123
|
+
});
|
|
124
|
+
return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, ...result });
|
|
125
|
+
}
|
|
126
|
+
if (method === 'PATCH') {
|
|
127
|
+
const body = await readJsonBody(req);
|
|
128
|
+
requireId(body.requestId);
|
|
129
|
+
const { replayed, result, revision } = await store.mutate({
|
|
130
|
+
requestId: body.requestId,
|
|
131
|
+
payload: { op: 'patchTeam', name: body.name, expectedRevision: body.expectedRevision },
|
|
132
|
+
expectedRevision: body.expectedRevision,
|
|
133
|
+
op: snapshot => {
|
|
134
|
+
const team = domain.requireTeam(snapshot);
|
|
135
|
+
if (body.name !== undefined) {
|
|
136
|
+
const trimmed = String(body.name).trim();
|
|
137
|
+
if (!trimmed) throw new WorkflowError('VALIDATION', 'Team name cannot be empty.');
|
|
138
|
+
team.name = trimmed.slice(0, 120);
|
|
139
|
+
}
|
|
140
|
+
team.revision += 1;
|
|
141
|
+
team.updatedAt = new Date().toISOString();
|
|
142
|
+
return domain.publicTeam(team);
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
return send(res, 200, { ok: true, replayed, revision, team: result });
|
|
146
|
+
}
|
|
147
|
+
throw new WorkflowError('NOT_FOUND', 'Unsupported method for /team.');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (pathname === '/api/workflow/v1/members') {
|
|
151
|
+
if (method === 'GET') {
|
|
152
|
+
const snapshot = await store.read();
|
|
153
|
+
return send(res, 200, { members: Object.values(snapshot.members).map(domain.publicMember) });
|
|
154
|
+
}
|
|
155
|
+
if (method === 'POST') {
|
|
156
|
+
const body = await readJsonBody(req);
|
|
157
|
+
requireId(body.requestId);
|
|
158
|
+
const { replayed, result, revision } = await store.mutate({
|
|
159
|
+
requestId: body.requestId,
|
|
160
|
+
payload: { op: 'createMember', member: body },
|
|
161
|
+
op: snapshot => {
|
|
162
|
+
domain.requireTeam(snapshot);
|
|
163
|
+
const draft = { name: body.name, role: body.role, driverId: body.driverId, profileId: body.profileId, model: body.model, memoryGroupIds: body.memoryGroupIds };
|
|
164
|
+
const errors = domain.validateMemberInput(draft);
|
|
165
|
+
if (errors.length) throw new WorkflowError('VALIDATION', `Invalid member: ${errors.join('; ')}`);
|
|
166
|
+
const crypto = require('crypto');
|
|
167
|
+
const memberId = `member_${crypto.randomBytes(10).toString('hex')}`;
|
|
168
|
+
snapshot.members[memberId] = {
|
|
169
|
+
memberId, teamId: snapshot.team.teamId,
|
|
170
|
+
name: String(body.name).trim(), role: body.role,
|
|
171
|
+
driverId: body.driverId || null, profileId: body.profileId || null, model: body.model || null,
|
|
172
|
+
memoryGroupIds: Array.isArray(body.memoryGroupIds) ? body.memoryGroupIds.map(String) : [],
|
|
173
|
+
enabled: true, revision: 1, createdAt: new Date().toISOString(),
|
|
174
|
+
};
|
|
175
|
+
return domain.publicMember(snapshot.members[memberId]);
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, member: result });
|
|
179
|
+
}
|
|
180
|
+
throw new WorkflowError('NOT_FOUND', 'Unsupported method for /members.');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const memberMatch = pathname.match(/^\/api\/workflow\/v1\/members\/([^/]+)$/);
|
|
184
|
+
if (memberMatch) {
|
|
185
|
+
const memberId = memberMatch[1];
|
|
186
|
+
if (method === 'GET') {
|
|
187
|
+
const snapshot = await store.read();
|
|
188
|
+
const member = snapshot.members[memberId];
|
|
189
|
+
if (!member) throw new WorkflowError('NOT_FOUND', 'Member not found.', { memberId });
|
|
190
|
+
return send(res, 200, { member: domain.publicMember(member) });
|
|
191
|
+
}
|
|
192
|
+
if (method === 'PATCH') {
|
|
193
|
+
const body = await readJsonBody(req);
|
|
194
|
+
requireId(body.requestId);
|
|
195
|
+
const { replayed, result, revision } = await store.mutate({
|
|
196
|
+
requestId: body.requestId,
|
|
197
|
+
payload: { op: 'patchMember', memberId, patch: body },
|
|
198
|
+
op: snapshot => domain.patchMember(snapshot, memberId, body, body.expectedRevision),
|
|
199
|
+
});
|
|
200
|
+
return send(res, 200, { ok: true, replayed, revision, member: result });
|
|
201
|
+
}
|
|
202
|
+
throw new WorkflowError('NOT_FOUND', 'Unsupported method for /members/:id.');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const projectMatch = pathname.match(/^\/api\/workflow\/v1\/projects\/([^/]+)\/settings$/);
|
|
206
|
+
if (projectMatch) {
|
|
207
|
+
const projectId = decodeURIComponent(projectMatch[1]);
|
|
208
|
+
if (method === 'GET') {
|
|
209
|
+
const snapshot = await store.read();
|
|
210
|
+
return send(res, 200, { settings: snapshot.projects[projectId] || { projectId, enabled: false, status: 'not_configured' } });
|
|
211
|
+
}
|
|
212
|
+
if (method === 'PUT') {
|
|
213
|
+
const body = await readJsonBody(req);
|
|
214
|
+
requireId(body.requestId);
|
|
215
|
+
const { replayed, result, revision } = await store.mutate({
|
|
216
|
+
requestId: body.requestId,
|
|
217
|
+
payload: { op: 'putProjectSettings', projectId, settings: body },
|
|
218
|
+
op: snapshot => domain.putProjectSettings(snapshot, projectId, body),
|
|
219
|
+
});
|
|
220
|
+
return send(res, 200, { ok: true, replayed, revision, settings: result });
|
|
221
|
+
}
|
|
222
|
+
throw new WorkflowError('NOT_FOUND', 'Unsupported method for project settings.');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (pathname === '/api/workflow/v1/overview' && method === 'GET') {
|
|
226
|
+
const snapshot = await store.read();
|
|
227
|
+
const allTasks = Object.values(snapshot.tasks);
|
|
228
|
+
return send(res, 200, {
|
|
229
|
+
revision: snapshot.revision,
|
|
230
|
+
team: snapshot.team ? { teamId: snapshot.team.teamId, name: snapshot.team.name } : null,
|
|
231
|
+
members: { total: Object.keys(snapshot.members).length, enabled: Object.values(snapshot.members).filter(m => m.enabled).length },
|
|
232
|
+
projects: Object.values(snapshot.projects).map(p => ({ projectId: p.projectId, enabled: p.enabled })),
|
|
233
|
+
tasks: {
|
|
234
|
+
total: allTasks.length,
|
|
235
|
+
active: allTasks.filter(t => !['done', 'cancelled'].includes(t.status)).length,
|
|
236
|
+
blocked: allTasks.filter(t => t.status === 'blocked').length,
|
|
237
|
+
},
|
|
238
|
+
capabilities: capabilitiesBody().capabilities,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------- business tasks (W3) ----------
|
|
243
|
+
|
|
244
|
+
if (pathname === '/api/workflow/v1/workflow-tasks') {
|
|
245
|
+
if (method === 'GET') {
|
|
246
|
+
const snapshot = await store.read();
|
|
247
|
+
const limit = Math.min(Number(url.searchParams.get('limit') || 50), 100);
|
|
248
|
+
const projectId = url.searchParams.get('projectId') || null;
|
|
249
|
+
const status = url.searchParams.get('status') || null;
|
|
250
|
+
const q = (url.searchParams.get('q') || '').toLowerCase();
|
|
251
|
+
const after = Number(url.searchParams.get('after') || 0);
|
|
252
|
+
let list = Object.values(snapshot.tasks)
|
|
253
|
+
.filter(t => !projectId || t.projectId === projectId)
|
|
254
|
+
.filter(t => !status || t.status === status)
|
|
255
|
+
.filter(t => !q || t.title.toLowerCase().includes(q))
|
|
256
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
257
|
+
if (after) list = list.filter(t => t.revision > 0); // cursor below is by changeSeq-independent updatedAt; keep simple bounded page
|
|
258
|
+
const cursorIndex = Number(url.searchParams.get('cursor') || 0);
|
|
259
|
+
const page = list.slice(cursorIndex, cursorIndex + limit);
|
|
260
|
+
return send(res, 200, {
|
|
261
|
+
tasks: page.map(tasksDomain.publicTask),
|
|
262
|
+
nextCursor: cursorIndex + limit < list.length ? cursorIndex + limit : null,
|
|
263
|
+
total: list.length,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
if (method === 'POST') {
|
|
267
|
+
const body = await readJsonBody(req);
|
|
268
|
+
requireId(body.requestId);
|
|
269
|
+
const { replayed, result, revision } = await store.mutate({
|
|
270
|
+
requestId: body.requestId,
|
|
271
|
+
payload: { op: 'createTask', input: body },
|
|
272
|
+
op: snapshot => {
|
|
273
|
+
if (!snapshot.team) throw new WorkflowError('VALIDATION', 'Create the default team before starting tasks.');
|
|
274
|
+
return tasksDomain.createTask(snapshot, body);
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, task: result });
|
|
278
|
+
}
|
|
279
|
+
throw new WorkflowError('NOT_FOUND', 'Unsupported method for /workflow-tasks.');
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const taskMatch = pathname.match(/^\/api\/workflow\/v1\/workflow-tasks\/([^/]+)(?:\/(session-bindings|checkpoints|runs|acceptance-decisions|reviews))?$/);
|
|
283
|
+
if (taskMatch) {
|
|
284
|
+
const taskId = taskMatch[1];
|
|
285
|
+
const sub = taskMatch[2] || null;
|
|
286
|
+
if (!sub && method === 'GET') {
|
|
287
|
+
const snapshot = await store.read();
|
|
288
|
+
return send(res, 200, { task: tasksDomain.publicTask(tasksDomain.requireTask(snapshot, taskId)) });
|
|
289
|
+
}
|
|
290
|
+
if (!sub && method === 'PATCH') {
|
|
291
|
+
const body = await readJsonBody(req);
|
|
292
|
+
requireId(body.requestId);
|
|
293
|
+
const { replayed, result, revision } = await store.mutate({
|
|
294
|
+
requestId: body.requestId,
|
|
295
|
+
payload: { op: 'patchTask', taskId, patch: body },
|
|
296
|
+
op: snapshot => tasksDomain.patchTask(snapshot, taskId, body, body.expectedRevision),
|
|
297
|
+
});
|
|
298
|
+
return send(res, 200, { ok: true, replayed, revision, task: result });
|
|
299
|
+
}
|
|
300
|
+
if (sub === 'reviews' && method === 'POST') {
|
|
301
|
+
// W5: run the deterministic checks over a fresh snapshot of the
|
|
302
|
+
// task's repository, persist receipts, and let the receipt verdicts
|
|
303
|
+
// drive automated acceptance. Model review orchestration (Workbench
|
|
304
|
+
// background execution) stays honestly 'pending-model-review' until
|
|
305
|
+
// its slice ships — nothing here fakes an opinion.
|
|
306
|
+
const body = await readJsonBody(req);
|
|
307
|
+
requireId(body.requestId);
|
|
308
|
+
const preSnapshot = await store.read();
|
|
309
|
+
const repoPath = body.repoPath || taskRepoPath(preSnapshot, taskId);
|
|
310
|
+
if (!repoPath || !fs.existsSync(repoPath)) throw new WorkflowError('VALIDATION', '任务的仓库路径不可用(repoPath)。', { taskId });
|
|
311
|
+
const tools = Array.isArray(body.tools) && body.tools.length ? body.tools : ['eslint'];
|
|
312
|
+
const runResult = await runChecks(repoPath, { tools, policyHash: body.policyHash || 'policy:none', acceptanceRevision: preSnapshot.tasks[taskId].acceptanceRevision, config: body.config || {} });
|
|
313
|
+
const applied = await store.mutate({
|
|
314
|
+
requestId: body.requestId,
|
|
315
|
+
payload: { op: 'applyChecks', taskId, receiptVerdicts: runResult.receipts.map(r => [r.toolId, r.verdict]) },
|
|
316
|
+
op: state => tasksDomain.applyCheckReceipts(state, taskId, { snapshot: runResult.snapshot, receipts: runResult.receipts, policyHash: body.policyHash || 'policy:none' }),
|
|
317
|
+
});
|
|
318
|
+
return send(res, applied.replayed ? 200 : 201, {
|
|
319
|
+
ok: true, replayed: applied.replayed, revision: applied.revision,
|
|
320
|
+
snapshot: { snapshotId: runResult.snapshot.snapshotId, fileCount: runResult.snapshot.fileCount },
|
|
321
|
+
receipts: runResult.receipts.map((r, i) => ({ receiptId: (applied.result.receiptIds || [])[i] || null, toolId: r.toolId, verdict: r.verdict, findingCount: r.findingCount ?? r.findings?.length ?? 0, completeness: r.completeness, executionStatus: r.executionStatus, message: r.message })),
|
|
322
|
+
decision: applied.result.decision,
|
|
323
|
+
modelReview: 'pending-model-review',
|
|
324
|
+
task: tasksDomain.publicTask((await store.read()).tasks[taskId]),
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
if (sub && method === 'POST') {
|
|
328
|
+
const body = await readJsonBody(req);
|
|
329
|
+
requireId(body.requestId);
|
|
330
|
+
const { replayed, result, revision } = await store.mutate({
|
|
331
|
+
requestId: body.requestId,
|
|
332
|
+
payload: { op: `task.${sub}`, taskId, body },
|
|
333
|
+
op: snapshot => {
|
|
334
|
+
if (sub === 'session-bindings') return tasksDomain.addSessionBinding(snapshot, taskId, body);
|
|
335
|
+
if (sub === 'checkpoints') return tasksDomain.addCheckpoint(snapshot, taskId, body);
|
|
336
|
+
if (sub === 'runs') return tasksDomain.addRun(snapshot, taskId, body);
|
|
337
|
+
if (sub === 'acceptance-decisions') {
|
|
338
|
+
const decision = tasksDomain.recordAcceptanceDecision(snapshot, taskId, body);
|
|
339
|
+
return { decision, task: tasksDomain.publicTask(snapshot.tasks[taskId]) };
|
|
340
|
+
}
|
|
341
|
+
throw new WorkflowError('NOT_FOUND', 'Unknown task subresource.');
|
|
342
|
+
},
|
|
343
|
+
});
|
|
344
|
+
const key = sub === 'session-bindings' ? 'binding' : sub === 'checkpoints' ? 'checkpoint' : sub === 'runs' ? 'run' : 'result';
|
|
345
|
+
return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, [key]: result });
|
|
346
|
+
}
|
|
347
|
+
throw new WorkflowError('NOT_FOUND', `Unsupported method for task ${sub || ''}.`);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const receiptMatch = pathname.match(/^\/api\/workflow\/v1\/check-receipts\/([^/]+)$/);
|
|
351
|
+
if (receiptMatch && method === 'GET') {
|
|
352
|
+
const snapshot = await store.read();
|
|
353
|
+
const receipt = (snapshot.checkReceipts || {})[receiptMatch[1]];
|
|
354
|
+
if (!receipt) throw new WorkflowError('NOT_FOUND', 'Check receipt not found.', { receiptId: receiptMatch[1] });
|
|
355
|
+
return send(res, 200, { receipt });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ---------- digests + reminders (W7) ----------
|
|
359
|
+
|
|
360
|
+
if (pathname === '/api/workflow/v1/daily-digests' && method === 'GET') {
|
|
361
|
+
const day = url.searchParams.get('day') || localDay(new Date().toISOString());
|
|
362
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new WorkflowError('VALIDATION', 'day must be YYYY-MM-DD (Asia/Shanghai).');
|
|
363
|
+
const snapshot = await store.read();
|
|
364
|
+
return send(res, 200, buildDailyDigest(snapshot, day));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (pathname === '/api/workflow/v1/reminders' && method === 'GET') {
|
|
368
|
+
const snapshot = await store.read();
|
|
369
|
+
const includeDismissed = url.searchParams.get('includeDismissed') === '1';
|
|
370
|
+
const nowIso = new Date().toISOString();
|
|
371
|
+
const reminders = (snapshot.reminders || []).filter(r => includeDismissed || (r.status !== 'dismissed' && !(r.status === 'snoozed' && r.snoozedUntil > nowIso)));
|
|
372
|
+
return send(res, 200, { reminders });
|
|
373
|
+
}
|
|
374
|
+
if (pathname === '/api/workflow/v1/reminders' && method === 'POST') {
|
|
375
|
+
const body = await readJsonBody(req);
|
|
376
|
+
requireId(body.requestId);
|
|
377
|
+
const { replayed, result, revision } = await store.mutate({
|
|
378
|
+
requestId: body.requestId,
|
|
379
|
+
payload: { op: 'reminder.upsert', body },
|
|
380
|
+
op: snapshot => upsertReminder(snapshot, body),
|
|
381
|
+
});
|
|
382
|
+
return send(res, replayed ? 200 : 201, { ok: true, replayed, revision, reminder: result });
|
|
383
|
+
}
|
|
384
|
+
const reminderMatch = pathname.match(/^\/api\/workflow\/v1\/reminders\/([^/]+)$/);
|
|
385
|
+
if (reminderMatch && method === 'PATCH') {
|
|
386
|
+
const body = await readJsonBody(req);
|
|
387
|
+
requireId(body.requestId);
|
|
388
|
+
const { replayed, result, revision } = await store.mutate({
|
|
389
|
+
requestId: body.requestId,
|
|
390
|
+
payload: { op: 'reminder.action', id: reminderMatch[1], action: body.action },
|
|
391
|
+
op: snapshot => reminderAction(snapshot, reminderMatch[1], body.action, body),
|
|
392
|
+
});
|
|
393
|
+
return send(res, 200, { ok: true, replayed, revision, reminder: result });
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (pathname === '/api/workflow/v1/consumer' && method === 'GET') {
|
|
397
|
+
const snapshot = await store.read();
|
|
398
|
+
return send(res, 200, {
|
|
399
|
+
...consumer.status(),
|
|
400
|
+
configured: Boolean(bridgeUrl),
|
|
401
|
+
cursors: snapshot.cursors || {},
|
|
402
|
+
pendingEvents: (snapshot.consumer && snapshot.consumer.pendingEvents) || 0,
|
|
403
|
+
inboxSize: Object.keys(snapshot.inbox || {}).length,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
if (pathname === '/api/workflow/v1/consumer/drain' && method === 'POST') {
|
|
407
|
+
if (!bridgeUrl) throw new WorkflowError('UNSUPPORTED', 'Event Bridge URL is not configured for this module.');
|
|
408
|
+
await readJsonBody(req);
|
|
409
|
+
const stats = await consumer.drain();
|
|
410
|
+
return send(res, 200, { ok: true, stats });
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (pathname === '/api/workflow/v1/workflow-changes' && method === 'GET') {
|
|
414
|
+
const snapshot = await store.read();
|
|
415
|
+
const after = Number(url.searchParams.get('after') || 0);
|
|
416
|
+
const limit = Math.min(Number(url.searchParams.get('limit') || 100), 200);
|
|
417
|
+
const changes = (snapshot.changes || []).filter(c => c.seq > after).slice(0, limit);
|
|
418
|
+
return send(res, 200, { revision: snapshot.revision, changes, latestSeq: snapshot.changeSeq || 0, truncated: (snapshot.changes || []).filter(c => c.seq > after).length > changes.length });
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (pathname === '/api/internal/context-bindings/validate' && method === 'POST') {
|
|
422
|
+
if (!isTrustedRequest(req)) throw new WorkflowError('UNAUTHENTICATED', 'Internal endpoints require the runtime token.');
|
|
423
|
+
// W4: read-only validation for the engine. Valid requires an OPEN
|
|
424
|
+
// session binding for (client, nativeSessionId) whose member exists,
|
|
425
|
+
// is enabled, and — when the caller pins a memberId — matches. The
|
|
426
|
+
// answer carries the member revision so the engine can reject stale
|
|
427
|
+
// local projections. This never widens: any miss returns valid:false.
|
|
428
|
+
const body = await readJsonBody(req);
|
|
429
|
+
const client = String(body.client || '');
|
|
430
|
+
const sessionId = String(body.sessionId || '');
|
|
431
|
+
const memberId = String(body.memberId || '');
|
|
432
|
+
if (!client || !sessionId || !memberId) return send(res, 200, { valid: false, reason: 'missing-identity' });
|
|
433
|
+
const snapshot = await store.read();
|
|
434
|
+
const open = Object.values(snapshot.sessionBindings).find(b => !b.validTo && b.client === client && b.nativeSessionId === sessionId);
|
|
435
|
+
if (!open) return send(res, 200, { valid: false, reason: 'no-open-binding' });
|
|
436
|
+
if (open.memberId !== memberId) return send(res, 200, { valid: false, reason: 'binding-member-mismatch' });
|
|
437
|
+
const member = snapshot.members[memberId];
|
|
438
|
+
if (!member || !member.enabled) return send(res, 200, { valid: false, reason: 'member-missing-or-disabled' });
|
|
439
|
+
return send(res, 200, { valid: true, memberId, memberRevision: member.revision, epoch: `rev${snapshot.revision}` });
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Bridge wake-up callback. Body is intentionally ignored (family contract
|
|
443
|
+
// I-16): like the shell's /api/bridge/notify and the engine's notify
|
|
444
|
+
// route, this only triggers an idempotent pull-drain — a forged wake-up
|
|
445
|
+
// at worst causes one harmless drain, so no token gate (the Bridge does
|
|
446
|
+
// not know this module's token).
|
|
447
|
+
if (pathname === '/api/internal/bridge-notify' && method === 'POST') {
|
|
448
|
+
await readJsonBody(req);
|
|
449
|
+
const stats = await consumer.drain().catch(error => ({ error: error.message }));
|
|
450
|
+
return send(res, 200, { ok: true, journals: Array.isArray(stats) ? stats.length : 0 });
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
throw new WorkflowError('NOT_FOUND', `No workflow API route for ${method} ${pathname}.`);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// ---------- static UI ----------
|
|
457
|
+
|
|
458
|
+
const STATIC_ROUTES = new Map([
|
|
459
|
+
['/', 'index.html'],
|
|
460
|
+
['/index.html', 'index.html'],
|
|
461
|
+
['/app.js', 'app.js'],
|
|
462
|
+
['/app.css', 'app.css'],
|
|
463
|
+
]);
|
|
464
|
+
|
|
465
|
+
function serveStatic(req, res, pathname) {
|
|
466
|
+
const rel = STATIC_ROUTES.get(pathname);
|
|
467
|
+
if (!rel || req.method !== 'GET') { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Not found'); return; }
|
|
468
|
+
const filePath = path.join(UI_ROOT, rel);
|
|
469
|
+
// Defense in depth: the route table is a fixed whitelist; the join is
|
|
470
|
+
// only a convenience. Reject anything that escaped the UI root.
|
|
471
|
+
if (!filePath.startsWith(UI_ROOT + path.sep)) { res.writeHead(404); res.end('Not found'); return; }
|
|
472
|
+
let data;
|
|
473
|
+
try { data = fs.readFileSync(filePath); } catch { res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end('Not found'); return; }
|
|
474
|
+
const type = rel.endsWith('.html') ? 'text/html; charset=utf-8' : rel.endsWith('.js') ? 'text/javascript; charset=utf-8' : rel.endsWith('.css') ? 'text/css; charset=utf-8' : 'application/octet-stream';
|
|
475
|
+
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-cache' });
|
|
476
|
+
res.end(data);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const server = http.createServer(async (req, res) => {
|
|
480
|
+
try {
|
|
481
|
+
const reqUrl = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`);
|
|
482
|
+
const pathname = reqUrl.pathname;
|
|
483
|
+
for (const header of PROXY_HOP_HEADERS) delete req.headers[header];
|
|
484
|
+
if (pathname.startsWith('/api/')) {
|
|
485
|
+
await apiRoute(req, res, pathname, reqUrl.search);
|
|
486
|
+
} else {
|
|
487
|
+
serveStatic(req, res, pathname);
|
|
488
|
+
}
|
|
489
|
+
} catch (error) {
|
|
490
|
+
if (error instanceof WorkflowError) return send(res, error.status, error.toJSON());
|
|
491
|
+
const message = error && error.code === 'EACCES' ? 'DATA_DIR_NOT_WRITABLE' : 'INTERNAL_ERROR';
|
|
492
|
+
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
493
|
+
res.end(JSON.stringify({ ok: false, error: message }));
|
|
494
|
+
if (!(error && error.code === 'EACCES')) console.error('[ai-coding-workflow] unhandled error:', error);
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
// Constructing the runtime never binds a port — callers decide: the CLI
|
|
499
|
+
// binds its explicit --port, tests bind an ephemeral one via listen(0).
|
|
500
|
+
// `ready` resolves once the runtime is constructed; `listen()` resolves
|
|
501
|
+
// with the bound address (and rejects on EADDRINUSE so the family port
|
|
502
|
+
// resolver can move to another port instead of crash-looping).
|
|
503
|
+
const ready = Promise.resolve({ server, store });
|
|
504
|
+
function listen(port, host) {
|
|
505
|
+
return new Promise((resolve, reject) => {
|
|
506
|
+
server.once('error', reject);
|
|
507
|
+
server.listen(port, host || '127.0.0.1', () => {
|
|
508
|
+
resolve({ server, store, port: server.address().port, host: server.address().address });
|
|
509
|
+
});
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
return {
|
|
514
|
+
server,
|
|
515
|
+
store,
|
|
516
|
+
consumer,
|
|
517
|
+
ready,
|
|
518
|
+
listen,
|
|
519
|
+
async close() {
|
|
520
|
+
consumer.stop();
|
|
521
|
+
store.close();
|
|
522
|
+
// undici fetch keeps idle keep-alive sockets open, and server.close()
|
|
523
|
+
// waits for every connection — without dropping them the close promise
|
|
524
|
+
// never resolves and test processes hang.
|
|
525
|
+
server.closeAllConnections?.();
|
|
526
|
+
server.closeIdleConnections?.();
|
|
527
|
+
await new Promise(resolve => server.close(resolve));
|
|
528
|
+
},
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
module.exports = { createWorkflowServer };
|
package/src/snapshots.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Code snapshots for the review/check pipeline (main plan §9.1).
|
|
4
|
+
//
|
|
5
|
+
// A snapshot captures the work tree the way a delivery actually looks:
|
|
6
|
+
// tracked files at HEAD, tracked files with local modifications, AND the
|
|
7
|
+
// explicitly included untracked source files. Each file keeps its path,
|
|
8
|
+
// origin (head|modified|untracked), byte length and content hash; the
|
|
9
|
+
// snapshot id is a hash over the manifest, so the same tree yields the same
|
|
10
|
+
// id and cached evidence stays reusable, while ANY change (even with HEAD
|
|
11
|
+
// unchanged) yields a new id and invalidates prior receipts (T11).
|
|
12
|
+
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
const { spawnSync } = require('child_process');
|
|
17
|
+
|
|
18
|
+
const SOURCE_EXTS = new Set(['.js', '.cjs', '.mjs', '.ts', '.jsx', '.tsx', '.cc', '.cpp', '.h', '.hpp', '.go', '.json', '.css', '.html']);
|
|
19
|
+
|
|
20
|
+
function git(repoPath, args) {
|
|
21
|
+
const result = spawnSync('git', ['-C', repoPath, ...args], { encoding: 'utf8', windowsHide: true });
|
|
22
|
+
if (result.status !== 0) throw Object.assign(new Error(`git ${args[0]} failed: ${(result.stderr || '').slice(0, 200)}`), { code: 'GIT_FAILED' });
|
|
23
|
+
return result.stdout;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function hashBytes(buffer) { return crypto.createHash('sha256').update(buffer).digest('hex'); }
|
|
27
|
+
|
|
28
|
+
function isSourceFile(relativePath, includePatterns) {
|
|
29
|
+
if (includePatterns && includePatterns.length) return includePatterns.some(p => relativePath.startsWith(p.replace(/\/$/, '') + '/') || relativePath === p);
|
|
30
|
+
return SOURCE_EXTS.has(path.extname(relativePath));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Materialize a snapshot record for a repository. `options.included` lists
|
|
35
|
+
* untracked files the delivery explicitly pulls in (runbook §9.1: candidates
|
|
36
|
+
* must not silently drop untracked sources).
|
|
37
|
+
*/
|
|
38
|
+
function captureSnapshot(repoPath, options = {}) {
|
|
39
|
+
const manifest = [];
|
|
40
|
+
const lsTree = git(repoPath, ['ls-files', '-z']);
|
|
41
|
+
const tracked = lsTree.split('\0').filter(Boolean);
|
|
42
|
+
const headOids = new Map();
|
|
43
|
+
if (tracked.length) {
|
|
44
|
+
const lsHead = git(repoPath, ['ls-tree', '-r', 'HEAD', '--format=%(objectname)%x09%(path)', '-z']);
|
|
45
|
+
for (const entry of lsHead.split('\0').filter(Boolean)) {
|
|
46
|
+
const [oid, p] = entry.split('\t');
|
|
47
|
+
if (p) headOids.set(p, oid);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const modified = new Set(git(repoPath, ['status', '--porcelain', '-z']).split('\0')
|
|
51
|
+
.filter(Boolean)
|
|
52
|
+
.map(line => line.slice(3).replace(/"/g, '')));
|
|
53
|
+
for (const relativePath of tracked) {
|
|
54
|
+
if (!isSourceFile(relativePath, options.includePatterns)) continue;
|
|
55
|
+
if (options.exclude && options.exclude.includes(relativePath)) continue;
|
|
56
|
+
const absolute = path.join(repoPath, relativePath);
|
|
57
|
+
let content;
|
|
58
|
+
try { content = fs.readFileSync(absolute); } catch { continue; } // deleted in worktree
|
|
59
|
+
const workHash = hashBytes(content);
|
|
60
|
+
const origin = modified.has(relativePath) ? 'modified' : (headOids.get(relativePath) === workHash ? 'head' : 'modified');
|
|
61
|
+
manifest.push({ path: relativePath, origin, bytes: content.length, hash: workHash });
|
|
62
|
+
}
|
|
63
|
+
for (const relativePath of options.included || []) {
|
|
64
|
+
if (tracked.includes(relativePath)) continue;
|
|
65
|
+
const absolute = path.join(repoPath, relativePath);
|
|
66
|
+
let content;
|
|
67
|
+
try { content = fs.readFileSync(absolute); } catch { continue; }
|
|
68
|
+
manifest.push({ path: relativePath, origin: 'untracked', bytes: content.length, hash: hashBytes(content) });
|
|
69
|
+
}
|
|
70
|
+
manifest.sort((a, b) => a.path.localeCompare(b.path));
|
|
71
|
+
const id = crypto.createHash('sha256').update(JSON.stringify(manifest)).digest('hex').slice(0, 32);
|
|
72
|
+
return { snapshotId: `snap_${id}`, files: manifest, fileCount: manifest.length, capturedAt: new Date().toISOString(), head: headCommit(repoPath) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function headCommit(repoPath) {
|
|
76
|
+
try { return git(repoPath, ['rev-parse', 'HEAD']).trim(); } catch { return null; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Evidence cache key (main plan §9.1): everything that can invalidate a receipt. */
|
|
80
|
+
function evidenceKey({ snapshotId, baselineId, policyHash, toolchainHash, acceptanceRevision }) {
|
|
81
|
+
return crypto.createHash('sha256').update(JSON.stringify({ snapshotId, baselineId, policyHash, toolchainHash, acceptanceRevision })).digest('hex');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = { captureSnapshot, evidenceKey, hashBytes };
|