@atolis-hq/wake 0.4.100 → 0.4.102

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.
Files changed (72) hide show
  1. package/dist/src/artifacts/application/operator-instructions-service.js +2 -2
  2. package/dist/src/bootstrap/artifact-mcp.d.ts +1 -0
  3. package/dist/src/bootstrap/artifact-mcp.js +27 -2
  4. package/dist/src/bootstrap/composition-root.js +6 -1
  5. package/dist/src/bootstrap/config/root-schema.d.ts +14 -0
  6. package/dist/src/bootstrap/delegation-authority.d.ts +10 -0
  7. package/dist/src/bootstrap/delegation-authority.js +52 -0
  8. package/dist/src/bootstrap/integration-runtime.js +5 -3
  9. package/dist/src/bootstrap/persistence-composition.js +1 -1
  10. package/dist/src/bootstrap/surface-api-delivery.d.ts +4 -0
  11. package/dist/src/bootstrap/surface-api-delivery.js +35 -0
  12. package/dist/src/bootstrap/surface-api-work-applications.js +2 -0
  13. package/dist/src/bootstrap/version.js +1 -1
  14. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +4 -1
  15. package/dist/src/control-plane/application/activation-scheduler.js +2 -1
  16. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +4 -15
  17. package/dist/src/control-plane/application/advance-once-dispatch.js +15 -26
  18. package/dist/src/control-plane/application/trigger-recovery.js +2 -1
  19. package/dist/src/control-plane/application/trigger-workflow.d.ts +2 -1
  20. package/dist/src/control-plane/application/work-cancellation-policy.d.ts +1 -0
  21. package/dist/src/control-plane/application/work-cancellation-policy.js +6 -1
  22. package/dist/src/control-plane/domain/delivery-capacity.d.ts +9 -0
  23. package/dist/src/control-plane/domain/delivery-capacity.js +40 -0
  24. package/dist/src/control-plane/domain/dispatch-policy.d.ts +1 -0
  25. package/dist/src/control-plane/domain/dispatch-policy.js +6 -0
  26. package/dist/src/control-plane/domain/open-work-policy.d.ts +2 -7
  27. package/dist/src/control-plane/domain/open-work-policy.js +12 -9
  28. package/dist/src/execution/application/repository-assignments.d.ts +1 -1
  29. package/dist/src/execution/application/repository-assignments.js +7 -4
  30. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.d.ts +9 -1
  31. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.d.ts.map +1 -1
  32. package/dist/src/node_modules/@atolis-hq/eventing/dist/runtime/cached-journal-view.js +62 -7
  33. package/dist/src/node_modules/@atolis-hq/eventing/dist/store/event-journal.d.ts +2 -5
  34. package/dist/src/node_modules/@atolis-hq/eventing/dist/store/event-journal.d.ts.map +1 -1
  35. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.d.ts +12 -13
  36. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.d.ts.map +1 -1
  37. package/dist/src/node_modules/@atolis-hq/eventing-filesystem/dist/file-event-journal.js +168 -109
  38. package/dist/src/orchestration/application/deferred-signals.d.ts +4 -2
  39. package/dist/src/orchestration/application/deferred-signals.js +47 -37
  40. package/dist/src/orchestration/application/delegated-work.d.ts +54 -0
  41. package/dist/src/orchestration/application/delegated-work.js +64 -1
  42. package/dist/src/orchestration/application/delegation-commands.d.ts +119 -0
  43. package/dist/src/orchestration/application/delegation-commands.js +99 -0
  44. package/dist/src/orchestration/application/delegation-gate.d.ts +15 -5
  45. package/dist/src/orchestration/application/delegation-gate.js +44 -4
  46. package/dist/src/orchestration/application/orchestration-service.d.ts +150 -2
  47. package/dist/src/orchestration/application/orchestration-service.js +52 -6
  48. package/dist/src/orchestration/contracts/config.d.ts +16 -0
  49. package/dist/src/orchestration/contracts/config.js +10 -0
  50. package/dist/src/orchestration/contracts/delegation-ports.d.ts +10 -1
  51. package/dist/src/orchestration/contracts/delegation.d.ts +34 -0
  52. package/dist/src/orchestration/contracts/delegation.js +8 -0
  53. package/dist/src/orchestration/domain/compiler.js +7 -0
  54. package/dist/src/orchestration/index.d.ts +3 -0
  55. package/dist/src/orchestration/index.js +1 -0
  56. package/dist/src/surfaces/api/contracts/work.d.ts +14 -0
  57. package/dist/src/surfaces/index.d.ts +1 -0
  58. package/dist/src/surfaces/index.js +1 -0
  59. package/dist/src/surfaces/mcp/delegation.d.ts +9 -0
  60. package/dist/src/surfaces/mcp/delegation.js +25 -0
  61. package/dist/src/surfaces/web-assets/assets/index-C5R-aWzH.js +1192 -0
  62. package/dist/src/surfaces/web-assets/index.html +1 -1
  63. package/dist/src/work/application/work-index.d.ts +21 -0
  64. package/dist/src/work/application/work-index.js +73 -0
  65. package/dist/src/work/application/work-service.d.ts +3 -0
  66. package/dist/src/work/application/work-service.js +3 -0
  67. package/dist/src/work/domain/delivery-availability.d.ts +14 -0
  68. package/dist/src/work/domain/delivery-availability.js +20 -0
  69. package/dist/src/work/index.d.ts +2 -0
  70. package/dist/src/work/index.js +2 -0
  71. package/package.json +2 -1
  72. package/dist/src/surfaces/web-assets/assets/index-s9CWgq-s.js +0 -1192
