-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdispatcher-strategies.js
More file actions
1472 lines (1324 loc) · 57.9 KB
/
dispatcher-strategies.js
File metadata and controls
1472 lines (1324 loc) · 57.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// dispatcher-strategies.js
// Strategy pattern for dispatchJob: each execution target returns a DispatchResult,
// and finalizeDispatch processes it uniformly.
import { fileURLToPath } from 'url';
/**
* DispatchResult shape (returned by every strategy):
* {
* status: 'ok' | 'error' | 'skipped',
* summary: string,
* content: string, // for delivery + trigger condition eval
* errorMessage: string | null,
* runFinishFields: object, // extra fields for finishRun (shell_exit_code, etc.)
* deliveryOverride: string | null, // override delivery content (null = use content)
* skipDelivery: boolean, // suppress delivery entirely
* skipJobUpdate: boolean, // strategy handled job state itself
* skipChildren: boolean, // don't fire triggered children
* skipDequeue: boolean, // don't drain overlap queue
* idemAction: 'keep' | 'release' | 'noop', // what to do with idempotency key
* retryFiresChildren: boolean, // whether retry path fires triggered children
* earlyReturn: boolean, // finalize should skip everything (strategy fully handled it)
* }
*/
export function makeDefaultResult() {
return {
status: 'ok',
summary: '',
content: '',
errorMessage: null,
runFinishFields: {},
deliveryOverride: null,
skipDelivery: false,
skipJobUpdate: false,
skipChildren: false,
skipDequeue: false,
skipAgentCleanup: true,
idemAction: 'noop',
retryFiresChildren: false,
earlyReturn: false,
};
}
/** Safely parse a JSON string. Returns parsed value or null on failure. */
function safeParse(str) {
if (str == null || str === '') return null;
try {
return JSON.parse(str);
} catch (_e) {
return null;
}
}
function shellSingleQuote(value) {
return "'" + String(value ?? '').replaceAll("'", "'\\''") + "'";
}
function parseStructuredWatchdogPayload(text) {
const direct = safeParse(text);
if (direct && typeof direct === 'object' && !Array.isArray(direct)) return direct;
const firstBrace = text.indexOf('{');
const lastBrace = text.lastIndexOf('}');
if (firstBrace === -1 || lastBrace <= firstBrace) return null;
const candidate = text.slice(firstBrace, lastBrace + 1);
const parsed = safeParse(candidate);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
}
const TERMINAL_WATCHDOG_STATUSES = new Set(['done', 'error', 'interrupted', 'spawn-warning']);
function normalizeWatchdogText(value) {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
function firstWatchdogText(...values) {
for (const value of values) {
const text = normalizeWatchdogText(value);
if (text) return text;
}
return null;
}
function resolveWatchdogTerminalPayload(stdout) {
const text = normalizeWatchdogText(stdout);
if (!text) return null;
const parsed = parseStructuredWatchdogPayload(text);
if (!parsed) return null;
const status = typeof parsed.status === 'string' ? parsed.status : null;
const terminal = parsed.terminal === true || (status ? TERMINAL_WATCHDOG_STATUSES.has(status) : false);
if (!terminal) return null;
const detail = firstWatchdogText(
parsed.deliveryText,
parsed.lastReply,
parsed.error,
parsed.summary,
parsed.completion?.deliveryText,
parsed.completion?.summary,
);
if (status && status !== 'done') {
return {
kind: 'failed',
detail: detail || `Task ended with status ${status}.`,
};
}
return {
kind: 'completed',
detail: detail || `Task reported terminal status ${status || 'done'}.`,
};
}
function buildFireAndForgetDeliveryInstruction(job) {
if (!job.delivery_mode || job.delivery_mode === 'none' || !job.delivery_channel || !job.delivery_to) {
return '';
}
const schedulerCliPath = fileURLToPath(new URL('./cli.js', import.meta.url));
const fromLabel = `scheduler-fire-and-forget:${job.id || job.name || 'job'}`;
const baseCmd = [
'node',
shellSingleQuote(schedulerCliPath),
'messages',
'send',
'--from', shellSingleQuote(fromLabel),
'--to', 'main',
'--channel', shellSingleQuote(job.delivery_channel),
'--delivery-to', shellSingleQuote(job.delivery_to),
].join(' ');
return [
'\n[SYSTEM NOTE -- delivery]',
'When you have completed this task, queue the result through the scheduler post office.',
`Final result: ${baseCmd} --kind result --body "<final result>"`,
`Progress update: ${baseCmd} --kind status --body "<brief progress update>"`,
'Do NOT use the message tool, sessions_send, or any direct chat delivery.',
'The inbox consumer will deliver queued messages durably to the configured target.',
'Keep queued updates concise and actionable.',
'If there is nothing noteworthy to report, do not queue a message.',
'[END SYSTEM NOTE]\n',
].join('\n');
}
function getIdentityTrustLevel(identity) {
if (!identity || typeof identity !== 'object') return null;
return identity.trust_level
|| identity.trust?.effective_level
|| identity.trust?.level
|| identity.session?.trust?.effective_level
|| identity.session?.trust?.level
|| identity.raw?.trust_level
|| identity.raw?.trust?.effective_level
|| identity.raw?.trust?.level
|| null;
}
function getJobTrustLevel(job, parsedIdentity = null) {
const identityBlob = parsedIdentity || safeParse(job?.identity);
return getIdentityTrustLevel(identityBlob) || job?.identity_trust_level || null;
}
function hasIdentityDeclaration(job) {
if (!job) return false;
return job.identity != null
|| job.identity_ref != null
|| job.identity_principal != null
|| job.identity_run_as != null
|| job.identity_attestation != null
|| job.identity_subject_kind != null
|| job.identity_subject_principal != null
|| job.identity_trust_level != null
|| job.identity_delegation_mode != null;
}
/**
* Redact session credentials from v02Outcomes before DB persistence.
* Uses the provider's describeSession() for redaction when available,
* otherwise strips the credentials key directly.
*/
export function redactOutcomesForPersistence(outcomes, deps) {
if (!outcomes?.identity_resolved?.session?.credentials) return outcomes;
const redacted = { ...outcomes };
const ir = { ...redacted.identity_resolved };
const session = { ...ir.session };
const providerName = ir.provider;
const provider = providerName && deps?.getIdentityProvider?.(providerName);
if (provider && typeof provider.describeSession === 'function') {
try {
ir.session = provider.describeSession(session);
} catch (_err) {
delete session.credentials;
ir.session = session;
}
} else {
delete session.credentials;
ir.session = session;
}
redacted.identity_resolved = ir;
return redacted;
}
function abortPreparedRun(job, run, summary, outcomes, state, deps, opts = {}) {
const {
finishRun, persistV02Outcomes, releaseIdempotencyKey, updateJobAfterRun,
setDispatchStatus, handleTriggeredChildren, dequeueJob, log,
} = deps;
finishRun(run.id, 'error', {
summary,
error_message: summary,
});
persistV02Outcomes(run.id, redactOutcomesForPersistence(outcomes, deps));
if (state.idemKey) releaseIdempotencyKey(state.idemKey);
updateJobAfterRun(job, 'error');
if (state.dispatchRecord) setDispatchStatus(state.dispatchRecord.id, 'done');
// Security-related aborts (identity/trust/auth/proof/credential failures)
// should not fire child jobs -- a parent that failed a security gate must
// not trigger downstream work that may have weaker security requirements.
if (!opts.skipChildren) {
handleTriggeredChildren(job.id, 'error', summary, run.id);
}
if (dequeueJob(job.id)) {
log('info', `Dequeued pending dispatch for ${job.name}`);
}
return null;
}
/**
* Uniform post-execution ceremony. Processes the DispatchResult from any strategy.
*
* @param {object} job - The job record
* @param {object} ctx - DispatchContext from prepareDispatch
* @param {object} result - DispatchResult from the strategy
* @param {object} deps - Injected dependencies
*/
export async function finalizeDispatch(job, ctx, result, deps) {
const {
finishRun, updateIdempotencyResultHash, releaseIdempotencyKey,
setAgentStatus, handleDelivery, shouldRetry, scheduleRetry,
getDb, updateJobAfterRun, setDispatchStatus, handleTriggeredChildren,
dequeueJob, log,
} = deps;
if (result.earlyReturn) return;
// 1. Finish the run
finishRun(ctx.run.id, result.status, {
summary: result.summary,
error_message: result.errorMessage,
...result.runFinishFields,
});
// 1b. v0.2 evidence and outcome persistence
if (ctx.v02Outcomes) {
const { generateEvidence, persistV02Outcomes } = deps;
if (job.evidence || job.evidence_ref) {
const runMetadata = { id: ctx.run.id, status: result.status };
const evidence = generateEvidence(job, runMetadata, ctx.v02Outcomes);
if (evidence) ctx.v02Outcomes.evidence_record = evidence;
}
persistV02Outcomes(ctx.run.id, redactOutcomesForPersistence(ctx.v02Outcomes, deps));
}
// 1c. Provider cleanup
if (ctx.materializationCleanup) {
try {
const { provider, cleanupState } = ctx.materializationCleanup;
if (typeof provider.cleanup === 'function') {
await provider.cleanup(cleanupState, { env: process.env, cwd: process.cwd() });
}
} catch (err) {
log('warn', `Provider cleanup failed for ${job.name}: ${err.message}`, { jobId: job.id });
}
}
// 2. Idempotency key management
if (ctx.idemKey) {
if (result.idemAction === 'keep') {
updateIdempotencyResultHash(ctx.idemKey, result.content);
} else if (result.idemAction === 'release') {
releaseIdempotencyKey(ctx.idemKey);
}
// 'noop' -- leave key claimed without writing result hash
}
// 3. Agent status cleanup (only for strategies that set busy)
if (!result.skipAgentCleanup && job.agent_id) setAgentStatus(job.agent_id, 'idle', null);
// 4. Delivery
if (!result.skipDelivery) {
const deliveryContent = result.deliveryOverride ?? result.content;
const shouldAnnounce = ['announce', 'announce-always'].includes(job.delivery_mode)
&& deliveryContent?.trim();
const deliveryOpts = result.imageAttachments?.length > 0
? { imageAttachments: result.imageAttachments }
: {};
if (shouldAnnounce) {
if (result.deliveryOverride) {
await handleDelivery(job, result.deliveryOverride, deliveryOpts);
} else if (result.status === 'error') {
const willRetry = (job.max_retries ?? 0) > 0 && (ctx.run.retry_count || 0) < job.max_retries;
const retryLabel = willRetry ? 'will retry' : 'no retries configured';
await handleDelivery(job, `\u26a0\ufe0f Job soft-failed (${retryLabel}): ${job.name}\n\n${deliveryContent}`, deliveryOpts);
} else {
await handleDelivery(job, deliveryContent, deliveryOpts);
}
}
}
// 5. Retry on error
if (result.status === 'error' && shouldRetry(job, ctx.run.id)) {
const retry = scheduleRetry(job, ctx.run.id);
if (retry.dispatch) {
log('info', `Scheduling retry ${retry.retryCount}/${job.max_retries} in ${retry.delaySec}s`, {
jobId: job.id, runId: ctx.run.id,
});
getDb().prepare('UPDATE runs SET retry_count = ? WHERE id = ?').run(retry.retryCount, ctx.run.id);
if (ctx.dispatchRecord) setDispatchStatus(ctx.dispatchRecord.id, 'done');
if (!result.skipDequeue && dequeueJob(job.id)) {
log('info', `Dequeued pending dispatch for ${job.name}`);
}
if (result.retryFiresChildren && !result.skipChildren) {
handleTriggeredChildren(job.id, 'error', result.content, ctx.run.id, ' on soft failure');
}
log('info', `Failed: ${job.name} (retry scheduled)`, { runId: ctx.run.id });
return; // retry path handles everything
}
log('warn', `Retry skipped for ${job.name} -- dispatch backlog limit reached`, {
jobId: job.id, runId: ctx.run.id,
maxQueuedDispatches: job.max_queued_dispatches || 25,
});
// Fall through to steps 6-9: updateJobAfterRun, dispatch status, children, dequeue
}
// 6. Update job state
if (!result.skipJobUpdate) {
updateJobAfterRun(job, result.status);
}
// 7. Complete dispatch
if (ctx.dispatchRecord) {
setDispatchStatus(ctx.dispatchRecord.id, 'done');
}
// 8. Triggered children
if (!result.skipChildren) {
handleTriggeredChildren(job.id, result.status, result.content, ctx.run.id);
}
// 9. Dequeue overlap
if (!result.skipDequeue && dequeueJob(job.id)) {
log('info', `Dequeued pending dispatch for ${job.name}`);
}
}
// -- Phase 1: Guards + run creation --------------------------
/**
* DispatchContext shape (returned by prepareDispatch):
* {
* dispatchRecord: object | null,
* idemKey: string | null,
* run: object, // the created run record
* retryCount: number,
* dispatchKind: string | null,
* isChainDispatch: boolean,
* }
*/
/**
* Phase 1: Guards + run creation. Returns DispatchContext or null (guard rejected).
*
* @param {object} job
* @param {object} opts - { approvalBypass, dispatchRecord }
* @param {object} deps - Injected dependencies
* @returns {object|null}
*/
export async function prepareDispatch(job, opts, deps) {
const {
claimDispatch, releaseDispatch, setDispatchStatus,
countPendingApprovalsForJob, getPendingApproval,
createApproval, createRun, getRun,
hasRunningRunForPool, hasRunningRun,
enqueueJob, getDispatchBacklogCount,
generateIdempotencyKey, generateChainIdempotencyKey,
generateRunNowIdempotencyKey, claimIdempotencyKey,
finishRun, getDb,
sqliteNow, adaptiveDeferralMs,
handleDelivery, advanceNextRun,
TICK_INTERVAL_MS,
log,
} = deps;
const approvalBypass = opts.approvalBypass === true;
let dispatchRecord = opts.dispatchRecord || null;
// Claim pending dispatch
if (dispatchRecord && dispatchRecord.status === 'pending') {
dispatchRecord = claimDispatch(dispatchRecord.id);
if (!dispatchRecord) {
log('debug', `Skipping claimed dispatch for ${job.name}`, { dispatchId: opts.dispatchRecord.id });
return null;
}
}
const completeCurrentDispatch = (status = 'done') => {
if (!dispatchRecord) return null;
return setDispatchStatus(dispatchRecord.id, status);
};
const dispatchKind = dispatchRecord?.dispatch_kind || null;
const isChainDispatch = dispatchKind === 'chain';
const dispatchBacklogDepth = getDispatchBacklogCount(job.id);
// HITL approval gate
if (job.approval_required && isChainDispatch && !approvalBypass) {
const pendingApprovalCount = countPendingApprovalsForJob(job.id);
if (pendingApprovalCount >= (job.max_pending_approvals || 10)) {
completeCurrentDispatch('cancelled');
log('warn', `Approval backlog limit reached for ${job.name}`, {
jobId: job.id,
pendingApprovals: pendingApprovalCount,
maxPendingApprovals: job.max_pending_approvals || 10,
});
return null;
}
const existing = getPendingApproval(job.id);
if (existing) {
releaseDispatch(dispatchRecord.id, sqliteNow(adaptiveDeferralMs(dispatchBacklogDepth)));
log('debug', `Skipping ${job.name} -- approval already pending`, {
approvalId: existing.id,
dispatchId: dispatchRecord?.id || null,
deferredMs: adaptiveDeferralMs(dispatchBacklogDepth),
});
return null;
}
const run = createRun(job.id, {
run_timeout_ms: job.run_timeout_ms,
status: 'awaiting_approval',
dispatch_queue_id: dispatchRecord?.id || null,
triggered_by_run: dispatchRecord?.source_run_id || null,
retry_of: dispatchRecord?.retry_of_run_id || null,
});
const approval = createApproval(job.id, run.id, dispatchRecord?.id || null);
if (dispatchRecord) setDispatchStatus(dispatchRecord.id, 'awaiting_approval');
log('info', `Approval required for ${job.name} -- awaiting operator`, { approvalId: approval.id, runId: run.id });
const msg = `\u26a0\ufe0f Job '${job.name}' requires approval.\nApprove: openclaw-scheduler jobs approve ${job.id}\nReject: openclaw-scheduler jobs reject ${job.id}`;
await handleDelivery({ ...job, delivery_mode: 'announce-always' }, msg);
return null;
}
// Resource pool concurrency
if (job.resource_pool && hasRunningRunForPool(job.resource_pool)) {
log('info', `Skipping ${job.name} -- resource pool '${job.resource_pool}' busy`, { jobId: job.id, pool: job.resource_pool });
if (dispatchRecord) {
releaseDispatch(dispatchRecord.id, sqliteNow(TICK_INTERVAL_MS));
} else {
advanceNextRun(job);
}
return null;
}
// Overlap control
if (hasRunningRun(job.id)) {
if (job.overlap_policy === 'skip') {
log('info', `Skipping ${job.name} -- previous run still active`, { jobId: job.id });
if (dispatchRecord) {
completeCurrentDispatch('cancelled');
} else {
advanceNextRun(job);
}
return null;
}
if (job.overlap_policy === 'queue') {
const queueResult = enqueueJob(job.id);
if (!queueResult.queued) {
log('warn', `Queue limit reached for ${job.name} -- dropping overlap dispatch`, {
jobId: job.id,
queuedCount: queueResult.queued_count,
maxQueuedDispatches: job.max_queued_dispatches || 25,
});
if (dispatchRecord) {
completeCurrentDispatch('cancelled');
} else {
advanceNextRun(job);
}
return null;
}
log('info', `Queueing ${job.name} -- previous run still active`, {
jobId: job.id,
queuedCount: queueResult.queued_count,
});
if (dispatchRecord) {
completeCurrentDispatch('done');
} else {
advanceNextRun(job);
}
return null;
}
// 'allow' falls through
}
// Idempotency key generation
const scheduledTime = job.schedule_at || job.next_run_at;
let idemKey;
if (dispatchKind === 'chain') {
idemKey = generateChainIdempotencyKey(dispatchRecord.source_run_id || dispatchRecord.id, job.id);
} else if (dispatchKind === 'manual') {
idemKey = generateRunNowIdempotencyKey(job.id);
} else if (dispatchKind === 'retry') {
idemKey = generateChainIdempotencyKey(dispatchRecord.retry_of_run_id || dispatchRecord.id, job.id);
} else {
idemKey = generateIdempotencyKey(job, scheduledTime);
}
// Idempotency dedup
if (idemKey) {
const existing = getDb().prepare("SELECT * FROM idempotency_ledger WHERE key = ? AND status = 'claimed'").get(idemKey);
if (existing) {
log('info', `Idempotency skip: ${job.name} (key ${idemKey.slice(0,8)}... already claimed by run ${existing.run_id.slice(0,8)}...)`);
if (dispatchRecord) {
completeCurrentDispatch('done');
} else {
advanceNextRun(job);
}
return null;
}
}
log('info', `Dispatching: ${job.name}`, { jobId: job.id, target: job.session_target });
const retryCount = dispatchKind === 'retry' && dispatchRecord?.retry_of_run_id
? (getRun(dispatchRecord.retry_of_run_id)?.retry_count || 0)
: 0;
const run = createRun(job.id, {
run_timeout_ms: job.run_timeout_ms,
idempotency_key: idemKey,
retry_count: retryCount,
dispatch_queue_id: dispatchRecord?.id || null,
triggered_by_run: dispatchRecord?.source_run_id || null,
retry_of: dispatchRecord?.retry_of_run_id || null,
});
// Claim idempotency key
if (idemKey) {
const expiresAt = job.delete_after_run
? sqliteNow(24 * 60 * 60 * 1000)
: sqliteNow(7 * 24 * 60 * 60 * 1000);
const claimed = claimIdempotencyKey(idemKey, job.id, run.id, expiresAt);
if (!claimed) {
log('warn', `Idempotency race: ${job.name} key ${idemKey.slice(0,8)}... claimed by concurrent dispatch`);
finishRun(run.id, 'skipped', { summary: 'Idempotency key already claimed (race)' });
if (dispatchRecord) {
completeCurrentDispatch('done');
} else {
advanceNextRun(job);
}
return null;
}
}
// v0.2 runtime evaluation
const {
resolveIdentity, evaluateTrust, verifyAuthorizationProof,
evaluateAuthorization, summarizeCredentialHandoff,
} = deps;
// Build provider context for v0.2 runtime calls
const providerCtx = {
getIdentityProvider: deps.getIdentityProvider,
getAuthorizationProvider: deps.getAuthorizationProvider,
getProofVerifier: deps.getProofVerifier,
env: process.env,
cwd: process.cwd(),
};
const v02Outcomes = {};
const hasV02Identity = hasIdentityDeclaration(job);
const hasV02Contract = job.contract_required_trust_level;
const needsAuthorization = job.authorization || job.authorization_ref;
const shouldResolveIdentity = hasV02Identity || hasV02Contract || needsAuthorization;
if (shouldResolveIdentity) {
v02Outcomes.identity_resolved = await resolveIdentity(job, providerCtx);
}
if (hasV02Identity) {
const handoff = summarizeCredentialHandoff(job);
if (handoff) v02Outcomes.credential_handoff_summary = handoff;
}
const hasDeclaredCredentialHandoff = v02Outcomes.credential_handoff_summary
&& (v02Outcomes.credential_handoff_summary.mode != null
|| v02Outcomes.credential_handoff_summary.bindings_count > 0);
if (hasDeclaredCredentialHandoff && job.session_target !== 'shell') {
return abortPreparedRun(
job,
run,
'Credential handoff presentation is only supported for shell jobs',
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
// Child credential policy enforcement.
// Apply this BEFORE trust/auth evaluation so later gates see the effective
// identity that will actually be materialized for the run. The policy can
// narrow (downscope) or remove (none) credentials, and it may also inherit
// the parent's auth_profile for downstream gateway calls.
if (job.parent_id) {
const { getDb: getDatabase } = deps;
const parentJob = getDatabase().prepare(
'SELECT id, child_credential_policy, identity, identity_trust_level, auth_profile FROM jobs WHERE id = ?'
).get(job.parent_id);
if (parentJob) {
const effectivePolicy = job.child_credential_policy
|| parentJob.child_credential_policy
|| 'none';
const parentIdentityBlob = safeParse(parentJob.identity);
const lastSuccessfulParentRun = (effectivePolicy === 'downscope' || effectivePolicy === 'independent')
? getDatabase().prepare(
'SELECT identity_resolved FROM runs WHERE job_id = ? AND status = ? ORDER BY started_at DESC LIMIT 1'
).get(parentJob.id, 'ok')
: null;
const parentResolvedIdentity = lastSuccessfulParentRun?.identity_resolved
? safeParse(lastSuccessfulParentRun.identity_resolved)
: null;
if (effectivePolicy === 'none') {
// No credentials from parent; suppress any identity the child resolved on its own
v02Outcomes.identity_resolved = null;
} else if (effectivePolicy === 'inherit' && parentJob.auth_profile) {
// Inherit parent's auth profile. Store in v02Outcomes rather than
// mutating the job DB record, which could leak to downstream writes.
v02Outcomes.effective_auth_profile = parentJob.auth_profile;
} else if (effectivePolicy === 'downscope') {
// Downscope: resolve narrower credentials via provider.
// Fail closed on every path -- if downscope is declared, we must
// either produce a downscoped session or abort dispatch.
const providerName = parentIdentityBlob?.provider || parentIdentityBlob?.auth?.provider;
const provider = deps.getIdentityProvider?.(providerName);
let downscopeApplied = false;
if (provider && typeof provider.prepareHandoff === 'function') {
// Get parent session from last run or re-resolve
let parentSession = parentResolvedIdentity?.session || null;
if (!parentSession && provider.resolveSession) {
// Fallback: re-resolve parent identity
try {
const parentScope = parentIdentityBlob?.scope || parentIdentityBlob?.auth?.scopes?.[0] || null;
const reResolved = await provider.resolveSession(
{ profile: parentIdentityBlob, instanceId: parentJob.id, scope: parentScope },
{ env: process.env, cwd: process.cwd() }
);
if (reResolved.ok) parentSession = reResolved.session;
} catch (resolveErr) {
log('warn', `Downscope parent re-resolve failed for ${job.name}: ${resolveErr.message}`, { jobId: job.id });
}
}
if (parentSession) {
const childIdentityBlob = safeParse(job.identity) || {};
const childScope = childIdentityBlob?.scope || childIdentityBlob?.auth?.scopes?.[0] || null;
try {
const handoffResult = await provider.prepareHandoff(
parentSession,
{ target_scope: childScope, parent_profile: parentIdentityBlob },
{ env: process.env, cwd: process.cwd() }
);
if (handoffResult.prepared) {
// Verify handoff actually downscoped: child trust must not
// exceed parent. A provider that returns an elevated session
// violates the downscope contract.
const parentTrustLevel = getIdentityTrustLevel(parentResolvedIdentity)
|| getIdentityTrustLevel({ session: parentSession })
|| getJobTrustLevel(parentJob, parentIdentityBlob);
const childTrustLevel = getIdentityTrustLevel({ session: handoffResult.session });
const { compareTrustLevels } = deps;
if (parentTrustLevel && childTrustLevel && compareTrustLevels(childTrustLevel, parentTrustLevel) > 0) {
log('warn', `Downscope handoff elevated trust from "${parentTrustLevel}" to "${childTrustLevel}" for ${job.name}`, { jobId: job.id });
// Do not set downscopeApplied -- will abort below
} else {
// Override the identity resolution with the handoff session
v02Outcomes.identity_resolved = {
provider: providerName,
session: handoffResult.session,
source: 'provider',
subject_kind: handoffResult.session?.subject?.kind || 'unknown',
principal: handoffResult.session?.subject?.principal || null,
trust_level: childTrustLevel,
delegation_mode: null,
raw: childIdentityBlob,
};
downscopeApplied = true;
}
}
} catch (err) {
log('warn', `Downscope handoff error for ${job.name}: ${err.message}`, { jobId: job.id });
}
}
}
if (!downscopeApplied) {
const reason = !provider
? `identity provider ${providerName || '(none)'} not loaded`
: typeof provider.prepareHandoff !== 'function'
? `provider ${providerName} does not support prepareHandoff`
: 'parent session unavailable or handoff did not produce a downscoped session';
return abortPreparedRun(
job,
run,
`Downscope credential policy failed: ${reason}`,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
} else if (effectivePolicy === 'independent') {
// Child uses its own resolved identity, but cannot exceed the parent's
// trust level. Without this cap, a child could declare a higher trust
// level than the parent and bypass the parent's authorization scope.
const parentTrustLevel = getIdentityTrustLevel(parentResolvedIdentity)
|| getJobTrustLevel(parentJob, parentIdentityBlob);
const childTrustLevel = v02Outcomes.identity_resolved?.trust_level || null;
if (parentTrustLevel && childTrustLevel) {
const { compareTrustLevels } = deps;
if (compareTrustLevels(childTrustLevel, parentTrustLevel) > 0) {
return abortPreparedRun(
job,
run,
`Independent child trust level "${childTrustLevel}" exceeds parent trust level "${parentTrustLevel}"`,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
}
}
}
}
if (v02Outcomes.identity_resolved?.source === 'provider-error') {
return abortPreparedRun(
job,
run,
'Identity resolution failed: ' + (v02Outcomes.identity_resolved.error || 'provider error'),
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
if (hasV02Identity || hasV02Contract || v02Outcomes.identity_resolved != null) {
v02Outcomes.trust_evaluation = evaluateTrust(job, v02Outcomes.identity_resolved);
if (v02Outcomes.trust_evaluation?.decision === 'warn') {
log('warn', `Trust evaluation warning for ${job.name}: ${v02Outcomes.trust_evaluation.reason}`, {
jobId: job.id,
runId: run.id,
});
}
if (v02Outcomes.trust_evaluation?.decision === 'deny') {
return abortPreparedRun(
job,
run,
'Trust enforcement blocked dispatch: ' + v02Outcomes.trust_evaluation.reason,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
}
if (job.authorization_proof || job.authorization_proof_ref) {
v02Outcomes.authorization_proof_verification = await verifyAuthorizationProof(job, providerCtx);
if (v02Outcomes.authorization_proof_verification?.verified === false) {
const proofError = v02Outcomes.authorization_proof_verification.error || 'verification returned false';
// Proof verification failure is blocking: the job declared a proof
// requirement, so proceeding without a valid proof violates policy.
return abortPreparedRun(
job,
run,
'Authorization proof verification failed: ' + proofError,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
}
if (needsAuthorization) {
v02Outcomes.authorization_decision = await evaluateAuthorization(
job, v02Outcomes.identity_resolved, v02Outcomes.trust_evaluation, providerCtx
);
if (v02Outcomes.authorization_decision?.decision === 'deny') {
return abortPreparedRun(
job,
run,
'Authorization denied: ' + v02Outcomes.authorization_decision.reason,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
if (v02Outcomes.authorization_decision?.decision === 'escalate') {
// Escalation means the authorization provider wants a human decision.
// Abort the dispatch so the approval system (or operator) can intervene.
return abortPreparedRun(
job,
run,
'Authorization requires escalation: ' + (v02Outcomes.authorization_decision.reason || 'provider requested escalation'),
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
if (v02Outcomes.authorization_decision?.advisory) {
log('warn', `Authorization advisory for ${job.name}: ${v02Outcomes.authorization_decision.reason}`, { jobId: job.id });
}
}
// Materialization phase
let materializedEnv = null;
let materializationCleanup = null;
if (v02Outcomes.identity_resolved?.source === 'provider' && v02Outcomes.identity_resolved.session) {
const providerName = v02Outcomes.identity_resolved.provider;
const provider = deps.getIdentityProvider?.(providerName);
const identityBlob = safeParse(job.identity) || {};
const presentation = identityBlob.presentation || {};
const hasPresentation = presentation && Object.keys(presentation).length > 0;
if (provider && typeof provider.materialize === 'function') {
try {
const matResult = await provider.materialize(
v02Outcomes.identity_resolved.session,
presentation,
{ env: process.env, cwd: process.cwd() }
);
if (matResult?.materialized) {
materializedEnv = matResult.env_vars || null;
if (matResult.cleanup_required) {
materializationCleanup = {
provider,
cleanupState: {
session: v02Outcomes.identity_resolved.session,
...matResult,
},
};
}
} else if (hasPresentation) {
// Materialization returned false but credentials were declared required
return abortPreparedRun(
job,
run,
`Credential materialization failed for provider ${providerName}: provider returned materialized=false`,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
} catch (err) {
if (hasPresentation) {
return abortPreparedRun(
job,
run,
`Credential materialization error for provider ${providerName}: ${err.message}`,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
// No presentation declared: provider materializes opportunistically.
// Warn and continue -- the shell job can still run without injected
// credentials when the identity blob has no presentation block.
log('warn', `Materialization failed for ${job.name}: ${err.message}`, { jobId: job.id });
}
} else if (hasPresentation) {
// Job declared credential presentation but provider has no materialize method
return abortPreparedRun(
job,
run,
`Job declares credential presentation but provider ${providerName || '(none)'} does not support materialization`,
v02Outcomes,
{ dispatchRecord, idemKey },
deps,
{ skipChildren: true },
);
}
}
return { dispatchRecord, idemKey, run, retryCount, dispatchKind, isChainDispatch, v02Outcomes, materializedEnv, materializationCleanup };
}
// -- Strategy: Watchdog --------------------------------------
export async function executeWatchdog(job, ctx, deps) {
const { runShellCommand, handleDelivery, updateJob, deleteJob, log } = deps;
const result = makeDefaultResult();
result.skipChildren = true;
result.skipDequeue = true;
const checkCmd = job.watchdog_check_cmd;
if (!checkCmd) {
result.status = 'error';
result.errorMessage = 'Watchdog job missing watchdog_check_cmd';
result.skipJobUpdate = false;
return result;
}
const shellExec = await runShellCommand(checkCmd, Math.min(job.run_timeout_ms || 300000, 60000));
const exitCode = shellExec.exitCode;
const stdout = (shellExec.stdout || '').trim();
const stderr = (shellExec.stderr || '').trim();
let timedOut = false;
let elapsedMin = 0;
if (job.watchdog_started_at && job.watchdog_timeout_min) {
const startedAt = new Date(job.watchdog_started_at).getTime();
elapsedMin = Math.round((Date.now() - startedAt) / 60000);
if (elapsedMin >= job.watchdog_timeout_min) timedOut = true;
}
const terminalPayload = resolveWatchdogTerminalPayload(stdout);
if (exitCode === 2) {
result.summary = `Watchdog check failed (transient): ${stderr || stdout}`;
result.skipDelivery = true;
log('debug', `Watchdog check transient failure: ${job.name}`, { exitCode, stderr: stderr.slice(0, 200) });
} else if (exitCode === 0 && terminalPayload) {
const completionMsg = terminalPayload.kind === 'failed'
? [
`⚠️ [watchdog] Task "${job.watchdog_target_label}" ended with failure -- watchdog disarmed`,
terminalPayload.detail ? `Details: ${terminalPayload.detail}` : null,
].filter(Boolean).join('\n')
: [
`\u2705 [watchdog] Task "${job.watchdog_target_label}" completed -- watchdog disarmed`,
terminalPayload.detail || null,
].filter(Boolean).join('\n\n');
result.summary = completionMsg;
result.content = completionMsg;
log(terminalPayload.kind === 'failed' ? 'warn' : 'info', `Watchdog: target terminal: ${job.watchdog_target_label}`, {
jobId: job.id,
terminalKind: terminalPayload.kind,
});
if (job.watchdog_alert_channel && job.watchdog_alert_target) {
await handleDelivery({
...job,
delivery_mode: 'announce-always',
delivery_channel: job.watchdog_alert_channel,
delivery_to: job.watchdog_alert_target,
}, completionMsg);
}
result.skipDelivery = true;
if (job.watchdog_self_destruct) {
result.skipJobUpdate = true;
updateJob(job.id, { enabled: 0 });
deleteJob(job.id);
log('info', `Watchdog self-destructed: ${job.name}`, { jobId: job.id });
}
} else if (exitCode === 1 || timedOut) {
const reason = timedOut
? `running for ${elapsedMin}min (threshold: ${job.watchdog_timeout_min}min)`
: `check command reported stuck`;
const alertMsg = [
`\ud83d\udea8 [watchdog] Task "${job.watchdog_target_label}" appears stuck`,
`- Dispatched: ${job.watchdog_started_at || 'unknown'}`,
`- Running for: ${elapsedMin} minutes (threshold: ${job.watchdog_timeout_min || '?'} min)`,