@alpacachen/dsh-kanban 1.11.3 → 1.12.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,900 @@
1
+ // Independent Workflow store; schema v1 is retained for existing data.
2
+ // Domain evidence must come from the authenticated gateway and runtime, not callers.
3
+ import { DatabaseSync } from 'node:sqlite'
4
+ import { createHash, randomUUID } from 'node:crypto'
5
+ import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync } from 'node:fs'
6
+ import { dirname, isAbsolute, resolve } from 'node:path'
7
+
8
+ const APPLICATION_ID = 0x44535746 // DSWF; never adopt another application's DB.
9
+ const SCHEMA_VERSION = 1
10
+ const SCHEMA = readFileSync(new URL('../docs/workflow-model.schema.sql', import.meta.url), 'utf8')
11
+ const SYSTEM = { kind: 'system', id: 'workflow-poc' }
12
+ const TERMINAL = new Set(['completed', 'terminated'])
13
+ const SETTLED = new Set(['succeeded', 'failed', 'cancelled'])
14
+ const NATIVE_POLICY = 'dsh-native/v1'
15
+ const PROCESS_STOP_POLICY = 'single-process-journal/v1'
16
+
17
+
18
+ function fail(code, message) {
19
+ const error = new Error(message)
20
+ error.code = `WF_${code}`
21
+ error.workflowValidation = true
22
+ throw error
23
+ }
24
+ function check(condition, code, message) { if (!condition) fail(code, message) }
25
+ function object(value, label) {
26
+ check(value !== null && typeof value === 'object' && !Array.isArray(value)
27
+ && [Object.prototype, null].includes(Object.getPrototypeOf(value)), 'INVALID_INPUT', `${label} must be a plain object`)
28
+ return value
29
+ }
30
+ function text(value, label, max = 10000) {
31
+ check(typeof value === 'string' && value.trim().length > 0 && value.length <= max, 'INVALID_INPUT', `${label} must be non-empty text (max ${max})`)
32
+ return value
33
+ }
34
+ function integer(value, label) {
35
+ check(Number.isSafeInteger(value) && value >= 0, 'INVALID_INPUT', `${label} must be a non-negative integer`)
36
+ return value
37
+ }
38
+ function exactKeys(value, allowed, label) {
39
+ object(value, label)
40
+ check(Object.keys(value).every(key => allowed.includes(key)), 'INVALID_INPUT', `${label} contains an unsupported field`)
41
+ }
42
+ function json(value, depth = 0) {
43
+ check(depth <= 24, 'INVALID_INPUT', 'JSON nesting exceeds the PoC limit')
44
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value)
45
+ if (typeof value === 'number') { check(Number.isFinite(value), 'INVALID_INPUT', 'JSON numbers must be finite'); return JSON.stringify(value) }
46
+ if (Array.isArray(value)) return `[${value.map(item => json(item, depth + 1)).join(',')}]`
47
+ object(value, 'JSON value')
48
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${json(value[key], depth + 1)}`).join(',')}}`
49
+ }
50
+ function copy(value) { return JSON.parse(json(value)) }
51
+ function hash(value) { return createHash('sha256').update(json(value)).digest('hex') }
52
+ function freeze(value) {
53
+ if (value && typeof value === 'object') { for (const child of Object.values(value)) freeze(child); Object.freeze(value) }
54
+ return value
55
+ }
56
+ function actorValue(actor) { object(actor, 'actor'); text(actor.kind, 'actor.kind', 100); return copy(actor) }
57
+ function optionalText(value, label, max) {
58
+ if (value === undefined) return ''
59
+ check(typeof value === 'string' && value.length <= max, 'INVALID_INPUT', `${label} must be text (max ${max})`)
60
+ return value
61
+ }
62
+ function processIdentity(value) {
63
+ exactKeys(value, ['pid', 'startedAt'], 'process identity')
64
+ check(Number.isSafeInteger(value.pid) && value.pid > 1, 'INVALID_INPUT', 'Process pid must be an integer greater than one')
65
+ text(value.startedAt, 'process startedAt', 80)
66
+ return { pid: value.pid, startedAt: value.startedAt }
67
+ }
68
+ function definitionView(input) {
69
+ return { description: input.description ?? '', inputLabel: input.inputLabel ?? '', inputHint: input.inputHint ?? '',
70
+ stages: input.stages }
71
+ }
72
+ function validateDefinition(input, { legacy = false } = {}) {
73
+ exactKeys(input, legacy ? ['stages'] : ['stages', 'description', 'inputLabel', 'inputHint', 'permissions'], 'definition')
74
+ const limit = legacy ? 32 : 16
75
+ check(Array.isArray(input.stages) && input.stages.length >= 1 && input.stages.length <= limit,
76
+ 'INVALID_DEFINITION', `Use between 1 and ${limit} sequential stages`)
77
+ optionalText(input.description, 'description', 4000)
78
+ optionalText(input.inputLabel, 'inputLabel', 200)
79
+ optionalText(input.inputHint, 'inputHint', 4000)
80
+ const earlier = new Map()
81
+ for (const stage of input.stages) {
82
+ exactKeys(stage, ['id', 'kind', 'title', 'prompt', 'returnStageId', 'modelSelection'], 'stage')
83
+ check(typeof stage.id === 'string' && /^[a-zA-Z0-9_.-]{1,64}$/.test(stage.id) && !earlier.has(stage.id), 'INVALID_DEFINITION', 'Stage ids must be unique, short identifiers')
84
+ text(stage.title, 'stage.title', 200)
85
+ check(['agent', 'review'].includes(stage.kind), 'INVALID_DEFINITION', 'Only agent and review stages are supported')
86
+ if (!legacy && stage.kind === 'review') optionalText(stage.prompt, 'stage.prompt', Infinity)
87
+ else if (!legacy || stage.prompt !== undefined) text(stage.prompt, 'stage.prompt', Infinity)
88
+ if (stage.kind === 'review') {
89
+ check(earlier.get(stage.returnStageId) === 'agent', 'INVALID_DEFINITION', 'Review must return to a fixed earlier agent stage')
90
+ } else check(stage.returnStageId === undefined, 'INVALID_DEFINITION', 'Only review stages have returnStageId')
91
+ if (stage.modelSelection !== undefined) {
92
+ check(stage.kind === 'agent', 'INVALID_DEFINITION', 'Only agent stages configure a model')
93
+ exactKeys(stage.modelSelection, ['provider', 'model', 'reasoningEffort'], 'stage.modelSelection')
94
+ text(stage.modelSelection.provider, 'stage.modelSelection.provider', 200)
95
+ text(stage.modelSelection.model, 'stage.modelSelection.model', 200)
96
+ if (stage.modelSelection.reasoningEffort !== undefined) text(stage.modelSelection.reasoningEffort, 'stage.modelSelection.reasoningEffort', 80)
97
+ }
98
+ earlier.set(stage.id, stage.kind)
99
+ }
100
+ check(input.stages[0].kind === 'agent', 'INVALID_DEFINITION', 'The first stage must be an agent')
101
+ return copy(legacy ? input : definitionView(input))
102
+ }
103
+ /** Validate complete stage structure before saving a reusable workflow. */
104
+ export function validateWorkflowDefinition(definition) { return validateDefinition(definition) }
105
+
106
+ // Model context is Host-owned and stays outside command fingerprints, so retries reuse the original receipt.
107
+ function inheritStageModels(definition, selection, previous = []) {
108
+ if (!selection) return definition
109
+ return validateWorkflowDefinition({ ...definition, stages: definition.stages.map(stage => {
110
+ if (stage.kind !== 'agent') return stage
111
+ const saved = previous.find(item => item.id === stage.id && item.kind === 'agent')
112
+ const next = { ...stage }
113
+ delete next.modelSelection
114
+ if (saved) { if (saved.modelSelection) next.modelSelection = saved.modelSelection }
115
+ else next.modelSelection = selection
116
+ return next
117
+ }) })
118
+ }
119
+
120
+ function schemaSignature(db) {
121
+ return json(db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name").all().map(row => ({ ...row })))
122
+ }
123
+ function expectedSignature() {
124
+ const db = new DatabaseSync(':memory:')
125
+ try { db.exec(SCHEMA); return schemaSignature(db) } finally { db.close() }
126
+ }
127
+ const EXPECTED_SCHEMA = expectedSignature()
128
+
129
+ /** Trusted Host path only. Never pass a model- or browser-selected database path. */
130
+ export function openWorkflowStore(path) {
131
+ check(typeof path === 'string' && (path === ':memory:' || isAbsolute(path)), 'DB_PATH', 'Use :memory: or a trusted absolute database path')
132
+ let fresh = path === ':memory:'
133
+ if (!fresh) {
134
+ const target = resolve(path)
135
+ if (!existsSync(target)) {
136
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 })
137
+ let fd
138
+ try { fd = openSync(target, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW || 0), 0o600); fresh = true }
139
+ catch (error) { if (error.code === 'EEXIST') fail('DB_BUSY', 'Another opener created this database; retry explicitly'); throw error }
140
+ finally { if (fd !== undefined) closeSync(fd) }
141
+ }
142
+ const stat = lstatSync(target)
143
+ check(stat.isFile() && !stat.isSymbolicLink() && stat.nlink === 1, 'DB_PATH', 'Database must be a regular, non-symlink, non-hardlinked file')
144
+ if (process.platform !== 'win32') check((stat.mode & 0o077) === 0 && stat.uid === process.getuid(), 'DB_PERMISSIONS', 'Database must be owned by this user with owner-only permissions')
145
+ path = realpathSync(target)
146
+ }
147
+ let db
148
+ try {
149
+ db = new DatabaseSync(path)
150
+ db.exec('PRAGMA busy_timeout=0; PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL; PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE;')
151
+ if (fresh) {
152
+ db.exec(SCHEMA)
153
+ db.exec(`PRAGMA application_id=${APPLICATION_ID}; PRAGMA user_version=${SCHEMA_VERSION};`)
154
+ } else {
155
+ check(db.prepare('PRAGMA application_id').get().application_id === APPLICATION_ID
156
+ && db.prepare('PRAGMA user_version').get().user_version === SCHEMA_VERSION
157
+ && schemaSignature(db) === EXPECTED_SCHEMA, 'DB_SCHEMA', 'Unknown application or schema: no adoption, reset, or automatic migration')
158
+ }
159
+ check(db.prepare('PRAGMA quick_check').get().quick_check === 'ok'
160
+ && db.prepare('PRAGMA foreign_key_check').all().length === 0, 'DB_CORRUPT', 'Database integrity or foreign-key check failed')
161
+ db.exec('COMMIT')
162
+ // ponytail: one lifecycle-exclusive writer per PoC DB, including between
163
+ // commands. SQLite releases its OS lock on process death; no expiry/stealing.
164
+ } catch (error) {
165
+ try { db?.exec('ROLLBACK') } catch { /* BEGIN may have failed. */ }
166
+ try { db?.close() } catch { /* Preserve the original failure. */ }
167
+ if (/database is locked|SQLITE_BUSY/.test(error.message)) fail('DB_BUSY', 'Workflow database already has an exclusive owner')
168
+ throw error
169
+ }
170
+ let closed = false
171
+ function transaction(operation) {
172
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
173
+ db.exec('BEGIN IMMEDIATE')
174
+ try {
175
+ const result = operation()
176
+ check(!result || typeof result.then !== 'function', 'ASYNC_TRANSACTION', 'Transactions must never await')
177
+ db.exec('COMMIT')
178
+ return result
179
+ } catch (error) {
180
+ try { db.exec('ROLLBACK') }
181
+ catch {
182
+ // An uncertain commit/rollback must never leave a usable writer behind.
183
+ try { db.close() } catch { /* Preserve the uncertain outcome. */ }
184
+ closed = true
185
+ fail('STORE_UNCERTAIN', 'Transaction outcome is unknown; close and reconcile after reopening')
186
+ }
187
+ throw error
188
+ }
189
+ }
190
+ const get = (sql, ...args) => db.prepare(sql).get(...args)
191
+ const all = (sql, ...args) => db.prepare(sql).all(...args)
192
+ const run = (sql, ...args) => db.prepare(sql).run(...args)
193
+ // Table/column identifiers below are only literals generated in this module.
194
+ function insert(table, values) {
195
+ const keys = Object.keys(values)
196
+ run(`INSERT INTO ${table} (${keys.join(',')}) VALUES (${keys.map(() => '?').join(',')})`, ...Object.values(values))
197
+ }
198
+ function update(table, id, values) {
199
+ const keys = Object.keys(values)
200
+ run(`UPDATE ${table} SET ${keys.map(key => `${key}=?`).join(',')} WHERE id=?`, ...Object.values(values), id)
201
+ }
202
+ function row(table, id) {
203
+ text(id, 'id', 200)
204
+ const found = get(`SELECT * FROM ${table} WHERE id=?`, id)
205
+ check(found, 'NOT_FOUND', `${table.replace('wf_', '')} record does not exist`)
206
+ return found
207
+ }
208
+ function versionOf(task) { return JSON.parse(row('wf_versions', task.workflow_version_id).definition_json) }
209
+ function revision(record, expected, label = 'Task') {
210
+ check(Number.isSafeInteger(expected) && expected === (record.revision ?? record.draft_revision), 'STALE_REVISION', `${label} changed; refresh before deciding`)
211
+ }
212
+ function workflowRoot(payload) {
213
+ text(payload.workspaceId, 'workspaceId', 200); text(payload.executionScope, 'executionScope', 1000); text(payload.name, 'name', 200)
214
+ check(typeof payload.rootPath === 'string' && isAbsolute(payload.rootPath), 'INVALID_INPUT', 'rootPath must be an absolute trusted workspace path')
215
+ const root = realpathSync(payload.rootPath)
216
+ check(lstatSync(root).isDirectory(), 'INVALID_INPUT', 'rootPath must identify a directory')
217
+ const other = get('SELECT execution_scope FROM wf_workflows WHERE root_path_snapshot=? LIMIT 1', root)
218
+ check(!other || other.execution_scope === payload.executionScope, 'SCOPE_MISMATCH', 'The same canonical directory must use the same execution scope')
219
+ return root
220
+ }
221
+ // A durable deletion receipt hides the flow without destroying immutable execution evidence.
222
+ function deletedWorkflow(id) {
223
+ return Boolean(get("SELECT 1 FROM wf_command_receipts WHERE namespace='workflow-poc' AND operation='deleteWorkflow' AND json_extract(response_json,'$.workflowId')=? LIMIT 1", id))
224
+ }
225
+ function deletedTask(id) {
226
+ return Boolean(get("SELECT 1 FROM wf_command_receipts WHERE namespace='workflow-poc' AND operation='deleteTask' AND json_extract(response_json,'$.taskId')=? LIMIT 1", id))
227
+ }
228
+ function activeWorkflow(id) {
229
+ const workflow = row('wf_workflows', id)
230
+ check(!deletedWorkflow(id), 'WORKFLOW_DELETED', '工作流已删除。')
231
+ return workflow
232
+ }
233
+ // Keep the deployed schema: draft_json stores the current definition and
234
+ // published_version_id points to an immutable execution snapshot, not a lifecycle state.
235
+ function snapshotWorkflow(workflow, who) {
236
+ const definition = definitionView(JSON.parse(workflow.draft_json))
237
+ const current = workflow.published_version_id && row('wf_versions', workflow.published_version_id)
238
+ if (current && json(definitionView(JSON.parse(current.definition_json))) === json(definition)) return current.id
239
+ validateWorkflowDefinition(definition)
240
+ const id = randomUUID(), now = Date.now()
241
+ const number = get('SELECT COALESCE(MAX(version_number),0)+1 AS n FROM wf_versions WHERE workflow_id=?', workflow.id).n
242
+ insert('wf_versions', { id, workflow_id: workflow.id, version_number: number,
243
+ definition_json: json(definition), definition_hash: hash(definition), published_by_json: json(who), published_at: now })
244
+ update('wf_workflows', workflow.id, { published_version_id: id, accepting_tasks: 1 })
245
+ return id
246
+ }
247
+ function getWorkflow(id) {
248
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
249
+ const workflow = activeWorkflow(id), definition = definitionView(JSON.parse(workflow.draft_json))
250
+ const snapshot = workflow.published_version_id && row('wf_versions', workflow.published_version_id)
251
+ const current = snapshot && json(definitionView(JSON.parse(snapshot.definition_json))) === json(definition)
252
+ return { id, workspaceId: workflow.workspace_id, name: workflow.name, description: definition.description,
253
+ revision: workflow.draft_revision, definition, versionId: current ? snapshot.id : null,
254
+ versionNumber: current ? snapshot.version_number : null,
255
+ taskCount: all('SELECT id FROM wf_tasks WHERE workflow_id=?', id).filter(item => !deletedTask(item.id)).length,
256
+ createdAt: workflow.created_at, updatedAt: workflow.updated_at,
257
+ rootPath: workflow.root_path_snapshot, executionScope: workflow.execution_scope }
258
+ }
259
+
260
+ function retryBlock(task) {
261
+ if (task.state !== 'needs_attention') return ['NOT_NEEDS_ATTENTION', 'Only a task needing attention can retry']
262
+ if (get("SELECT id FROM wf_attempts WHERE task_id=? AND state='unknown'", task.id))
263
+ return ['RETRY_UNKNOWN', 'Unknown execution must be reconciled; stopping alone does not authorize retry']
264
+ if (get("SELECT id FROM wf_attempts WHERE task_id=? AND (quiesced_at IS NULL OR state IN ('prepared','running'))", task.id)
265
+ || get('SELECT s.attempt_id FROM wf_execution_slots s JOIN wf_attempts a ON a.id=s.attempt_id WHERE a.task_id=?', task.id))
266
+ return ['STOP_UNCONFIRMED', 'Retry requires all previous attempts to be stopped and their execution slots released']
267
+ const visit = row('wf_stage_visits', task.current_visit_id)
268
+ if (visit.outcome !== 'open' || visit.superseded_by_review_id
269
+ || versionOf(task).stages.find(stage => stage.id === visit.stage_id)?.kind !== 'agent')
270
+ return ['INVALID_STAGE', 'Retry requires the current open agent stage']
271
+ return null
272
+ }
273
+ function record(taskId, kind, data, actor = SYSTEM, changes, requestId = null) {
274
+ let task = row('wf_tasks', taskId)
275
+ if (changes) {
276
+ check(!TERMINAL.has(task.state), 'TASK_TERMINAL', 'Terminal task cannot change')
277
+ update('wf_tasks', taskId, { ...changes, revision: task.revision + 1, updated_at: Date.now() })
278
+ task = row('wf_tasks', taskId)
279
+ }
280
+ const sequence = get('SELECT COALESCE(MAX(sequence),0)+1 AS n FROM wf_task_events WHERE task_id=?', taskId).n
281
+ insert('wf_task_events', { id: randomUUID(), task_id: taskId, sequence, task_revision: task.revision, kind,
282
+ actor_json: json(actor), data_json: json(data), request_id: requestId, created_at: Date.now() })
283
+ }
284
+ function command(operation, payload, actor, apply) {
285
+ text(payload.requestId, 'requestId', 200)
286
+ actor = actorValue(actor)
287
+ const fingerprint = hash({ operation, payload, actor })
288
+ return transaction(() => {
289
+ const old = get("SELECT * FROM wf_command_receipts WHERE namespace='workflow-poc' AND request_id=?", payload.requestId)
290
+ if (old) {
291
+ check(old.payload_hash === fingerprint && old.operation === operation, 'IDEMPOTENCY_CONFLICT', 'This request id was already used with different content or actor')
292
+ return JSON.parse(old.response_json)
293
+ }
294
+ const result = apply(actor)
295
+ insert('wf_command_receipts', { namespace: 'workflow-poc', request_id: payload.requestId, operation,
296
+ payload_hash: fingerprint, actor_json: json(actor), response_json: json(result), committed_at: Date.now() })
297
+ return result
298
+ })
299
+ }
300
+ function creationReceipt(requestId, operation) {
301
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
302
+ text(requestId, 'requestId', 200)
303
+ const receipt = get("SELECT operation,response_json FROM wf_command_receipts WHERE namespace='workflow-poc' AND request_id=?", requestId)
304
+ if (!receipt) return null
305
+ check(receipt.operation === operation, 'IDEMPOTENCY_CONFLICT', 'This request id was already used for a different operation')
306
+ // Binding lookup is neither authorization nor replay. The full command must
307
+ // still validate its payload and actor fingerprint before returning a receipt.
308
+ return JSON.parse(receipt.response_json)
309
+ }
310
+ function makeVisit(taskId, stageId, cause = null, identity = randomUUID()) {
311
+ const ordinal = get('SELECT COALESCE(MAX(ordinal),0)+1 AS n FROM wf_stage_visits WHERE task_id=?', taskId).n
312
+ insert('wf_stage_visits', { id: identity, task_id: taskId, stage_id: stageId, ordinal,
313
+ entered_by: cause ? 'rework' : ordinal === 1 ? 'start' : 'advance', caused_by_review_id: cause,
314
+ outcome: 'open', opened_at: Date.now() })
315
+ return identity
316
+ }
317
+ function currentArtifactIds(taskId) {
318
+ return all(`SELECT a.result_json FROM wf_stage_visits v JOIN wf_attempts a ON a.id=v.accepted_attempt_id
319
+ WHERE v.task_id=? AND v.superseded_by_review_id IS NULL AND v.outcome='succeeded' ORDER BY v.ordinal`, taskId)
320
+ .flatMap(item => JSON.parse(item.result_json).artifactIds)
321
+ }
322
+ function feedbackFor(task) {
323
+ const stages = versionOf(task).stages
324
+ const current = row('wf_stage_visits', task.current_visit_id)
325
+ const stageIndex = stages.findIndex(stage => stage.id === current.stage_id)
326
+ return all(`SELECT v.stage_id,r.id,r.feedback FROM wf_stage_visits v JOIN wf_reviews r ON r.id=v.caused_by_review_id
327
+ WHERE v.task_id=? AND v.superseded_by_review_id IS NULL ORDER BY v.ordinal`, task.id)
328
+ .filter(item => stages.findIndex(stage => stage.id === item.stage_id) <= stageIndex)
329
+ .map(item => ({ reviewId: item.id, feedback: item.feedback }))
330
+ }
331
+ function artifactView(item) {
332
+ return { id: item.id, taskId: item.task_id, attemptId: item.attempt_id, outputKey: item.output_key,
333
+ label: item.label, mediaType: item.media_type, contentHash: item.content_hash, byteLength: item.byte_length,
334
+ snapshotRef: item.snapshot_ref, createdAt: item.created_at }
335
+ }
336
+ function attemptView(item) {
337
+ const snapshot = JSON.parse(item.executor_snapshot_json)
338
+ const { _workflowOwner: owner, ...executorSnapshot } = snapshot
339
+ const payload = JSON.parse(item.prompt_payload_json)
340
+ return { id: item.id, taskId: item.task_id, visitId: item.visit_id, attemptNumber: item.attempt_number,
341
+ state: item.state, sessionId: item.session_id, requestId: item.prompt_request_id,
342
+ prompt: payload.content[0].text, promptPayload: payload, promptHash: item.prompt_payload_hash,
343
+ ownerToken: owner.ownerToken, ownerInstanceId: owner.ownerInstanceId,
344
+ inputBundle: JSON.parse(item.input_bundle_json), executorSnapshot, messageId: item.message_id,
345
+ turnNumber: item.turn_number, lastObservedSeq: item.last_observed_seq, acceptedAt: item.accepted_at,
346
+ claimedAt: item.claimed_at, cancelRequestedAt: item.cancel_requested_at, cancelReason: item.cancel_reason,
347
+ createdAt: item.created_at, settledAt: item.settled_at,
348
+ hostEnd: item.host_end_json && JSON.parse(item.host_end_json),
349
+ quiescedAt: item.quiesced_at, result: item.result_json && JSON.parse(item.result_json),
350
+ error: item.error_json && JSON.parse(item.error_json), evidence: item.reconciliation_json && JSON.parse(item.reconciliation_json) }
351
+ }
352
+ function ownedAttempt(id, token) {
353
+ const attempt = row('wf_attempts', id)
354
+ const owner = JSON.parse(attempt.executor_snapshot_json)._workflowOwner
355
+ check(typeof token === 'string' && token === owner.ownerToken, 'OWNER_MISMATCH', 'Attempt owner token does not match')
356
+ return attempt
357
+ }
358
+ function getAttemptProcesses(attemptId) {
359
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
360
+ const attempt = row('wf_attempts', attemptId)
361
+ return all("SELECT data_json FROM wf_task_events WHERE task_id=? AND kind='attempt.process_registered' AND json_extract(data_json,'$.attemptId')=? ORDER BY sequence",
362
+ attempt.task_id, attempt.id).map(item => {
363
+ const { pid, startedAt } = JSON.parse(item.data_json)
364
+ return { pid, startedAt }
365
+ })
366
+ }
367
+ function terminateStoppedTask(task, who, requestId, attemptId = null) {
368
+ const visit = row('wf_stage_visits', task.current_visit_id)
369
+ if (visit.outcome === 'open') update('wf_stage_visits', visit.id, { outcome: 'terminated', closed_at: Date.now() })
370
+ const pending = get("SELECT id FROM wf_reviews WHERE task_id=? AND state='pending'", task.id)
371
+ if (pending) update('wf_reviews', pending.id, { state: 'terminated', decided_by_json: json(who), decision_request_id: requestId, decided_at: Date.now() })
372
+ record(task.id, 'task.terminated', { attemptId }, who,
373
+ { state: 'terminated', finished_at: Date.now(), attention_json: null }, requestId)
374
+ return getTask(task.id)
375
+ }
376
+ function getTask(id) {
377
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
378
+ const task = row('wf_tasks', id)
379
+ check(!deletedTask(id), 'TASK_DELETED', '任务已删除。')
380
+ const workflow = row('wf_workflows', task.workflow_id)
381
+ const version = row('wf_versions', task.workflow_version_id)
382
+ const definition = JSON.parse(version.definition_json)
383
+ const visits = all('SELECT * FROM wf_stage_visits WHERE task_id=? ORDER BY ordinal', id).map(item => ({
384
+ id: item.id, taskId: item.task_id, stageId: item.stage_id, ordinal: item.ordinal, enteredBy: item.entered_by,
385
+ causedByReviewId: item.caused_by_review_id, outcome: item.outcome, acceptedAttemptId: item.accepted_attempt_id,
386
+ supersededByReviewId: item.superseded_by_review_id, openedAt: item.opened_at, closedAt: item.closed_at }))
387
+ const reviews = all('SELECT * FROM wf_reviews WHERE task_id=? ORDER BY requested_at,id', id).map(item => ({
388
+ id: item.id, taskId: item.task_id, visitId: item.visit_id, state: item.state, subject: JSON.parse(item.subject_json),
389
+ subjectHash: item.subject_hash, returnStageId: item.return_stage_id, feedback: item.feedback,
390
+ decidedBy: item.decided_by_json && JSON.parse(item.decided_by_json), requestId: item.decision_request_id,
391
+ requestedAt: item.requested_at, decidedAt: item.decided_at }))
392
+ const currentVisit = visits.find(visit => visit.id === task.current_visit_id)
393
+ return { id, workflowId: task.workflow_id, workflowVersionId: task.workflow_version_id,
394
+ workflowName: workflow.name, versionNumber: version.version_number, canRetry: retryBlock(task) === null,
395
+ workspaceId: workflow.workspace_id, rootPath: workflow.root_path_snapshot, executionScope: workflow.execution_scope,
396
+ title: task.title, state: task.state, revision: task.revision, input: JSON.parse(task.input_json),
397
+ executionConfig: JSON.parse(task.execution_config_json), definition, currentVisitId: task.current_visit_id,
398
+ currentStage: definition.stages.find(stage => stage.id === currentVisit.stageId),
399
+ visits, attempts: all('SELECT * FROM wf_attempts WHERE task_id=? ORDER BY created_at,rowid', id).map(attemptView),
400
+ artifacts: all('SELECT * FROM wf_artifacts WHERE task_id=? ORDER BY created_at,rowid', id).map(artifactView),
401
+ currentArtifactIds: currentArtifactIds(id), effectiveArtifacts: currentArtifactIds(id).map(artifactId => artifactView(row('wf_artifacts', artifactId))),
402
+ feedback: feedbackFor(task).map(item => item.feedback), feedbackDetails: feedbackFor(task),
403
+ review: reviews.find(review => review.state === 'pending' && review.visitId === task.current_visit_id) || null,
404
+ reviews, attention: task.attention_json && JSON.parse(task.attention_json),
405
+ events: all('SELECT * FROM wf_task_events WHERE task_id=? ORDER BY sequence', id).map(item => ({
406
+ id: item.id, sequence: item.sequence, taskRevision: item.task_revision, kind: item.kind,
407
+ actor: JSON.parse(item.actor_json), data: JSON.parse(item.data_json), requestId: item.request_id, createdAt: item.created_at })),
408
+ createdAt: task.created_at, updatedAt: task.updated_at, finishedAt: task.finished_at }
409
+ }
410
+ function advance(task, visit) {
411
+ const stages = versionOf(task).stages
412
+ const next = stages[stages.findIndex(stage => stage.id === visit.stage_id) + 1]
413
+ if (!next) return { state: 'completed', finished_at: Date.now(), attention_json: null }
414
+ const visitId = makeVisit(task.id, next.id)
415
+ if (next.kind === 'agent') return { state: 'queued', current_visit_id: visitId, queued_at: Date.now(), attention_json: null }
416
+ const artifactIds = currentArtifactIds(task.id)
417
+ check(artifactIds.length > 0, 'REVIEW_SUBJECT', 'Review requires at least one valid immutable artifact')
418
+ const subject = { workflowVersionId: task.workflow_version_id, artifactIds,
419
+ artifacts: artifactIds.map(id => artifactView(row('wf_artifacts', id))) }
420
+ insert('wf_reviews', { id: randomUUID(), task_id: task.id, visit_id: visitId, subject_json: json(subject),
421
+ subject_hash: hash(subject), return_stage_id: next.returnStageId, state: 'pending', requested_at: Date.now() })
422
+ return { state: 'waiting_review', current_visit_id: visitId, attention_json: null }
423
+ }
424
+ function addArtifact(attempt, artifact) {
425
+ exactKeys(artifact, ['snapshotRef', 'contentHash', 'byteLength', 'label', 'mediaType'], 'artifact')
426
+ check(typeof artifact.contentHash === 'string' && /^[0-9a-f]{64}$/.test(artifact.contentHash), 'INVALID_ARTIFACT', 'Artifact needs a SHA-256 content hash')
427
+ integer(artifact.byteLength, 'artifact.byteLength'); text(artifact.label, 'artifact.label', 200); text(artifact.mediaType, 'artifact.mediaType', 100)
428
+ let ref
429
+ try { ref = JSON.parse(artifact.snapshotRef) } catch { fail('INVALID_ARTIFACT', 'Artifact must reference stored DSH FileAttachmentRef JSON, never a workspace path') }
430
+ exactKeys(ref, ['attachmentId', 'name', 'bytes'], 'artifact.snapshotRef')
431
+ check(ref.attachmentId === `sha256:${artifact.contentHash}` && ref.bytes === artifact.byteLength && typeof ref.name === 'string',
432
+ 'INVALID_ARTIFACT', 'Stored attachment reference must match the artifact digest and size')
433
+ const existing = get("SELECT * FROM wf_artifacts WHERE attempt_id=? AND output_key='result'", attempt.id)
434
+ if (existing) {
435
+ const view = artifactView(existing)
436
+ check(Object.keys(artifact).every(key => artifact[key] === view[key]), 'ARTIFACT_CONFLICT', 'Previously recorded artifact differs')
437
+ return existing.id
438
+ }
439
+ const id = randomUUID()
440
+ insert('wf_artifacts', { id, task_id: attempt.task_id, attempt_id: attempt.id, output_key: 'result', label: artifact.label,
441
+ media_type: artifact.mediaType, content_hash: artifact.contentHash, byte_length: artifact.byteLength,
442
+ snapshot_ref: artifact.snapshotRef, created_at: Date.now() })
443
+ return id
444
+ }
445
+ function validateSuccessTools(attempt, evidence) {
446
+ const snapshot = JSON.parse(attempt.executor_snapshot_json)
447
+ if (snapshot.policy === NATIVE_POLICY) {
448
+ check(evidence.policy === NATIVE_POLICY
449
+ && [evidence.userSeq, evidence.assistantSeq, evidence.endSeq].every(value => Number.isSafeInteger(value) && value >= 0)
450
+ && evidence.userSeq < evidence.assistantSeq && evidence.assistantSeq < evidence.endSeq,
451
+ 'SUCCESS_UNCONFIRMED', 'Native DSH success requires a durable input, report and completed turn')
452
+ } else {
453
+ check(evidence.toolInvocationCount === 0, 'SUCCESS_UNCONFIRMED', 'Legacy text execution requires tool-free evidence')
454
+ }
455
+ }
456
+ function validateEvidence(attempt, evidence, outcome) {
457
+ if (evidence === undefined || evidence === null) return false
458
+ object(evidence, 'evidence')
459
+ check(['dsh-session-log', 'workflow-preflight'].includes(evidence.kind) && evidence.attemptId === attempt.id
460
+ && evidence.sessionId === attempt.session_id && evidence.requestId === attempt.prompt_request_id,
461
+ 'EVIDENCE_MISMATCH', 'Runtime evidence must match this exact attempt, session, and request')
462
+ if (evidence.kind === 'workflow-preflight') check(outcome !== 'succeeded' && attempt.state === 'prepared'
463
+ && attempt.message_id === null && attempt.turn_number === null && evidence.messageId == null && evidence.turnNumber == null
464
+ && evidence.completed === false && evidence.flushConfirmed === false && evidence.toolInvocationCount === 0,
465
+ 'INVALID_EVIDENCE', 'Preflight evidence applies only to an unstarted prepared attempt and cannot prove success')
466
+ check(typeof evidence.quiescent === 'boolean', 'INVALID_EVIDENCE', 'Evidence must explicitly state quiescence')
467
+ check(attempt.quiesced_at === null || evidence.quiescent, 'EVIDENCE_MISMATCH', 'Confirmed quiescence cannot be withdrawn')
468
+ if (evidence.messageId != null) text(evidence.messageId, 'evidence.messageId', 200)
469
+ if (evidence.turnNumber != null) integer(evidence.turnNumber, 'evidence.turnNumber')
470
+ if (evidence.messageId != null && attempt.message_id != null) check(evidence.messageId === attempt.message_id, 'EVIDENCE_MISMATCH', 'Message correlation changed')
471
+ if (evidence.turnNumber != null && attempt.turn_number != null) check(evidence.turnNumber === attempt.turn_number, 'EVIDENCE_MISMATCH', 'Turn correlation changed')
472
+ if (evidence.quiescent) check(evidence.ownedJobCount === 0, 'STOP_UNCONFIRMED', 'Owned jobs must be confirmed absent')
473
+ json(evidence)
474
+ return evidence.quiescent
475
+ }
476
+
477
+ return {
478
+ getWorkflow,
479
+ listWorkflows(workspaceId) {
480
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
481
+ const rows = workspaceId === undefined
482
+ ? all('SELECT id FROM wf_workflows ORDER BY created_at,rowid')
483
+ : all('SELECT id FROM wf_workflows WHERE workspace_id=? ORDER BY created_at,rowid', text(workspaceId, 'workspaceId', 200))
484
+ return rows.filter(item => !deletedWorkflow(item.id)).map(item => getWorkflow(item.id))
485
+ },
486
+ createWorkflow(payload, actor, selection) {
487
+ exactKeys(payload, ['requestId', 'workspaceId', 'rootPath', 'executionScope', 'name', 'definition'], 'createWorkflow')
488
+ return command('createWorkflow', payload, actor, who => {
489
+ const root = workflowRoot(payload)
490
+ const definition = inheritStageModels(validateWorkflowDefinition(payload.definition), selection)
491
+ const id = randomUUID(), now = Date.now()
492
+ insert('wf_workflows', { id, workspace_id: payload.workspaceId, root_path_snapshot: root, execution_scope: payload.executionScope,
493
+ name: payload.name, draft_json: json(definition), draft_revision: 1, created_at: now, updated_at: now })
494
+ snapshotWorkflow(row('wf_workflows', id), who)
495
+ return getWorkflow(id)
496
+ })
497
+ },
498
+ updateWorkflow(payload, actor, selection) {
499
+ exactKeys(payload, ['requestId', 'workflowId', 'expectedRevision', 'name', 'definition'], 'updateWorkflow')
500
+ return command('updateWorkflow', payload, actor, who => {
501
+ const workflow = activeWorkflow(payload.workflowId)
502
+ revision(workflow, payload.expectedRevision, 'Workflow')
503
+ text(payload.name, 'name', 200)
504
+ const definition = inheritStageModels(validateWorkflowDefinition(payload.definition), selection, JSON.parse(workflow.draft_json).stages)
505
+ update('wf_workflows', workflow.id, { name: payload.name, draft_json: json(definition),
506
+ draft_revision: workflow.draft_revision + 1, updated_at: Date.now() })
507
+ snapshotWorkflow(row('wf_workflows', workflow.id), who)
508
+ return getWorkflow(workflow.id)
509
+ })
510
+ },
511
+ deleteWorkflow(payload, actor) {
512
+ exactKeys(payload, ['requestId', 'workflowId', 'expectedRevision'], 'deleteWorkflow')
513
+ return command('deleteWorkflow', payload, actor, who => {
514
+ check(who.kind === 'user', 'HUMAN_REQUIRED', '请在工作流页面确认删除。')
515
+ const workflow = activeWorkflow(payload.workflowId)
516
+ revision(workflow, payload.expectedRevision, 'Workflow')
517
+ check(!get("SELECT id FROM wf_tasks WHERE workflow_id=? AND state NOT IN ('completed','terminated') LIMIT 1", workflow.id),
518
+ 'WORKFLOW_HAS_ACTIVE_TASKS', '此工作流有未结束的任务,请先处理任务后再删除。')
519
+ check(!get("SELECT a.id FROM wf_attempts a JOIN wf_tasks t ON t.id=a.task_id WHERE t.workflow_id=? AND a.quiesced_at IS NULL LIMIT 1", workflow.id),
520
+ 'STOP_UNCONFIRMED', '尚未确认所有执行已停止,请先核对任务状态。')
521
+ update('wf_workflows', workflow.id, { accepting_tasks: 0, draft_revision: workflow.draft_revision + 1, updated_at: Date.now() })
522
+ return { workflowId: workflow.id, deleted: true }
523
+ })
524
+ },
525
+ getTask,
526
+ listTaskSummaries(workspaceId) {
527
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
528
+ const rows = all(`SELECT t.id,t.workflow_id,t.workflow_version_id,t.current_visit_id,t.title,t.state,t.revision,
529
+ t.created_at,t.updated_at,w.name AS workflow_name,w.workspace_id,v.version_number,
530
+ json_extract(stage.value,'$.title') AS stage_title, json_extract(t.input_json,'$.text') AS input_text
531
+ FROM wf_tasks t JOIN wf_workflows w ON w.id=t.workflow_id
532
+ JOIN wf_versions v ON v.id=t.workflow_version_id JOIN wf_stage_visits visit ON visit.id=t.current_visit_id
533
+ JOIN json_each(v.definition_json,'$.stages') stage ON json_extract(stage.value,'$.id')=visit.stage_id
534
+ ${workspaceId === undefined ? '' : 'WHERE w.workspace_id=?'} ORDER BY t.created_at,t.rowid`,
535
+ ...(workspaceId === undefined ? [] : [text(workspaceId, 'workspaceId', 200)]))
536
+ return rows.filter(task => !deletedTask(task.id)).map(task => ({ id: task.id, workflowId: task.workflow_id, workflowName: task.workflow_name,
537
+ workflowVersionId: task.workflow_version_id, versionNumber: task.version_number, workspaceId: task.workspace_id, title: task.title, inputText: task.input_text, state: task.state,
538
+ revision: task.revision, stageTitle: task.stage_title, createdAt: task.created_at, updatedAt: task.updated_at,
539
+ canRetry: retryBlock(task) === null }))
540
+ },
541
+ listTasks(workspaceId) {
542
+ check(!closed, 'STORE_CLOSED', 'Workflow store is closed')
543
+ const rows = workspaceId === undefined
544
+ ? all('SELECT id FROM wf_tasks ORDER BY created_at,rowid')
545
+ : all('SELECT t.id FROM wf_tasks t JOIN wf_workflows w ON w.id=t.workflow_id WHERE w.workspace_id=? ORDER BY t.created_at,t.rowid', text(workspaceId, 'workspaceId', 200))
546
+ return rows.filter(item => !deletedTask(item.id)).map(item => getTask(item.id))
547
+ },
548
+ getCreateTaskBinding(requestId) {
549
+ const task = creationReceipt(requestId, 'createTask')
550
+ return task ? { workflowId: task.workflowId, workspaceId: task.workspaceId } : null
551
+ },
552
+ getCreateTaskSnapshot(requestId) {
553
+ const task = creationReceipt(requestId, 'createTask')
554
+ return task ? { workflowId: task.workflowId, workflowVersionId: task.workflowVersionId,
555
+ workspaceId: task.workspaceId, executionConfig: task.executionConfig } : null
556
+ },
557
+ getCreateWorkflowBinding(requestId) {
558
+ const workflow = creationReceipt(requestId, 'createWorkflow')
559
+ return workflow ? { workspaceId: workflow.workspaceId, rootPath: workflow.rootPath, executionScope: workflow.executionScope } : null
560
+ },
561
+ publishDefinition(payload, actor) {
562
+ exactKeys(payload, ['requestId', 'workspaceId', 'rootPath', 'executionScope', 'name', 'definition'], 'publishDefinition')
563
+ return command('publishDefinition', payload, actor, who => {
564
+ const root = workflowRoot(payload)
565
+ // Preserve the deployed prototype's definition/receipt contract.
566
+ const definition = validateDefinition(payload.definition, { legacy: true })
567
+ const id = randomUUID(), versionId = randomUUID(), now = Date.now()
568
+ insert('wf_workflows', { id, workspace_id: payload.workspaceId, root_path_snapshot: root, execution_scope: payload.executionScope,
569
+ name: payload.name, draft_json: json(definition), draft_revision: 1, created_at: now, updated_at: now })
570
+ insert('wf_versions', { id: versionId, workflow_id: id, version_number: 1, definition_json: json(definition),
571
+ definition_hash: hash(definition), published_by_json: json(who), published_at: now })
572
+ update('wf_workflows', id, { published_version_id: versionId, accepting_tasks: 1 })
573
+ return { workflowId: id, versionId, workflow: { id, workspaceId: payload.workspaceId, rootPath: root,
574
+ executionScope: payload.executionScope, name: payload.name, publishedVersionId: versionId },
575
+ version: { id: versionId, workflowId: id, versionNumber: 1, definition, definitionHash: hash(definition) } }
576
+ })
577
+ },
578
+ createTask(payload, actor) {
579
+ exactKeys(payload, ['requestId', 'workflowId', 'expectedVersionId', 'title', 'input', 'executionConfig'], 'createTask')
580
+ return command('createTask', payload, actor, who => {
581
+ text(payload.title, 'title', 200); exactKeys(payload.input, ['text'], 'input'); text(payload.input.text, 'input.text', Infinity)
582
+ object(payload.executionConfig, 'executionConfig')
583
+ const workflow = activeWorkflow(payload.workflowId)
584
+ const versionId = snapshotWorkflow(workflow, who)
585
+ if (payload.expectedVersionId !== undefined) {
586
+ text(payload.expectedVersionId, 'expectedVersionId', 200)
587
+ check(payload.expectedVersionId === versionId, 'VERSION_CHANGED', 'The workflow changed; refresh before creating this task')
588
+ }
589
+ const definition = JSON.parse(row('wf_versions', versionId).definition_json)
590
+ const id = randomUUID(), visitId = randomUUID(), now = Date.now()
591
+ insert('wf_tasks', { id, workflow_id: workflow.id, workflow_version_id: versionId,
592
+ title: payload.title, input_json: json(payload.input), execution_config_json: json(payload.executionConfig),
593
+ state: 'queued', current_visit_id: visitId, revision: 1, queued_at: now, created_at: now, updated_at: now })
594
+ makeVisit(id, definition.stages[0].id, null, visitId)
595
+ record(id, 'task.created', {}, who, undefined, payload.requestId)
596
+ return getTask(id)
597
+ })
598
+ },
599
+ prepareAttempt(payload) {
600
+ exactKeys(payload, ['taskId', 'expectedRevision', 'prompt', 'executorSnapshot', 'ownerInstanceId'], 'prepareAttempt')
601
+ return transaction(() => {
602
+ const task = row('wf_tasks', payload.taskId)
603
+ revision(task, payload.expectedRevision)
604
+ check(task.state === 'queued', 'TASK_NOT_QUEUED', 'Only a queued task can dispatch; uncertain work requires reconciliation')
605
+ text(payload.prompt, 'prompt', Infinity); text(payload.ownerInstanceId, 'ownerInstanceId', 200); object(payload.executorSnapshot, 'executorSnapshot')
606
+ check(!Object.hasOwn(payload.executorSnapshot, '_workflowOwner'), 'INVALID_INPUT', 'Reserved executor snapshot key')
607
+ if (payload.executorSnapshot.stopPolicy !== undefined || payload.executorSnapshot.hostProcess !== undefined) {
608
+ check(payload.executorSnapshot.stopPolicy === PROCESS_STOP_POLICY, 'INVALID_INPUT', 'Unsupported process stop policy')
609
+ processIdentity(payload.executorSnapshot.hostProcess)
610
+ }
611
+ const definition = versionOf(task)
612
+ const visit = row('wf_stage_visits', task.current_visit_id)
613
+ const stage = definition.stages.find(stage => stage.id === visit.stage_id)
614
+ check(stage.kind === 'agent' && visit.outcome === 'open' && !visit.superseded_by_review_id, 'INVALID_STAGE', 'Dispatch requires a current open agent stage')
615
+ const scope = row('wf_workflows', task.workflow_id).execution_scope
616
+ check(!get('SELECT attempt_id FROM wf_execution_slots WHERE execution_scope=?', scope), 'SLOT_BUSY', 'Another attempt still owns this execution directory')
617
+ const id = randomUUID(), sessionId = randomUUID(), requestId = randomUUID(), ownerToken = randomUUID(), now = Date.now()
618
+ const feedback = feedbackFor(task)
619
+ const bundle = { input: JSON.parse(task.input_json), artifactIds: currentArtifactIds(task.id),
620
+ feedbackReviewIds: feedback.map(item => item.reviewId), feedback }
621
+ const promptPayload = { mode: 'queue', content: [{ type: 'text', text: payload.prompt }] }
622
+ insert('wf_attempts', { id, task_id: task.id, visit_id: visit.id,
623
+ attempt_number: get('SELECT COALESCE(MAX(attempt_number),0)+1 AS n FROM wf_attempts WHERE visit_id=?', visit.id).n,
624
+ state: 'prepared', input_bundle_json: json(bundle), executor_snapshot_json: json({ ...payload.executorSnapshot,
625
+ _workflowOwner: { ownerInstanceId: payload.ownerInstanceId, ownerToken } }),
626
+ prompt_request_id: requestId, prompt_payload_json: json(promptPayload), prompt_payload_hash: hash(promptPayload), session_id: sessionId, created_at: now })
627
+ insert('wf_execution_slots', { execution_scope: scope, attempt_id: id, owner_instance_id: payload.ownerInstanceId,
628
+ owner_token: ownerToken, acquired_at: now, last_observed_at: now })
629
+ record(task.id, 'attempt.prepared', { attemptId: id }, SYSTEM, { state: 'running', attention_json: null })
630
+ return freeze(attemptView(row('wf_attempts', id)))
631
+ })
632
+ },
633
+ getAttemptProcesses,
634
+ recordProcess(payload) {
635
+ exactKeys(payload, ['attemptId', 'ownerToken', 'pid', 'startedAt'], 'recordProcess')
636
+ return transaction(() => {
637
+ const attempt = ownedAttempt(payload.attemptId, payload.ownerToken)
638
+ check(['prepared', 'running'].includes(attempt.state), 'ATTEMPT_NOT_ACTIVE', 'Only an active prepared or running attempt may register a process')
639
+ check(get('SELECT attempt_id FROM wf_execution_slots WHERE attempt_id=? AND owner_token=?', attempt.id, payload.ownerToken),
640
+ 'OWNER_MISMATCH', 'Process registration requires the current owned execution slot')
641
+ const process = processIdentity({ pid: payload.pid, startedAt: payload.startedAt })
642
+ if (!getAttemptProcesses(attempt.id).some(item => item.pid === process.pid && item.startedAt === process.startedAt))
643
+ record(attempt.task_id, 'attempt.process_registered', { attemptId: attempt.id, ...process })
644
+ return process
645
+ })
646
+ },
647
+ observeAttempt(payload) {
648
+ exactKeys(payload, ['attemptId', 'ownerToken', 'sessionId', 'requestId', 'messageId', 'turnNumber', 'lastObservedSeq', 'acceptedAt', 'claimedAt', 'hostEnd'], 'observeAttempt')
649
+ return transaction(() => {
650
+ const attempt = ownedAttempt(payload.attemptId, payload.ownerToken)
651
+ check(!SETTLED.has(attempt.state), 'ATTEMPT_TERMINAL', 'Settled attempt observations are immutable')
652
+ if (payload.sessionId !== undefined) check(payload.sessionId === attempt.session_id, 'CORRELATION_MISMATCH', 'Session cannot change')
653
+ if (payload.requestId !== undefined) check(payload.requestId === attempt.prompt_request_id, 'CORRELATION_MISMATCH', 'Request cannot change')
654
+ const changes = {}
655
+ const fields = { messageId: 'message_id', turnNumber: 'turn_number', lastObservedSeq: 'last_observed_seq', acceptedAt: 'accepted_at', claimedAt: 'claimed_at' }
656
+ for (const [key, column] of Object.entries(fields)) {
657
+ if (payload[key] === undefined) continue
658
+ if (key === 'messageId') text(payload[key], key, 200); else integer(payload[key], key)
659
+ if (key === 'lastObservedSeq') check(attempt[column] === null || payload[key] >= attempt[column], 'CORRELATION_MISMATCH', 'Observation sequence cannot go backwards')
660
+ else check(attempt[column] === null || payload[key] === attempt[column], 'CORRELATION_MISMATCH', `${key} cannot be rebound`)
661
+ changes[column] = payload[key]
662
+ }
663
+ if (payload.hostEnd !== undefined) changes.host_end_json = json(payload.hostEnd)
664
+ if (attempt.state === 'prepared' && (payload.acceptedAt !== undefined || payload.claimedAt !== undefined || payload.turnNumber !== undefined)) changes.state = 'running'
665
+ if (Object.keys(changes).length) update('wf_attempts', attempt.id, changes)
666
+ run('UPDATE wf_execution_slots SET last_observed_at=? WHERE attempt_id=?', Date.now(), attempt.id)
667
+ const { ownerToken: ignored, ...observation } = payload
668
+ record(attempt.task_id, 'attempt.observed', observation)
669
+ return getTask(attempt.task_id)
670
+ })
671
+ },
672
+ finishAttempt(payload) {
673
+ exactKeys(payload, ['attemptId', 'ownerToken', 'outcome', 'artifact', 'evidence', 'error'], 'finishAttempt')
674
+ return transaction(() => {
675
+ const attempt = ownedAttempt(payload.attemptId, payload.ownerToken)
676
+ check(!SETTLED.has(attempt.state), 'ATTEMPT_TERMINAL', 'Known terminal attempt cannot change')
677
+ check(['succeeded', 'failed', 'cancelled', 'unknown'].includes(payload.outcome), 'INVALID_OUTCOME', 'Unsupported attempt outcome')
678
+ const task = row('wf_tasks', attempt.task_id)
679
+ check(!TERMINAL.has(task.state), 'TASK_TERMINAL', 'Terminal task cannot change')
680
+ const quiet = validateEvidence(attempt, payload.evidence, payload.outcome)
681
+ check(payload.outcome === 'unknown' || quiet || attempt.quiesced_at !== null, 'STOP_UNCONFIRMED', 'Only confirmed quiescent work may settle')
682
+ if (payload.outcome === 'succeeded') {
683
+ check(payload.evidence?.completed === true && payload.evidence?.flushConfirmed === true
684
+ && payload.evidence?.ownedJobCount === 0
685
+ && typeof payload.evidence?.messageId === 'string' && Number.isSafeInteger(payload.evidence?.turnNumber),
686
+ 'SUCCESS_UNCONFIRMED', 'Success requires durable completed, correlated and physically stopped runtime evidence')
687
+ validateSuccessTools(attempt, payload.evidence)
688
+ }
689
+ let artifactId
690
+ if (payload.artifact !== undefined) artifactId = addArtifact(attempt, payload.artifact)
691
+ else artifactId = get("SELECT id FROM wf_artifacts WHERE attempt_id=? AND output_key='result'", attempt.id)?.id
692
+ if (payload.outcome === 'succeeded') {
693
+ check(artifactId, 'ARTIFACT_REQUIRED', 'Success needs an immutable artifact')
694
+ if (payload.evidence.outputSha256 !== undefined) check(payload.evidence.outputSha256 === row('wf_artifacts', artifactId).content_hash, 'EVIDENCE_MISMATCH', 'Output evidence does not match the immutable artifact')
695
+ }
696
+ const quiescedAt = attempt.quiesced_at ?? (quiet ? Date.now() : null)
697
+ update('wf_attempts', attempt.id, { state: payload.outcome, quiesced_at: quiescedAt,
698
+ message_id: attempt.message_id ?? payload.evidence?.messageId ?? null,
699
+ turn_number: attempt.turn_number ?? payload.evidence?.turnNumber ?? null,
700
+ settled_at: SETTLED.has(payload.outcome) ? Date.now() : null,
701
+ result_json: artifactId ? json({ artifactIds: [artifactId] }) : null,
702
+ error_json: payload.error === undefined ? null : json(payload.error),
703
+ reconciliation_json: payload.evidence === undefined ? attempt.reconciliation_json : json(payload.evidence) })
704
+ if (quiescedAt !== null) run('DELETE FROM wf_execution_slots WHERE attempt_id=?', attempt.id)
705
+ const visit = row('wf_stage_visits', attempt.visit_id)
706
+ let changes
707
+ if (task.state === 'terminating') {
708
+ if (quiescedAt !== null) {
709
+ update('wf_stage_visits', visit.id, { outcome: 'terminated', closed_at: Date.now() })
710
+ changes = { state: 'terminated', finished_at: Date.now(), attention_json: null }
711
+ } else changes = { state: 'terminating' }
712
+ } else if (payload.outcome === 'succeeded') {
713
+ update('wf_stage_visits', visit.id, { outcome: 'succeeded', accepted_attempt_id: attempt.id, closed_at: Date.now() })
714
+ changes = advance(task, visit)
715
+ } else changes = { state: 'needs_attention', attention_json: json({ reason: payload.outcome, attemptId: attempt.id,
716
+ ...(payload.error?.code ? { code: payload.error.code } : {}), ...(payload.error?.message ? { message: payload.error.message } : {}) }) }
717
+ record(task.id, `attempt.${payload.outcome}`, { attemptId: attempt.id, quiescent: quiescedAt !== null,
718
+ evidence: payload.evidence ?? null }, SYSTEM, changes)
719
+ return getTask(task.id)
720
+ })
721
+ },
722
+ // Trusted Host-only proof: the caller must verify OS process births/stops.
723
+ // Evidence is intentionally outside the command fingerprint; replay never
724
+ // rechecks an already committed recovery against new observations.
725
+ reconcileTask(payload, actor, evidence) {
726
+ exactKeys(payload, ['requestId', 'taskId', 'expectedRevision', 'confirmedStopped'], 'reconcileTask')
727
+ return command('reconcileTask', payload, actor, who => {
728
+ check(who.kind === 'user', 'HUMAN_REQUIRED', 'Only a real user may request execution reconciliation')
729
+ const task = row('wf_tasks', payload.taskId)
730
+ revision(task, payload.expectedRevision)
731
+ check(['running', 'needs_attention', 'terminating'].includes(task.state), 'RECONCILIATION_UNAVAILABLE', 'Only unfinished executions can be reconciled')
732
+ const attempts = all("SELECT * FROM wf_attempts WHERE task_id=? AND state IN ('prepared','running','unknown')", task.id)
733
+ check(attempts.length === 1 && attempts[0].visit_id === task.current_visit_id,
734
+ 'RECONCILIATION_UNAVAILABLE', 'Recovery requires exactly one unfinished attempt in the current stage')
735
+ const attempt = attempts[0], snapshot = JSON.parse(attempt.executor_snapshot_json)
736
+ check(attempt.state === 'unknown' || snapshot.policy === NATIVE_POLICY && snapshot.stopPolicy === undefined,
737
+ 'RECONCILIATION_UNAVAILABLE', 'Live-owner recovery requires native Session ownership evidence')
738
+ object(evidence, 'reconciliation evidence')
739
+ check(evidence.attemptId === attempt.id
740
+ && evidence.sessionId === attempt.session_id && evidence.requestId === attempt.prompt_request_id,
741
+ 'EVIDENCE_MISMATCH', 'Recovery evidence must match this exact attempt, session and request')
742
+ if (snapshot.policy === NATIVE_POLICY && snapshot.stopPolicy === undefined) {
743
+ check(evidence.kind === 'dsh-native-stop' && ['live-idle', 'exclusive-session', 'session-absent'].includes(evidence.ownership)
744
+ && (attempt.message_id === null || evidence.messageId === attempt.message_id)
745
+ && (attempt.turn_number === null || evidence.turnNumber === attempt.turn_number)
746
+ && (evidence.ownership !== 'session-absent' || attempt.message_id === null && attempt.turn_number === null && evidence.logLastSeq === -1)
747
+ && Number.isSafeInteger(evidence.logLastSeq) && evidence.logLastSeq >= -1,
748
+ 'EVIDENCE_MISMATCH', 'Native recovery requires correlated Session ownership evidence')
749
+ check(evidence.quiescent === true && evidence.ownedJobCount === 0, 'STOP_UNCONFIRMED', 'Native execution must be idle with no running jobs')
750
+ check(attempt.state !== 'unknown' || evidence.ownership !== 'exclusive-session' || evidence.operatorConfirmedStopped === true,
751
+ 'RECOVERY_CONFIRM_REQUIRED', 'A cold interrupted execution requires human confirmation that prior operations have stopped')
752
+ } else {
753
+ check(snapshot.stopPolicy === PROCESS_STOP_POLICY, 'RECOVERY_UNSUPPORTED', 'This attempt has no supported stop evidence')
754
+ const host = processIdentity(snapshot.hostProcess), processes = getAttemptProcesses(attempt.id)
755
+ check(evidence.kind === 'workflow-process-journal' && json(processIdentity(evidence.hostProcess)) === json(host) && Array.isArray(evidence.processes)
756
+ && json(evidence.processes.map(processIdentity)) === json(processes),
757
+ 'EVIDENCE_MISMATCH', 'Recovery evidence must cover the exact Host birth and complete process journal')
758
+ check(evidence.quiescent === true && evidence.ownedJobCount === 0
759
+ && evidence.hostStopped === true && evidence.processesStopped === true,
760
+ 'STOP_UNCONFIRMED', 'The previous Host and all registered processes must be confirmed stopped')
761
+ }
762
+ const now = Date.now(), outcome = task.state === 'terminating' ? 'cancelled' : 'failed'
763
+ update('wf_attempts', attempt.id, { state: outcome, quiesced_at: attempt.quiesced_at ?? now, settled_at: now,
764
+ error_json: attempt.error_json ?? json({ code: 'WF_EXECUTION_INTERRUPTED', message: 'Execution stopped without a verified result' }),
765
+ reconciliation_json: json(evidence) })
766
+ run('DELETE FROM wf_execution_slots WHERE attempt_id=?', attempt.id)
767
+ let changes
768
+ if (task.state === 'terminating') {
769
+ update('wf_stage_visits', task.current_visit_id, { outcome: 'terminated', closed_at: now })
770
+ changes = { state: 'terminated', finished_at: now, attention_json: null }
771
+ } else changes = { state: 'needs_attention', attention_json: json({ reason: 'execution_reconciled', attemptId: attempt.id,
772
+ message: '旧执行已结束,未自动重新执行。请核对已发生的操作,再决定是否重试当前阶段;上游成果已保留。' }) }
773
+ record(task.id, 'attempt.reconciled', { attemptId: attempt.id, outcome, evidence,
774
+ previousEvidence: attempt.reconciliation_json && JSON.parse(attempt.reconciliation_json) }, who, changes, payload.requestId)
775
+ return getTask(task.id)
776
+ })
777
+ },
778
+ retryTask(payload, actor) {
779
+ exactKeys(payload, ['requestId', 'taskId', 'expectedRevision'], 'retryTask')
780
+ return command('retryTask', payload, actor, who => {
781
+ const task = row('wf_tasks', payload.taskId)
782
+ revision(task, payload.expectedRevision)
783
+ const blocked = retryBlock(task)
784
+ if (blocked) fail(...blocked)
785
+ record(task.id, 'task.retry_requested', { visitId: task.current_visit_id }, who,
786
+ { state: 'queued', queued_at: Date.now(), attention_json: null }, payload.requestId)
787
+ return getTask(task.id)
788
+ })
789
+ },
790
+ // Only the outer trusted review boundary may call this. actor is an audit
791
+ // assertion supplied by that boundary, NOT evidence of a human click.
792
+ decideReview(payload, actor) {
793
+ exactKeys(payload, ['taskId', 'reviewId', 'subjectHash', 'expectedRevision', 'requestId', 'decision', 'feedback'], 'decideReview')
794
+ return command('decideReview', payload, actor, who => {
795
+ const task = row('wf_tasks', payload.taskId)
796
+ revision(task, payload.expectedRevision)
797
+ check(task.state === 'waiting_review', 'NOT_WAITING_REVIEW', 'Task is not awaiting this review')
798
+ const review = row('wf_reviews', payload.reviewId)
799
+ check(review.task_id === task.id && review.visit_id === task.current_visit_id && review.state === 'pending', 'REVIEW_STALE', 'Review is stale or belongs to another task')
800
+ check(review.subject_hash === payload.subjectHash, 'SUBJECT_CHANGED', 'Review subject does not match')
801
+ check(['approved', 'returned', 'terminated'].includes(payload.decision), 'INVALID_DECISION', 'Unsupported review decision')
802
+ if (payload.feedback !== undefined) check(typeof payload.feedback === 'string' && payload.feedback.length <= 10000,
803
+ 'INVALID_INPUT', 'feedback must be text of at most 10000 characters')
804
+ if (payload.decision === 'returned') text(payload.feedback, 'feedback', 10000)
805
+ const subject = JSON.parse(review.subject_json)
806
+ check(json(subject.artifactIds) === json(currentArtifactIds(task.id)), 'SUBJECT_CHANGED', 'Current valid outputs no longer match review')
807
+ const visit = row('wf_stage_visits', review.visit_id)
808
+ update('wf_reviews', review.id, { state: payload.decision, feedback: payload.feedback ?? null,
809
+ decided_by_json: json(who), decision_request_id: payload.requestId, decided_at: Date.now() })
810
+ update('wf_stage_visits', visit.id, { outcome: payload.decision === 'approved' ? 'succeeded' : payload.decision, closed_at: Date.now() })
811
+ let changes
812
+ if (payload.decision === 'returned') {
813
+ const stages = versionOf(task).stages
814
+ const index = stages.findIndex(stage => stage.id === review.return_stage_id)
815
+ check(index >= 0 && stages[index].kind === 'agent', 'INVALID_DEFINITION', 'Fixed rework target is invalid')
816
+ for (const stage of stages.slice(index)) run('UPDATE wf_stage_visits SET superseded_by_review_id=? WHERE task_id=? AND stage_id=? AND superseded_by_review_id IS NULL', review.id, task.id, stage.id)
817
+ const newVisit = makeVisit(task.id, review.return_stage_id, review.id)
818
+ changes = { state: 'queued', current_visit_id: newVisit, queued_at: Date.now(), attention_json: null }
819
+ } else if (payload.decision === 'terminated') changes = { state: 'terminated', finished_at: Date.now(), attention_json: null }
820
+ else changes = advance(task, visit)
821
+ record(task.id, `review.${payload.decision}`, { reviewId: review.id }, who, changes, payload.requestId)
822
+ return getTask(task.id)
823
+ })
824
+ },
825
+ deleteTask(payload, actor) {
826
+ exactKeys(payload, ['taskId', 'expectedRevision', 'requestId'], 'deleteTask')
827
+ return command('deleteTask', payload, actor, who => {
828
+ check(who.kind === 'user', 'HUMAN_REQUIRED', '请在任务列表中确认删除。')
829
+ const task = row('wf_tasks', payload.taskId)
830
+ check(!deletedTask(task.id), 'TASK_DELETED', '任务已删除。')
831
+ revision(task, payload.expectedRevision)
832
+ check(!get("SELECT id FROM wf_attempts WHERE task_id=? AND (quiesced_at IS NULL OR state IN ('prepared','running')) LIMIT 1", task.id)
833
+ && !get('SELECT s.attempt_id FROM wf_execution_slots s JOIN wf_attempts a ON a.id=s.attempt_id WHERE a.task_id=? LIMIT 1', task.id),
834
+ 'STOP_UNCONFIRMED', '任务仍在执行或尚未确认停止,请先终止任务后再删除。')
835
+ if (!TERMINAL.has(task.state)) terminateStoppedTask(task, who, payload.requestId)
836
+ return { taskId: task.id, workflowId: task.workflow_id, deleted: true }
837
+ })
838
+ },
839
+ listPendingTaskDeletions() {
840
+ return all(`SELECT t.id,w.root_path_snapshot AS rootPath FROM wf_tasks t
841
+ JOIN wf_workflows w ON w.id=t.workflow_id
842
+ WHERE EXISTS (SELECT 1 FROM wf_command_receipts r WHERE r.operation='deleteTask'
843
+ AND r.namespace='workflow-poc' AND json_extract(r.response_json,'$.taskId')=t.id)
844
+ AND NOT EXISTS (SELECT 1 FROM wf_task_events e WHERE e.task_id=t.id AND e.kind='task.files_deleted')`)
845
+ },
846
+ finishTaskDeletion(taskId) {
847
+ return transaction(() => {
848
+ check(deletedTask(taskId), 'TASK_NOT_DELETED', 'Commit Task deletion before cleaning its directory')
849
+ if (!get("SELECT 1 FROM wf_task_events WHERE task_id=? AND kind='task.files_deleted'", taskId)) {
850
+ record(taskId, 'task.files_deleted', {})
851
+ }
852
+ })
853
+ },
854
+ terminateTask(payload, actor) {
855
+ exactKeys(payload, ['taskId', 'expectedRevision', 'requestId', 'confirmedStopped'], 'terminateTask')
856
+ return command('terminateTask', payload, actor, who => {
857
+ const task = row('wf_tasks', payload.taskId)
858
+ revision(task, payload.expectedRevision)
859
+ check(!TERMINAL.has(task.state), 'TASK_TERMINAL', 'Task is already terminal')
860
+ if (task.state === 'terminating') return getTask(task.id)
861
+ const attempt = get("SELECT * FROM wf_attempts WHERE task_id=? AND state IN ('prepared','running','unknown')", task.id)
862
+ if (!attempt || attempt.quiesced_at !== null) return terminateStoppedTask(task, who, payload.requestId, attempt?.id)
863
+ update('wf_attempts', attempt.id, { cancel_requested_at: Date.now(), cancel_reason: 'task.terminate' })
864
+ record(task.id, 'task.cancel_requested', { attemptId: attempt.id }, who, { state: 'terminating', attention_json: null }, payload.requestId)
865
+ return getTask(task.id)
866
+ })
867
+ },
868
+ flagTaskAttention(taskId, code, message) {
869
+ text(code, 'attention code', 200); text(message, 'attention message', 10000)
870
+ return transaction(() => {
871
+ const task = row('wf_tasks', taskId)
872
+ check(task.state === 'queued'
873
+ && !get("SELECT id FROM wf_attempts WHERE task_id=? AND state IN ('prepared','running','unknown')", taskId)
874
+ && !get('SELECT s.attempt_id FROM wf_execution_slots s JOIN wf_attempts a ON a.id=s.attempt_id WHERE a.task_id=?', taskId),
875
+ 'TASK_NOT_QUEUED', 'Only a queued task without an unsettled attempt or owned slot may be flagged')
876
+ record(taskId, 'task.needs_attention', { code, message }, SYSTEM,
877
+ { state: 'needs_attention', attention_json: json({ code, message }) })
878
+ return getTask(taskId)
879
+ })
880
+ },
881
+ recoverInterrupted(ownerInstanceId) {
882
+ text(ownerInstanceId, 'ownerInstanceId', 200)
883
+ return transaction(() => {
884
+ const recovered = []
885
+ for (const attempt of all("SELECT * FROM wf_attempts WHERE state IN ('prepared','running')")) {
886
+ if (JSON.parse(attempt.executor_snapshot_json)._workflowOwner.ownerInstanceId === ownerInstanceId) continue
887
+ const task = row('wf_tasks', attempt.task_id)
888
+ if (TERMINAL.has(task.state) || ['queued', 'waiting_review'].includes(task.state)) continue
889
+ update('wf_attempts', attempt.id, { state: 'unknown', reconciliation_json: json({ reason: 'owner_interrupted', observedBy: ownerInstanceId }) })
890
+ record(task.id, 'attempt.interrupted', { attemptId: attempt.id }, SYSTEM, task.state === 'terminating'
891
+ ? { state: 'terminating' }
892
+ : { state: 'needs_attention', attention_json: json({ reason: 'owner_interrupted', attemptId: attempt.id }) })
893
+ recovered.push(getTask(task.id))
894
+ }
895
+ return recovered
896
+ })
897
+ },
898
+ close() { if (!closed) { db.close(); closed = true } },
899
+ }
900
+ }