@@ -21,6 +21,7 @@ export class DelegatedWork {
21
21
  claims;
22
22
  definitions;
23
23
  workflows;
24
+ dependencies;
24
25
  ledger;
25
26
  artifacts;
26
27
  repositories;
@@ -31,11 +32,50 @@ export class DelegatedWork {
31
32
  this.claims = claims;
32
33
  this.definitions = definitions;
33
34
  this.workflows = workflows;
35
+ this.dependencies = dependencies;
34
36
  this.ledger = new DelegationLedger(repository);
35
37
  this.artifacts = dependencies.artifacts;
36
38
  this.repositories = dependencies.repositories;
37
39
  this.runHasEnded = dependencies.runHasEnded;
38
40
  }
41
+ async inspect(id) {
42
+ const item = await this.work.get(id);
43
+ const root = item?.delegation?.rootWorkItemId ?? id;
44
+ const events = await this.ledger.events();
45
+ const reservations = reservationsOf(events).filter((entry) => entry.rootWorkItemId === root);
46
+ return Promise.all(reservations.map(async (reservation) => ({
47
+ ...reservation,
48
+ settled: isSettled(events, reservation),
49
+ children: await Promise.all(reservation.children.map(async (child) => ({
50
+ ...child,
51
+ work: await this.work.get(child.workItemId),
52
+ workflow: (await this.repository.load(child.workflowInstanceId)).view,
53
+ }))),
54
+ })));
55
+ }
56
+ async runLimit(id) {
57
+ const item = await this.work.get(id);
58
+ const root = item?.delegation?.rootWorkItemId ?? id;
59
+ const reserved = (await this.ledger.reservations()).find((entry) => entry.rootWorkItemId === root)?.maxConcurrentRuns;
60
+ if (reserved !== undefined)
61
+ return reserved;
62
+ const claim = await this.claims.primaryWorkflowInstanceId(root);
63
+ if (claim === undefined)
64
+ return undefined;
65
+ const view = (await this.repository.load(workflowInstanceId(claim))).view;
66
+ if (view === null)
67
+ return undefined;
68
+ return (await this.definitions.resolve(view)).delegation?.maxConcurrentRuns;
69
+ }
70
+ async repositoryScope(workItemId) {
71
+ const child = (await this.ledger.reservations())
72
+ .flatMap((entry) => entry.children)
73
+ .find((entry) => entry.workItemId === workItemId);
74
+ if (child === undefined)
75
+ return undefined;
76
+ return (child.repositoryResourceIds ??
77
+ (child.repository === undefined ? [] : [child.repository.resourceId]));
78
+ }
39
79
  async repositoryFor(workItemId) {
40
80
  return (await this.ledger.reservations())
41
81
  .flatMap((entry) => entry.children)
@@ -76,6 +116,7 @@ export class DelegatedWork {
76
116
  const events = await this.ledger.events();
77
117
  const all = reservationsOf(rootFacts).filter((entry) => entry.rootWorkItemId === reservation.rootWorkItemId);
78
118
  const rootLimits = {
119
+ ...rootRunLimit(all, limits),
79
120
  maxDepth: all[0]?.maxDepth ?? limits.maxDepth,
80
121
  maxDescendants: all[0]?.maxDescendants ?? limits.maxDescendants,
81
122
  };
@@ -161,6 +202,9 @@ export class DelegatedWork {
161
202
  return capacity;
162
203
  }
163
204
  async parentIdentity(parent) {
205
+ const availability = await this.deliveryAvailability(parent.workItemId);
206
+ if (availability.reason !== undefined)
207
+ throw new Error(availability.reason);
164
208
  const item = await this.work.get(parent.workItemId);
165
209
  if (item === null || item.state !== WorkStatus.Open || item.frozen || item.deleted)
166
210
  throw new Error('Delegation requires open, unfrozen work');
@@ -181,6 +225,9 @@ export class DelegatedWork {
181
225
  };
182
226
  }
183
227
  async assertReservable(caller, existing, reservation, limits) {
228
+ const availability = await this.deliveryAvailability(reservation.parentWorkItemId);
229
+ if (availability.reason !== undefined)
230
+ throw new Error(availability.reason);
184
231
  const current = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
185
232
  if (current.pendingActivation?.activationId !== caller.activationId ||
186
233
  current.status !== WorkflowStatus.Active)
@@ -223,6 +270,8 @@ export class DelegatedWork {
223
270
  async reconcileReservation(artifacts, reservation, context) {
224
271
  if (isSettled(await this.ledger.events(), reservation))
225
272
  return;
273
+ if ((await this.deliveryAvailability(reservation.parentWorkItemId)).reason !== undefined)
274
+ return;
226
275
  const parent = (await this.repository.loadRequired(reservation.parentWorkflowInstanceId)).view;
227
276
  if (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting) {
228
277
  await this.fail(reservation, 'Delegating parent is no longer active or waiting', context);
@@ -337,6 +386,8 @@ export class DelegatedWork {
337
386
  }
338
387
  /** Starts the pinned definition, then records the result only once the child qualifies. */
339
388
  async advanceChild(artifacts, root, reservation, child, context) {
389
+ if ((await this.deliveryAvailability(reservation.parentWorkItemId)).reason !== undefined)
390
+ return;
340
391
  const existing = await this.repository.load(child.workflowInstanceId);
341
392
  if (await this.childWorkTerminated(child.workItemId, existing.view)) {
342
393
  await this.fail(reservation, 'Delegated child work is no longer open', context);
@@ -402,9 +453,17 @@ export class DelegatedWork {
402
453
  endedRun(id) {
403
454
  return this.runHasEnded(id);
404
455
  }
456
+ /** Commit-boundary read: observes appends from other hosts, then answers from memory. */
457
+ async deliveryAvailability(id) {
458
+ return (await this.work.deliverySnapshot()).availability(id);
459
+ }
460
+ async canJoin(reservation) {
461
+ return ((await this.endedRun(reservation.runId)) &&
462
+ (await this.deliveryAvailability(reservation.parentWorkItemId)).reason === undefined);
463
+ }
405
464
  /** Join and continuation commit together, so a duplicate trigger cannot resume the parent twice. */
406
465
  async join(reservation, results, context) {
407
- if (!(await this.endedRun(reservation.runId)))
466
+ if (!(await this.canJoin(reservation)))
408
467
  return;
409
468
  const parentId = reservation.parentWorkflowInstanceId;
410
469
  for (;;) {
@@ -448,6 +507,10 @@ export class DelegatedWork {
448
507
  }
449
508
  }
450
509
  }
510
+ function rootRunLimit(reservations, limits) {
511
+ const maxConcurrentRuns = reservations[0]?.maxConcurrentRuns ?? limits.maxConcurrentRuns;
512
+ return maxConcurrentRuns === undefined ? {} : { maxConcurrentRuns };
513
+ }
451
514
  function assertReplay(prior, caller, assignments) {
452
515
  if (prior.parentWorkflowInstanceId !== caller.workflowInstanceId ||
453
516
  prior.activationId !== caller.activationId ||
@@ -0,0 +1,119 @@
1
+ import type { CommandContext } from '@atolis-hq/eventing';
2
+ import type { WorkService } from '../../work/index.js';
3
+ import type { DelegationAuthority } from '../contracts/delegation-ports.js';
4
+ import { type DelegationCaller, type DelegationSubmission } from '../contracts/delegation.js';
5
+ import type { WorkflowInstanceView } from '../contracts/views.js';
6
+ import type { DelegatedWork } from './delegated-work.js';
7
+ import type { OrchestrationRepository } from './orchestration-repository.js';
8
+ import type { StartWorkflow } from './start-workflow.js';
9
+ import type { WorkflowDefinitionRegistry } from './workflow-definition-registry.js';
10
+ /** Agent inputs describe work; authority comes from the current Run and workflow. */
11
+ export declare class DelegationCommands {
12
+ private readonly repository;
13
+ private readonly work;
14
+ private readonly workflows;
15
+ private readonly definitions;
16
+ private readonly delegated;
17
+ private readonly authority;
18
+ constructor(repository: OrchestrationRepository, work: WorkService, workflows: StartWorkflow, definitions: WorkflowDefinitionRegistry, delegated: DelegatedWork, authority: DelegationAuthority);
19
+ submit(caller: DelegationCaller, input: DelegationSubmission, context: CommandContext): Promise<{
20
+ cohortId: string;
21
+ parentWorkflowInstanceId: import("../index.js").WorkflowInstanceId;
22
+ parentWorkItemId: import("../../work/index.js").WorkItemId;
23
+ rootWorkItemId: import("../../work/index.js").WorkItemId;
24
+ activationId: import("../../activities/index.js").ActivationId;
25
+ runId: string;
26
+ ancestors: import("../../work/index.js").WorkItemId[];
27
+ maxDepth: number;
28
+ maxDescendants: number;
29
+ children: {
30
+ assignmentId: string;
31
+ objective: string;
32
+ criteria: string[];
33
+ workflowName: import("../index.js").WorkflowName;
34
+ workflowFingerprint: string;
35
+ context: {
36
+ workItemId: import("../../work/index.js").WorkItemId;
37
+ revisionId: string;
38
+ }[];
39
+ outputs: ({
40
+ name: string;
41
+ path: string;
42
+ } | {
43
+ name: string;
44
+ kind: "change";
45
+ requireReview?: boolean | undefined;
46
+ requireChecks?: boolean | undefined;
47
+ })[];
48
+ workItemId: import("../../work/index.js").WorkItemId;
49
+ workflowInstanceId: import("../index.js").WorkflowInstanceId;
50
+ grantId: string;
51
+ repositoryResourceIds?: string[] | undefined;
52
+ repository?: {
53
+ resourceId: string;
54
+ sourceRef: string;
55
+ pullRequestBase: string;
56
+ sourceRevision: string;
57
+ } | undefined;
58
+ }[];
59
+ maxConcurrentRuns?: number | undefined;
60
+ }>;
61
+ inspect(caller: DelegationCaller, context: CommandContext): Promise<{
62
+ policy: {
63
+ workflows: string[];
64
+ maxDepth: number;
65
+ maxDescendants: number;
66
+ maxConcurrentRuns: number;
67
+ repositories?: string[] | undefined;
68
+ } | null;
69
+ repositories: string[];
70
+ tree: {
71
+ settled: boolean;
72
+ children: {
73
+ work: import("../../work/index.js").WorkItemView | null;
74
+ workflow: WorkflowInstanceView | null;
75
+ assignmentId: string;
76
+ objective: string;
77
+ criteria: string[];
78
+ workflowName: import("../index.js").WorkflowName;
79
+ workflowFingerprint: string;
80
+ context: {
81
+ workItemId: import("../../work/index.js").WorkItemId;
82
+ revisionId: string;
83
+ }[];
84
+ outputs: ({
85
+ name: string;
86
+ path: string;
87
+ } | {
88
+ name: string;
89
+ kind: "change";
90
+ requireReview?: boolean | undefined;
91
+ requireChecks?: boolean | undefined;
92
+ })[];
93
+ workItemId: import("../../work/index.js").WorkItemId;
94
+ workflowInstanceId: import("../index.js").WorkflowInstanceId;
95
+ grantId: string;
96
+ repositoryResourceIds?: string[] | undefined;
97
+ repository?: {
98
+ resourceId: string;
99
+ sourceRef: string;
100
+ pullRequestBase: string;
101
+ sourceRevision: string;
102
+ } | undefined;
103
+ }[];
104
+ cohortId: string;
105
+ parentWorkflowInstanceId: import("../index.js").WorkflowInstanceId;
106
+ parentWorkItemId: import("../../work/index.js").WorkItemId;
107
+ rootWorkItemId: import("../../work/index.js").WorkItemId;
108
+ activationId: import("../../activities/index.js").ActivationId;
109
+ runId: string;
110
+ ancestors: import("../../work/index.js").WorkItemId[];
111
+ maxDepth: number;
112
+ maxDescendants: number;
113
+ maxConcurrentRuns?: number | undefined;
114
+ }[];
115
+ }>;
116
+ /** Effective repository scope: the parent's inherited scope bounded by parent and root policy. */
117
+ private scopeFor;
118
+ private rootFor;
119
+ }
@@ -0,0 +1,99 @@
1
+ import { delegationSubmissionSchema, } from '../contracts/delegation.js';
2
+ import { WorkflowStatus } from '../contracts/vocabulary.js';
3
+ /** Agent inputs describe work; authority comes from the current Run and workflow. */
4
+ export class DelegationCommands {
5
+ repository;
6
+ work;
7
+ workflows;
8
+ definitions;
9
+ delegated;
10
+ authority;
11
+ constructor(repository, work, workflows, definitions, delegated, authority) {
12
+ this.repository = repository;
13
+ this.work = work;
14
+ this.workflows = workflows;
15
+ this.definitions = definitions;
16
+ this.delegated = delegated;
17
+ this.authority = authority;
18
+ }
19
+ async submit(caller, input, context) {
20
+ const command = delegationSubmissionSchema.parse(input);
21
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
22
+ await this.authority.assertCaller(caller, parent);
23
+ if ((parent.pendingActivation?.activationId ?? parent.delegationFence?.activationId) !==
24
+ caller.activationId ||
25
+ (parent.status !== WorkflowStatus.Active && parent.status !== WorkflowStatus.Waiting))
26
+ throw new Error('Delegation requires the current active activation');
27
+ const availability = (await this.work.deliverySnapshot()).availability(parent.workItemId);
28
+ if (availability.reason !== undefined)
29
+ throw new Error(availability.reason);
30
+ const policy = (await this.workflows.definitionFor(parent)).delegation;
31
+ if (policy === undefined)
32
+ throw new Error('Workflow delegation is disabled');
33
+ const { rootPolicy, permitted } = await this.scopeFor(parent, policy, context);
34
+ const assignments = command.assignments.map((assignment) => {
35
+ if (!policy.workflows.includes(assignment.workflowName) ||
36
+ rootPolicy === undefined ||
37
+ !rootPolicy.workflows.includes(assignment.workflowName))
38
+ throw new Error('Delegation workflow is not allowed');
39
+ // The permitted set only bounds explicit requests; it never selects a checkout target.
40
+ const repositories = assignment.repositoryResourceIds ?? permitted;
41
+ const requested = [
42
+ ...repositories,
43
+ ...(assignment.repository === undefined ? [] : [assignment.repository.resourceId]),
44
+ ];
45
+ if (assignment.repository !== undefined &&
46
+ !repositories.includes(assignment.repository.resourceId))
47
+ throw new Error('Delegation repository authority exceeded');
48
+ if (requested.some((id) => !permitted.includes(id) ||
49
+ (policy.repositories !== undefined && !policy.repositories.includes(id)) ||
50
+ (rootPolicy.repositories !== undefined && !rootPolicy.repositories.includes(id))))
51
+ throw new Error('Delegation repository authority exceeded');
52
+ return {
53
+ ...assignment,
54
+ repositoryResourceIds: repositories,
55
+ workflowFingerprint: this.definitions.currentDefinition(assignment.workflowName)
56
+ .fingerprint,
57
+ };
58
+ });
59
+ return this.delegated.reserve(caller, command.cohortId, assignments, context, {
60
+ maxDepth: policy.maxDepth,
61
+ maxDescendants: policy.maxDescendants,
62
+ maxConcurrentRuns: policy.maxConcurrentRuns,
63
+ });
64
+ }
65
+ async inspect(caller, context) {
66
+ const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
67
+ await this.authority.assertCaller(caller, parent);
68
+ const policy = (await this.workflows.definitionFor(parent)).delegation;
69
+ return {
70
+ policy: policy ?? null,
71
+ // Resource IDs an explicit repository selection may name; empty when none is authorized.
72
+ repositories: policy === undefined ? [] : (await this.scopeFor(parent, policy, context)).permitted,
73
+ tree: await this.delegated.inspect(parent.workItemId),
74
+ };
75
+ }
76
+ /** Effective repository scope: the parent's inherited scope bounded by parent and root policy. */
77
+ async scopeFor(parent, policy, context) {
78
+ const root = await this.rootFor(parent);
79
+ const rootPolicy = (await this.workflows.definitionFor(root)).delegation;
80
+ await this.authority.bindRepositoryScope?.(root, context);
81
+ const rootRepositories = await this.authority.repositories(root);
82
+ const inherited = ((await this.delegated.repositoryScope(parent.workItemId)) ??
83
+ (await this.authority.repositories(parent))).filter((id) => rootRepositories.includes(id));
84
+ const permitted = inherited.filter((id) => (policy.repositories === undefined || policy.repositories.includes(id)) &&
85
+ (rootPolicy?.repositories === undefined || rootPolicy.repositories.includes(id)));
86
+ return { rootPolicy, permitted };
87
+ }
88
+ async rootFor(parent) {
89
+ const item = await this.work.get(parent.workItemId);
90
+ if (item?.delegation === undefined)
91
+ return parent;
92
+ const root = (await this.repository.list()).find(({ view }) => view !== null &&
93
+ view.workItemId === item.delegation?.rootWorkItemId &&
94
+ view.parentWorkflowInstanceId === undefined)?.view;
95
+ if (root == null)
96
+ throw new Error('Delegation root workflow is unavailable');
97
+ return root;
98
+ }
99
+ }
@@ -1,17 +1,27 @@
1
1
  import type { ActivationId } from '../../activities/index.js';
2
+ import type { WorkService } from '../../work/index.js';
2
3
  import type { WorkflowInstanceId } from '../contracts/identifiers.js';
3
4
  import type { WorkflowInstanceView } from '../contracts/views.js';
4
5
  import type { OrchestrationRepository } from './orchestration-repository.js';
5
6
  /** One admission policy for ordinary advancement while a committed cohort owns the parent. */
6
7
  export declare class DelegationGate {
7
8
  private readonly repository;
8
- constructor(repository: OrchestrationRepository);
9
+ private readonly work;
10
+ constructor(repository: OrchestrationRepository, work: WorkService);
11
+ /** Standalone work keeps existing freeze semantics; only delegated trees and fenced parents are held. */
12
+ private heldBy;
13
+ /** Commit-boundary check for one instance; batches use `filterAvailable`. */
14
+ unavailable(view: WorkflowInstanceView): Promise<boolean>;
9
15
  allows(view: WorkflowInstanceView): boolean;
10
16
  fenced(id: WorkflowInstanceId): Promise<boolean>;
17
+ /** The subset of `ids` whose workflow is fenced or held, against one Work synchronisation. */
18
+ fencedAmong(ids: readonly WorkflowInstanceId[]): Promise<ReadonlySet<WorkflowInstanceId>>;
11
19
  run<T>(id: WorkflowInstanceId, operation: () => Promise<T>): Promise<T>;
12
20
  outcome<T>(id: WorkflowInstanceId, activationId: ActivationId, operation: () => Promise<T>, held: () => Promise<T>): Promise<T>;
13
- availableInstances(): Promise<{
14
- readonly sequence: number;
15
- readonly view: WorkflowInstanceView | null;
16
- }[]>;
21
+ /**
22
+ * Admits the items whose workflow may advance, against one synchronisation
23
+ * with Work however many items there are. Nothing is read when none are
24
+ * unfenced, so a quiet tick costs no storage round trip.
25
+ */
26
+ filterAvailable<T>(items: readonly T[], viewOf: (item: T) => WorkflowInstanceView | null): Promise<T[]>;
17
27
  }
@@ -2,15 +2,41 @@ import { DelegationPendingError } from '../contracts/delegation.js';
2
2
  /** One admission policy for ordinary advancement while a committed cohort owns the parent. */
3
3
  export class DelegationGate {
4
4
  repository;
5
- constructor(repository) {
5
+ work;
6
+ constructor(repository, work) {
6
7
  this.repository = repository;
8
+ this.work = work;
9
+ }
10
+ /** Standalone work keeps existing freeze semantics; only delegated trees and fenced parents are held. */
11
+ heldBy(snapshot, view) {
12
+ if (snapshot.invalid(view.workItemId))
13
+ return true;
14
+ if (snapshot.get(view.workItemId)?.delegation === undefined &&
15
+ view.delegationFence === undefined)
16
+ return false;
17
+ return snapshot.availability(view.workItemId).reason !== undefined;
18
+ }
19
+ /** Commit-boundary check for one instance; batches use `filterAvailable`. */
20
+ async unavailable(view) {
21
+ return this.heldBy(await this.work.deliverySnapshot(), view);
7
22
  }
8
23
  allows(view) {
9
24
  return view.delegationFence === undefined;
10
25
  }
11
26
  async fenced(id) {
12
27
  const view = (await this.repository.load(id)).view;
13
- return view !== null && !this.allows(view);
28
+ return view !== null && (!this.allows(view) || (await this.unavailable(view)));
29
+ }
30
+ /** The subset of `ids` whose workflow is fenced or held, against one Work synchronisation. */
31
+ async fencedAmong(ids) {
32
+ const loaded = await Promise.all(ids.map(async (id) => [id, (await this.repository.load(id)).view]));
33
+ const views = loaded.filter((entry) => entry[1] !== null);
34
+ const snapshot = views.some(([, view]) => this.allows(view))
35
+ ? await this.work.deliverySnapshot()
36
+ : undefined;
37
+ return new Set(views
38
+ .filter(([, view]) => !this.allows(view) || this.heldBy(snapshot, view))
39
+ .map(([id]) => id));
14
40
  }
15
41
  async run(id, operation) {
16
42
  if (await this.fenced(id))
@@ -19,13 +45,27 @@ export class DelegationGate {
19
45
  }
20
46
  async outcome(id, activationId, operation, held) {
21
47
  const view = (await this.repository.load(id)).view;
48
+ if (view !== null && (await this.unavailable(view)))
49
+ throw new DelegationPendingError(id);
22
50
  if (view === null || this.allows(view))
23
51
  return operation();
24
52
  if (view.delegationFence?.activationId !== activationId)
25
53
  throw new DelegationPendingError(id);
26
54
  return held();
27
55
  }
28
- async availableInstances() {
29
- return (await this.repository.list()).filter(({ view }) => view !== null && this.allows(view));
56
+ /**
57
+ * Admits the items whose workflow may advance, against one synchronisation
58
+ * with Work however many items there are. Nothing is read when none are
59
+ * unfenced, so a quiet tick costs no storage round trip.
60
+ */
61
+ async filterAvailable(items, viewOf) {
62
+ const unfenced = items.filter((item) => {
63
+ const view = viewOf(item);
64
+ return view !== null && this.allows(view);
65
+ });
66
+ if (unfenced.length === 0)
67
+ return [];
68
+ const snapshot = await this.work.deliverySnapshot();
69
+ return unfenced.filter((item) => !this.heldBy(snapshot, viewOf(item)));
30
70
  }
31
71
  }
@@ -1,9 +1,10 @@
1
- import type { DelegationArtifacts, DelegationRepositories } from '../contracts/delegation-ports.js';
1
+ import type { DelegationArtifacts, DelegationAuthority, DelegationRepositories } from '../contracts/delegation-ports.js';
2
+ import type { DelegationCaller, DelegationSubmission } from '../contracts/delegation.js';
2
3
  import type { ResourceTransitionEvidence } from './resource-transition-evidence.js';
3
4
  import type { CommandContext, EventJournal, ProjectionStore } from '@atolis-hq/eventing';
4
5
  import { type ActivationId, type ActivityOutcome } from '../../activities/index.js';
5
6
  import type { ExecutionFailureCode } from '../../execution/index.js';
6
- import { type WorkItemId, type WorkService } from '../../work/index.js';
7
+ import { type WorkItemId, type WorkItemView, type WorkService } from '../../work/index.js';
7
8
  import type { StartWorkflowInstance } from '../contracts/commands.js';
8
9
  import type { CompiledWorkflow, TransitionTarget } from '../contracts/config.js';
9
10
  import type { ChildWorkflowRequest, OrchestrationSignal, SignalExpectation, SupplementalActivityRequest } from '../contracts/events.js';
@@ -13,6 +14,7 @@ import { AdvanceWorkflow } from './advance-workflow.js';
13
14
  import { type ConversationCommandInput, type ConversationCommandResult } from './conversation-command.js';
14
15
  import type { AgentActivityClassifier } from './pending-activations.js';
15
16
  export declare class OrchestrationService {
17
+ private readonly delegationCommands;
16
18
  private readonly delegationGate;
17
19
  private readonly delegatedWork;
18
20
  private readonly repository;
@@ -30,6 +32,7 @@ export declare class OrchestrationService {
30
32
  private readonly definitions;
31
33
  private readonly work;
32
34
  constructor(journal: EventJournal, work: WorkService, definitions: Readonly<Record<string, CompiledWorkflow>>, projections?: ProjectionStore, isAgentActivity?: AgentActivityClassifier, delegation?: DelegationDependenciesFactory);
35
+ repositoryAuthority(workItemId: string): Promise<string[] | undefined>;
33
36
  repositoryAssignment(workItemId: string): Promise<{
34
37
  resourceId: string;
35
38
  sourceRef: string;
@@ -37,6 +40,150 @@ export declare class OrchestrationService {
37
40
  sourceRevision: string;
38
41
  } | undefined>;
39
42
  isActivationAccepted(id: string, item?: string): Promise<boolean>;
43
+ submitDelegation(caller: DelegationCaller, input: DelegationSubmission, context: CommandContext): Promise<{
44
+ cohortId: string;
45
+ parentWorkflowInstanceId: WorkflowInstanceId;
46
+ parentWorkItemId: WorkItemId;
47
+ rootWorkItemId: WorkItemId;
48
+ activationId: ActivationId;
49
+ runId: string;
50
+ ancestors: WorkItemId[];
51
+ maxDepth: number;
52
+ maxDescendants: number;
53
+ children: {
54
+ assignmentId: string;
55
+ objective: string;
56
+ criteria: string[];
57
+ workflowName: import("../contracts/identifiers.js").WorkflowName;
58
+ workflowFingerprint: string;
59
+ context: {
60
+ workItemId: WorkItemId;
61
+ revisionId: string;
62
+ }[];
63
+ outputs: ({
64
+ name: string;
65
+ path: string;
66
+ } | {
67
+ name: string;
68
+ kind: "change";
69
+ requireReview?: boolean | undefined;
70
+ requireChecks?: boolean | undefined;
71
+ })[];
72
+ workItemId: WorkItemId;
73
+ workflowInstanceId: WorkflowInstanceId;
74
+ grantId: string;
75
+ repositoryResourceIds?: string[] | undefined;
76
+ repository?: {
77
+ resourceId: string;
78
+ sourceRef: string;
79
+ pullRequestBase: string;
80
+ sourceRevision: string;
81
+ } | undefined;
82
+ }[];
83
+ maxConcurrentRuns?: number | undefined;
84
+ }>;
85
+ inspectDelegation(caller: DelegationCaller, context: CommandContext): Promise<{
86
+ policy: {
87
+ workflows: string[];
88
+ maxDepth: number;
89
+ maxDescendants: number;
90
+ maxConcurrentRuns: number;
91
+ repositories?: string[] | undefined;
92
+ } | null;
93
+ repositories: string[];
94
+ tree: {
95
+ settled: boolean;
96
+ children: {
97
+ work: WorkItemView | null;
98
+ workflow: WorkflowInstanceView | null;
99
+ assignmentId: string;
100
+ objective: string;
101
+ criteria: string[];
102
+ workflowName: import("../contracts/identifiers.js").WorkflowName;
103
+ workflowFingerprint: string;
104
+ context: {
105
+ workItemId: WorkItemId;
106
+ revisionId: string;
107
+ }[];
108
+ outputs: ({
109
+ name: string;
110
+ path: string;
111
+ } | {
112
+ name: string;
113
+ kind: "change";
114
+ requireReview?: boolean | undefined;
115
+ requireChecks?: boolean | undefined;
116
+ })[];
117
+ workItemId: WorkItemId;
118
+ workflowInstanceId: WorkflowInstanceId;
119
+ grantId: string;
120
+ repositoryResourceIds?: string[] | undefined;
121
+ repository?: {
122
+ resourceId: string;
123
+ sourceRef: string;
124
+ pullRequestBase: string;
125
+ sourceRevision: string;
126
+ } | undefined;
127
+ }[];
128
+ cohortId: string;
129
+ parentWorkflowInstanceId: WorkflowInstanceId;
130
+ parentWorkItemId: WorkItemId;
131
+ rootWorkItemId: WorkItemId;
132
+ activationId: ActivationId;
133
+ runId: string;
134
+ ancestors: WorkItemId[];
135
+ maxDepth: number;
136
+ maxDescendants: number;
137
+ maxConcurrentRuns?: number | undefined;
138
+ }[];
139
+ }>;
140
+ deliveryTree(id: WorkItemId): Promise<{
141
+ settled: boolean;
142
+ children: {
143
+ work: WorkItemView | null;
144
+ workflow: WorkflowInstanceView | null;
145
+ assignmentId: string;
146
+ objective: string;
147
+ criteria: string[];
148
+ workflowName: import("../contracts/identifiers.js").WorkflowName;
149
+ workflowFingerprint: string;
150
+ context: {
151
+ workItemId: WorkItemId;
152
+ revisionId: string;
153
+ }[];
154
+ outputs: ({
155
+ name: string;
156
+ path: string;
157
+ } | {
158
+ name: string;
159
+ kind: "change";
160
+ requireReview?: boolean | undefined;
161
+ requireChecks?: boolean | undefined;
162
+ })[];
163
+ workItemId: WorkItemId;
164
+ workflowInstanceId: WorkflowInstanceId;
165
+ grantId: string;
166
+ repositoryResourceIds?: string[] | undefined;
167
+ repository?: {
168
+ resourceId: string;
169
+ sourceRef: string;
170
+ pullRequestBase: string;
171
+ sourceRevision: string;
172
+ } | undefined;
173
+ }[];
174
+ cohortId: string;
175
+ parentWorkflowInstanceId: WorkflowInstanceId;
176
+ parentWorkItemId: WorkItemId;
177
+ rootWorkItemId: WorkItemId;
178
+ activationId: ActivationId;
179
+ runId: string;
180
+ ancestors: WorkItemId[];
181
+ maxDepth: number;
182
+ maxDescendants: number;
183
+ maxConcurrentRuns?: number | undefined;
184
+ }[]>;
185
+ deliveryRunLimit(id: WorkItemId): Promise<number | undefined>;
186
+ hasLiveDelegatedWork(id: WorkItemId): Promise<boolean>;
40
187
  joinedDelegationResults(id: WorkflowInstanceId, cohortId: string): Promise<readonly {
41
188
  cohortId: string;
42
189
  childWorkItemId: WorkItemId;
@@ -138,6 +285,7 @@ type DelegationDependenciesFactory = (queries: {
138
285
  isActivationAccepted: (activationId: string, workItemId?: string) => Promise<boolean>;
139
286
  }) => {
140
287
  artifacts: DelegationArtifacts;
288
+ authority?: DelegationAuthority;
141
289
  repositories?: DelegationRepositories;
142
290
  runHasEnded: (runId: string) => Promise<boolean>;
143
291
  };