@atolis-hq/wake 0.4.109 → 0.4.111

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 (70) hide show
  1. package/dist/src/bootstrap/analytics-reports.d.ts +2 -0
  2. package/dist/src/bootstrap/analytics-reports.js +14 -4
  3. package/dist/src/bootstrap/board-projection.d.ts +4 -0
  4. package/dist/src/bootstrap/board-projection.js +33 -19
  5. package/dist/src/bootstrap/composition-root.d.ts +3 -1
  6. package/dist/src/bootstrap/composition-root.js +21 -6
  7. package/dist/src/bootstrap/delegated-artifact-context.d.ts +15 -0
  8. package/dist/src/bootstrap/delegated-artifact-context.js +17 -0
  9. package/dist/src/bootstrap/initialise.js +20 -2
  10. package/dist/src/bootstrap/integration-runtime.js +1 -0
  11. package/dist/src/bootstrap/objective-title-context.d.ts +7 -0
  12. package/dist/src/bootstrap/objective-title-context.js +15 -0
  13. package/dist/src/bootstrap/surface-api-delivery.js +148 -56
  14. package/dist/src/bootstrap/surface-api-work-applications.js +39 -5
  15. package/dist/src/bootstrap/surface-api-workflow-diagrams.js +8 -4
  16. package/dist/src/bootstrap/version.js +1 -1
  17. package/dist/src/conversations/application/control-plane-entry.d.ts +14 -0
  18. package/dist/src/conversations/application/control-plane-entry.js +16 -0
  19. package/dist/src/conversations/index.d.ts +1 -0
  20. package/dist/src/conversations/index.js +1 -0
  21. package/dist/src/integrations/application/agent-run-publication-reactor.d.ts +2 -1
  22. package/dist/src/integrations/application/agent-run-publication-reactor.js +6 -17
  23. package/dist/src/integrations/application/agent-run-publication-target.d.ts +12 -0
  24. package/dist/src/integrations/application/agent-run-publication-target.js +31 -0
  25. package/dist/src/integrations/application/artifact-registration-reactor.js +4 -2
  26. package/dist/src/integrations/contracts/provider.d.ts +5 -0
  27. package/dist/src/integrations/github/application/inbound-translator.d.ts +7 -0
  28. package/dist/src/integrations/github/application/inbound-translator.js +46 -0
  29. package/dist/src/integrations/github/provider.js +1 -0
  30. package/dist/src/orchestration/application/conversation-command-reactor.js +6 -25
  31. package/dist/src/orchestration/application/delegated-work.d.ts +12 -2
  32. package/dist/src/orchestration/application/delegated-work.js +30 -3
  33. package/dist/src/orchestration/application/delegation-attention-state.d.ts +2 -0
  34. package/dist/src/orchestration/application/delegation-attention-state.js +11 -1
  35. package/dist/src/orchestration/application/delegation-attention.d.ts +9 -11
  36. package/dist/src/orchestration/application/delegation-attention.js +42 -23
  37. package/dist/src/orchestration/application/delivery-activity-report.d.ts +13 -0
  38. package/dist/src/orchestration/application/delivery-activity-report.js +127 -0
  39. package/dist/src/orchestration/application/orchestration-service.d.ts +11 -4
  40. package/dist/src/orchestration/application/orchestration-service.js +22 -16
  41. package/dist/src/orchestration/application/prerequisite-readiness.d.ts +8 -0
  42. package/dist/src/orchestration/application/prerequisite-readiness.js +35 -0
  43. package/dist/src/orchestration/application/work-completion-summary.d.ts +10 -1
  44. package/dist/src/orchestration/application/work-completion-summary.js +8 -4
  45. package/dist/src/orchestration/contracts/delegation-ports.d.ts +16 -0
  46. package/dist/src/orchestration/contracts/delegation.d.ts +6 -4
  47. package/dist/src/orchestration/contracts/delegation.js +13 -3
  48. package/dist/src/orchestration/contracts/vocabulary.d.ts +1 -0
  49. package/dist/src/orchestration/contracts/vocabulary.js +1 -0
  50. package/dist/src/orchestration/domain/delegated-brief.d.ts +8 -0
  51. package/dist/src/orchestration/domain/delegated-brief.js +35 -0
  52. package/dist/src/orchestration/index.d.ts +2 -1
  53. package/dist/src/orchestration/index.js +1 -0
  54. package/dist/src/resources/contracts/events.js +1 -0
  55. package/dist/src/resources/contracts/vocabulary.d.ts +2 -0
  56. package/dist/src/resources/contracts/vocabulary.js +2 -0
  57. package/dist/src/surfaces/api/contracts/board.d.ts +4 -0
  58. package/dist/src/surfaces/api/contracts/observability.d.ts +2 -0
  59. package/dist/src/surfaces/api/contracts/work.d.ts +59 -0
  60. package/dist/src/surfaces/mcp/delegation.js +2 -2
  61. package/dist/src/surfaces/web-assets/assets/index-CHhBIiQQ.js +1192 -0
  62. package/dist/src/surfaces/web-assets/assets/index-DKNzCDQl.css +1 -0
  63. package/dist/src/surfaces/web-assets/index.html +2 -2
  64. package/docker/Dockerfile.runtime +10 -1
  65. package/docker/Dockerfile.runtime.packaged +10 -1
  66. package/package.json +1 -1
  67. package/dist/src/orchestration/application/delegation-attention-escalations.d.ts +0 -11
  68. package/dist/src/orchestration/application/delegation-attention-escalations.js +0 -36
  69. package/dist/src/surfaces/web-assets/assets/index-EVgZ9q9N.css +0 -1
  70. package/dist/src/surfaces/web-assets/assets/index-ih1h3dxC.js +0 -1192
