-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapproval-service.ts
More file actions
1993 lines (1852 loc) · 86.2 KB
/
Copy pathapproval-service.ts
File metadata and controls
1993 lines (1852 loc) · 86.2 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { createHash, randomBytes } from 'node:crypto';
import {
APPROVAL_BRANCH_LABELS,
type ApprovalNodeConfig,
} from '@objectstack/spec/automation';
import type {
IApprovalService,
ApprovalRequestRow,
ApprovalActionRow,
ApprovalDecisionInput,
ApprovalDecisionResult,
ApprovalRecallInput,
ApprovalRecallResult,
ApprovalSendBackInput,
ApprovalSendBackResult,
ApprovalResubmitInput,
ApprovalResubmitResult,
ApprovalStatus,
SharingExecutionContext,
} from '@objectstack/spec/contracts';
/**
* Node-era approval runtime (ADR-0019).
*
* Approval is no longer a standalone engine — it is a **flow node**. A flow's
* Approval node opens a request via {@link ApprovalService.openNodeRequest} and
* the run suspends; a human decision via {@link ApprovalService.decide}
* finalises the request and resumes the owning run down the matching
* `approve` / `reject` edge.
*
* This service owns the durable approval *state* — `sys_approval_request` /
* `sys_approval_action`, approver resolution (team / department / position /
* role / manager graph), and the optional status-field mirror — plus the decision
* API. It does not author processes, submit, or walk multi-step machinery
* anymore; that orchestration lives on the one automation engine.
*/
export interface ApprovalEngine {
find(object: string, options?: any): Promise<any[]>;
insert(object: string, data: any, options?: any): Promise<any>;
update(object: string, idOrData: any, dataOrOptions?: any, options?: any): Promise<any>;
delete(object: string, options?: any): Promise<any>;
}
export interface ApprovalClock { now(): Date }
/**
* Minimal automation surface the service uses to resume a suspended flow run
* once a decision finalises a node-driven request. Optional — attached by the
* plugin when an automation engine is present (see `approval-node.ts`).
*/
export interface ApprovalResumeSurface {
resume?(runId: string, signal?: { output?: Record<string, unknown>; branchLabel?: string }): Promise<unknown>;
/** Flow definition lookup, used to derive step-progress display data. */
getFlow?(name: string): Promise<any | null>;
/**
* Terminally cancel a suspended run (ADR-0044). Used when a recall lands
* during a revision window — the run is paused at the revise wait node,
* which has no reject edge to resume down.
*/
cancelRun?(runId: string, reason?: string): Promise<unknown>;
}
/**
* Optional messaging surface (ADR-0012 `messaging` service). When attached,
* thread interactions (reassign / remind / request-info / comment) notify the
* affected users; without it they degrade to audit-only.
*/
export interface ApprovalMessagingSurface {
emit(input: {
topic: string;
audience: string[];
payload?: Record<string, unknown>;
severity?: string;
dedupKey?: string;
source?: { object: string; id: string };
actorId?: string;
}): Promise<unknown>;
}
/** Minimum time between submitter reminders on one request. */
export const REMIND_COOLDOWN_MS = 4 * 60 * 60 * 1000;
/** Named job under which the SLA escalation scan is registered (ADR-0042). */
export const ESCALATION_JOB_NAME = 'approvals-sla-escalation';
/** Default interval between SLA escalation scans. */
export const ESCALATION_SCAN_INTERVAL_MS = 5 * 60 * 1000;
/** Reserved actor id for machine decisions made by the SLA scanner. */
export const SLA_ACTOR_ID = 'system:sla';
/** Default lifetime of an actionable-link token (ADR-0043). */
export const ACTION_TOKEN_TTL_MS = 72 * 60 * 60 * 1000;
/** Outcome of redeeming (or peeking) an actionable-link token. */
export type ActionTokenOutcome =
| { ok: true; action: 'approve' | 'reject'; request: ApprovalRequestRow; approverId: string }
| { ok: false; reason: 'invalid' | 'expired' | 'consumed' | 'not_pending' | 'not_approver'; request?: ApprovalRequestRow };
const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const;
function uid(prefix: string): string {
const g: any = globalThis as any;
if (g.crypto?.randomUUID) return `${prefix}_${g.crypto.randomUUID()}`;
return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
}
function parseJson<T = any>(raw: unknown, fallback: T): T {
if (raw == null || raw === '') return fallback;
if (typeof raw === 'string') {
try { return JSON.parse(raw) as T; } catch { return fallback; }
}
return raw as T;
}
function csvSplit(raw: unknown): string[] {
if (!raw) return [];
if (Array.isArray(raw)) return raw.map(String).filter(Boolean);
return String(raw).split(',').map(s => s.trim()).filter(Boolean);
}
/**
* Humanize a machine name for display fallback: strips a `flow:` prefix and
* title-cases underscore/dash segments (`flow:manager_review` → "Manager
* Review"). Used only when no authored label was snapshotted on the row.
*/
function prettifyMachineName(raw: string | null | undefined): string | undefined {
if (!raw) return undefined;
const base = String(raw).replace(/^flow:/, '').trim();
if (!base) return undefined;
return base
.split(/[_\-\s]+/)
.filter(Boolean)
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
}
function rowFromRequest(row: any): ApprovalRequestRow {
// Authored display labels ride the node-config snapshot (`__flowLabel` /
// `__nodeLabel`) so they survive without a schema migration; fall back to a
// prettified machine name for rows written before labels were captured.
const cfg = parseJson<any>(row.node_config_json, undefined);
return {
id: String(row.id),
organization_id: row.organization_id ?? undefined,
process_name: String(row.process_name ?? ''),
object_name: String(row.object_name ?? ''),
record_id: String(row.record_id ?? ''),
submitter_id: row.submitter_id ?? undefined,
submitter_comment: row.submitter_comment ?? undefined,
status: (row.status as ApprovalStatus) ?? 'pending',
current_step: row.current_step ?? undefined,
current_step_index: row.current_step_index ?? undefined,
pending_approvers: csvSplit(row.pending_approvers),
payload: parseJson(row.payload_json, undefined),
flow_run_id: row.flow_run_id ?? undefined,
flow_node_id: row.flow_node_id ?? undefined,
completed_at: row.completed_at ?? undefined,
created_at: row.created_at ?? undefined,
updated_at: row.updated_at ?? undefined,
// The row is created at submission time; expose the stable inbox-facing name.
submitted_at: row.created_at ?? undefined,
process_label: cfg?.__flowLabel ?? prettifyMachineName(row.process_name),
step_label: cfg?.__nodeLabel ?? prettifyMachineName(row.current_step),
sla_due_at: slaDueAt(row.created_at, cfg),
// ADR-0044 revision round (rides the config snapshot; absent ⇒ round 1).
round: typeof cfg?.__round === 'number' ? cfg.__round : undefined,
} as any;
}
/** `created_at + escalation.timeoutHours`, when the node declares an SLA. */
function slaDueAt(createdAt: unknown, cfg: any): string | undefined {
const hours = cfg?.escalation?.timeoutHours;
if (typeof hours !== 'number' || hours <= 0 || !createdAt) return undefined;
const t = Date.parse(String(createdAt));
if (Number.isNaN(t)) return undefined;
return new Date(t + hours * 3600_000).toISOString();
}
function rowFromAction(row: any): ApprovalActionRow {
return {
id: String(row.id),
request_id: String(row.request_id),
step_name: row.step_name ?? undefined,
step_index: row.step_index ?? undefined,
action: row.action,
actor_id: row.actor_id ?? undefined,
comment: row.comment ?? undefined,
created_at: row.created_at ?? undefined,
};
}
export interface ApprovalServiceOptions {
engine: ApprovalEngine;
clock?: ApprovalClock;
logger?: { info?: (msg: any, ...rest: any[]) => void; warn?: (msg: any, ...rest: any[]) => void; error?: (msg: any, ...rest: any[]) => void; debug?: (msg: any, ...rest: any[]) => void };
/**
* Optional automation surface used to resume a suspended flow run when a
* decision finalises a request. Usually attached after construction via
* {@link ApprovalService.attachAutomation} once the automation engine is
* available.
*/
automation?: ApprovalResumeSurface;
/** Optional messaging service for thread notifications. */
messaging?: ApprovalMessagingSurface;
/**
* Absolute origin prefixed onto actionable links (ADR-0043), e.g.
* `https://app.example.com`. Defaults to relative URLs, which work inside
* the Console and IM webviews; outbound email needs the absolute form.
*/
publicBaseUrl?: string;
}
export class ApprovalService implements IApprovalService {
private readonly engine: ApprovalEngine;
private readonly clock: ApprovalClock;
private readonly logger?: ApprovalServiceOptions['logger'];
private automation?: ApprovalResumeSurface;
private messaging?: ApprovalMessagingSurface;
private publicBaseUrl: string;
constructor(opts: ApprovalServiceOptions) {
this.engine = opts.engine;
this.clock = opts.clock ?? { now: () => new Date() };
this.logger = opts.logger;
this.automation = opts.automation;
this.messaging = opts.messaging;
this.publicBaseUrl = (opts.publicBaseUrl ?? '').replace(/\/$/, '');
}
/** Attach (or replace) the automation surface used to resume flow runs. */
attachAutomation(automation: ApprovalResumeSurface): void {
this.automation = automation;
}
/** Attach (or replace) the messaging surface used for thread notifications. */
attachMessaging(messaging: ApprovalMessagingSurface): void {
this.messaging = messaging;
}
/** Best-effort notification fan-out — failures only log. */
private async notify(input: {
topic: string;
audience: string[];
payload?: Record<string, unknown>;
dedupKey?: string;
source?: { object: string; id: string };
actorId?: string;
}): Promise<number> {
const audience = input.audience.filter(a => a && !a.includes(':'));
if (!this.messaging || !audience.length) return 0;
try {
await this.messaging.emit({ severity: 'info', ...input, audience });
return audience.length;
} catch (err: any) {
this.logger?.warn?.('[approvals] notification failed', {
topic: input.topic, error: err?.message ?? String(err),
});
return 0;
}
}
/** Load a request row and assert it is still pending. */
private async loadPendingRow(requestId: string): Promise<any> {
if (!requestId) throw new Error('VALIDATION_FAILED: requestId is required');
const rows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rows) ? rows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
if (raw.status !== 'pending') throw new Error(`INVALID_STATE: request is ${raw.status}`);
return raw;
}
/**
* Expand the approvers on an Approval node into user IDs by querying the
* graph tables for `team:` / `department:` / `position:` / `role:` /
* `manager:` approver types. Falls back to a prefixed literal
* (`type:value`) when graph lookups produce nothing — so existing fixtures
* and flows that rely on substring matching keep working.
*
* **Graph semantics:**
* - `team` → flat members of `sys_team` (better-auth; no BFS)
* - `department` → recursive BFS of `sys_business_unit.parent_business_unit_id`
* → members of every descendant via `sys_business_unit_member`
* - `position` → holders via `sys_user_position` ∪ `sys_member.role`
* transition source (ADR-0090 D3 / ADR-0057 D4)
* - `role` → users with `sys_member.role = value` in tenant — the
* better-auth MEMBERSHIP TIER (owner/admin/member), not a
* position; author `position` for org positions
* - `manager` → `sys_user.manager_id` of `record[value] ?? record.owner_id`
* - `field` → literal user id stored in `record[value]`
* - `user` → literal value
*/
private async expandApprovers(step: any, record?: any, organizationId?: string | null): Promise<string[]> {
if (!step || !Array.isArray(step.approvers)) return [];
const out: string[] = [];
for (const a of step.approvers) {
if (!a) continue;
if (a.type === 'user') { out.push(String(a.value)); continue; }
if (a.type === 'field' && record) { out.push(String((record as any)[a.value] ?? '')); continue; }
try {
if (a.type === 'team') {
const users = await this.expandTeamUsers(String(a.value));
if (users.length) { for (const u of users) out.push(u); continue; }
} else if (a.type === 'department' || a.type === 'business_unit' || a.type === 'bu') {
const users = await this.expandBusinessUnitUsers(String(a.value), organizationId);
if (users.length) { for (const u of users) out.push(u); continue; }
} else if (a.type === 'position') {
const users = await this.expandPositionUsers(String(a.value), organizationId);
if (users.length) { for (const u of users) out.push(u); continue; }
} else if (a.type === 'role') {
const users = await this.expandRoleUsers(String(a.value), organizationId);
if (users.length) { for (const u of users) out.push(u); continue; }
} else if (a.type === 'manager' && record) {
const subject = (record as any)[a.value] ?? (record as any).owner_id;
if (subject) {
const mgr = await this.lookupManager(String(subject));
if (mgr) { out.push(mgr); continue; }
}
}
} catch { /* fall through */ }
out.push(`${a.type}:${a.value}`);
}
return out.filter(Boolean);
}
/** Flat team — `sys_team` is better-auth's collaboration grouping (no hierarchy). */
private async expandTeamUsers(teamId: string): Promise<string[]> {
if (!teamId) return [];
let rows: any[] = [];
try {
rows = await this.engine.find('sys_team_member', {
filter: { team_id: teamId },
fields: ['user_id'],
limit: 10000,
context: SYSTEM_CTX,
} as any);
} catch { rows = []; }
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
}
/** Recursive department — walks `sys_business_unit.parent_business_unit_id`. */
private async expandBusinessUnitUsers(businessUnitId: string, organizationId?: string | null): Promise<string[]> {
if (!businessUnitId) return [];
// Seed sanity check: skip if dept doesn't exist or is inactive within tenant.
try {
const seed = await this.engine.find('sys_business_unit', {
filter: organizationId
? { id: businessUnitId, organization_id: organizationId }
: { id: businessUnitId },
fields: ['id', 'active'],
limit: 1,
context: SYSTEM_CTX,
} as any);
const seedRow: any = Array.isArray(seed) ? seed[0] : null;
if (!seedRow || seedRow.active === false) return [];
} catch { return []; }
const seen = new Set<string>([businessUnitId]);
const queue: string[] = [businessUnitId];
while (queue.length) {
const parent = queue.shift()!;
let kids: any[] = [];
try {
const filter: any = { parent_business_unit_id: parent, active: { $ne: false } };
if (organizationId) filter.organization_id = organizationId;
kids = await this.engine.find('sys_business_unit', { filter, fields: ['id'], limit: 1000, context: SYSTEM_CTX } as any);
} catch { kids = []; }
for (const k of kids ?? []) {
const kid = String((k as any).id ?? '');
if (kid && !seen.has(kid)) { seen.add(kid); queue.push(kid); }
}
}
let rows: any[] = [];
try {
rows = await this.engine.find('sys_business_unit_member', {
filter: { business_unit_id: { $in: Array.from(seen) } },
fields: ['user_id'],
limit: 10000,
context: SYSTEM_CTX,
} as any);
} catch { rows = []; }
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
}
/**
* Position holders (ADR-0090 D3): `sys_user_position` is the platform-owned
* assignment table, keyed by the position's machine name (ADR-0057 D4),
* unioned with the better-auth membership string (`sys_member.role`) as a
* transition source — the same semantics as `PositionGraphService` in
* `plugin-sharing`, so an approval routes to exactly the users the sharing
* engine would expand for the same position.
*/
private async expandPositionUsers(positionName: string, organizationId?: string | null): Promise<string[]> {
if (!positionName) return [];
const users = new Set<string>();
const filter: any = { position: positionName };
if (organizationId) filter.organization_id = organizationId;
try {
const rows = await this.engine.find('sys_user_position', {
filter, fields: ['user_id'], limit: 10000, context: SYSTEM_CTX,
} as any);
for (const r of (rows ?? []) as any[]) {
const uid = String(r.user_id ?? '');
if (uid) users.add(uid);
}
} catch { /* table may not exist on minimal stacks — union source below still applies */ }
for (const uid of await this.expandRoleUsers(positionName, organizationId)) users.add(uid);
return Array.from(users);
}
/** better-auth org-membership tier (`sys_member.role`) — NOT positions. */
private async expandRoleUsers(roleName: string, organizationId?: string | null): Promise<string[]> {
if (!roleName) return [];
const filter: any = { role: roleName };
if (organizationId) filter.organization_id = organizationId;
let rows: any[] = [];
try {
rows = await this.engine.find('sys_member', { filter, fields: ['user_id'], limit: 10000, context: SYSTEM_CTX } as any);
} catch { rows = []; }
return Array.from(new Set((rows ?? []).map((r: any) => String(r.user_id ?? '')).filter(Boolean)));
}
private async lookupManager(userId: string): Promise<string | null> {
try {
const rows = await this.engine.find('sys_user', {
filter: { id: userId }, fields: ['id', 'manager_id'], limit: 1, context: SYSTEM_CTX,
} as any);
const row: any = Array.isArray(rows) ? rows[0] : null;
return row?.manager_id ? String(row.manager_id) : null;
} catch { return null; }
}
/** Mirror a request status onto a business-object field, if configured. */
private async mirrorStatusField(object: string, recordId: string, field: string, status: string): Promise<void> {
try {
await this.engine.update(object, { id: recordId, [field]: status }, { context: SYSTEM_CTX });
} catch (err: any) {
this.logger?.warn?.(`[approvals] mirrorStatusField failed: ${err?.message ?? err}`);
}
}
// ── ADR-0019: Approval-as-flow-node ──────────────────────────
//
// A flow's Approval node opens a request via `openNodeRequest` (carrying its
// own approvers/behavior config and the suspended run id), then suspends. A
// later `decide` finalizes it and resumes the flow run down the matching
// `approve`/`reject` edge. The record lock is enforced by a beforeUpdate hook
// keyed on a *pending* request, so finalizing auto-releases it.
/**
* Open a pending approval request on behalf of a flow's Approval node. The
* node config (approvers / behavior / status field) is snapshotted on the row
* so a decision can be made without any process to resolve against.
*/
async openNodeRequest(
input: {
object: string;
recordId: string;
runId: string;
nodeId: string;
config: ApprovalNodeConfig;
flowName?: string;
/** Authored flow label, snapshotted for inbox display. */
flowLabel?: string;
/** Authored node label, snapshotted for inbox display. */
nodeLabel?: string;
submitterId?: string | null;
record?: any;
organizationId?: string | null;
},
context: SharingExecutionContext,
): Promise<ApprovalRequestRow> {
if (!input.object) throw new Error('VALIDATION_FAILED: object is required');
if (!input.recordId) throw new Error('VALIDATION_FAILED: recordId is required');
if (!input.runId) throw new Error('VALIDATION_FAILED: runId is required');
// One pending request per (object, record).
const existing = await this.engine.find('sys_approval_request', {
where: { object_name: input.object, record_id: input.recordId, status: 'pending' },
limit: 1, context: SYSTEM_CTX,
});
if (Array.isArray(existing) && existing[0]) {
throw new Error(`DUPLICATE_REQUEST: a pending approval already exists for ${input.object}/${input.recordId}`);
}
const ctxOrg = (context as any)?.organizationId ?? (context as any)?.tenantId ?? input.organizationId ?? null;
const approvers = await this.expandApprovers({ approvers: input.config.approvers }, input.record, ctxOrg);
const now = this.clock.now().toISOString();
const id = uid('areq');
const processName = `flow:${input.flowName ?? input.nodeId}`;
// Display labels ride the config snapshot (no schema migration needed);
// `rowFromRequest` surfaces them as `process_label` / `step_label`.
const configSnapshot: any = { ...input.config };
if (input.flowLabel) configSnapshot.__flowLabel = input.flowLabel;
if (input.nodeLabel) configSnapshot.__nodeLabel = input.nodeLabel;
// ADR-0044 round numbering: rounds of a revise loop share the run — count
// this (run, node)'s prior requests; the new one is round N+1. Stamped on
// the snapshot (precedent: __flowLabel), so no schema migration.
try {
const prior = await this.engine.find('sys_approval_request', {
where: { flow_run_id: input.runId, flow_node_id: input.nodeId }, limit: 500, context: SYSTEM_CTX,
});
const n = Array.isArray(prior) ? prior.length : 0;
if (n > 0) configSnapshot.__round = n + 1;
} catch { /* round display is best-effort */ }
const row: any = {
id,
process_name: processName,
object_name: input.object,
record_id: input.recordId,
submitter_id: input.submitterId ?? context.userId ?? null,
status: 'pending',
current_step: input.nodeId,
current_step_index: 0,
pending_approvers: approvers.join(','),
payload_json: input.record != null ? JSON.stringify(input.record) : null,
flow_run_id: input.runId,
flow_node_id: input.nodeId,
node_config_json: JSON.stringify(configSnapshot),
organization_id: ctxOrg,
created_at: now,
updated_at: now,
};
await this.engine.insert('sys_approval_request', row, { context: SYSTEM_CTX });
await this.syncApproverIndex(id, approvers, ctxOrg, now);
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: id, organization_id: ctxOrg,
step_name: input.nodeId, step_index: 0, action: 'submit',
actor_id: input.submitterId ?? context.userId ?? null, comment: null, created_at: now,
}, { context: SYSTEM_CTX });
// Record lock (when `lockRecord !== false`) is enforced by the beforeUpdate
// hook keyed on the now-pending request; no extra write needed here.
if (input.config.approvalStatusField) {
await this.mirrorStatusField(input.object, input.recordId, input.config.approvalStatusField, 'pending');
}
return rowFromRequest(row);
}
/**
* Record a decision on a node-driven request. Honours the node's `unanimous`
* behavior (holds until every approver has approved). When the request
* finalizes, returns the suspended run id + node id so the caller (or
* {@link ApprovalService.decide}) can resume the flow down the matching
* branch.
*/
async decideNode(
requestId: string,
input: { decision: 'approve' | 'reject'; actorId: string; comment?: string },
context: SharingExecutionContext,
): Promise<{ request: ApprovalRequestRow; runId: string | null; nodeId: string | null; finalized: boolean; decision: 'approve' | 'reject' }> {
if (!requestId) throw new Error('VALIDATION_FAILED: requestId is required');
if (!input?.actorId) throw new Error('VALIDATION_FAILED: actorId is required');
if (input.decision !== 'approve' && input.decision !== 'reject') {
throw new Error('VALIDATION_FAILED: decision must be approve|reject');
}
// Read the raw row to reach flow_* correlation + the node config snapshot.
const rawRows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rawRows) ? rawRows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
if (raw.status !== 'pending') throw new Error(`INVALID_STATE: request is ${raw.status}`);
const pendingApprovers = csvSplit(raw.pending_approvers);
if (!context.isSystem && !pendingApprovers.includes(input.actorId)) {
throw new Error(`FORBIDDEN: actor '${input.actorId}' is not a pending approver`);
}
const config = parseJson<ApprovalNodeConfig>(raw.node_config_json, { approvers: [], behavior: 'first_response' } as any);
const org = raw.organization_id ?? null;
const nodeId: string | null = raw.flow_node_id ?? raw.current_step ?? null;
const runId: string | null = raw.flow_run_id ?? null;
const now = this.clock.now().toISOString();
// Audit the decision first so the unanimous tally below sees it.
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: input.decision,
actor_id: input.actorId, comment: input.comment ?? null, created_at: now,
}, { context: SYSTEM_CTX });
// Unanimous approve: advance only once every approver has approved.
if (input.decision === 'approve' && config.behavior === 'unanimous') {
const original = await this.expandApprovers(
{ approvers: config.approvers }, parseJson(raw.payload_json, undefined), org,
);
const acts = await this.engine.find('sys_approval_action', {
where: { request_id: requestId, step_index: 0, action: 'approve' }, limit: 500, context: SYSTEM_CTX,
});
const approved = new Set<string>((acts ?? []).map((a: any) => String(a.actor_id ?? '')).filter(Boolean));
const stillPending = original.filter(a => !approved.has(a));
if (stillPending.length > 0) {
await this.engine.update('sys_approval_request', {
id: requestId, pending_approvers: stillPending.join(','), updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, stillPending, org, now);
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, nodeId, finalized: false, decision: input.decision };
}
}
const finalStatus = input.decision === 'approve' ? 'approved' : 'rejected';
await this.engine.update('sys_approval_request', {
id: requestId, status: finalStatus, pending_approvers: null, completed_at: now, updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, [], org, now);
if (config.approvalStatusField) {
await this.mirrorStatusField(raw.object_name, raw.record_id, config.approvalStatusField, finalStatus);
}
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, nodeId, finalized: true, decision: input.decision };
}
/**
* Public contract entrypoint (ADR-0019). Records a decision on a node-driven
* request via {@link ApprovalService.decideNode} and, when it finalizes,
* resumes the owning flow run down the matching `approve` / `reject` edge.
*/
async decide(
requestId: string,
input: ApprovalDecisionInput,
context: SharingExecutionContext,
): Promise<ApprovalDecisionResult> {
const result = await this.decideNode(requestId, input, context);
let resumed = false;
if (result.finalized && result.runId && typeof this.automation?.resume === 'function') {
const branchLabel = result.decision === 'approve'
? APPROVAL_BRANCH_LABELS.approve
: APPROVAL_BRANCH_LABELS.reject;
try {
await this.automation.resume(result.runId, {
branchLabel,
output: { decision: result.decision, requestId },
});
resumed = true;
} catch (err: any) {
this.logger?.warn?.('[approvals] resume after decision failed', {
request: requestId, run: result.runId, error: err?.message ?? String(err),
});
}
}
return {
request: result.request,
finalized: result.finalized,
decision: result.decision,
runId: result.runId,
resumed,
};
}
/**
* Withdraw a pending request (submitter only). Finalises the row as
* `recalled`, releases the record lock (keyed on pending status), mirrors
* the status field when configured, and resumes the owning flow run down
* the `reject` branch with `output.decision = 'recall'` — leaving the run
* suspended forever would leak it.
*
* ADR-0044: also valid on the LATEST `returned` request of its run — the
* submitter abandons the revision window instead of resubmitting. The run
* is then paused at the revise wait node (no reject edge), so it is
* terminally cancelled via {@link ApprovalResumeSurface.cancelRun} rather
* than resumed.
*/
async recall(
requestId: string,
input: ApprovalRecallInput,
context: SharingExecutionContext,
): Promise<ApprovalRecallResult> {
if (!requestId) throw new Error('VALIDATION_FAILED: requestId is required');
if (!input?.actorId) throw new Error('VALIDATION_FAILED: actorId is required');
const rawRows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rawRows) ? rawRows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
const inReviseWindow = raw.status === 'returned';
if (raw.status !== 'pending' && !inReviseWindow) {
throw new Error(`INVALID_STATE: request is ${raw.status}`);
}
if (!context.isSystem && raw.submitter_id && String(raw.submitter_id) !== String(input.actorId)) {
throw new Error(`FORBIDDEN: only the submitter may recall this request`);
}
// A returned request is only recallable while it is still the run's live
// frontier — a resubmitted (or later-node) request supersedes it.
if (inReviseWindow) await this.assertLatestForRun(raw);
const config = parseJson<ApprovalNodeConfig>(raw.node_config_json, { approvers: [], behavior: 'first_response' } as any);
const org = raw.organization_id ?? null;
const nodeId: string | null = raw.flow_node_id ?? raw.current_step ?? null;
const runId: string | null = raw.flow_run_id ?? null;
const now = this.clock.now().toISOString();
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: 'recall',
actor_id: input.actorId, comment: input.comment ?? null, created_at: now,
}, { context: SYSTEM_CTX });
await this.engine.update('sys_approval_request', {
id: requestId, status: 'recalled', pending_approvers: null, completed_at: now, updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, [], org, now);
if (config.approvalStatusField) {
await this.mirrorStatusField(raw.object_name, raw.record_id, config.approvalStatusField, 'recalled');
}
let resumed = false;
if (inReviseWindow) {
// ADR-0044: the run is paused at the revise wait node, which has no
// reject out-edge to resume down — terminally cancel it instead.
if (runId && typeof this.automation?.cancelRun === 'function') {
try {
await this.automation.cancelRun(runId, `approval request ${requestId} recalled during revision`);
} catch (err: any) {
this.logger?.warn?.('[approvals] cancelRun after revise-window recall failed', {
request: requestId, run: runId, error: err?.message ?? String(err),
});
}
}
} else if (runId && typeof this.automation?.resume === 'function') {
try {
await this.automation.resume(runId, {
branchLabel: APPROVAL_BRANCH_LABELS.reject,
output: { decision: 'recall', requestId },
});
resumed = true;
} catch (err: any) {
this.logger?.warn?.('[approvals] resume after recall failed', {
request: requestId, run: runId, error: err?.message ?? String(err),
});
}
}
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, resumed };
}
// ── Send back for revision / resubmit (ADR-0044) ─────────────
/**
* ADR-0044 send back for revision. Finalises the pending request as
* `returned` (a third terminal state — approver-initiated rework, distinct
* from submitter-initiated `recalled`) and resumes the owning flow run down
* its `revise` edge to a wait point: the record lock (keyed on `pending`)
* releases, the submitter reworks the data, then {@link resubmit}s.
*
* Requires the approval node to declare a `revise` out-edge — validated
* BEFORE any mutation, because resuming with an unmatched `branchLabel`
* falls back to *all* out-edges. Past the node's `maxRevisions` budget the
* request auto-rejects instead (resumes down `reject` with
* `output.autoRejected = true`) so instances cannot orbit forever.
*/
async sendBack(
requestId: string,
input: ApprovalSendBackInput,
context: SharingExecutionContext,
): Promise<ApprovalSendBackResult> {
if (!input?.actorId) throw new Error('VALIDATION_FAILED: actorId is required');
const raw = await this.loadPendingRow(requestId);
const pending = csvSplit(raw.pending_approvers);
if (!context.isSystem && !pending.includes(input.actorId)) {
throw new Error(`FORBIDDEN: actor '${input.actorId}' is not a pending approver`);
}
const config = parseJson<ApprovalNodeConfig>(raw.node_config_json, { approvers: [], behavior: 'first_response' } as any);
const org = raw.organization_id ?? null;
const nodeId: string | null = raw.flow_node_id ?? raw.current_step ?? null;
const runId: string | null = raw.flow_run_id ?? null;
await this.assertReviseEdge(raw, nodeId);
const now = this.clock.now().toISOString();
const maxRevisions = typeof (config as any).maxRevisions === 'number' ? (config as any).maxRevisions : 3;
let priorSendBacks = 0;
if (runId && nodeId) {
const siblings = await this.engine.find('sys_approval_request', {
where: { flow_run_id: runId, flow_node_id: nodeId, status: 'returned' }, limit: 500, context: SYSTEM_CTX,
});
priorSendBacks = Array.isArray(siblings) ? siblings.length : 0;
}
// Audit the revise intent first (audit-first, like decideNode) — on the
// auto-reject path the trail then reads `revise → reject`, preserving
// what the approver actually asked for.
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: 'revise',
actor_id: input.actorId, comment: input.comment ?? null, created_at: now,
}, { context: SYSTEM_CTX });
if (priorSendBacks >= maxRevisions) {
// Revision budget exhausted — auto-reject (ADR-0044 loop guard).
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: 'reject',
actor_id: input.actorId,
comment: `Auto-rejected: revision limit (${maxRevisions}) exceeded`, created_at: now,
}, { context: SYSTEM_CTX });
await this.engine.update('sys_approval_request', {
id: requestId, status: 'rejected', pending_approvers: null, completed_at: now, updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, [], org, now);
if (config.approvalStatusField) {
await this.mirrorStatusField(raw.object_name, raw.record_id, config.approvalStatusField, 'rejected');
}
let resumed = false;
if (runId && typeof this.automation?.resume === 'function') {
try {
await this.automation.resume(runId, {
branchLabel: APPROVAL_BRANCH_LABELS.reject,
output: { decision: 'reject', autoRejected: true, requestId },
});
resumed = true;
} catch (err: any) {
this.logger?.warn?.('[approvals] resume after auto-reject failed', {
request: requestId, run: runId, error: err?.message ?? String(err),
});
}
}
if (raw.submitter_id) {
await this.notify({
topic: 'approval.returned',
audience: [String(raw.submitter_id)],
actorId: input.actorId,
source: { object: 'sys_approval_request', id: requestId },
payload: {
title: 'Approval auto-rejected',
message: `Your ${raw.object_name}/${raw.record_id} exceeded the revision limit (${maxRevisions}) and was rejected.`,
actionUrl: '/system/approvals',
},
});
}
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, resumed, autoRejected: true };
}
await this.engine.update('sys_approval_request', {
id: requestId, status: 'returned', pending_approvers: null, completed_at: now, updated_at: now,
}, { context: SYSTEM_CTX });
await this.syncApproverIndex(requestId, [], org, now);
if (config.approvalStatusField) {
await this.mirrorStatusField(raw.object_name, raw.record_id, config.approvalStatusField, 'returned');
}
let resumed = false;
if (runId && typeof this.automation?.resume === 'function') {
try {
await this.automation.resume(runId, {
branchLabel: APPROVAL_BRANCH_LABELS.revise,
output: { decision: 'revise', requestId },
});
resumed = true;
} catch (err: any) {
this.logger?.warn?.('[approvals] resume after send-back failed', {
request: requestId, run: runId, error: err?.message ?? String(err),
});
}
}
if (raw.submitter_id) {
await this.notify({
topic: 'approval.returned',
audience: [String(raw.submitter_id)],
actorId: input.actorId,
source: { object: 'sys_approval_request', id: requestId },
payload: {
title: 'Sent back for revision',
message: input.comment?.trim() || `Your ${raw.object_name}/${raw.record_id} needs rework before it can be approved.`,
actionUrl: '/system/approvals',
},
});
}
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, resumed };
}
/**
* ADR-0044 resubmit after rework. Valid on the LATEST `returned` request of
* its run, submitter-only. Audits `resubmit` on the returned (round-N)
* request and resumes the run from the revise wait node; traversal walks
* the declared back-edge into the approval node, whose executor opens the
* round-N+1 request — fresh approver slate, record re-locks.
*/
async resubmit(
requestId: string,
input: ApprovalResubmitInput,
context: SharingExecutionContext,
): Promise<ApprovalResubmitResult> {
if (!input?.actorId) throw new Error('VALIDATION_FAILED: actorId is required');
const rawRows = await this.engine.find('sys_approval_request', {
where: { id: requestId }, limit: 1, context: SYSTEM_CTX,
});
const raw: any = Array.isArray(rawRows) ? rawRows[0] : null;
if (!raw) throw new Error(`REQUEST_NOT_FOUND: ${requestId}`);
if (raw.status !== 'returned') {
throw new Error(`INVALID_STATE: request is ${raw.status} (resubmit applies to returned requests)`);
}
if (!context.isSystem && raw.submitter_id && String(raw.submitter_id) !== String(input.actorId)) {
throw new Error('FORBIDDEN: only the submitter may resubmit');
}
await this.assertLatestForRun(raw);
// A colliding pending request on the same record (e.g. a record-change
// trigger re-fired off an edit made inside the revise window) would make
// the approval node's re-entry fail AFTER the engine consumed the
// suspension — permanently killing the run. Refuse up front instead; the
// submitter resolves the collision (recall the other request) first.
const colliding = await this.engine.find('sys_approval_request', {
where: { object_name: raw.object_name, record_id: raw.record_id, status: 'pending' },
limit: 1, context: SYSTEM_CTX,
});
if (Array.isArray(colliding) && colliding[0]) {
throw new Error(
`DUPLICATE_REQUEST: another approval request is already pending on ${raw.object_name}/${raw.record_id} — resolve it before resubmitting`,
);
}
const org = raw.organization_id ?? null;
const nodeId: string | null = raw.flow_node_id ?? raw.current_step ?? null;
const runId: string | null = raw.flow_run_id ?? null;
const now = this.clock.now().toISOString();
await this.engine.insert('sys_approval_action', {
id: uid('aact'), request_id: requestId, organization_id: org,
step_name: nodeId, step_index: 0, action: 'resubmit',
actor_id: input.actorId, comment: input.comment ?? null, created_at: now,
}, { context: SYSTEM_CTX });
// The next round only exists if this resume lands — surface `resumed`
// honestly so a stuck run is visible instead of silently swallowed.
let resumed = false;
if (runId && typeof this.automation?.resume === 'function') {
try {
await this.automation.resume(runId, {
branchLabel: APPROVAL_BRANCH_LABELS.resubmit,
output: { resubmitted: true, requestId },
});
resumed = true;
} catch (err: any) {
this.logger?.warn?.('[approvals] resume after resubmit failed', {
request: requestId, run: runId, error: err?.message ?? String(err),
});
}
}
const fresh = await this.getRequest(requestId, context);
return { request: fresh!, runId, resumed };
}
/**
* ADR-0044 guard: the flow's approval node must declare a `revise`
* out-edge before send-back is allowed — the engine's branch-label fallback
* (no matching label ⇒ ALL out-edges) must never be reachable from a user
* action.
*/
private async assertReviseEdge(raw: any, nodeId: string | null): Promise<void> {
const processName = String(raw.process_name ?? '');
const flowName = processName.startsWith('flow:') ? processName.slice('flow:'.length) : undefined;
if (!flowName || !nodeId || typeof this.automation?.getFlow !== 'function') {
throw new Error('VALIDATION_FAILED: send-back requires the owning flow definition (automation engine unavailable)');
}
const flow: any = await this.automation.getFlow(flowName);
const hasRevise = Array.isArray(flow?.edges)
&& flow.edges.some((e: any) => e?.source === nodeId && e?.label === APPROVAL_BRANCH_LABELS.revise);
if (!hasRevise) {
throw new Error(
`VALIDATION_FAILED: approval node '${nodeId}' has no '${APPROVAL_BRANCH_LABELS.revise}' out-edge — ` +
'the flow does not support send-back for revision',
);
}
}
/**
* ADR-0044 guard: a `returned` request is only actionable (resubmit /
* recall) while it is still the newest request on its run — a later round
* or a later node's request supersedes it.
*/
private async assertLatestForRun(raw: any): Promise<void> {
const runId = raw.flow_run_id;
if (!runId) return;
// SortNode's key is `order` (spec/data/query.zod.ts) — `direction` would
// silently default to ascending and return the OLDEST row.
const rows = await this.engine.find('sys_approval_request', {
where: { flow_run_id: runId },
orderBy: [{ field: 'created_at', order: 'desc' }], limit: 1, context: SYSTEM_CTX,
});
const latest: any = Array.isArray(rows) ? rows[0] : null;
if (latest && String(latest.id) !== String(raw.id)) {
throw new Error('INVALID_STATE: a newer approval request supersedes this one');
}