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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ // Independent Event Bridge journal consumer for the workflow module.
4
+ //
5
+ // Contract (main plan §7.2):
6
+ // - Own consumer name `workflow:<storeId>`; never shares engine cursors.
7
+ // - Per-journal (journalId, sequence) cursors; sequences of different
8
+ // journals are never compared.
9
+ // - Projection order: events + derived state + pending ACK cursor are
10
+ // persisted in ONE store mutation, THEN the Bridge is ACKed. A crash
11
+ // before persist keeps the old cursor (events re-delivered, deduped by
12
+ // eventId); a crash after persist replays the outbox without duplicates.
13
+ // - Events whose session cannot be matched to an open binding are counted
14
+ // as pending (待关联) — never attributed by title similarity (U09).
15
+ // - Gaps (sequence jumps) are re-read from cursor+1; unrecoverable holes are
16
+ // recorded as gaps, not silently skipped.
17
+
18
+ const { WorkflowError } = require('./errors');
19
+
20
+ const DEFAULT_LIMIT = 100;
21
+
22
+ class BridgeClient {
23
+ constructor(url, { fetchImpl, timeoutMs = 8000 } = {}) {
24
+ this.url = String(url || '').replace(/\/+$/, '');
25
+ this.fetchImpl = fetchImpl || fetch;
26
+ this.timeoutMs = timeoutMs;
27
+ }
28
+ async request(route, body) {
29
+ if (!this.url) throw new WorkflowError('UPSTREAM_UNAVAILABLE', 'Event Bridge URL is not configured.');
30
+ const controller = new AbortController();
31
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
32
+ try {
33
+ const response = await this.fetchImpl(new URL(route, this.url), {
34
+ method: body ? 'POST' : 'GET',
35
+ headers: { 'Content-Type': 'application/json' },
36
+ body: body ? JSON.stringify(body) : undefined,
37
+ signal: controller.signal,
38
+ });
39
+ if (!response.ok) throw new WorkflowError('UPSTREAM_UNAVAILABLE', `Bridge ${route} answered ${response.status}.`);
40
+ return await response.json();
41
+ } catch (error) {
42
+ if (error instanceof WorkflowError) throw error;
43
+ throw new WorkflowError('UPSTREAM_UNAVAILABLE', `Bridge ${route} unreachable: ${error.message}`);
44
+ } finally { clearTimeout(timer); }
45
+ }
46
+ async listJournals() { return (await this.request('/api/journals')).journals; }
47
+ async registerConsumer(name, meta) { return this.request('/api/consumers/register', { name, meta }); }
48
+ async readEvents({ journalId, fromSequence, limit = DEFAULT_LIMIT }) {
49
+ const params = new URLSearchParams({ journalId, fromSequence: String(fromSequence), limit: String(limit) });
50
+ return (await this.request(`/api/journal/events?${params}`)).events;
51
+ }
52
+ async ackConsumerCursor(name, sequence, journalId) { return this.request('/api/consumers/ack', { name, sequence, journalId }); }
53
+ }
54
+
55
+ class WorkflowConsumer {
56
+ constructor({ store, bridgeUrl, consumerName, logger }) {
57
+ this.store = store;
58
+ this.bridge = new BridgeClient(bridgeUrl);
59
+ this.name = consumerName || 'workflow:default';
60
+ this.logger = logger || { info: () => {}, warn: () => {} };
61
+ this.drainPromise = null;
62
+ this.stopped = false;
63
+ this.lastDrain = null;
64
+ }
65
+
66
+ /** One drain pass over every journal. Returns per-journal stats. */
67
+ async drain({ register = true } = {}) {
68
+ if (this.drainPromise) return this.drainPromise;
69
+ this.drainPromise = this._drain({ register }).finally(() => { this.drainPromise = null; });
70
+ return this.drainPromise;
71
+ }
72
+
73
+ async _drain({ register, notifyUrl } = {}) {
74
+ const stats = [];
75
+ if (register) {
76
+ const meta = { module: 'ai-coding-workflow' };
77
+ if (notifyUrl) meta.notifyUrl = notifyUrl;
78
+ try { await this.bridge.registerConsumer(this.name, meta); }
79
+ catch (error) { this.logger.warn('workflow.consumer.register_failed', error.message, {}); }
80
+ }
81
+ let journals;
82
+ try { journals = await this.bridge.listJournals(); } catch (error) { this.lastDrain = { at: new Date().toISOString(), error: error.message }; throw error; }
83
+ for (const journal of journals) {
84
+ if (this.stopped) break;
85
+ const journalId = typeof journal === 'string' ? journal : journal.journalId || journal.id;
86
+ stats.push(await this._drainJournal(journalId));
87
+ }
88
+ this.lastDrain = { at: new Date().toISOString(), ok: true, journals: stats };
89
+ return stats;
90
+ }
91
+
92
+ async _drainJournal(journalId) {
93
+ const stat = { journalId, projected: 0, pending: 0, duplicated: 0, ackedTo: null, gap: false };
94
+ // Catch-up ACK first: a previous drain may have persisted the cursor but
95
+ // lost the Bridge round-trip (crash/503). Re-acking an already-acked
96
+ // sequence is idempotent for the Bridge.
97
+ {
98
+ const snapshot = await this.store.read();
99
+ const cursor = snapshot.cursors[journalId] ?? 0;
100
+ snapshot.consumer = snapshot.consumer || {};
101
+ snapshot.consumer.lastAcked = snapshot.consumer.lastAcked || {};
102
+ if (cursor > 0 && (snapshot.consumer.lastAcked[journalId] ?? 0) < cursor) {
103
+ try {
104
+ await this.bridge.ackConsumerCursor(this.name, cursor, journalId);
105
+ await this.store.mutate({ op: state => { state.consumer = state.consumer || {}; state.consumer.lastAcked = state.consumer.lastAcked || {}; state.consumer.lastAcked[journalId] = cursor; return { ackedTo: cursor }; } });
106
+ stat.ackedTo = cursor;
107
+ } catch (error) { stat.ackError = error.message; return stat; }
108
+ }
109
+ }
110
+ for (;;) {
111
+ if (this.stopped) break;
112
+ const snapshot = await this.store.read();
113
+ const cursor = snapshot.cursors[journalId] ?? 0;
114
+ let events;
115
+ try { events = await this.bridge.readEvents({ journalId, fromSequence: cursor + 1 }); }
116
+ catch (error) { stat.error = error.message; return stat; }
117
+ if (!Array.isArray(events) || !events.length) break;
118
+ // Gap detection: sequences must start exactly at cursor+1.
119
+ const first = events[0];
120
+ if (Number(first.sequence) !== cursor + 1) { stat.gap = true; stat.error = `expected sequence ${cursor + 1}, got ${first.sequence}`; break; }
121
+ const persist = await this.store.mutate({
122
+ op: state => this._project(state, journalId, events),
123
+ });
124
+ // Persisted (revision bumped) — safe to ACK. Crash between persist and
125
+ // ack replays the same events; eventId dedup in _project keeps the
126
+ // projection idempotent.
127
+ stat.projected += persist.result.projected;
128
+ stat.pending += persist.result.pending;
129
+ stat.duplicated += persist.result.duplicated;
130
+ const ackTo = persist.result.advancedTo;
131
+ if (persist.result.gap) { stat.gap = true; stat.gapDetail = persist.result.gap; }
132
+ if (!ackTo || ackTo <= cursor) break;
133
+ try { await this.bridge.ackConsumerCursor(this.name, ackTo, journalId); }
134
+ catch (error) { stat.ackError = error.message; break; } // cursor already persisted; the next drain's catch-up ack re-sends
135
+ await this.store.mutate({ op: state => { state.consumer = state.consumer || {}; state.consumer.lastAcked = state.consumer.lastAcked || {}; state.consumer.lastAcked[journalId] = ackTo; return { ackedTo: ackTo }; } });
136
+ stat.ackedTo = ackTo;
137
+ if (persist.result.gap) break; // surfaced; do not read past the hole
138
+ if (events.length < DEFAULT_LIMIT) break;
139
+ }
140
+ return stat;
141
+ }
142
+
143
+ /**
144
+ * Pure projection over one batch. Inside the store lock: extend inbox with
145
+ * unseen eventIds, match bindings, update tasks, advance the cursor.
146
+ */
147
+ _project(state, journalId, events) {
148
+ state.inbox = state.inbox || {};
149
+ state.cursors = state.cursors || {};
150
+ state.consumer = state.consumer || { pendingEvents: 0, gaps: [] };
151
+ const result = { projected: 0, pending: 0, duplicated: 0, gap: null };
152
+ let maxSeq = state.cursors[journalId] ?? 0;
153
+ for (const event of events) {
154
+ const seq = Number(event.sequence);
155
+ if (!Number.isFinite(seq)) continue;
156
+ if (seq <= maxSeq) { result.duplicated += 1; continue; }
157
+ if (seq !== maxSeq + 1) {
158
+ // Hole inside or ahead of the batch: stop at the gap; the cursor
159
+ // stays at maxSeq and the gap is reported, never skipped.
160
+ result.gap = { expected: maxSeq + 1, got: seq };
161
+ if (state.consumer.gaps) {
162
+ state.consumer.gaps.push({ journalId, at: new Date().toISOString(), ...result.gap });
163
+ if (state.consumer.gaps.length > 50) state.consumer.gaps = state.consumer.gaps.slice(-50);
164
+ }
165
+ break;
166
+ }
167
+ const eventId = String(event.eventId || `${journalId}:${seq}`);
168
+ if (state.inbox[eventId]) { result.duplicated += 1; maxSeq = seq; continue; }
169
+ // Persist the raw event in the replayable inbox (bounded per journal).
170
+ state.inbox[eventId] = { journalId, sequence: seq, event, receivedAt: new Date().toISOString() };
171
+ const inboxIds = Object.keys(state.inbox);
172
+ if (inboxIds.length > 5000) {
173
+ for (const id of inboxIds.sort((a, b) => state.inbox[a].sequence - state.inbox[b].sequence).slice(0, inboxIds.length - 5000)) delete state.inbox[id];
174
+ }
175
+ const task = this._matchBinding(state, event);
176
+ if (task) {
177
+ task.observation = task.observation || { state: 'unknown' };
178
+ task.observation.state = 'connected';
179
+ task.observation.since = new Date().toISOString();
180
+ task.observation.lastEventAt = new Date().toISOString();
181
+ task.activityCount = (task.activityCount || 0) + 1;
182
+ result.projected += 1;
183
+ } else {
184
+ state.consumer.pendingEvents += 1;
185
+ result.pending += 1;
186
+ }
187
+ maxSeq = seq;
188
+ }
189
+ state.cursors[journalId] = maxSeq;
190
+ result.advancedTo = maxSeq;
191
+ return result;
192
+ }
193
+
194
+ /** Match an event to the task owning its (client, sessionId) right now. */
195
+ _matchBinding(state, event) {
196
+ const meta = event.meta || event;
197
+ const client = meta.client || meta.clientKind || null;
198
+ const sessionId = meta.sessionId || null;
199
+ if (!sessionId) return null;
200
+ for (const binding of Object.values(state.sessionBindings)) {
201
+ if (binding.validTo) continue;
202
+ if (binding.nativeSessionId !== sessionId) continue;
203
+ if (client && binding.client !== client) continue;
204
+ return state.tasks[binding.taskId] || null;
205
+ }
206
+ return null;
207
+ }
208
+
209
+ status() {
210
+ return {
211
+ consumer: this.name,
212
+ bridgeUrl: this.bridge.url || null,
213
+ running: Boolean(this.drainPromise),
214
+ stopped: this.stopped,
215
+ lastDrain: this.lastDrain,
216
+ };
217
+ }
218
+
219
+ stop() { this.stopped = true; }
220
+ }
221
+
222
+ module.exports = { WorkflowConsumer, BridgeClient };
package/src/digests.js ADDED
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ // Daily digest + reminders (main plan §10). Deterministic aggregation over
4
+ // the task/change records — no model is involved in producing a digest, and
5
+ // 'idle' is never presented as completion. Reminders are in-app records with
6
+ // dedup keys; nothing here sends external notifications.
7
+
8
+ const crypto = require('crypto');
9
+ const { appendChange } = require('./tasks');
10
+
11
+ const TZ = 'Asia/Shanghai';
12
+
13
+ /** Local workday (Asia/Shanghai) for an instant: YYYY-MM-DD. */
14
+ function localDay(iso) {
15
+ const date = new Date(iso);
16
+ const shifted = new Date(date.getTime() + 8 * 3600 * 1000);
17
+ return shifted.toISOString().slice(0, 10);
18
+ }
19
+ function dayBoundsLocal(day) {
20
+ // UTC interval of the local workday [00:00, 24:00) Shanghai.
21
+ const startUtcMs = Date.parse(`${day}T00:00:00Z`) - 8 * 3600 * 1000;
22
+ return { start: new Date(startUtcMs).toISOString(), end: new Date(startUtcMs + 24 * 3600 * 1000).toISOString() };
23
+ }
24
+
25
+ /**
26
+ * Aggregate one workday from the store snapshot. Every line cites the
27
+ * underlying change seqs; categories stay separate (activity vs delivered vs
28
+ * blocked) and duplicated events on the same task dedupe to one entry.
29
+ */
30
+ function buildDailyDigest(state, day) {
31
+ const { start, end } = dayBoundsLocal(day);
32
+ const changes = (state.changes || []).filter(c => c.at >= start && c.at < end);
33
+ const tasksTouched = new Map();
34
+ for (const change of changes) {
35
+ if (!change.taskId) continue;
36
+ const entry = tasksTouched.get(change.taskId) || { taskId: change.taskId, kinds: new Set(), seqs: [], lastAt: change.at };
37
+ entry.kinds.add(change.kind);
38
+ entry.seqs.push(change.seq);
39
+ if (change.at > entry.lastAt) entry.lastAt = change.at;
40
+ tasksTouched.set(change.taskId, entry);
41
+ }
42
+ const activity = [];
43
+ const deliveredToday = [];
44
+ const blocked = [];
45
+ const inProgress = [];
46
+ for (const [taskId, entry] of tasksTouched) {
47
+ const task = state.tasks[taskId];
48
+ if (!task) continue;
49
+ const summary = { taskId, title: task.title, projectId: task.projectId, events: entry.seqs.length, kinds: [...entry.kinds], evidenceSeqs: entry.seqs.slice(0, 5), lastAt: entry.lastAt };
50
+ activity.push(summary);
51
+ if (task.status === 'done' && task.doneAt && task.doneAt >= start && task.doneAt < end) deliveredToday.push(summary);
52
+ if (task.status === 'blocked') blocked.push({ ...summary, reason: task.blockers || null });
53
+ else if (['in_progress', 'verifying', 'in_review'].includes(task.status)) inProgress.push(summary);
54
+ }
55
+ const sortRecent = list => list.sort((a, b) => b.lastAt.localeCompare(a.lastAt));
56
+ return {
57
+ day, timezone: TZ, windowUtc: { start, end },
58
+ counts: { activity: activity.length, delivered: deliveredToday.length, blocked: blocked.length, inProgress: inProgress.length },
59
+ activity: sortRecent(activity).slice(0, 50),
60
+ delivered: sortRecent(deliveredToday),
61
+ blocked: sortRecent(blocked),
62
+ inProgress: sortRecent(inProgress).slice(0, 50),
63
+ generatedAt: new Date().toISOString(),
64
+ model: 'deterministic-aggregation',
65
+ };
66
+ }
67
+
68
+ const REMINDER_KINDS = ['waiting-user', 'check-failed', 'due-soon', 'dependency-ready', 'observation-lost'];
69
+
70
+ function upsertReminder(state, { kind, taskId, message, dueAt, dedupKey }) {
71
+ if (!REMINDER_KINDS.includes(kind)) throw new Error(`unsupported reminder kind ${kind}`);
72
+ state.reminders = state.reminders || [];
73
+ const key = dedupKey || `${kind}:${taskId}`;
74
+ const existing = state.reminders.find(r => r.dedupKey === key && !r.dismissedAt && !r.snoozedUntilOrAfter);
75
+ if (existing) { existing.message = message || existing.message; existing.updatedAt = new Date().toISOString(); return existing; }
76
+ const reminder = {
77
+ reminderId: `rem_${crypto.randomBytes(8).toString('hex')}`,
78
+ kind, taskId: taskId || null, dedupKey: key,
79
+ message: message ? String(message).slice(0, 500) : null,
80
+ dueAt: dueAt || null,
81
+ status: 'open', // open | read | snoozed | dismissed
82
+ snoozedUntil: null, dismissedAt: null,
83
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
84
+ };
85
+ state.reminders.push(reminder);
86
+ if (state.reminders.length > 500) state.reminders = state.reminders.slice(-500);
87
+ appendChange(state, { kind: 'reminder.created', taskId: taskId || null, reminderKind: kind });
88
+ return reminder;
89
+ }
90
+
91
+ function reminderAction(state, reminderId, action, { until } = {}) {
92
+ state.reminders = state.reminders || [];
93
+ const reminder = state.reminders.find(r => r.reminderId === reminderId);
94
+ if (!reminder) throw new Error('reminder not found');
95
+ if (action === 'read') reminder.status = reminder.status === 'open' ? 'read' : reminder.status;
96
+ else if (action === 'snooze') { reminder.status = 'snoozed'; reminder.snoozedUntil = until || new Date(Date.now() + 24 * 3600 * 1000).toISOString(); }
97
+ else if (action === 'dismiss') { reminder.status = 'dismissed'; reminder.dismissedAt = new Date().toISOString(); }
98
+ else throw new Error(`unsupported action ${action}`);
99
+ reminder.updatedAt = new Date().toISOString();
100
+ return reminder;
101
+ }
102
+
103
+ module.exports = { buildDailyDigest, upsertReminder, reminderAction, localDay, REMINDER_KINDS };
package/src/domain.js ADDED
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+
3
+ // Domain logic for the default team, agent members and per-project workflow
4
+ // settings. W1 delivers the real persistence contracts (idempotent create,
5
+ // CAS update, disable); the wizard UI (W2) and tasks (W3) build on these
6
+ // same records — no re-creation paths, no seeded demo data.
7
+
8
+ const crypto = require('crypto');
9
+ const { WorkflowError } = require('./errors');
10
+
11
+ function newId(prefix) {
12
+ return `${prefix}_${crypto.randomBytes(10).toString('hex')}`;
13
+ }
14
+
15
+ const MEMBER_ROLES = ['developer', 'reviewer'];
16
+
17
+ function validateMemberInput(input) {
18
+ const errors = [];
19
+ if (!input || typeof input !== 'object') return ['member must be an object'];
20
+ if (!input.name || typeof input.name !== 'string' || !input.name.trim()) errors.push('name is required');
21
+ if (input.name && String(input.name).length > 80) errors.push('name too long (max 80)');
22
+ if (!MEMBER_ROLES.includes(input.role)) errors.push(`role must be one of ${MEMBER_ROLES.join(', ')}`);
23
+ // driverId references a Workbench driver (claude/codex/...); profileId
24
+ // references a Workbench profile. Both are references only — this module
25
+ // never stores credentials.
26
+ if (input.driverId && typeof input.driverId !== 'string') errors.push('driverId must be a string');
27
+ if (input.profileId && typeof input.profileId !== 'string') errors.push('profileId must be a string');
28
+ if (input.model && typeof input.model !== 'string') errors.push('model must be a string');
29
+ if (input.instructions && typeof input.instructions !== 'string') errors.push('instructions must be a string');
30
+ if (input.instructions && String(input.instructions).length > 2000) errors.push('instructions too long (max 2000)');
31
+ if (input.memoryGroupIds && !Array.isArray(input.memoryGroupIds)) errors.push('memoryGroupIds must be an array');
32
+ return errors;
33
+ }
34
+
35
+ /**
36
+ * Create the default team. One team per brain (data dir); a second create
37
+ * with a different requestId is rejected, a retry with the same requestId is
38
+ * replayed by the store's idempotency table, so "retry after flaky network"
39
+ * never duplicates members.
40
+ */
41
+ function createTeam(state, { name, memberDrafts, projectSettings }) {
42
+ if (state.team) {
43
+ throw new WorkflowError('CONFLICT', 'A default team already exists for this brain.', { teamId: state.team.teamId });
44
+ }
45
+ const teamName = (name && String(name).trim()) || '我的开发团队';
46
+ if (teamName.length > 120) throw new WorkflowError('VALIDATION', 'Team name too long (max 120).');
47
+ const drafts = Array.isArray(memberDrafts) && memberDrafts.length ? memberDrafts : [
48
+ { role: 'developer', name: '开发成员' },
49
+ { role: 'reviewer', name: 'Review 成员' },
50
+ ];
51
+ const members = {};
52
+ for (const draft of drafts) {
53
+ const errors = validateMemberInput(draft);
54
+ if (errors.length) throw new WorkflowError('VALIDATION', `Invalid member: ${errors.join('; ')}`, { member: draft.name || '(unnamed)' });
55
+ }
56
+ const teamId = newId('team');
57
+ for (const draft of drafts) {
58
+ const memberId = newId('member');
59
+ members[memberId] = {
60
+ memberId,
61
+ teamId,
62
+ name: String(draft.name).trim(),
63
+ role: draft.role,
64
+ instructions: draft.instructions ? String(draft.instructions).slice(0, 2000) : null,
65
+ driverId: draft.driverId || null,
66
+ profileId: draft.profileId || null,
67
+ model: draft.model || null,
68
+ // Memory group references live in the knowledge-engine; store IDs only.
69
+ memoryGroupIds: Array.isArray(draft.memoryGroupIds) ? draft.memoryGroupIds.map(String) : [],
70
+ enabled: true,
71
+ revision: 1,
72
+ createdAt: new Date().toISOString(),
73
+ };
74
+ }
75
+ state.team = { teamId, name: teamName, workflowId: 'default/v1', createdAt: new Date().toISOString(), revision: 1 };
76
+ state.members = members;
77
+ if (projectSettings && typeof projectSettings === 'object') {
78
+ for (const [projectId, settings] of Object.entries(projectSettings)) {
79
+ state.projects[String(projectId)] = normalizeProjectSettings(projectId, settings);
80
+ }
81
+ }
82
+ return { team: publicTeam(state.team), members: Object.values(members).map(publicMember) };
83
+ }
84
+
85
+ function publicTeam(team) {
86
+ return { teamId: team.teamId, name: team.name, workflowId: team.workflowId, revision: team.revision, createdAt: team.createdAt };
87
+ }
88
+
89
+ function publicMember(member) {
90
+ // Never widen this projection with credential-ish fields; references only.
91
+ // executionMode is derived: developers follow the native dev session (their
92
+ // model is controlled by the client), reviewers run in the background via
93
+ // the referenced Workbench profile.
94
+ return {
95
+ memberId: member.memberId,
96
+ teamId: member.teamId,
97
+ name: member.name,
98
+ role: member.role,
99
+ instructions: member.instructions || null,
100
+ executionMode: member.role === 'developer' ? 'follow-session' : 'background',
101
+ driverId: member.driverId,
102
+ profileId: member.profileId,
103
+ model: member.model,
104
+ memoryGroupIds: member.memoryGroupIds.slice(),
105
+ enabled: member.enabled,
106
+ revision: member.revision,
107
+ createdAt: member.createdAt,
108
+ };
109
+ }
110
+
111
+ function requireTeam(state) {
112
+ if (!state.team) throw new WorkflowError('NOT_FOUND', 'No team exists yet. Create the default team first.');
113
+ return state.team;
114
+ }
115
+
116
+ function patchMember(state, memberId, patch, expectedRevision) {
117
+ requireTeam(state);
118
+ const member = state.members[memberId];
119
+ if (!member) throw new WorkflowError('NOT_FOUND', 'Member not found.', { memberId });
120
+ if (expectedRevision !== undefined && expectedRevision !== null && Number(expectedRevision) !== member.revision) {
121
+ throw new WorkflowError('STALE_REVISION', 'The member changed while you were editing.', { currentRevision: member.revision });
122
+ }
123
+ const errors = validateMemberInput({ ...member, ...patch, role: patch.role || member.role, name: patch.name || member.name });
124
+ if (errors.length) throw new WorkflowError('VALIDATION', `Invalid member patch: ${errors.join('; ')}`);
125
+ if (patch.name !== undefined) member.name = String(patch.name).trim();
126
+ if (patch.role !== undefined) member.role = patch.role;
127
+ if (patch.instructions !== undefined) member.instructions = patch.instructions ? String(patch.instructions).slice(0, 2000) : null;
128
+ if (patch.driverId !== undefined) member.driverId = patch.driverId || null;
129
+ if (patch.profileId !== undefined) member.profileId = patch.profileId || null;
130
+ if (patch.model !== undefined) member.model = patch.model || null;
131
+ if (patch.memoryGroupIds !== undefined) member.memoryGroupIds = patch.memoryGroupIds.map(String);
132
+ if (patch.enabled !== undefined) member.enabled = Boolean(patch.enabled);
133
+ member.revision += 1;
134
+ member.updatedAt = new Date().toISOString();
135
+ return publicMember(member);
136
+ }
137
+
138
+ function normalizeProjectSettings(projectId, settings) {
139
+ if (!projectId || typeof projectId !== 'string') throw new WorkflowError('VALIDATION', 'projectId is required.');
140
+ return {
141
+ projectId,
142
+ enabled: Boolean(settings && settings.enabled),
143
+ autoRecord: settings ? settings.autoRecord !== false : true,
144
+ deliveryChecks: settings ? settings.deliveryChecks !== false : true,
145
+ substantiveCodeReview: settings ? settings.substantiveCodeReview !== false : true,
146
+ reminders: settings ? settings.reminders !== false : true, // in-app only, default ON
147
+ autoDispatch: Boolean(settings && settings.autoDispatch), // background autonomous coding, default OFF
148
+ autoDelete: Boolean(settings && settings.autoDelete), // never default ON
149
+ externalNotifications: Boolean(settings && settings.externalNotifications), // default OFF
150
+ historyBackfill: Boolean(settings && settings.historyBackfill), // full-history replay, default OFF
151
+ checkConfig: (settings && settings.checkConfig) || null,
152
+ updatedAt: new Date().toISOString(),
153
+ revision: 1,
154
+ };
155
+ }
156
+
157
+ function putProjectSettings(state, projectId, settings) {
158
+ const existing = state.projects[projectId];
159
+ const normalized = normalizeProjectSettings(projectId, settings);
160
+ if (existing) {
161
+ if (settings && settings.expectedRevision !== undefined && settings.expectedRevision !== null && Number(settings.expectedRevision) !== existing.revision) {
162
+ throw new WorkflowError('STALE_REVISION', 'Project settings changed while you were editing.', { currentRevision: existing.revision });
163
+ }
164
+ normalized.revision = existing.revision + 1;
165
+ normalized.createdAt = existing.createdAt;
166
+ }
167
+ state.projects[projectId] = normalized;
168
+ return normalized;
169
+ }
170
+
171
+ module.exports = {
172
+ newId, MEMBER_ROLES, createTeam, publicTeam, publicMember, requireTeam,
173
+ patchMember, putProjectSettings, normalizeProjectSettings, validateMemberInput,
174
+ };
package/src/errors.js ADDED
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+
3
+ // Error taxonomy for the workflow module. Every API failure maps to one of
4
+ // these codes so clients can distinguish identity/scope failures (4xx,
5
+ // caller's fault), conflicts (409, retryable with a fresh revision),
6
+ // unsupported capabilities (501), upstream unavailability (503) and internal
7
+ // execution failures (500). Raw vendor or filesystem messages are never
8
+ // echoed to browsers; `details` carries sanitized context only.
9
+
10
+ const CODES = {
11
+ VALIDATION: { status: 400, retryable: false },
12
+ UNAUTHENTICATED: { status: 401, retryable: false },
13
+ FORBIDDEN: { status: 403, retryable: false },
14
+ NOT_FOUND: { status: 404, retryable: false },
15
+ CONFLICT: { status: 409, retryable: true },
16
+ STALE_REVISION: { status: 409, retryable: true },
17
+ PAYLOAD_MISMATCH: { status: 409, retryable: false },
18
+ DATA_CORRUPT: { status: 500, retryable: false },
19
+ UNSUPPORTED: { status: 501, retryable: false },
20
+ UPSTREAM_UNAVAILABLE: { status: 503, retryable: true },
21
+ EXECUTION_FAILED: { status: 500, retryable: true },
22
+ };
23
+
24
+ class WorkflowError extends Error {
25
+ constructor(code, message, details = {}) {
26
+ const meta = CODES[code] || CODES.EXECUTION_FAILED;
27
+ super(message);
28
+ this.name = 'WorkflowError';
29
+ this.code = code;
30
+ this.status = meta.status;
31
+ this.retryable = meta.retryable;
32
+ this.details = details;
33
+ }
34
+ toJSON() {
35
+ return { ok: false, error: this.code, message: this.message, details: this.details };
36
+ }
37
+ }
38
+
39
+ function isWorkflowError(error) {
40
+ return error instanceof WorkflowError;
41
+ }
42
+
43
+ module.exports = { WorkflowError, isWorkflowError, ERROR_CODES: Object.keys(CODES) };
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+
3
+ // Versioned identity and capability declaration. The shell's module
4
+ // supervisor probes GET /api/health and matches this body to decide "our
5
+ // workflow module already runs on that port" versus a foreign listener
6
+ // (family contract, module-bridge MODULE_IDENTITY). Changing the `name` or
7
+ // dropping `apiVersion` breaks reuse detection — treat both as frozen.
8
+
9
+ const pkg = require('../package.json');
10
+
11
+ const MODULE_NAME = 'ai-coding-workflow';
12
+ const API_VERSION = 'v1';
13
+
14
+ // Capability switches are additive per release; a shell older than a given
15
+ // capability must degrade to "not supported" instead of guessing. Consumers
16
+ // gate features on these flags, never on the package version string.
17
+ const CAPABILITIES = {
18
+ team: true, // default team + members (W2)
19
+ tasks: true, // business tasks + session bindings + checkpoints (W3)
20
+ bridgeConsumer: true, // independent Bridge journal consumer (W3)
21
+ reviews: false, // model review orchestration via Workbench (later slice of W5)
22
+ checks: true, // deterministic quality CLI runner (eslint/knip subprocess receipts)
23
+ memberMemory: true, // member binding validation for engine reads (W4)
24
+ digests: true, // daily digest + reminders, deterministic aggregation (W7)
25
+ internalEndpoints: true, // trusted-service validation endpoints (engine/workbench)
26
+ };
27
+
28
+ function healthBody({ uptimeSec, dataDir, managed } = {}) {
29
+ return {
30
+ ok: true,
31
+ name: MODULE_NAME,
32
+ version: pkg.version,
33
+ apiVersion: API_VERSION,
34
+ schema: 'workflow-health/v1',
35
+ capabilities: { ...CAPABILITIES },
36
+ managed: Boolean(managed),
37
+ ...(uptimeSec !== undefined ? { uptimeSec } : {}),
38
+ ...(dataDir !== undefined ? { dataDir } : {}),
39
+ time: new Date().toISOString(),
40
+ };
41
+ }
42
+
43
+ function capabilitiesBody() {
44
+ return { apiVersion: API_VERSION, moduleVersion: pkg.version, capabilities: { ...CAPABILITIES } };
45
+ }
46
+
47
+ module.exports = { MODULE_NAME, API_VERSION, CAPABILITIES, healthBody, capabilitiesBody };