@@ -1,6 +1,6 @@
1
1
  import { type CommandContext } from '@atolis-hq/eventing';
2
2
  import { type ActivityName } from '../../activities/index.js';
3
- import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
3
+ import type { DelegationArtifacts, DelegationMessages } from '../contracts/delegation-ports.js';
4
4
  import type { DelegationAttentionBlocker, DelegationAttentionReply, DelegationCaller, DelegationReservation } from '../contracts/delegation.js';
5
5
  import { type WorkflowOrchestrationEvent } from '../contracts/events.js';
6
6
  import type { WorkflowInstanceId } from '../contracts/identifiers.js';
@@ -16,6 +16,8 @@ export interface DelegationAttentionDependencies {
16
16
  readonly resumeChild: (id: WorkflowInstanceId, context: CommandContext) => Promise<WorkflowInstanceView | null>;
17
17
  /** Work items whose artifacts the parent may reference (its own hierarchy). */
18
18
  readonly contextWorkItems: (parent: WorkflowInstanceView) => Promise<ReadonlySet<string>>;
19
+ /** Where a parent's free-text answer is posted: the child's own conversation. */
20
+ readonly messages?: DelegationMessages | undefined;
19
21
  /** Run end and delivery availability gate every attention continuation, like the join. */
20
22
  readonly canContinue: (reservation: DelegationReservation) => Promise<boolean>;
21
23
  }
