@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
@@ -7,6 +7,7 @@ import { ApprovalAuthorityKind, conversationCommand, ConversationSurfaceCapabili
7
7
  import { workCorrelationsProjection, } from '../resources/index.js';
8
8
  import { ApiCommandStatus, fromWorkItemKey, presentResource, presentRun, presentWorkflowInstance, presentWorkItem, toWorkItemKey, } from '../surfaces/index.js';
9
9
  import { workItemId, WorkStatus } from '../work/index.js';
10
+ import { delegatedGrantReferences } from './delegated-artifact-context.js';
10
11
  import { primaryExternalRef } from './external-ref.js';
11
12
  import { presentDelivery } from './surface-api-delivery.js';
12
13
  import { presentPrimaryWorkflow } from './surface-api-merge-policy.js';
@@ -259,10 +260,13 @@ async function presentArtifacts(root, id) {
259
260
  const partial = root;
260
261
  if (partial.artifacts === undefined || partial.orchestration?.listAll === undefined)
261
262
  return [];
262
- const accepted = new Set((await partial.orchestration.listAll())
263
- .filter((workflow) => workflow.workItemId === id)
264
- .flatMap((workflow) => workflow.acceptedOutcomes));
265
- return (await partial.artifacts.latestPublished(id, async (activationId) => accepted.has(activationId))).map((artifact) => ({
263
+ const workflows = await partial.orchestration.listAll();
264
+ const accepted = new Set(workflows.filter((workflow) => workflow.workItemId === id).flatMap((w) => w.acceptedOutcomes));
265
+ const own = (await partial.artifacts.latestPublished(id, async (activationId) => accepted.has(activationId))).map((artifact) => presentArtifact(id, artifact));
266
+ return [...own, ...(await contextArtifacts(root, id, workflows))];
267
+ }
268
+ function presentArtifact(owner, artifact) {
269
+ return {
266
270
  revisionId: artifact.revisionId,
267
271
  producer: artifact.producer,
268
272
  path: artifact.path,
@@ -270,7 +274,37 @@ async function presentArtifacts(root, id) {
270
274
  ...(artifact.mediaType === undefined ? {} : { mediaType: artifact.mediaType }),
271
275
  ...(artifact.byteLength === undefined ? {} : { byteLength: artifact.byteLength }),
272
276
  ...(artifact.digest === undefined ? {} : { digest: artifact.digest }),
273
- href: `/api/v1/work-items/${encodeURIComponent(toWorkItemKey(id))}/artifacts/${encodeURIComponent(artifact.revisionId)}`,
277
+ href: `/api/v1/work-items/${encodeURIComponent(toWorkItemKey(owner))}/artifacts/${encodeURIComponent(artifact.revisionId)}`,
278
+ };
279
+ }
280
+ /**
281
+ * Artifacts other work items published into this one's context. Resolution reuses the
282
+ * visibility rules an activation is held to, so the screen cannot list what an agent cannot read.
283
+ */
284
+ async function contextArtifacts(root, id, workflows) {
285
+ const partial = root;
286
+ if (partial.artifactContexts === undefined || partial.work === undefined)
287
+ return [];
288
+ const granted = await delegatedGrantReferences({
289
+ work: partial.work,
290
+ contexts: partial.artifactContexts,
291
+ })(id);
292
+ if (granted.length === 0)
293
+ return [];
294
+ const acceptedAnywhere = new Set(workflows.flatMap((workflow) => workflow.acceptedOutcomes));
295
+ const visible = await partial.artifacts.visibleTo({
296
+ workItemId: id,
297
+ producer: 'artifact-view',
298
+ runId: 'artifact-view',
299
+ activationId: 'artifact-view',
300
+ readableProducers: new Set(),
301
+ sharedReferences: granted,
302
+ }, async (activationId) => acceptedAnywhere.has(activationId));
303
+ return visible
304
+ .filter((artifact) => artifact.access === 'shared')
305
+ .map((artifact) => ({
306
+ ...presentArtifact(artifact.workItemId, artifact),
307
+ source: { workItemKey: toWorkItemKey(artifact.workItemId), relation: 'granted' },
274
308
  }));
275
309
  }
276
310
  function safeMediaType(value) {
@@ -9,9 +9,13 @@ export function createWorkflowDiagramApplications(root, now) {
9
9
  const overlay = workItemKey === undefined
10
10
  ? undefined
11
11
  : await loadOverlay(root, fromWorkItemKey(workItemKey));
12
- const definitions = overlay === undefined
13
- ? root.orchestration.listCurrentDefinitions().map((entry) => entry.definition)
14
- : [await root.orchestration.definitionFor(overlay.primary)];
12
+ // Work that has no primary instance yet (e.g. a delegated child still waiting on its
13
+ // prerequisites) has nothing to overlay; that is not an error.
14
+ const definitions = workItemKey !== undefined && overlay === undefined
15
+ ? []
16
+ : overlay === undefined
17
+ ? root.orchestration.listCurrentDefinitions().map((entry) => entry.definition)
18
+ : [await root.orchestration.definitionFor(overlay.primary)];
15
19
  return {
16
20
  data: {
17
21
  diagrams: definitions.map((definition) => presentWorkflowDiagram(definition, overlay)),
@@ -87,7 +91,7 @@ async function loadOverlay(root, workItemId) {
87
91
  const workflows = await root.orchestration.listForWorkItem(workItemId);
88
92
  const primary = workflows.find((workflow) => workflow.parentWorkflowInstanceId === undefined);
89
93
  if (primary === undefined)
90
- throw new Error('Workflow instance not found');
94
+ return undefined;
91
95
  const runs = (await root.execution.list()).filter((run) => workflows.some((workflow) => workflow.workflowInstanceId === run.workflowInstanceId));
92
96
  return {
93
97
  primary,
@@ -124,6 +124,6 @@ export function resolveWakeVersion(options = {}) {
124
124
  return `g${headHash.slice(0, 7)}`;
125
125
  return '0.1.0-dev';
126
126
  }
127
- export const wakeVersion = "v0.4.109";
127
+ export const wakeVersion = "v0.4.111";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -0,0 +1,14 @@
1
+ import type { CommandContext } from '@atolis-hq/eventing';
2
+ import type { WorkItemId } from '../../work/index.js';
3
+ import type { ConversationService } from './conversation-service.js';
4
+ /**
5
+ * Posts a message authored by Wake on someone's behalf (a delegating parent's assignment or
6
+ * reply) to a work item's conversation, creating the conversation if needed. Both steps are
7
+ * idempotent, so a replayed command records the message once.
8
+ */
9
+ export declare function postControlPlaneEntry(conversations: Pick<ConversationService, 'createForWorkItem' | 'record'>, input: {
10
+ readonly workItemId: WorkItemId;
11
+ readonly entryId: string;
12
+ readonly authorId: string;
13
+ readonly body: string;
14
+ }, context: CommandContext): Promise<void>;
@@ -0,0 +1,16 @@
1
+ import { conversationIdForWorkItem } from '../contracts/identifiers.js';
2
+ import { ConversationOriginKind } from '../contracts/vocabulary.js';
3
+ /**
4
+ * Posts a message authored by Wake on someone's behalf (a delegating parent's assignment or
5
+ * reply) to a work item's conversation, creating the conversation if needed. Both steps are
6
+ * idempotent, so a replayed command records the message once.
7
+ */
8
+ export async function postControlPlaneEntry(conversations, input, context) {
9
+ await conversations.createForWorkItem(input.workItemId, context);
10
+ await conversations.record({
11
+ conversationId: conversationIdForWorkItem(input.workItemId),
12
+ entryId: input.entryId,
13
+ body: input.body,
14
+ origin: { kind: ConversationOriginKind.ControlPlane, actorId: input.authorId },
15
+ }, context);
16
+ }
@@ -1,5 +1,6 @@
1
1
  export * from './application/conversation-projection.js';
2
2
  export * from './application/conversation-service.js';
3
+ export * from './application/control-plane-entry.js';
3
4
  export * from './contracts/commands.js';
4
5
  export * from './contracts/events.js';
5
6
  export * from './contracts/event-factory.js';
@@ -1,5 +1,6 @@
1
1
  export * from './application/conversation-projection.js';
2
2
  export * from './application/conversation-service.js';
3
+ export * from './application/control-plane-entry.js';
3
4
  export * from './contracts/commands.js';
4
5
  export * from './contracts/events.js';
5
6
  export * from './contracts/event-factory.js';
@@ -3,6 +3,7 @@ import { type ConversationService } from '../../conversations/index.js';
3
3
  import { type RunRepository } from '../../execution/index.js';
4
4
  import { selectWorkflowOrchestrationEvent, type OrchestrationService } from '../../orchestration/index.js';
5
5
  import type { ResourceService } from '../../resources/index.js';
6
+ import type { WorkService } from '../../work/index.js';
6
7
  import { type ReplyPublicationConfig } from '../contracts/reply-routing.js';
7
8
  /** Projects terminal agent runs into one durable outbound intent per configured resource. */
8
9
  export declare class AgentRunPublicationReactor {
@@ -13,6 +14,7 @@ export declare class AgentRunPublicationReactor {
13
14
  readonly runs: RunRepository;
14
15
  readonly resources: Pick<ResourceService, 'correlationsForWork' | 'get'>;
15
16
  readonly orchestration: Pick<OrchestrationService, 'listAll'>;
17
+ readonly work?: Pick<WorkService, 'get'> | undefined;
16
18
  readonly conversations?: Pick<ConversationService, 'createForWorkItem' | 'record'>;
17
19
  readonly replies?: ReplyPublicationConfig | undefined;
18
20
  });
@@ -21,6 +23,5 @@ export declare class AgentRunPublicationReactor {
21
23
  private publish;
22
24
  private publishMergeWait;
23
25
  private recordConversationEntry;
24
- private resourceForTarget;
25
26
  private stageForActivation;
26
27
  }
@@ -3,13 +3,14 @@ import { BuiltInActivityName } from '../../activities/index.js';
3
3
  import { conversationIdForWorkItem, ConversationOriginKind, } from '../../conversations/index.js';
4
4
  import { RunStatus } from '../../execution/index.js';
5
5
  import { OrchestrationEventType, OrchestrationStreamKind, selectWorkflowOrchestrationEvent, } from '../../orchestration/index.js';
6
- import { BuiltInResourceKind, ResourceCorrelationRole, resourceStream, } from '../../resources/index.js';
6
+ import { resourceStream } from '../../resources/index.js';
7
7
  import { ReplyTarget } from '../contracts/reply-routing.js';
8
8
  import { createDeliveryIntentEventData } from '../delivery/contracts/event-factory.js';
9
9
  import { DeliveryIntentEventType } from '../delivery/contracts/intents.js';
10
10
  import { defaultReplyPublication, selectReplyTarget, } from '../github/application/reply-target-selector.js';
11
11
  import { projectTerminalAgentRunReport } from './terminal-agent-run-report.js';
12
12
  import { agentRunReportInput, mergeWaitComment } from './agent-run-publication-report.js';
13
+ import { labelledForSharedResource, resourceForTarget } from './agent-run-publication-target.js';
13
14
  /** Projects terminal agent runs into one durable outbound intent per configured resource. */
14
15
  export class AgentRunPublicationReactor {
15
16
  dependencies;
@@ -71,9 +72,10 @@ export class AgentRunPublicationReactor {
71
72
  const target = selectReplyTarget({ stage, outcome: report.outcome }, replies.rules, replies.default);
72
73
  if (target === ReplyTarget.None)
73
74
  return;
74
- const resource = await this.resourceForTarget(workflow.workItemId, target);
75
+ const resource = await resourceForTarget(this.dependencies.resources, workflow.workItemId, target);
75
76
  if (resource === undefined)
76
77
  return;
78
+ const published = await labelledForSharedResource(this.dependencies.work, workflow.workItemId, resource, report);
77
79
  const stream = resourceStream(resource.resourceId);
78
80
  const sequence = (await this.dependencies.journal.readStream(stream)).length;
79
81
  try {
@@ -96,7 +98,7 @@ export class AgentRunPublicationReactor {
96
98
  conversationId: conversationIdForWorkItem(workflow.workItemId),
97
99
  conversationEntryId: `agent-run:${run.runId}`,
98
100
  }),
99
- report,
101
+ report: published,
100
102
  },
101
103
  }),
102
104
  ]);
@@ -118,7 +120,7 @@ export class AgentRunPublicationReactor {
118
120
  const target = selectReplyTarget({ stage: workflow.currentStage, outcome: 'DONE' }, replies.rules, replies.default);
119
121
  if (target === ReplyTarget.None)
120
122
  return;
121
- const resource = await this.resourceForTarget(workflow.workItemId, target);
123
+ const resource = await resourceForTarget(this.dependencies.resources, workflow.workItemId, target);
122
124
  if (resource === undefined)
123
125
  return;
124
126
  const stream = resourceStream(resource.resourceId);
@@ -168,19 +170,6 @@ export class AgentRunPublicationReactor {
168
170
  },
169
171
  }, { ...context, commandId: `agent-run:${runId}` });
170
172
  }
171
- async resourceForTarget(workItemId, target) {
172
- const correlations = await this.dependencies.resources.correlationsForWork(workItemId);
173
- const primary = () => correlations.find((value) => value.role === ResourceCorrelationRole.Primary);
174
- if (target === ReplyTarget.Primary)
175
- return primary();
176
- const kind = target === ReplyTarget.Issue ? BuiltInResourceKind.Issue : BuiltInResourceKind.PullRequest;
177
- for (const correlation of correlations) {
178
- const resource = await this.dependencies.resources.get(correlation.resourceId);
179
- if (resource?.kind === kind)
180
- return correlation;
181
- }
182
- return primary();
183
- }
184
173
  async stageForActivation(workflowInstanceId, activationId) {
185
174
  const events = await this.dependencies.journal.readStream({
186
175
  kind: OrchestrationStreamKind.WorkflowInstance,
@@ -0,0 +1,12 @@
1
+ import { type ResourceCorrelationView, type ResourceService } from '../../resources/index.js';
2
+ import type { WorkService } from '../../work/index.js';
3
+ import { ReplyTarget, type ReplyPublicationConfig } from '../contracts/reply-routing.js';
4
+ /** The resource a work item's reply should be published on, or undefined when it has none. */
5
+ export declare function resourceForTarget(resources: Pick<ResourceService, 'correlationsForWork' | 'get'>, workItemId: Parameters<ResourceService['correlationsForWork']>[0], target: Exclude<ReplyPublicationConfig['default'], typeof ReplyTarget.None>): Promise<ResourceCorrelationView | undefined>;
6
+ /**
7
+ * A delegated child publishes onto its parent's resource, shared with its siblings, so its
8
+ * comment names the work it speaks for. The child's own conversation entry stays unlabelled.
9
+ */
10
+ export declare function labelledForSharedResource<Report extends {
11
+ readonly displayBody: string;
12
+ }>(work: Pick<WorkService, 'get'> | undefined, workItemId: Parameters<ResourceService['correlationsForWork']>[0], resource: ResourceCorrelationView, report: Report): Promise<Report>;
@@ -0,0 +1,31 @@
1
+ import { BuiltInResourceKind, ResourceCorrelationProvenance, ResourceCorrelationRole, } from '../../resources/index.js';
2
+ import { ReplyTarget } from '../contracts/reply-routing.js';
3
+ /** The resource a work item's reply should be published on, or undefined when it has none. */
4
+ export async function resourceForTarget(resources, workItemId, target) {
5
+ const correlations = await resources.correlationsForWork(workItemId);
6
+ const primary = () => correlations.find((value) => value.role === ResourceCorrelationRole.Primary);
7
+ const delegated = () => correlations.find((value) => value.provenance === ResourceCorrelationProvenance.Delegated);
8
+ // A child has no primary resource of its own until it reports a PR; until then it speaks on
9
+ // the resource its parent delegated it from.
10
+ if (target === ReplyTarget.Primary)
11
+ return primary() ?? delegated();
12
+ const kind = target === ReplyTarget.Issue ? BuiltInResourceKind.Issue : BuiltInResourceKind.PullRequest;
13
+ for (const correlation of correlations) {
14
+ const resource = await resources.get(correlation.resourceId);
15
+ if (resource?.kind === kind)
16
+ return correlation;
17
+ }
18
+ return primary();
19
+ }
20
+ /**
21
+ * A delegated child publishes onto its parent's resource, shared with its siblings, so its
22
+ * comment names the work it speaks for. The child's own conversation entry stays unlabelled.
23
+ */
24
+ export async function labelledForSharedResource(work, workItemId, resource, report) {
25
+ if (resource.provenance !== ResourceCorrelationProvenance.Delegated)
26
+ return report;
27
+ const objective = (await work?.get(workItemId))?.objective;
28
+ if (objective === undefined)
29
+ return report;
30
+ return { ...report, displayBody: `**Child work:** ${objective}\n\n${report.displayBody}` };
31
+ }
@@ -89,9 +89,9 @@ export class ArtifactRegistrationReactor {
89
89
  await this.recordUnresolved(provider, record, verified, attempt);
90
90
  return;
91
91
  }
92
- await this.registerVerified(record, verified, workItemId);
92
+ await this.registerVerified(record, verified, workItemId, provider);
93
93
  }
94
- async registerVerified(record, verified, workItemId) {
94
+ async registerVerified(record, verified, workItemId, provider) {
95
95
  const existing = await this.dependencies.resources.findByExternalKey(verified.externalKey);
96
96
  // Re-discover an existing resource so a re-report records its newly verified head.
97
97
  const resource = await this.dependencies.resources.discover({
@@ -107,7 +107,9 @@ export class ArtifactRegistrationReactor {
107
107
  }
108
108
  catch {
109
109
  // Resources records primary conflicts durably; this flow never guesses a secondary relation.
110
+ return;
110
111
  }
112
+ await provider.reobserve?.(verified.externalKey);
111
113
  }
112
114
  async recordUnresolved(provider, record, result, attempt) {
113
115
  const stream = integrationStream(provider.adapter);
@@ -80,6 +80,11 @@ export interface ProviderInstance {
80
80
  readonly workspaceRevision?: string;
81
81
  readonly pullRequestBase?: string;
82
82
  }): Promise<VerifiedArtifact | ArtifactVerificationResult>;
83
+ /**
84
+ * Re-applies the latest journaled observation of a resource Wake has just begun tracking,
85
+ * for observations that arrived before the resource had a WorkItem.
86
+ */
87
+ readonly reobserve?: (externalKey: ExternalResourceKey) => Promise<void>;
83
88
  readonly checkConnectivity?: () => Promise<void>;
84
89
  readonly health?: () => readonly AdapterHealthCheck[];
85
90
  /** Lets the poll runner report whole-poll failures (lock contention, timeouts) as health. */
@@ -67,6 +67,13 @@ export declare class InboundTranslator {
67
67
  private readonly conversations;
68
68
  private readonly conversationCapabilities;
69
69
  private conversationRecordRecoveryPending;
70
+ /**
71
+ * Applies the newest journaled observation of a pull request Wake has just correlated to
72
+ * a WorkItem. A poll that saw the PR earlier was skipped as unowned, and unchanged evidence
73
+ * is not re-emitted, so without this the PR would never gain its WorkItem observation.
74
+ */
75
+ reapplyObservation(externalKey: string): Promise<void>;
76
+ private latestPullRequestObservation;
70
77
  private reconcileOnce;
71
78
  private selectInboundEvent;
72
79
  private isTranslatable;
@@ -88,6 +88,52 @@ export class InboundTranslator {
88
88
  conversations;
89
89
  conversationCapabilities;
90
90
  conversationRecordRecoveryPending;
91
+ /**
92
+ * Applies the newest journaled observation of a pull request Wake has just correlated to
93
+ * a WorkItem. A poll that saw the PR earlier was skipped as unowned, and unchanged evidence
94
+ * is not re-emitted, so without this the PR would never gain its WorkItem observation.
95
+ */
96
+ async reapplyObservation(externalKey) {
97
+ if (this.journal === undefined || this.resources === undefined)
98
+ return;
99
+ const pullRequests = this.pullRequests;
100
+ if (pullRequests === undefined)
101
+ return;
102
+ const latest = await this.latestPullRequestObservation(externalKey);
103
+ if (latest === undefined)
104
+ return;
105
+ const resourceIdValue = await this.lookup?.resourceIdForExternalKey({
106
+ adapter: this.adapter,
107
+ key: externalKey,
108
+ });
109
+ if (resourceIdValue === null || resourceIdValue === undefined)
110
+ return;
111
+ const primary = (await this.resources.correlations(resourceIdValue)).find((correlation) => correlation.role === ResourceCorrelationRole.Primary);
112
+ if (primary === undefined)
113
+ return;
114
+ await this.applyReobservation({
115
+ payload: latest.event.payload,
116
+ context: {
117
+ ...commandContext(latest),
118
+ commandId: `${latest.event.eventId}:reobserve:${resourceIdValue}`,
119
+ },
120
+ pullRequests,
121
+ resourceId: resourceIdValue,
122
+ workItemId: primary.workItemId,
123
+ });
124
+ }
125
+ async latestPullRequestObservation(externalKey) {
126
+ let latest;
127
+ for (const envelope of await this.journal.readStream(integrationStream(this.adapter))) {
128
+ const owned = selectGitHubAdapterEvent(envelope);
129
+ if (owned !== null &&
130
+ isGitHubAdapterEventType(owned, GitHubEventType.WorkObserved) &&
131
+ owned.event.payload.kind === 'pull-request' &&
132
+ owned.event.payload.externalKey === externalKey)
133
+ latest = owned;
134
+ }
135
+ return latest;
136
+ }
91
137
  async reconcileOnce() {
92
138
  if (this.journal === undefined || this.work === undefined || this.resources === undefined) {
93
139
  throw new Error('InboundTranslator services are required to run evidence translation');
@@ -208,6 +208,7 @@ export const gitHubProviderDefinition = {
208
208
  },
209
209
  inbound,
210
210
  reconciler: inbound.reconciler,
211
+ reobserve: (externalKey) => inbound.reapplyObservation(externalKey.key),
211
212
  checkConnectivity: async () => {
212
213
  await client.authenticatedLogin();
213
214
  },
@@ -49,7 +49,12 @@ export function createConversationCommandReactor(orchestration, feedback) {
49
49
  }
50
50
  if (entry.origin.canClarify === false)
51
51
  return;
52
- await routeEscalatedReply(orchestration, feedback, event, workItemId, entry.origin.adapter);
52
+ await orchestration.requestReplyAssessment(workItemId, event.eventId, {
53
+ commandId: `${event.eventId}:reply-assessment`,
54
+ correlationId: correlationId(event.correlationId),
55
+ occurredAt: event.occurredAt,
56
+ actor: { kind: EventActorKind.Integration, id: entry.origin.adapter },
57
+ });
53
58
  for (const workflow of await orchestration.listAll()) {
54
59
  if (workflow.workItemId !== workItemId)
55
60
  continue;
@@ -67,30 +72,6 @@ export function createConversationCommandReactor(orchestration, feedback) {
67
72
  }),
68
73
  };
69
74
  }
70
- /**
71
- * A parent that escalated a delegated child's question to a human has no stage to resume. The
72
- * human's reply is recorded on each asking child's own conversation, where the ordinary reply path
73
- * resumes it; the cohort stays tracked and nothing is settled or joined.
74
- */
75
- async function routeEscalatedReply(orchestration, feedback, event, workItemId, adapter) {
76
- if (feedback === undefined)
77
- return;
78
- const context = {
79
- commandId: `${event.eventId}:escalated-reply`,
80
- correlationId: correlationId(event.correlationId),
81
- occurredAt: event.occurredAt,
82
- actor: { kind: EventActorKind.Integration, id: adapter },
83
- };
84
- for (const childWorkItemId of await orchestration.escalatedReplyTargets(workItemId)) {
85
- const conversation = await feedback.conversations.createForWorkItem(childWorkItemId, context);
86
- await feedback.conversations.record({
87
- conversationId: conversation.conversationId,
88
- entryId: `${event.eventId}:routed:${childWorkItemId}`,
89
- body: event.entry.body,
90
- origin: event.entry.origin,
91
- }, context);
92
- }
93
- }
94
75
  async function applyExternalCommand(orchestration, feedback, event, input, context) {
95
76
  const entryId = context.commandId + ':feedback';
96
77
  const canPublish = input.authorized || input.reviewAuthorized === true;
@@ -3,7 +3,7 @@ import type { DelegationAuthority } from '../contracts/delegation-ports.js';
3
3
  import { type CommandContext } from '@atolis-hq/eventing';
4
4
  import type { ActivityName } from '../../activities/index.js';
5
5
  import { type WorkService } from '../../work/index.js';
6
- import type { DelegationArtifacts, DelegationRepositories } from '../contracts/delegation-ports.js';
6
+ import type { DelegationArtifacts, DelegationMessages, DelegationRepositories, DelegationResources } from '../contracts/delegation-ports.js';
7
7
  import type { DelegatedAssignment, DelegationCaller, DelegationLimits, DelegationReservation, DelegationResult } from '../contracts/delegation.js';
8
8
  import { type WorkflowInstanceId } from '../contracts/identifiers.js';
9
9
  import type { WorkflowInstanceView } from '../contracts/views.js';
@@ -37,8 +37,16 @@ export declare class DelegatedWork {
37
37
  readonly authority?: DelegationAuthority | undefined;
38
38
  readonly supportsAttention?: ((activity: ActivityName) => boolean) | undefined;
39
39
  readonly resumeChild?: DelegationAttentionDependencies['resumeChild'] | undefined;
40
+ readonly messages?: DelegationMessages | undefined;
41
+ readonly resources?: DelegationResources | undefined;
40
42
  });
41
- inspect(id: WorkItemId): Promise<{
43
+ /**
44
+ * `verify` re-checks upstream outputs with the provider. Reads default to recorded facts
45
+ * because that check costs provider round trips on every call.
46
+ */
47
+ inspect(id: WorkItemId, options?: {
48
+ readonly verify?: boolean;
49
+ }): Promise<{
42
50
  settled: boolean;
43
51
  failureReason: string | undefined;
44
52
  children: {
@@ -164,6 +172,8 @@ export declare class DelegatedWork {
164
172
  /** Appends the reservation only if the root stream is unchanged since `events` was read. */
165
173
  private commit;
166
174
  private reconcileReservation;
175
+ /** A human reply on a parent: wake it to pass the answer to the children still waiting. */
176
+ assessReply(parent: WorkflowInstanceView, replyEntryId: string, context: CommandContext): Promise<void>;
167
177
  /** Independent members keep advancing; a blocked member is skipped, never retried blindly. */
168
178
  private advanceMembers;
169
179
  private settleUnusable;
@@ -9,6 +9,7 @@ import { OrchestrationEventType } from '../contracts/events.js';
9
9
  import { orchestrationGroupId, workflowInstanceId, } from '../contracts/identifiers.js';
10
10
  import { DelegationConflictCode, DelegationPrerequisiteCondition, WorkflowStatus, } from '../contracts/vocabulary.js';
11
11
  import { nextOrdinal } from '../domain/decision-events.js';
12
+ import { renderDelegatedBrief } from '../domain/delegated-brief.js';
12
13
  import { assertCriteriaPreserving, originalOf } from '../domain/delivery-replacement.js';
13
14
  import { isSuccessfulWorkflowCompletion } from '../domain/workflow-completion.js';
14
15
  import { DelegationAttention, } from './delegation-attention.js';
@@ -18,6 +19,8 @@ import { assertWithinRootLimits, buildReservation, matchesAssignments, } from '.
18
19
  import { resolvePrerequisites } from './delegation-wait-graph.js';
19
20
  import { readDeliveryFacts } from './delivery-facts-reader.js';
20
21
  const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
22
+ /** How long completed-child outputs may stay invisible before the child is blocked. */
23
+ const OUTPUT_VISIBILITY_GRACE_MS = 120_000;
21
24
  /**
22
25
  * Durable delegation of independent child WorkItems. Reservation is the single commit point;
23
26
  * every later boundary is reconciled idempotently from it, and the parent stays fenced until join.
@@ -50,12 +53,17 @@ export class DelegatedWork {
50
53
  resumeChild: (id, context) => dependencies.resumeChild?.(id, context) ?? Promise.resolve(null),
51
54
  contextWorkItems: (parent) => this.contextWorkItems(parent),
52
55
  canContinue: (reservation) => this.canJoin(reservation),
56
+ messages: dependencies.messages,
53
57
  });
54
58
  this.prerequisites = new DelegationPrerequisites(repository, this.ledger, dependencies.artifacts, dependencies.repositories, work);
55
59
  this.repositories = dependencies.repositories;
56
60
  this.runHasEnded = dependencies.runHasEnded;
57
61
  }
58
- async inspect(id) {
62
+ /**
63
+ * `verify` re-checks upstream outputs with the provider. Reads default to recorded facts
64
+ * because that check costs provider round trips on every call.
65
+ */
66
+ async inspect(id, options = {}) {
59
67
  const item = await this.work.get(id);
60
68
  const root = item?.delegation?.rootWorkItemId ?? id;
61
69
  const events = await this.ledger.events();
@@ -72,7 +80,9 @@ export class DelegatedWork {
72
80
  children: await Promise.all(reservation.children.map(async (child) => ({
73
81
  ...child,
74
82
  work: await this.work.get(child.workItemId),
75
- prerequisiteBlocker: (await read.reason(child.workItemId)) ?? childBlocker(events, child.workItemId),
83
+ prerequisiteBlocker: (options.verify === true
84
+ ? await read.reason(child.workItemId)
85
+ : read.recordedReason(child.workItemId)) ?? childBlocker(events, child.workItemId),
76
86
  consumedInputs: read.inputs(child.workItemId),
77
87
  workflow: read.workflow(child.workflowInstanceId) ?? null,
78
88
  }))),
@@ -364,6 +374,13 @@ export class DelegatedWork {
364
374
  if (await this.childrenQualified(reservation, results, context))
365
375
  await this.join(reservation, results, context);
366
376
  }
377
+ /** A human reply on a parent: wake it to pass the answer to the children still waiting. */
378
+ async assessReply(parent, replyEntryId, context) {
379
+ const reservation = (await this.ledger.reservations()).find((entry) => entry.parentWorkflowInstanceId === parent.workflowInstanceId &&
380
+ entry.cohortId === parent.delegationWait?.cohortId);
381
+ if (reservation !== undefined)
382
+ await this.attention.raiseForReply(reservation, replyEntryId, context);
383
+ }
367
384
  /** Independent members keep advancing; a blocked member is skipped, never retried blindly. */
368
385
  async advanceMembers(artifacts, root, reservation, context) {
369
386
  const read = await this.prerequisites.read();
@@ -510,6 +527,13 @@ export class DelegatedWork {
510
527
  ancestors: reservation.ancestors,
511
528
  },
512
529
  }, childContext);
530
+ await this.dependencies.resources?.relateChild({ childWorkItemId: child.workItemId, parentWorkItemId: reservation.parentWorkItemId }, childContext);
531
+ await this.dependencies.messages?.post({
532
+ workItemId: child.workItemId,
533
+ entryId: `delegation:${child.grantId}`,
534
+ authorId: `delegation:${reservation.parentWorkItemId}`,
535
+ body: renderDelegatedBrief(child),
536
+ }, childContext);
513
537
  await this.claims.claimPrimary(child.workItemId, child.workflowInstanceId, childContext);
514
538
  await artifacts.registerChild({
515
539
  delegationId: child.grantId,
@@ -598,7 +622,10 @@ export class DelegatedWork {
598
622
  });
599
623
  return;
600
624
  }
601
- if (observed.event.causationId !== context.commandId)
625
+ // Provider evidence (e.g. a PR observation) lags the child's completion, so a later
626
+ // pass alone does not prove the output is missing; only a bounded wait does.
627
+ const waitedMs = Date.parse(context.occurredAt) - Date.parse(observed.event.occurredAt);
628
+ if (observed.event.causationId !== context.commandId && waitedMs >= OUTPUT_VISIBILITY_GRACE_MS)
602
629
  await this.failChild(reservation, child, `Child ${child.workItemId} completed without required outputs`, context);
603
630
  }
604
631
  endedRun(id) {
@@ -50,4 +50,6 @@ export declare function reject(code: DelegationAttentionRejection, message: stri
50
50
  * blocker and its kind, and the assignment revision. Returns the earlier identical reply, if any.
51
51
  */
52
52
  export declare function assertReplyAllowed(parent: WorkflowInstanceView, attention: OpenAttention | null, caller: DelegationCaller, reply: DelegationAttentionReply): DelegationAttentionResponse | undefined;
53
+ /** Only the parked cohort wait may start an assessment; a running one coalesces new reasons. */
54
+ export declare function canRequestAssessment(view: WorkflowInstanceView, reservation: DelegationReservation): boolean;
53
55
  export {};
@@ -188,7 +188,17 @@ export function assertReplyAllowed(parent, attention, caller, reply) {
188
188
  if (reply.expectedRevision !== attention.revision)
189
189
  throw reject(DelegationAttentionRejection.StaleRevision, 'The assignment revision changed; inspect before replying');
190
190
  const prior = attention.responses.find((entry) => entry.blockerId === reply.blockerId);
191
- if (prior !== undefined && JSON.stringify(prior.references) !== JSON.stringify(reply.references))
191
+ if (prior !== undefined &&
192
+ (JSON.stringify(prior.references) !== JSON.stringify(reply.references) ||
193
+ prior.message !== reply.message))
192
194
  throw reject(DelegationAttentionRejection.Duplicate, 'This blocker already has a different accepted reply');
195
+ if (reply.references.length === 0 && reply.message === undefined)
196
+ throw reject(DelegationAttentionRejection.EmptyReply, 'A reply needs a message, accepted artifact references, or both');
193
197
  return prior;
194
198
  }
199
+ /** Only the parked cohort wait may start an assessment; a running one coalesces new reasons. */
200
+ export function canRequestAssessment(view, reservation) {
201
+ return (view.status === WorkflowStatus.Waiting &&
202
+ view.delegationWait?.cohortId === reservation.cohortId &&
203
+ view.delegationAttention === undefined);
204
+ }