@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/store.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// File-backed state store for the workflow module.
|
|
4
|
+
//
|
|
5
|
+
// Contract (main plan §5, runbook §2.2):
|
|
6
|
+
// - One aggregate JSON document per data dir, replaced atomically
|
|
7
|
+
// (write temp + fsync + rename). Cross-process single-writer via a lock
|
|
8
|
+
// file with a pid/nonce owner record; stale locks are broken only when the
|
|
9
|
+
// owning pid is provably dead.
|
|
10
|
+
// - Every mutation carries a requestId. The idempotency table lives inside
|
|
11
|
+
// the same aggregate: same requestId + same payload hash replays the
|
|
12
|
+
// recorded result; same requestId + different payload is a 409
|
|
13
|
+
// PAYLOAD_MISMATCH, never a silent overwrite.
|
|
14
|
+
// - Optimistic concurrency: mutations pass expectedRevision; a mismatch is a
|
|
15
|
+
// 409 STALE_REVISION with the current revision in details.
|
|
16
|
+
// - The aggregate also holds the event inbox (replayable Bridge events) and
|
|
17
|
+
// the outbox (pending side effects). A mutation persists state + inbox +
|
|
18
|
+
// outbox in ONE atomic replace; side effects fire only after the rename.
|
|
19
|
+
// Crash before rename keeps the old state; crash after rename replays the
|
|
20
|
+
// outbox without duplicating (each outbox entry has a stable idempotency
|
|
21
|
+
// key the receiver verifies).
|
|
22
|
+
// - Corrupt state is never reset in place: it is preserved aside and
|
|
23
|
+
// DATA_CORRUPT is raised, so a human can inspect it.
|
|
24
|
+
|
|
25
|
+
const fs = require('fs');
|
|
26
|
+
const path = require('path');
|
|
27
|
+
const crypto = require('crypto');
|
|
28
|
+
const { WorkflowError } = require('./errors');
|
|
29
|
+
|
|
30
|
+
const STATE_SCHEMA = 'ai-coding-workflow/state/v1';
|
|
31
|
+
const LOCK_TIMEOUT_MS = 10_000;
|
|
32
|
+
const LOCK_STALE_MS = 120_000;
|
|
33
|
+
const LOCK_RETRY_MS = 25;
|
|
34
|
+
const IDEMPOTENCY_LIMIT = 500;
|
|
35
|
+
|
|
36
|
+
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
|
|
37
|
+
|
|
38
|
+
function isProcessAlive(pid) {
|
|
39
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
40
|
+
try { process.kill(pid, 0); return true; } catch (error) { return error && error.code === 'EPERM'; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sha256(value) { return crypto.createHash('sha256').update(value).digest('hex'); }
|
|
44
|
+
|
|
45
|
+
function stableStringify(value) {
|
|
46
|
+
// Canonical JSON so the same logical payload always hashes identically
|
|
47
|
+
// regardless of key order in the request body.
|
|
48
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
49
|
+
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
|
|
50
|
+
const keys = Object.keys(value).sort();
|
|
51
|
+
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function payloadHash(payload) { return sha256(stableStringify(payload === undefined ? null : payload)); }
|
|
55
|
+
|
|
56
|
+
class WorkflowStore {
|
|
57
|
+
constructor(dataDir) {
|
|
58
|
+
if (!dataDir) throw new Error('WorkflowStore requires an explicit --data directory');
|
|
59
|
+
this.dataDir = path.join(dataDir, 'workflow');
|
|
60
|
+
this.statePath = path.join(this.dataDir, 'state.json');
|
|
61
|
+
this.lockPath = path.join(this.dataDir, 'state.lock');
|
|
62
|
+
this.corruptDir = path.join(this.dataDir, 'corrupt');
|
|
63
|
+
// In-process write serialization: the file lock covers cross-process
|
|
64
|
+
// races, the queue covers two concurrent calls in this process.
|
|
65
|
+
this._queue = Promise.resolve();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ---------- lock ----------
|
|
69
|
+
|
|
70
|
+
async _acquireLock() {
|
|
71
|
+
const nonce = crypto.randomBytes(12).toString('hex');
|
|
72
|
+
fs.mkdirSync(this.dataDir, { recursive: true });
|
|
73
|
+
const started = Date.now();
|
|
74
|
+
for (;;) {
|
|
75
|
+
try {
|
|
76
|
+
const fd = fs.openSync(this.lockPath, 'wx', 0o600);
|
|
77
|
+
const owner = { pid: process.pid, startedAt: new Date().toISOString(), nonce };
|
|
78
|
+
fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, 'utf8');
|
|
79
|
+
fs.fsyncSync(fd);
|
|
80
|
+
fs.closeSync(fd);
|
|
81
|
+
return async () => {
|
|
82
|
+
try {
|
|
83
|
+
const current = JSON.parse(fs.readFileSync(this.lockPath, 'utf8'));
|
|
84
|
+
if (current.nonce !== nonce) return;
|
|
85
|
+
fs.unlinkSync(this.lockPath);
|
|
86
|
+
} catch (error) { if (error && error.code !== 'ENOENT') throw error; }
|
|
87
|
+
};
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (!error || error.code !== 'EEXIST') throw error;
|
|
90
|
+
let stat; try { stat = fs.statSync(this.lockPath); } catch { stat = null; }
|
|
91
|
+
let owner = null; try { owner = JSON.parse(fs.readFileSync(this.lockPath, 'utf8')); } catch { /* mid-write */ }
|
|
92
|
+
if (owner && Number.isInteger(Number(owner.pid)) ? !isProcessAlive(Number(owner.pid)) : (stat && (Date.now() - stat.mtimeMs) >= LOCK_STALE_MS)) {
|
|
93
|
+
try { fs.unlinkSync(this.lockPath); continue; } catch { /* raced; fall through to wait */ }
|
|
94
|
+
}
|
|
95
|
+
if ((Date.now() - started) >= LOCK_TIMEOUT_MS) {
|
|
96
|
+
throw new WorkflowError('CONFLICT', 'Timed out waiting for the workflow state lock.', { lock: 'state.lock' });
|
|
97
|
+
}
|
|
98
|
+
await delay(LOCK_RETRY_MS);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------- state IO ----------
|
|
104
|
+
|
|
105
|
+
_initialState() {
|
|
106
|
+
return {
|
|
107
|
+
schema: STATE_SCHEMA,
|
|
108
|
+
revision: 0,
|
|
109
|
+
createdAt: new Date().toISOString(),
|
|
110
|
+
team: null,
|
|
111
|
+
members: {},
|
|
112
|
+
projects: {}, // projectId -> settings (enabled, review flags, checks)
|
|
113
|
+
tasks: {}, // taskId -> task record
|
|
114
|
+
sessionBindings: {},
|
|
115
|
+
requests: {}, // requestId -> { payloadHash, result, revision, at }
|
|
116
|
+
inbox: {}, // inboxId -> raw event (pre-projection journal events)
|
|
117
|
+
outbox: [], // pending side effects, drained after persist
|
|
118
|
+
cursors: {}, // journalId -> last acked sequence
|
|
119
|
+
consumers: {}, // consumer registration bookkeeping
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
_readStateUnlocked() {
|
|
124
|
+
let raw;
|
|
125
|
+
try { raw = fs.readFileSync(this.statePath, 'utf8'); }
|
|
126
|
+
catch (error) {
|
|
127
|
+
if (error && error.code === 'ENOENT') return this._initialState();
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
const parsed = JSON.parse(raw);
|
|
132
|
+
if (parsed.schema !== STATE_SCHEMA) {
|
|
133
|
+
throw new WorkflowError('DATA_CORRUPT', 'Workflow state has an unsupported schema.', { found: parsed.schema, expected: STATE_SCHEMA });
|
|
134
|
+
}
|
|
135
|
+
return parsed;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (error instanceof WorkflowError) throw error;
|
|
138
|
+
// Preserve the corrupt bytes for inspection; never reset in place.
|
|
139
|
+
fs.mkdirSync(this.corruptDir, { recursive: true });
|
|
140
|
+
const preserved = path.join(this.corruptDir, `state.${Date.now()}.${crypto.randomBytes(4).toString('hex')}.json`);
|
|
141
|
+
try { fs.writeFileSync(preserved, raw, 'utf8'); } catch { /* preservation is best-effort; the error below is the contract */ }
|
|
142
|
+
throw new WorkflowError('DATA_CORRUPT', 'Workflow state file is corrupt and was preserved for inspection.', { preserved: path.basename(preserved) });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
_writeStateUnlocked(state) {
|
|
147
|
+
fs.mkdirSync(this.dataDir, { recursive: true });
|
|
148
|
+
const tempPath = path.join(this.dataDir, `.state.${process.pid}.${Date.now()}.${crypto.randomBytes(6).toString('hex')}.tmp`);
|
|
149
|
+
const payload = `${JSON.stringify(state, null, 2)}\n`;
|
|
150
|
+
let fd;
|
|
151
|
+
try {
|
|
152
|
+
fd = fs.openSync(tempPath, 'wx', 0o600);
|
|
153
|
+
fs.writeFileSync(fd, payload, 'utf8');
|
|
154
|
+
fs.fsyncSync(fd);
|
|
155
|
+
fs.closeSync(fd);
|
|
156
|
+
fd = null;
|
|
157
|
+
// Windows rename-over-existing can transiently fail with EPERM while an
|
|
158
|
+
// external reader holds the target; bounded retries mirror the family's
|
|
159
|
+
// atomic-file helper.
|
|
160
|
+
let lastError;
|
|
161
|
+
let renamed = false;
|
|
162
|
+
for (let attempt = 0; attempt <= 8 && !renamed; attempt += 1) {
|
|
163
|
+
try { fs.renameSync(tempPath, this.statePath); renamed = true; }
|
|
164
|
+
catch (error) {
|
|
165
|
+
lastError = error;
|
|
166
|
+
if (!error || !['EPERM', 'EACCES', 'EBUSY'].includes(error.code) || attempt === 8) throw error;
|
|
167
|
+
const wait = new Int32Array(new SharedArrayBuffer(4));
|
|
168
|
+
Atomics.wait(wait, 0, 0, Math.min(250, 10 * (2 ** attempt)));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (!renamed) throw lastError;
|
|
172
|
+
try { const dirFd = fs.openSync(this.dataDir, 'r'); fs.fsyncSync(dirFd); fs.closeSync(dirFd); } catch { /* best effort */ }
|
|
173
|
+
} catch (error) {
|
|
174
|
+
if (fd != null) try { fs.closeSync(fd); } catch { /* keep original error */ }
|
|
175
|
+
try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch { /* keep original error */ }
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------- public API ----------
|
|
181
|
+
|
|
182
|
+
async read() {
|
|
183
|
+
const release = await this._acquireLock();
|
|
184
|
+
try { return this._readStateUnlocked(); } finally { await release(); }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Idempotent, CAS-guarded mutation.
|
|
189
|
+
*
|
|
190
|
+
* `op` receives (state) and mutates it in place; it returns the operation
|
|
191
|
+
* result (plain JSON) or throws a WorkflowError. `op` may also push
|
|
192
|
+
* entries onto state.outbox — they fire (persisted) after the rename via
|
|
193
|
+
* the `drain` callback and are removed in a follow-up mutation once the
|
|
194
|
+
* side effect is acknowledged.
|
|
195
|
+
*/
|
|
196
|
+
async mutate({ requestId, payload, expectedRevision, op }) {
|
|
197
|
+
if (!op || typeof op !== 'function') throw new WorkflowError('VALIDATION', 'mutate requires an operation.');
|
|
198
|
+
const run = async () => {
|
|
199
|
+
const release = await this._acquireLock();
|
|
200
|
+
let state;
|
|
201
|
+
let result;
|
|
202
|
+
let effects = [];
|
|
203
|
+
try {
|
|
204
|
+
state = this._readStateUnlocked();
|
|
205
|
+
// Idempotency first: a replayed requestId answers from the table
|
|
206
|
+
// without touching state again.
|
|
207
|
+
if (requestId) {
|
|
208
|
+
const prior = state.requests[requestId];
|
|
209
|
+
if (prior) {
|
|
210
|
+
if (prior.payloadHash !== payloadHash(payload)) {
|
|
211
|
+
throw new WorkflowError('PAYLOAD_MISMATCH', 'This requestId was already used with a different payload.', { requestId });
|
|
212
|
+
}
|
|
213
|
+
return { replayed: true, result: prior.result, revision: prior.revision };
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (expectedRevision !== undefined && expectedRevision !== null) {
|
|
217
|
+
if (Number(expectedRevision) !== state.revision) {
|
|
218
|
+
throw new WorkflowError('STALE_REVISION', 'The record changed while you were editing.', { currentRevision: state.revision, expectedRevision: Number(expectedRevision) });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
result = op(state);
|
|
222
|
+
state.revision += 1;
|
|
223
|
+
if (requestId) {
|
|
224
|
+
state.requests[requestId] = { payloadHash: payloadHash(payload), result, revision: state.revision, at: new Date().toISOString() };
|
|
225
|
+
// Bound the table: oldest entries fall off; correctness of a
|
|
226
|
+
// replayed request older than the window degrades to a normal
|
|
227
|
+
// (rejected by CAS) write instead of a false replay.
|
|
228
|
+
const ids = Object.keys(state.requests);
|
|
229
|
+
if (ids.length > IDEMPOTENCY_LIMIT) {
|
|
230
|
+
ids.sort((a, b) => state.requests[a].at.localeCompare(state.requests[b].at));
|
|
231
|
+
for (const id of ids.slice(0, ids.length - IDEMPOTENCY_LIMIT)) delete state.requests[id];
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
effects = state.outbox.slice();
|
|
235
|
+
this._writeStateUnlocked(state);
|
|
236
|
+
return { replayed: false, result, revision: state.revision, effects };
|
|
237
|
+
} finally { await release(); }
|
|
238
|
+
};
|
|
239
|
+
// Serialize in-process mutators; failures do not poison the queue.
|
|
240
|
+
const gate = this._queue.then(run, run);
|
|
241
|
+
this._queue = gate.then(() => {}, () => {});
|
|
242
|
+
return gate;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Remove acknowledged outbox entries (called after a side effect landed). */
|
|
246
|
+
async ackOutbox(effectIds) {
|
|
247
|
+
if (!Array.isArray(effectIds) || effectIds.length === 0) return;
|
|
248
|
+
await this.mutate({ op: state => {
|
|
249
|
+
state.outbox = state.outbox.filter(effect => !effectIds.includes(effect.id));
|
|
250
|
+
return { acknowledged: effectIds.length };
|
|
251
|
+
} });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
close() { /* file-based: nothing held between calls */ }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
module.exports = { WorkflowStore, STATE_SCHEMA, payloadHash, stableStringify };
|
package/src/tasks.js
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Business-task domain: Task entities, acceptance items, session bindings,
|
|
4
|
+
// checkpoints and the server-side delivery decision.
|
|
5
|
+
//
|
|
6
|
+
// Three state families are kept apart (main plan §6.2):
|
|
7
|
+
// - business: draft -> ready -> in_progress -> verifying -> in_review -> done
|
|
8
|
+
// (+ blocked / cancelled). `done` is ONLY set by the delivery decision
|
|
9
|
+
// (evaluateDelivery), never by an ordinary PATCH — the API layer rejects
|
|
10
|
+
// `status: 'done'` writes.
|
|
11
|
+
// - execution attempts (runs): queued/starting/running/waiting_user/
|
|
12
|
+
// succeeded/failed/cancelled/dispatch_unknown — recorded per attempt, a
|
|
13
|
+
// successful run never marks the task done.
|
|
14
|
+
// - observation health: connected/stale/disconnected/partial/unknown —
|
|
15
|
+
// derived from event recency, never a progress percentage.
|
|
16
|
+
|
|
17
|
+
const crypto = require('crypto');
|
|
18
|
+
const { WorkflowError } = require('./errors');
|
|
19
|
+
|
|
20
|
+
const TASK_PHASES = ['clarify', 'plan', 'implement', 'verify', 'review', 'rework', 'deliver'];
|
|
21
|
+
const TASK_STATUSES = ['draft', 'ready', 'in_progress', 'verifying', 'in_review', 'done', 'blocked', 'cancelled'];
|
|
22
|
+
const RUN_STATUSES = ['queued', 'starting', 'running', 'waiting_user', 'succeeded', 'failed', 'cancelled', 'dispatch_unknown'];
|
|
23
|
+
const HEALTH_STATES = ['connected', 'stale', 'disconnected', 'partial', 'unknown'];
|
|
24
|
+
|
|
25
|
+
function newId(prefix) { return `${prefix}_${crypto.randomBytes(10).toString('hex')}`; }
|
|
26
|
+
|
|
27
|
+
function validateAcceptance(item, index) {
|
|
28
|
+
if (!item || typeof item !== 'object' || !item.title || typeof item.title !== 'string') {
|
|
29
|
+
throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1} needs a title.`);
|
|
30
|
+
}
|
|
31
|
+
if (item.kind && !['automated', 'manual', 'model_review'].includes(item.kind)) {
|
|
32
|
+
throw new WorkflowError('VALIDATION', `Acceptance item ${index + 1} has an unsupported kind.`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function createTask(state, input) {
|
|
37
|
+
const title = String(input.title || '').trim();
|
|
38
|
+
if (!title) throw new WorkflowError('VALIDATION', 'Task title is required.');
|
|
39
|
+
if (title.length > 200) throw new WorkflowError('VALIDATION', 'Task title too long (max 200).');
|
|
40
|
+
if (!input.projectId || typeof input.projectId !== 'string') throw new WorkflowError('VALIDATION', 'projectId is required.');
|
|
41
|
+
const acceptance = Array.isArray(input.acceptance) ? input.acceptance : [];
|
|
42
|
+
acceptance.forEach(validateAcceptance);
|
|
43
|
+
const taskId = newId('task');
|
|
44
|
+
const now = new Date().toISOString();
|
|
45
|
+
state.tasks[taskId] = {
|
|
46
|
+
taskId,
|
|
47
|
+
projectId: String(input.projectId),
|
|
48
|
+
title,
|
|
49
|
+
goal: input.goal ? String(input.goal).slice(0, 4000) : null,
|
|
50
|
+
sourceRefs: Array.isArray(input.sourceRefs) ? input.sourceRefs.map(String) : [],
|
|
51
|
+
acceptance: acceptance.map((item, i) => ({
|
|
52
|
+
id: `acc-${i + 1}`,
|
|
53
|
+
title: String(item.title),
|
|
54
|
+
kind: item.kind || 'automated', // automated | manual | model_review
|
|
55
|
+
status: 'pending', // pending | satisfied | failed | waived(with expiry)
|
|
56
|
+
updatedAt: now,
|
|
57
|
+
})),
|
|
58
|
+
acceptanceRevision: 1,
|
|
59
|
+
scope: input.scope ? String(input.scope).slice(0, 2000) : null,
|
|
60
|
+
priority: input.priority || 'normal',
|
|
61
|
+
prioritySource: input.priority || 'normal',
|
|
62
|
+
dueAt: input.dueAt || null,
|
|
63
|
+
dependencies: Array.isArray(input.dependencies) ? input.dependencies.map(String) : [],
|
|
64
|
+
ownerMemberId: input.ownerMemberId || null,
|
|
65
|
+
phase: input.phase && TASK_PHASES.includes(input.phase) ? input.phase : 'implement',
|
|
66
|
+
status: 'in_progress',
|
|
67
|
+
nextAction: input.nextAction ? String(input.nextAction).slice(0, 500) : null,
|
|
68
|
+
blockers: [],
|
|
69
|
+
runs: [],
|
|
70
|
+
observation: { state: 'unknown', since: now, lastEventAt: null },
|
|
71
|
+
createdAt: now,
|
|
72
|
+
updatedAt: now,
|
|
73
|
+
revision: 1,
|
|
74
|
+
};
|
|
75
|
+
appendChange(state, { kind: 'task.created', taskId, projectId: state.tasks[taskId].projectId, title });
|
|
76
|
+
return publicTask(state.tasks[taskId]);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function requireTask(state, taskId) {
|
|
80
|
+
const task = state.tasks[taskId];
|
|
81
|
+
if (!task) throw new WorkflowError('NOT_FOUND', 'Task not found.', { taskId });
|
|
82
|
+
return task;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Fields an ordinary PATCH may touch. `status` is intentionally absent: the
|
|
86
|
+
// business status moves through explicit transitions below; `done` only via
|
|
87
|
+
// evaluateDelivery, `blocked/cancelled` via dedicated transitions.
|
|
88
|
+
const PATCHABLE = ['title', 'goal', 'scope', 'priority', 'dueAt', 'nextAction', 'ownerMemberId', 'dependencies'];
|
|
89
|
+
|
|
90
|
+
function patchTask(state, taskId, patch, expectedRevision) {
|
|
91
|
+
const task = requireTask(state, taskId);
|
|
92
|
+
if (expectedRevision !== undefined && expectedRevision !== null && Number(expectedRevision) !== task.revision) {
|
|
93
|
+
throw new WorkflowError('STALE_REVISION', 'The task changed while you were editing.', { currentRevision: task.revision });
|
|
94
|
+
}
|
|
95
|
+
if (patch.status !== undefined || patch.phase !== undefined) {
|
|
96
|
+
if (patch.status === task.status && patch.phase === task.phase) { /* no-op same value */ }
|
|
97
|
+
else if (['blocked', 'cancelled'].includes(patch.status) && TASK_STATUSES.includes(patch.status)) {
|
|
98
|
+
// Explicit pause/abort transitions carry a reason.
|
|
99
|
+
task.status = patch.status;
|
|
100
|
+
task.blockers = patch.blockers !== undefined ? String(patch.blockers).slice(0, 500) : task.blockers;
|
|
101
|
+
appendChange(state, { kind: 'task.status', taskId, status: patch.status });
|
|
102
|
+
} else if (patch.status !== undefined && patch.status !== task.status) {
|
|
103
|
+
throw new WorkflowError('VALIDATION', `Status '${patch.status}' cannot be written directly; use task actions (start/resume/checkpoint/review/decision).`);
|
|
104
|
+
} else if (patch.phase !== undefined && TASK_PHASES.includes(patch.phase) && patch.phase !== task.phase) {
|
|
105
|
+
task.phase = patch.phase;
|
|
106
|
+
appendChange(state, { kind: 'task.phase', taskId, phase: patch.phase });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
for (const key of PATCHABLE) {
|
|
110
|
+
if (patch[key] === undefined) continue;
|
|
111
|
+
if (key === 'title') { const t = String(patch.title).trim(); if (!t) throw new WorkflowError('VALIDATION', 'Title cannot be empty.'); task.title = t.slice(0, 200); }
|
|
112
|
+
else if (key === 'dependencies') task.dependencies = Array.isArray(patch.dependencies) ? patch.dependencies.map(String) : [];
|
|
113
|
+
else task[key] = patch[key];
|
|
114
|
+
}
|
|
115
|
+
if (patch.acceptance !== undefined) {
|
|
116
|
+
// Acceptance edits bump the acceptanceRevision: prior evidence against
|
|
117
|
+
// the old definition is stale by contract.
|
|
118
|
+
const acceptance = Array.isArray(patch.acceptance) ? patch.acceptance : [];
|
|
119
|
+
acceptance.forEach(validateAcceptance);
|
|
120
|
+
task.acceptance = acceptance.map((item, i) => ({ id: `acc-${i + 1}`, title: String(item.title), kind: item.kind || 'automated', status: 'pending', updatedAt: new Date().toISOString() }));
|
|
121
|
+
task.acceptanceRevision += 1;
|
|
122
|
+
appendChange(state, { kind: 'task.acceptance_redefined', taskId, acceptanceRevision: task.acceptanceRevision });
|
|
123
|
+
}
|
|
124
|
+
if (task.status === 'blocked' && patch.unblock) { task.status = 'in_progress'; appendChange(state, { kind: 'task.status', taskId, status: 'in_progress' }); }
|
|
125
|
+
task.revision += 1;
|
|
126
|
+
task.updatedAt = new Date().toISOString();
|
|
127
|
+
return publicTask(task);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function addRun(state, taskId, run) {
|
|
131
|
+
const task = requireTask(state, taskId);
|
|
132
|
+
const entry = {
|
|
133
|
+
runId: run.runId || newId('run'),
|
|
134
|
+
kind: run.kind || 'session', // session | check | review
|
|
135
|
+
status: RUN_STATUSES.includes(run.status) ? run.status : 'queued',
|
|
136
|
+
startedAt: run.startedAt || new Date().toISOString(),
|
|
137
|
+
finishedAt: run.finishedAt || null,
|
|
138
|
+
attempt: task.runs.filter(r => r.kind === (run.kind || 'session')).length + 1,
|
|
139
|
+
executionRef: run.executionRef || null, // workbench executionId / runner receipt id
|
|
140
|
+
summary: run.summary ? String(run.summary).slice(0, 2000) : null,
|
|
141
|
+
};
|
|
142
|
+
task.runs.push(entry);
|
|
143
|
+
if (task.runs.length > 100) task.runs = task.runs.slice(-100);
|
|
144
|
+
// A run fact moves the business phase forward when it verifies/reviews, but
|
|
145
|
+
// NEVER to done: a succeeded run is evidence, not delivery.
|
|
146
|
+
if (entry.kind === 'check' && entry.status === 'succeeded' && task.phase === 'verify') task.phase = 'review';
|
|
147
|
+
task.revision += 1;
|
|
148
|
+
task.updatedAt = new Date().toISOString();
|
|
149
|
+
appendChange(state, { kind: 'task.run', taskId, runId: entry.runId, runKind: entry.kind, status: entry.status });
|
|
150
|
+
return entry;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function addSessionBinding(state, taskId, binding) {
|
|
154
|
+
const task = requireTask(state, taskId);
|
|
155
|
+
for (const field of ['client', 'nativeSessionId', 'workspaceIdentity']) {
|
|
156
|
+
if (!binding[field] || typeof binding[field] !== 'string') throw new WorkflowError('VALIDATION', `Session binding needs ${field}.`);
|
|
157
|
+
}
|
|
158
|
+
const now = new Date().toISOString();
|
|
159
|
+
// Same native session switching tasks must be cut into explicit intervals:
|
|
160
|
+
// close any open binding of the same client+session first.
|
|
161
|
+
for (const existing of Object.values(state.sessionBindings)) {
|
|
162
|
+
if (existing.taskId !== taskId && existing.client === binding.client && existing.nativeSessionId === binding.nativeSessionId && !existing.validTo) {
|
|
163
|
+
existing.validTo = now;
|
|
164
|
+
existing.revision += 1;
|
|
165
|
+
appendChange(state, { kind: 'binding.closed', bindingId: existing.bindingId, taskId: existing.taskId, reason: 'session-rebound' });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const bindingId = newId('bind');
|
|
169
|
+
state.sessionBindings[bindingId] = {
|
|
170
|
+
bindingId,
|
|
171
|
+
taskId,
|
|
172
|
+
memberId: binding.memberId || null,
|
|
173
|
+
client: binding.client,
|
|
174
|
+
nativeSessionId: binding.nativeSessionId,
|
|
175
|
+
workbenchSessionId: binding.workbenchSessionId || null,
|
|
176
|
+
workspaceIdentity: binding.workspaceIdentity,
|
|
177
|
+
validFrom: now,
|
|
178
|
+
validTo: null,
|
|
179
|
+
revision: 1,
|
|
180
|
+
verificationBasis: binding.verificationBasis ? String(binding.verificationBasis).slice(0, 500) : 'declared', // declared | verified-hook | verified-workbench
|
|
181
|
+
createdAt: now,
|
|
182
|
+
};
|
|
183
|
+
task.revision += 1;
|
|
184
|
+
appendChange(state, { kind: 'binding.opened', bindingId, taskId, client: binding.client });
|
|
185
|
+
return state.sessionBindings[bindingId];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function addCheckpoint(state, taskId, input) {
|
|
189
|
+
const task = requireTask(state, taskId);
|
|
190
|
+
const checkpoint = {
|
|
191
|
+
checkpointId: newId('ckpt'),
|
|
192
|
+
taskId,
|
|
193
|
+
taskRevision: task.revision,
|
|
194
|
+
acceptanceRevision: task.acceptanceRevision,
|
|
195
|
+
kind: input.kind === 'fact' ? 'fact' : 'candidate', // inferred checkpoints stay candidates
|
|
196
|
+
summary: input.summary ? String(input.summary).slice(0, 2000) : null,
|
|
197
|
+
decided: Array.isArray(input.decided) ? input.decided.map(String) : [],
|
|
198
|
+
verifiedResults: Array.isArray(input.verifiedResults) ? input.verifiedResults : [],
|
|
199
|
+
remaining: Array.isArray(input.remaining) ? input.remaining.map(String) : [],
|
|
200
|
+
nextAction: input.nextAction ? String(input.nextAction).slice(0, 500) : task.nextAction,
|
|
201
|
+
eventRefs: Array.isArray(input.eventRefs) ? input.eventRefs.map(String) : [],
|
|
202
|
+
createdAt: new Date().toISOString(),
|
|
203
|
+
};
|
|
204
|
+
task.checkpoints = task.checkpoints || [];
|
|
205
|
+
task.checkpoints.push(checkpoint);
|
|
206
|
+
if (task.checkpoints.length > 50) task.checkpoints = task.checkpoints.slice(-50);
|
|
207
|
+
if (checkpoint.kind === 'fact' && checkpoint.nextAction) task.nextAction = checkpoint.nextAction;
|
|
208
|
+
task.revision += 1;
|
|
209
|
+
task.updatedAt = checkpoint.createdAt;
|
|
210
|
+
appendChange(state, { kind: 'task.checkpoint', taskId, checkpointId: checkpoint.checkpointId, kind: checkpoint.kind });
|
|
211
|
+
return checkpoint;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Apply check receipts to a task (called by the review orchestration):
|
|
216
|
+
* stores the snapshot + receipts, then drives automated acceptance items
|
|
217
|
+
* from the receipts. A failing/erroring/missing receipt never satisfies an
|
|
218
|
+
* item; a passing receipt satisfies it WITH its evidence key, so a later
|
|
219
|
+
* snapshot change invalidates the delivery (T11/U16).
|
|
220
|
+
*/
|
|
221
|
+
function applyCheckReceipts(state, taskId, { snapshot, receipts, policyHash }) {
|
|
222
|
+
const task = requireTask(state, taskId);
|
|
223
|
+
task.latestSnapshot = { snapshotId: snapshot.snapshotId, fileCount: snapshot.fileCount, head: snapshot.head, capturedAt: snapshot.capturedAt };
|
|
224
|
+
state.checkReceipts = state.checkReceipts || {};
|
|
225
|
+
const receiptIds = [];
|
|
226
|
+
for (const receipt of receipts) {
|
|
227
|
+
const receiptId = `chk_${crypto.randomBytes(8).toString('hex')}`;
|
|
228
|
+
state.checkReceipts[receiptId] = { receiptId, taskId, ...receipt };
|
|
229
|
+
receiptIds.push(receiptId);
|
|
230
|
+
task.runs.push({
|
|
231
|
+
runId: `run_${receiptId}`, kind: 'check',
|
|
232
|
+
status: receipt.executionStatus === 'ok' ? 'succeeded' : 'failed',
|
|
233
|
+
startedAt: receipt.receivedAt, finishedAt: receipt.receivedAt,
|
|
234
|
+
attempt: task.runs.filter(r => r.kind === 'check').length + 1,
|
|
235
|
+
executionRef: receiptId,
|
|
236
|
+
summary: `${receipt.toolId}: ${receipt.verdict} (${receipt.findingCount ?? 0} findings, completeness=${receipt.completeness})`,
|
|
237
|
+
});
|
|
238
|
+
if (task.runs.length > 100) task.runs = task.runs.slice(-100);
|
|
239
|
+
appendChange(state, { kind: 'task.check', taskId, receiptId, tool: receipt.toolId, verdict: receipt.verdict, snapshotId: snapshot.snapshotId });
|
|
240
|
+
}
|
|
241
|
+
// Automated acceptance items track the check verdicts of THIS snapshot.
|
|
242
|
+
const passAll = receipts.length > 0 && receipts.every(r => r.verdict === 'pass');
|
|
243
|
+
const anyBlocking = receipts.some(r => r.verdict === 'fail' || r.verdict === 'error' || r.completeness !== 'complete');
|
|
244
|
+
// Rework queue for the Review member: concrete file:line[rule] findings of
|
|
245
|
+
// the CURRENT snapshot only — a later snapshot clears the list until its
|
|
246
|
+
// own receipts speak again.
|
|
247
|
+
if (anyBlocking) {
|
|
248
|
+
task.reworkItems = [];
|
|
249
|
+
for (const receipt of receipts) {
|
|
250
|
+
const source = state.checkReceipts[receiptIds[receipts.indexOf(receipt)]];
|
|
251
|
+
for (const finding of (receipt.findings || []).slice(0, 50)) {
|
|
252
|
+
task.reworkItems.push({
|
|
253
|
+
receiptId: source && source.receiptId,
|
|
254
|
+
toolId: finding.toolId || receipt.toolId,
|
|
255
|
+
ruleId: finding.ruleId,
|
|
256
|
+
file: finding.file, line: finding.line,
|
|
257
|
+
severity: finding.severity,
|
|
258
|
+
message: finding.message,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
if (receipt.completeness !== 'complete' && receipt.message) {
|
|
262
|
+
task.reworkItems.push({ receiptId: source && source.receiptId, toolId: receipt.toolId, ruleId: `${receipt.completeness}`, file: null, line: null, severity: 'error', message: receipt.message });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
task.nextAction = `按整改清单修复 ${task.reworkItems.length} 个问题后重新提交审查(project_workflow_request_review)`;
|
|
266
|
+
} else {
|
|
267
|
+
task.reworkItems = [];
|
|
268
|
+
}
|
|
269
|
+
for (const item of task.acceptance) {
|
|
270
|
+
if (item.kind !== 'automated') continue;
|
|
271
|
+
const was = item.status;
|
|
272
|
+
if (anyBlocking) {
|
|
273
|
+
item.status = item.status === 'satisfied' ? 'satisfied' : 'failed'; // keep old satisfied until a NEW snapshot re-verifies? No: fail now, evidence first.
|
|
274
|
+
item.status = 'failed';
|
|
275
|
+
item.evidenceRef = receiptIds[0] || item.evidenceRef;
|
|
276
|
+
} else if (passAll) {
|
|
277
|
+
item.status = 'satisfied';
|
|
278
|
+
item.evidenceRef = receiptIds[0];
|
|
279
|
+
} else {
|
|
280
|
+
item.status = 'pending';
|
|
281
|
+
}
|
|
282
|
+
item.updatedAt = new Date().toISOString();
|
|
283
|
+
if (was !== item.status) appendChange(state, { kind: 'task.acceptance', taskId, acceptanceId: item.id, result: item.status, via: 'checks' });
|
|
284
|
+
}
|
|
285
|
+
task.revision += 1;
|
|
286
|
+
task.updatedAt = new Date().toISOString();
|
|
287
|
+
if (task.status === 'verifying') task.phase = 'review';
|
|
288
|
+
return { receiptIds, decision: evaluateDelivery(task) };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Server-side delivery decision. `done` requires: every acceptance item
|
|
293
|
+
* satisfied or validly waived, no open blockers, and (when automated items
|
|
294
|
+
* exist) current evidence against the current acceptanceRevision. Model
|
|
295
|
+
* claims arrive as inputs with program receipts; they never write done
|
|
296
|
+
* directly.
|
|
297
|
+
*/
|
|
298
|
+
function recordAcceptanceDecision(state, taskId, input) {
|
|
299
|
+
const task = requireTask(state, taskId);
|
|
300
|
+
const item = task.acceptance.find(a => a.id === input.acceptanceId);
|
|
301
|
+
if (!item) throw new WorkflowError('NOT_FOUND', 'Acceptance item not found.', { acceptanceId: input.acceptanceId });
|
|
302
|
+
if (input.result === 'satisfied') {
|
|
303
|
+
if (item.kind === 'manual' && input.basis !== 'human') {
|
|
304
|
+
throw new WorkflowError('FORBIDDEN', 'Manual acceptance requires a human confirmation basis.', { acceptanceId: item.id });
|
|
305
|
+
}
|
|
306
|
+
if (item.kind === 'automated') {
|
|
307
|
+
// Program items are satisfied by receipts only — a model or user claim
|
|
308
|
+
// cannot flip them (T18/U17).
|
|
309
|
+
const receipt = input.evidenceRef && state.checkReceipts && state.checkReceipts[input.evidenceRef];
|
|
310
|
+
const matches = receipt && task.latestSnapshot && receipt.snapshotId === task.latestSnapshot.snapshotId
|
|
311
|
+
&& receipt.verdict === 'pass' && Number(receipt.acceptanceRevision) === task.acceptanceRevision;
|
|
312
|
+
if (!matches) throw new WorkflowError('FORBIDDEN', 'Automated acceptance needs a passing receipt for the current snapshot and acceptance revision.', { acceptanceId: item.id });
|
|
313
|
+
}
|
|
314
|
+
item.status = 'satisfied';
|
|
315
|
+
} else if (input.result === 'failed') {
|
|
316
|
+
item.status = 'failed';
|
|
317
|
+
if (task.status === 'verifying' || task.status === 'in_review') task.status = 'in_progress';
|
|
318
|
+
} else if (input.result === 'waived') {
|
|
319
|
+
if (!input.waiver || !input.waiver.reason || !input.waiver.expiresAt) {
|
|
320
|
+
throw new WorkflowError('VALIDATION', 'A waiver needs a reason and an expiry.');
|
|
321
|
+
}
|
|
322
|
+
item.status = 'waived';
|
|
323
|
+
item.waiver = { reason: String(input.waiver.reason).slice(0, 1000), expiresAt: input.waiver.expiresAt, recordedAt: new Date().toISOString() };
|
|
324
|
+
} else throw new WorkflowError('VALIDATION', "result must be satisfied | failed | waived.");
|
|
325
|
+
item.evidenceRef = input.evidenceRef ? String(input.evidenceRef).slice(0, 500) : null;
|
|
326
|
+
item.updatedAt = new Date().toISOString();
|
|
327
|
+
task.revision += 1;
|
|
328
|
+
appendChange(state, { kind: 'task.acceptance', taskId, acceptanceId: item.id, result: input.result });
|
|
329
|
+
return evaluateDelivery(task);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function evaluateDelivery(task) {
|
|
333
|
+
const now = new Date().toISOString();
|
|
334
|
+
const open = task.acceptance.filter(a => a.status === 'pending' || a.status === 'failed');
|
|
335
|
+
const expiredWaivers = task.acceptance.filter(a => a.status === 'waived' && a.waiver && a.waiver.expiresAt < now);
|
|
336
|
+
const blockers = [];
|
|
337
|
+
if (open.length) blockers.push(`${open.length} acceptance item(s) not satisfied`);
|
|
338
|
+
for (const a of expiredWaivers) { a.status = 'pending'; blockers.push(`waiver expired on ${a.id}`); }
|
|
339
|
+
if (blockers.length) {
|
|
340
|
+
// A previously delivered task whose evidence went stale (snapshot moved,
|
|
341
|
+
// receipt re-run failed) drops out of done: delivery tracks evidence.
|
|
342
|
+
if (task.status === 'done') { task.status = 'verifying'; task.deliveryNote = '交付状态待复核:有效证据不再完整。'; appendDeliveryChange(task); }
|
|
343
|
+
return { delivered: false, reasons: blockers, status: task.status };
|
|
344
|
+
}
|
|
345
|
+
if (!task.acceptance.length) return { delivered: false, reasons: ['no acceptance items defined'], status: task.status };
|
|
346
|
+
if (task.status !== 'done') { task.status = 'done'; task.phase = 'deliver'; task.doneAt = now; task.updatedAt = now; task.deliveryNote = null; appendDeliveryChange(task); }
|
|
347
|
+
return { delivered: true, reasons: [], status: 'done' };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function appendDeliveryChange(task) {
|
|
351
|
+
// Delivered via the task's own changes entry through appendChange upstream;
|
|
352
|
+
// minimal inline bookkeeping here (change log is state-level).
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Bounded change log for the overview/restore projection. */
|
|
356
|
+
function appendChange(state, change) {
|
|
357
|
+
state.changes = state.changes || [];
|
|
358
|
+
state.changes.push({ seq: (state.changeSeq = (state.changeSeq || 0) + 1), at: new Date().toISOString(), ...change });
|
|
359
|
+
if (state.changes.length > 2000) state.changes = state.changes.slice(-2000);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function publicTask(task) {
|
|
363
|
+
return {
|
|
364
|
+
taskId: task.taskId,
|
|
365
|
+
projectId: task.projectId,
|
|
366
|
+
title: task.title,
|
|
367
|
+
goal: task.goal,
|
|
368
|
+
sourceRefs: task.sourceRefs.slice(),
|
|
369
|
+
acceptance: task.acceptance.map(a => ({ ...a })),
|
|
370
|
+
acceptanceRevision: task.acceptanceRevision,
|
|
371
|
+
scope: task.scope,
|
|
372
|
+
priority: task.priority,
|
|
373
|
+
dueAt: task.dueAt,
|
|
374
|
+
dependencies: task.dependencies.slice(),
|
|
375
|
+
ownerMemberId: task.ownerMemberId,
|
|
376
|
+
phase: task.phase,
|
|
377
|
+
status: task.status,
|
|
378
|
+
nextAction: task.nextAction,
|
|
379
|
+
blockers: task.blockers,
|
|
380
|
+
runs: task.runs.slice(-10),
|
|
381
|
+
observation: { ...task.observation },
|
|
382
|
+
checkpoints: (task.checkpoints || []).slice(-5),
|
|
383
|
+
reworkItems: (task.reworkItems || []).slice(0, 50),
|
|
384
|
+
createdAt: task.createdAt,
|
|
385
|
+
updatedAt: task.updatedAt,
|
|
386
|
+
doneAt: task.doneAt || null,
|
|
387
|
+
revision: task.revision,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
module.exports = {
|
|
392
|
+
TASK_PHASES, TASK_STATUSES, RUN_STATUSES, HEALTH_STATES,
|
|
393
|
+
createTask, requireTask, patchTask, addRun, addSessionBinding, addCheckpoint,
|
|
394
|
+
recordAcceptanceDecision, evaluateDelivery, applyCheckReceipts, publicTask, appendChange,
|
|
395
|
+
};
|