@@ -33,8 +35,12 @@ export declare class DelegationAttention {
33
35
  * Callers settle fully terminal batches through the ordinary unsuccessful continuation instead.
34
36
  */
35
37
  raise(reservation: DelegationReservation, context: CommandContext): Promise<void>;
36
- /** Only the parked cohort wait may start an assessment; a running one coalesces new reasons. */
37
- private canRequest;
38
+ /**
39
+ * A human replied on the parent while children wait on a clarification. The reply is new
40
+ * information on blockers already assessed, so wake the parent once per reply to decide how
41
+ * to pass it on; replaying the same reply never wakes it twice.
42
+ */
43
+ raiseForReply(reservation: DelegationReservation, replyEntryId: string, context: CommandContext): Promise<void>;
38
44
  /** Returns false when a concurrent append won and the caller must re-read. */
39
45
  private request;
40
46
  /** The open attention request for a parent, with the replies already accepted. */
@@ -47,12 +53,4 @@ export declare class DelegationAttention {
47
53
  /** Ends the assessment and restores the unresolved wait; a pending join then proceeds. */
48
54
  resolve(parentId: WorkflowInstanceId, attentionActivation: string, context: CommandContext, verdict?: AttentionVerdict): Promise<WorkflowInstanceView>;
49
55
  private priorFailures;
50
- /**
51
- * Children whose assignment-context blocker the parent escalated to a human and which are still
52
- * blocked on it. A human reply on the parent is routed to exactly these, so a published question
53
- * always has an answer path that moves the delivery without settling or joining the cohort.
54
- */
55
- escalatedTargets(parent: WorkflowInstanceView): Promise<readonly {
56
- readonly childWorkItemId: string;
57
- }[]>;
58
56
  }
@@ -1,10 +1,9 @@
1
1
  import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
2
  import { activationId } from '../../activities/index.js';
3
3
  import { OrchestrationEventType } from '../contracts/events.js';
4
- import { DelegationAttentionRejection, WorkflowStatus } from '../contracts/vocabulary.js';
4
+ import { DelegationAttentionRejection, DelegationBlockerKind } from '../contracts/vocabulary.js';
5
5
  import { nextOrdinal } from '../domain/decision-events.js';
6
- import { escalatedTargets } from './delegation-attention-escalations.js';
7
- import { assertReplyAllowed, assessedBlockers, attentionKeyOf, blockerOf, contextBlockerId, digest, MaxAssessmentAttempts, reject, resolutionDrafts, } from './delegation-attention-state.js';
6
+ import { assertReplyAllowed, assessedBlockers, attentionKeyOf, blockerOf, canRequestAssessment, contextBlockerId, digest, MaxAssessmentAttempts, reject, resolutionDrafts, } from './delegation-attention-state.js';
8
7
  import { delegationDraft, isSettled } from './delegation-ledger.js';
9
8
  /** Durable cohort/blocker state for the parent attention protocol. */
10
9
  export class DelegationAttention {
@@ -49,17 +48,36 @@ export class DelegationAttention {
49
48
  const attentionKey = attentionKeyOf(reservation, blockers.map((blocker) => blocker.blockerId));
50
49
  for (;;) {
51
50
  const loaded = await this.repository.loadRequired(reservation.parentWorkflowInstanceId);
52
- if (!this.canRequest(loaded.view, reservation))
51
+ if (!canRequestAssessment(loaded.view, reservation))
53
52
  return;
54
53
  if (await this.request(reservation, loaded, { attentionKey, blockers }, context))
55
54
  return;
56
55
  }
57
56
  }
58
- /** Only the parked cohort wait may start an assessment; a running one coalesces new reasons. */
59
- canRequest(view, reservation) {
60
- return (view.status === WorkflowStatus.Waiting &&
61
- view.delegationWait?.cohortId === reservation.cohortId &&
62
- view.delegationAttention === undefined);
57
+ /**
58
+ * A human replied on the parent while children wait on a clarification. The reply is new
59
+ * information on blockers already assessed, so wake the parent once per reply to decide how
60
+ * to pass it on; replaying the same reply never wakes it twice.
61
+ */
62
+ async raiseForReply(reservation, replyEntryId, context) {
63
+ const events = await this.ledger.events();
64
+ if (isSettled(events, reservation))
65
+ return;
66
+ const blockers = (await this.blockers(reservation, events)).filter((blocker) => blocker.kind === DelegationBlockerKind.Context);
67
+ if (blockers.length === 0 || !(await this.dependencies.canContinue(reservation)))
68
+ return;
69
+ const attentionKey = `${attentionKeyOf(reservation, blockers.map((blocker) => blocker.blockerId))}:reply:${digest(replyEntryId)}`;
70
+ const asked = events.some(({ event }) => event.eventType === OrchestrationEventType.DelegationAttentionRequested &&
71
+ event.payload.attentionKey === attentionKey);
72
+ if (asked)
73
+ return;
74
+ for (;;) {
75
+ const loaded = await this.repository.loadRequired(reservation.parentWorkflowInstanceId);
76
+ if (!canRequestAssessment(loaded.view, reservation))
77
+ return;
78
+ if (await this.request(reservation, loaded, { attentionKey, blockers }, context))
79
+ return;
80
+ }
63
81
  }
64
82
  /** Returns false when a concurrent append won and the caller must re-read. */
65
83
  async request(reservation, loaded, input, context) {
@@ -158,12 +176,21 @@ export class DelegationAttention {
158
176
  eventType: OrchestrationEventType.DelegationAttentionResponded,
159
177
  payload: { cohortId: attention.cohortId, attentionKey: attention.attentionKey, ...reply },
160
178
  });
161
- await this.dependencies.artifacts.registerChild({
162
- delegationId: `${child.grantId}:response:${key}`,
163
- parentWorkItemId: reservation.parentWorkItemId,
164
- childWorkItemId: child.workItemId,
165
- childReferences: reply.references,
166
- }, context);
179
+ if (reply.references.length > 0)
180
+ await this.dependencies.artifacts.registerChild({
181
+ delegationId: `${child.grantId}:response:${key}`,
182
+ parentWorkItemId: reservation.parentWorkItemId,
183
+ childWorkItemId: child.workItemId,
184
+ childReferences: reply.references,
185
+ }, context);
186
+ // Posted before the child resumes, so its next turn reads the answer.
187
+ if (reply.message !== undefined)
188
+ await this.dependencies.messages?.post({
189
+ workItemId: child.workItemId,
190
+ entryId: `delegation-reply:${key}`,
191
+ authorId: `delegation:${reservation.parentWorkItemId}`,
192
+ body: reply.message,
193
+ }, context);
167
194
  if (stillBlocked)
168
195
  await this.dependencies.resumeChild(child.workflowInstanceId, {
169
196
  ...context,
@@ -195,12 +222,4 @@ export class DelegationAttention {
195
222
  event.payload.attentionKey === attentionKey &&
196
223
  event.payload.assessmentFailure !== undefined).length;
197
224
  }
198
- /**
199
- * Children whose assignment-context blocker the parent escalated to a human and which are still
200
- * blocked on it. A human reply on the parent is routed to exactly these, so a published question
201
- * always has an answer path that moves the delivery without settling or joining the cohort.
202
- */
203
- escalatedTargets(parent) {
204
- return escalatedTargets(this.repository, this.ledger, parent);
205
- }
206
225
  }
@@ -0,0 +1,13 @@
1
+ import { type EventJournal } from '@atolis-hq/eventing';
2
+ import { type ReportDefinition, type ReportQuery, type TimeSeriesReport } from '../../kernel/index.js';
3
+ import { type CompletionFacts } from './work-completion-summary.js';
4
+ export declare const DeliveryActivityReportId: {
5
+ readonly Activity: "delivery-activity";
6
+ };
7
+ export declare const DeliveryActivityMeasure: {
8
+ readonly RootDeliveries: "root-deliveries";
9
+ readonly AcceptedChildResults: "accepted-child-results";
10
+ readonly CorrectiveActivations: "corrective-activations";
11
+ };
12
+ export declare function createDeliveryActivityReport(journal: EventJournal): ReportDefinition;
13
+ export declare function queryDeliveryActivity(journal: EventJournal, query: ReportQuery, shared?: CompletionFacts): Promise<TimeSeriesReport>;
@@ -0,0 +1,127 @@
1
+ import { scanJournal, yieldScan } from '@atolis-hq/eventing';
2
+ import { ExecutionEventType, selectRunExecutionEvent } from '../../execution/index.js';
3
+ import { defineClosedVocabulary, } from '../../kernel/index.js';
4
+ import { selectOrchestrationEvent } from '../contracts/event-decoder.js';
5
+ import { OrchestrationEventType } from '../contracts/events.js';
6
+ import { readCompletionFacts } from './work-completion-summary.js';
7
+ export const DeliveryActivityReportId = defineClosedVocabulary({
8
+ Activity: 'delivery-activity',
9
+ });
10
+ export const DeliveryActivityMeasure = defineClosedVocabulary({
11
+ RootDeliveries: 'root-deliveries',
12
+ AcceptedChildResults: 'accepted-child-results',
13
+ CorrectiveActivations: 'corrective-activations',
14
+ });
15
+ const descriptor = { id: DeliveryActivityReportId.Activity, title: 'Delivery activity' };
16
+ const series = [
17
+ { id: DeliveryActivityMeasure.RootDeliveries, title: 'Root deliveries', unit: 'work items' },
18
+ {
19
+ id: DeliveryActivityMeasure.AcceptedChildResults,
20
+ title: 'Accepted child results',
21
+ unit: 'results',
22
+ },
23
+ {
24
+ id: DeliveryActivityMeasure.CorrectiveActivations,
25
+ title: 'Corrective activations',
26
+ unit: 'activations',
27
+ },
28
+ ];
29
+ export function createDeliveryActivityReport(journal) {
30
+ return { ...descriptor, query: (query) => queryDeliveryActivity(journal, query) };
31
+ }
32
+ function acceptDeliveryFact(facts, event) {
33
+ const run = selectRunExecutionEvent(event);
34
+ if (run !== null) {
35
+ if (run.event.eventType === ExecutionEventType.RunPreparationStarted ||
36
+ run.event.eventType === ExecutionEventType.RunStarted)
37
+ facts.runs.push({
38
+ activationId: run.event.payload.activationId,
39
+ workflowInstanceId: run.event.payload.workflowInstanceId,
40
+ startedAt: Date.parse(run.event.payload.startedAt),
41
+ });
42
+ return;
43
+ }
44
+ const owned = selectOrchestrationEvent(event);
45
+ if (owned === null)
46
+ return;
47
+ switch (owned.event.eventType) {
48
+ case OrchestrationEventType.DelegationReserved:
49
+ for (const child of owned.event.payload.children)
50
+ if (child.replaces !== undefined)
51
+ facts.correctiveInstances.add(child.workflowInstanceId);
52
+ return;
53
+ case OrchestrationEventType.DeliveryMaintenanceRecorded:
54
+ facts.correctiveActivations.add(owned.event.payload.producer.activationId);
55
+ return;
56
+ case OrchestrationEventType.DelegationResultSelected: {
57
+ const key = `${owned.event.payload.cohortId}/${owned.event.payload.childWorkItemId}`;
58
+ if (!facts.resultTimes.has(key))
59
+ facts.resultTimes.set(key, Date.parse(owned.event.occurredAt));
60
+ return;
61
+ }
62
+ default:
63
+ return;
64
+ }
65
+ }
66
+ /** Retries of one activation are separate Run attempts; the earliest start places the activation. */
67
+ function correctiveStarts(facts) {
68
+ for (const run of facts.runs)
69
+ if (facts.correctiveInstances.has(run.workflowInstanceId))
70
+ facts.correctiveActivations.add(run.activationId);
71
+ const firstStart = new Map();
72
+ for (const run of facts.runs) {
73
+ if (!facts.correctiveActivations.has(run.activationId) || !Number.isFinite(run.startedAt))
74
+ continue;
75
+ const known = firstStart.get(run.activationId);
76
+ if (known === undefined || run.startedAt < known)
77
+ firstStart.set(run.activationId, run.startedAt);
78
+ }
79
+ return firstStart;
80
+ }
81
+ export async function queryDeliveryActivity(journal, query, shared) {
82
+ const roots = shared ?? (await readCompletionFacts(journal, query));
83
+ const facts = {
84
+ resultTimes: new Map(),
85
+ correctiveInstances: new Set(),
86
+ correctiveActivations: new Set(),
87
+ runs: [],
88
+ };
89
+ for await (const event of scanJournal(journal, query.signal))
90
+ acceptDeliveryFact(facts, event);
91
+ const firstStart = correctiveStarts(facts);
92
+ const resultTimes = facts.resultTimes;
93
+ const from = Date.parse(query.window.from), to = Date.parse(query.window.to);
94
+ const first = Math.floor(from / query.window.bucketMs) * query.window.bucketMs;
95
+ const buckets = [];
96
+ for (let start = first; start < to; start += query.window.bucketMs)
97
+ buckets.push({
98
+ from: new Date(start).toISOString(),
99
+ to: new Date(start + query.window.bucketMs).toISOString(),
100
+ values: Object.fromEntries(series.map(({ id }) => [id, 0])),
101
+ });
102
+ const totals = Object.fromEntries(series.map(({ id }) => [id, 0]));
103
+ let processed = 0;
104
+ const add = (measure, at) => {
105
+ if (!(at >= from && at < to))
106
+ return;
107
+ totals[measure]++;
108
+ buckets[Math.floor((at - first) / query.window.bucketMs)].values[measure]++;
109
+ };
110
+ for (const at of roots.completed.values()) {
111
+ if (processed++ % 100 === 0)
112
+ await yieldScan(query.signal);
113
+ add(DeliveryActivityMeasure.RootDeliveries, at);
114
+ }
115
+ for (const at of resultTimes.values())
116
+ add(DeliveryActivityMeasure.AcceptedChildResults, at);
117
+ for (const at of firstStart.values())
118
+ add(DeliveryActivityMeasure.CorrectiveActivations, at);
119
+ const report = {
120
+ report: descriptor,
121
+ window: query.window,
122
+ series,
123
+ totals,
124
+ buckets,
125
+ };
126
+ return report;
127
+ }
@@ -1,4 +1,4 @@
1
- import type { DelegationArtifacts, DelegationAuthority, DelegationRepositories } from '../contracts/delegation-ports.js';
1
+ import type { DelegationArtifacts, DelegationAuthority, DelegationMessages, DelegationRepositories, DelegationResources } from '../contracts/delegation-ports.js';
2
2
  import type { DelegationAttentionReply, DelegationCaller, DelegationSubmission } from '../contracts/delegation.js';
3
3
  import type { DeliveryIntegration } from '../contracts/delivery-ports.js';
4
4
  import type { DeliveryCandidateCommand, DeliveryMaintenanceCommand, DeliveryQaCommand, DeliverySelectionCommand } from '../contracts/delivery.js';
@@ -547,7 +547,9 @@ export declare class OrchestrationService {
547
547
  maxConcurrentRuns?: number | undefined;
548
548
  }[];
549
549
  }>;
550
- deliveryTree(id: WorkItemId): Promise<{
550
+ deliveryTree(id: WorkItemId, options?: {
551
+ readonly verify?: boolean;
552
+ }): Promise<{
551
553
  settled: boolean;
552
554
  failureReason: string | undefined;
553
555
  children: {
@@ -682,8 +684,11 @@ export declare class OrchestrationService {
682
684
  * number of times. The cohort is never settled or cancelled by the assessment itself.
683
685
  */
684
686
  private endAttention;
685
- /** Delegated children still blocked on a question this work item's parent escalated to a human. */
686
- escalatedReplyTargets(workItemId: WorkItemId): Promise<WorkItemId[]>;
687
+ /**
688
+ * A human replied on this work item while delegated children wait on a clarification: wake
689
+ * the delegating stage once, so the parent decides how to pass the reply to each child.
690
+ */
691
+ requestReplyAssessment(workItemId: WorkItemId, replyEntryId: string, context: CommandContext): Promise<void>;
687
692
  /** The open attention request when `activationId` is the attention activation, else null. */
688
693
  openDelegationAttention(id: WorkflowInstanceId, activationId: ActivationId): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
689
694
  respondToDelegationAttention(caller: DelegationCaller, reply: DelegationAttentionReply, context: CommandContext): Promise<import("./delegation-attention-state.js").OpenAttention | null>;
@@ -761,6 +766,8 @@ type DelegationDependenciesFactory = (queries: {
761
766
  artifacts: DelegationArtifacts;
762
767
  authority?: DelegationAuthority;
763
768
  repositories?: DelegationRepositories;
769
+ messages?: DelegationMessages;
770
+ resources?: DelegationResources;
764
771
  integration?: DeliveryIntegration;
765
772
  runHasEnded: (runId: string) => Promise<boolean>;
766
773
  };
@@ -62,14 +62,7 @@ export class OrchestrationService {
62
62
  this.claims = new CoordinationClaims(journal);
63
63
  this.definitions = new WorkflowDefinitionRegistry(journal, projections, definitions);
64
64
  this.startWorkflow = new StartWorkflow(repository, this.claims, work, this.definitions);
65
- this.delegatedWork = new DelegatedWork(repository, work, this.claims, this.definitions, this.startWorkflow, {
66
- authority: dependencies?.authority,
67
- artifacts: dependencies?.artifacts ?? unavailableArtifacts,
68
- repositories: dependencies?.repositories,
69
- runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
70
- supportsAttention: isAgentActivity,
71
- resumeChild: this.resumeClarification,
72
- });
65
+ this.delegatedWork = new DelegatedWork(repository, work, this.claims, this.definitions, this.startWorkflow, delegatedWorkDependencies(dependencies, isAgentActivity, this.resumeClarification));
73
66
  this.delegationCommands = new DelegationCommands(repository, work, this.startWorkflow, this.definitions, this.delegatedWork, dependencies?.authority ?? unavailableDelegationAuthority);
74
67
  this.delivery = new DeliveryCoordinator(repository, deliveryDependencies(dependencies, async (parent) => this.startWorkflow.definitionFor(parent), work));
75
68
  this.advanceWorkflow = new AdvanceWorkflow(repository, this.startWorkflow, (command, context) => this.acceptOutcome(command, context), isAgentActivity);
@@ -155,8 +148,8 @@ export class OrchestrationService {
155
148
  delivery: await this.delivery.inspectFor(caller),
156
149
  };
157
150
  }
158
- deliveryTree(id) {
159
- return this.delegatedWork.inspect(id);
151
+ deliveryTree(id, options) {
152
+ return this.delegatedWork.inspect(id, options);
160
153
  }
161
154
  deliveryRunLimit(id) {
162
155
  return this.delegatedWork.runLimit(id);
@@ -204,14 +197,14 @@ export class OrchestrationService {
204
197
  await this.delegatedWork.reconcile(context);
205
198
  return (await this.repository.loadRequired(command.workflowInstanceId)).view;
206
199
  }
207
- /** Delegated children still blocked on a question this work item's parent escalated to a human. */
208
- async escalatedReplyTargets(workItemId) {
209
- const targets = [];
200
+ /**
201
+ * A human replied on this work item while delegated children wait on a clarification: wake
202
+ * the delegating stage once, so the parent decides how to pass the reply to each child.
203
+ */
204
+ async requestReplyAssessment(workItemId, replyEntryId, context) {
210
205
  for (const parent of await this.advanceWorkflow.listAll())
211
206
  if (parent.workItemId === workItemId)
212
- for (const target of await this.delegatedWork.attention.escalatedTargets(parent))
213
- targets.push(target.childWorkItemId);
214
- return targets;
207
+ await this.delegatedWork.assessReply(parent, replyEntryId, context);
215
208
  }
216
209
  /** The open attention request when `activationId` is the attention activation, else null. */
217
210
  async openDelegationAttention(id, activationId) {
@@ -500,6 +493,19 @@ function isReviewConversationCommand(command) {
500
493
  command === ConversationBuiltInCommand.Accepted ||
501
494
  command === ConversationBuiltInCommand.Changes);
502
495
  }
496
+ /** The delegation dependencies Orchestration hands to DelegatedWork, with safe unavailable stubs. */
497
+ function delegatedWorkDependencies(dependencies, supportsAttention, resumeChild) {
498
+ return {
499
+ authority: dependencies?.authority,
500
+ artifacts: dependencies?.artifacts ?? unavailableArtifacts,
501
+ repositories: dependencies?.repositories,
502
+ runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
503
+ supportsAttention,
504
+ resumeChild,
505
+ messages: dependencies?.messages,
506
+ resources: dependencies?.resources,
507
+ };
508
+ }
503
509
  async function unavailableRunCompletion() {
504
510
  throw new Error('Delegation adapters unavailable');
505
511
  }
@@ -56,6 +56,14 @@ export declare class PrerequisiteReadiness {
56
56
  } | undefined;
57
57
  } | undefined;
58
58
  workflow(id: string): WorkflowInstanceView | undefined;
59
+ /**
60
+ * Why a child is held back, from recorded facts only. Read paths use this because the full
61
+ * evaluation asks the provider to re-verify upstream outputs; drift is detected by
62
+ * reconciliation, which records a block this method then reports.
63
+ */
64
+ recordedReason(id: string, seen?: Set<string>): string | undefined;
65
+ private upstreamOf;
66
+ private recordedUpstreamReason;
59
67
  reason(id: string): Promise<string | undefined>;
60
68
  block(id: string, seen?: Set<string>): Promise<PrerequisiteBlock | undefined>;
61
69
  private evaluate;
@@ -55,6 +55,41 @@ export class PrerequisiteReadiness {
55
55
  workflow(id) {
56
56
  return this.workflows.get(id);
57
57
  }
58
+ /**
59
+ * Why a child is held back, from recorded facts only. Read paths use this because the full
60
+ * evaluation asks the provider to re-verify upstream outputs; drift is detected by
61
+ * reconciliation, which records a block this method then reports.
62
+ */
63
+ recordedReason(id, seen = new Set()) {
64
+ const blocked = this.blockers.get(id);
65
+ if (blocked !== undefined)
66
+ return blocked.reason;
67
+ const child = this.children.get(id);
68
+ // Pinned inputs mean every prerequisite was met when the child was started.
69
+ if (child === undefined || this.receipts.has(id) || seen.has(id))
70
+ return undefined;
71
+ for (const edge of child.prerequisites ?? []) {
72
+ const upstream = this.upstreamOf(child, edge);
73
+ if (upstream === undefined)
74
+ continue;
75
+ return this.recordedUpstreamReason(upstream, edge, new Set([...seen, id]));
76
+ }
77
+ return undefined;
78
+ }
79
+ upstreamOf(child, edge) {
80
+ const owner = this.owners.get(child.workItemId);
81
+ return [...this.children.values()].find((entry) => this.owners.get(entry.workItemId) === owner && entry.assignmentId === edge.assignmentId);
82
+ }
83
+ recordedUpstreamReason(upstream, edge, seen) {
84
+ const inherited = this.recordedReason(upstream.workItemId, seen);
85
+ if (inherited !== undefined)
86
+ return inherited;
87
+ const workflow = this.workflows.get(upstream.workflowInstanceId);
88
+ if (workflow === undefined)
89
+ return `Waiting for upstream ${upstream.assignmentId}`;
90
+ return (workflowReason(workflow, edge) ??
91
+ `Waiting for ${edge.condition} output ${upstream.assignmentId}/${edge.output}`);
92
+ }
58
93
  async reason(id) {
59
94
  return (await this.block(id))?.reason;
60
95
  }
@@ -1,9 +1,18 @@
1
1
  import { type EventJournal } from '@atolis-hq/eventing';
2
2
  import { type ReportDefinition, type ReportQuery, type TimeSeriesReport } from '../../kernel/index.js';
3
- export declare function queryWorkCompletionSummary(journal: EventJournal, query: ReportQuery): Promise<{
3
+ export interface CompletionFacts {
4
+ readonly created: Map<string, number>;
5
+ readonly titles: Map<string, string>;
6
+ readonly instances: Map<string, string>;
7
+ readonly completed: Map<string, number>;
8
+ /** Registered delegated descendants: their completion is a child result, not a delivered root. */
9
+ readonly delegated: Set<string>;
10
+ }
11
+ export declare function queryWorkCompletionSummary(journal: EventJournal, query: ReportQuery, shared?: CompletionFacts): Promise<{
4
12
  workItemsDone: number;
5
13
  medianEndToEndDurationMs: number | null;
6
14
  }>;
15
+ export declare function readCompletionFacts(journal: EventJournal, query: ReportQuery): Promise<CompletionFacts>;
7
16
  export declare const WorkReportId: {
8
17
  readonly Throughput: "work-item-throughput";
9
18
  };
@@ -3,8 +3,8 @@ import { defineClosedVocabulary, median, } from '../../kernel/index.js';
3
3
  import { selectWorkEvent, WorkEventType } from '../../work/index.js';
4
4
  import { selectWorkflowOrchestrationEvent } from '../contracts/event-decoder.js';
5
5
  import { OrchestrationEventType } from '../contracts/events.js';
6
- export async function queryWorkCompletionSummary(journal, query) {
7
- const facts = await readCompletionFacts(journal, query);
6
+ export async function queryWorkCompletionSummary(journal, query, shared) {
7
+ const facts = shared ?? (await readCompletionFacts(journal, query));
8
8
  const from = Date.parse(query.window.from), to = Date.parse(query.window.to);
9
9
  let workItemsDone = 0, processed = 0;
10
10
  const durations = [];
@@ -28,13 +28,16 @@ function acceptFact(facts, event) {
28
28
  if (work?.event.eventType === WorkEventType.ItemCreated) {
29
29
  facts.created.set(work.stream.id, Date.parse(work.event.occurredAt));
30
30
  facts.titles.set(work.stream.id, work.event.payload.objective);
31
+ if (work.event.payload.delegation !== undefined)
32
+ facts.delegated.add(work.stream.id);
31
33
  }
32
34
  const workflow = selectWorkflowOrchestrationEvent(event);
33
35
  if (workflow === null)
34
36
  return;
35
37
  switch (workflow.event.eventType) {
36
38
  case OrchestrationEventType.InstanceStarted:
37
- if (!('parentWorkflowInstanceId' in workflow.event.payload))
39
+ if (!('parentWorkflowInstanceId' in workflow.event.payload) &&
40
+ !facts.delegated.has(workflow.event.payload.workItemId))
38
41
  facts.instances.set(workflow.stream.id, workflow.event.payload.workItemId);
39
42
  return;
40
43
  case OrchestrationEventType.InstanceCompleted: {
@@ -47,12 +50,13 @@ function acceptFact(facts, event) {
47
50
  return;
48
51
  }
49
52
  }
50
- async function readCompletionFacts(journal, query) {
53
+ export async function readCompletionFacts(journal, query) {
51
54
  const facts = {
52
55
  created: new Map(),
53
56
  titles: new Map(),
54
57
  instances: new Map(),
55
58
  completed: new Map(),
59
+ delegated: new Set(),
56
60
  };
57
61
  for await (const event of scanJournal(journal, query.signal))
58
62
  acceptFact(facts, event);
@@ -14,6 +14,22 @@ export interface DelegationArtifacts {
14
14
  }, context: CommandContext): Promise<void>;
15
15
  qualifyingOutputs(child: WorkflowInstanceView, outputs: DelegatedAssignment['outputs']): Promise<DelegationResult['outputs'] | null>;
16
16
  }
17
+ /** Posts Wake-authored messages, on a parent's behalf, to a delegated child's conversation. */
18
+ export interface DelegationMessages {
19
+ post(input: {
20
+ readonly workItemId: DelegationReservation['parentWorkItemId'];
21
+ readonly entryId: string;
22
+ readonly authorId: string;
23
+ readonly body: string;
24
+ }, context: CommandContext): Promise<void>;
25
+ }
26
+ /** Relates a delegated child to its parent's primary resource, e.g. so its runs publish there. */
27
+ export interface DelegationResources {
28
+ relateChild(input: {
29
+ readonly childWorkItemId: DelegationReservation['parentWorkItemId'];
30
+ readonly parentWorkItemId: DelegationReservation['parentWorkItemId'];
31
+ }, context: CommandContext): Promise<void>;
32
+ }
17
33
  export interface DelegationAuthority {
18
34
  assertQaCaller?(caller: DelegationCaller, candidateId: string, selectionRevision: number, revisions: readonly {
19
35
  resourceId: string;
@@ -288,20 +288,22 @@ export declare const delegationAttentionReplySchema: z.ZodObject<{
288
288
  childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
289
289
  blockerId: z.ZodString;
290
290
  expectedRevision: z.ZodNumber;
291
- references: z.ZodArray<z.ZodObject<{
291
+ references: z.ZodDefault<z.ZodArray<z.ZodObject<{
292
292
  workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
293
293
  revisionId: z.ZodString;
294
- }, z.core.$strict>>;
294
+ }, z.core.$strict>>>;
295
+ message: z.ZodOptional<z.ZodString>;
295
296
  }, z.core.$strict>;
296
297
  export type DelegationAttentionReply = z.infer<typeof delegationAttentionReplySchema>;
297
298
  export declare const delegationAttentionResponseSchema: z.ZodObject<{
298
299
  childWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
299
300
  blockerId: z.ZodString;
300
301
  expectedRevision: z.ZodNumber;
301
- references: z.ZodArray<z.ZodObject<{
302
+ references: z.ZodDefault<z.ZodArray<z.ZodObject<{
302
303
  workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
303
304
  revisionId: z.ZodString;
304
- }, z.core.$strict>>;
305
+ }, z.core.$strict>>>;
306
+ message: z.ZodOptional<z.ZodString>;
305
307
  cohortId: z.ZodString;
306
308
  attentionKey: z.ZodString;
307
309
  }, z.core.$strict>;
@@ -33,8 +33,15 @@ export const repositoryAssignmentRequestSchema = z
33
33
  export const delegatedAssignmentSchema = z
34
34
  .object({
35
35
  assignmentId: z.string().min(1),
36
- objective: z.string().trim().min(1),
37
- criteria: z.array(z.string().trim().min(1)).min(1),
36
+ objective: z
37
+ .string()
38
+ .trim()
39
+ .min(1)
40
+ .describe('A one-line summary of the task. It becomes the child work item title, so keep it short and put instructions in criteria or a granted artifact.'),
41
+ criteria: z
42
+ .array(z.string().trim().min(1))
43
+ .min(1)
44
+ .describe('The specific, checkable requirements. They are delivered to the child, with the objective, as the opening message of its conversation.'),
38
45
  workflowName: brandedStringSchema(workflowName),
39
46
  repositoryResourceIds: z.array(z.string().min(1)).optional(),
40
47
  workflowFingerprint: z.string().min(1),
@@ -178,7 +185,10 @@ export const delegationAttentionReplySchema = z
178
185
  childWorkItemId: brandedStringSchema(workItemId),
179
186
  blockerId: z.string().min(1),
180
187
  expectedRevision: z.number().int().positive(),
181
- references: z.array(delegationRevisionReferenceSchema),
188
+ /** Accepted artifact revisions the child may read from now on. */
189
+ references: z.array(delegationRevisionReferenceSchema).default([]),
190
+ /** Free-text answer, posted to the child's conversation. */
191
+ message: z.string().trim().min(1).max(20_000).optional(),
182
192
  })
183
193
  .strict();
184
194
  export const delegationAttentionResponseSchema = delegationAttentionReplySchema
@@ -73,6 +73,7 @@ export declare const DelegationAttentionRejection: {
73
73
  readonly StaleRevision: "stale-revision";
74
74
  readonly NotBlocked: "not-blocked";
75
75
  readonly Duplicate: "duplicate";
76
+ readonly EmptyReply: "empty-reply";
76
77
  };
77
78
  export type DelegationAttentionRejection = ValueOf<typeof DelegationAttentionRejection>;
78
79
  export declare const DelegationConflictCode: {
@@ -65,6 +65,7 @@ export const DelegationAttentionRejection = defineClosedVocabulary({
65
65
  StaleRevision: 'stale-revision',
66
66
  NotBlocked: 'not-blocked',
67
67
  Duplicate: 'duplicate',
68
+ EmptyReply: 'empty-reply',
68
69
  });
69
70
  export const DelegationConflictCode = defineClosedVocabulary({
70
71
  SelfDependency: 'self-dependency',
@@ -0,0 +1,8 @@
1
+ import type { DelegationReservation } from '../contracts/delegation.js';
2
+ type Child = Pick<DelegationReservation['children'][number], 'objective' | 'criteria' | 'outputs' | 'context'>;
3
+ /**
4
+ * The text a delegated child is opened with. The objective stays a one-line summary and
5
+ * the work item's title; this is where the child reads what it was asked to do.
6
+ */
7
+ export declare function renderDelegatedBrief(child: Child): string;
8
+ export {};