@atolis-hq/wake 0.4.95 → 0.4.97

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 (107) hide show
  1. package/dist/src/activities/agent/agent-activity.js +12 -1
  2. package/dist/src/activities/agent/agent-result.d.ts +1 -0
  3. package/dist/src/activities/agent/agent-result.js +1 -0
  4. package/dist/src/activities/contracts/activity.d.ts +7 -0
  5. package/dist/src/artifacts/application/delegation-artifacts.d.ts +29 -0
  6. package/dist/src/artifacts/application/delegation-artifacts.js +37 -0
  7. package/dist/src/artifacts/index.d.ts +1 -0
  8. package/dist/src/artifacts/index.js +1 -0
  9. package/dist/src/bootstrap/composition-root.d.ts +6 -1
  10. package/dist/src/bootstrap/composition-root.js +50 -12
  11. package/dist/src/bootstrap/version.js +1 -1
  12. package/dist/src/control-plane/application/activation-scheduler-ports.d.ts +3 -1
  13. package/dist/src/control-plane/application/activation-scheduler.js +28 -43
  14. package/dist/src/control-plane/application/advance-once-dispatch.d.ts +1 -14
  15. package/dist/src/control-plane/application/advance-once-dispatch.js +14 -26
  16. package/dist/src/control-plane/application/dispatch-resources.d.ts +4 -0
  17. package/dist/src/control-plane/application/dispatch-resources.js +13 -0
  18. package/dist/src/control-plane/application/in-process-scheduler-serialiser.d.ts +1 -0
  19. package/dist/src/control-plane/application/in-process-scheduler-serialiser.js +15 -0
  20. package/dist/src/control-plane/application/runner-quota-outcome.d.ts +13 -0
  21. package/dist/src/control-plane/application/runner-quota-outcome.js +23 -0
  22. package/dist/src/execution/application/execution-service.js +27 -5
  23. package/dist/src/execution/application/execution-validation.d.ts +6 -1
  24. package/dist/src/execution/application/execution-validation.js +29 -11
  25. package/dist/src/execution/application/repository-assignments.d.ts +11 -0
  26. package/dist/src/execution/application/repository-assignments.js +18 -0
  27. package/dist/src/execution/application/run-lifecycle.d.ts +1 -0
  28. package/dist/src/execution/application/run-lifecycle.js +30 -10
  29. package/dist/src/execution/contracts/commands.d.ts +2 -0
  30. package/dist/src/execution/contracts/events.d.ts +20 -0
  31. package/dist/src/execution/contracts/events.js +9 -0
  32. package/dist/src/execution/contracts/repository-assignment.d.ts +17 -0
  33. package/dist/src/execution/contracts/repository-assignment.js +9 -0
  34. package/dist/src/execution/contracts/views.d.ts +5 -0
  35. package/dist/src/execution/contracts/workspace.d.ts +6 -0
  36. package/dist/src/execution/domain/run.js +9 -0
  37. package/dist/src/execution/index.d.ts +3 -0
  38. package/dist/src/execution/index.js +3 -0
  39. package/dist/src/execution/infrastructure/workspace/git-source.d.ts +6 -0
  40. package/dist/src/execution/infrastructure/workspace/git-source.js +35 -0
  41. package/dist/src/execution/infrastructure/workspace/git-workspace.d.ts +5 -0
  42. package/dist/src/execution/infrastructure/workspace/git-workspace.js +50 -3
  43. package/dist/src/integrations/application/artifact-registration-reactor.d.ts +6 -0
  44. package/dist/src/integrations/application/artifact-registration-reactor.js +35 -11
  45. package/dist/src/integrations/application/artifact-source.d.ts +9 -0
  46. package/dist/src/integrations/application/artifact-source.js +12 -0
  47. package/dist/src/integrations/application/delegation-outputs.d.ts +15 -0
  48. package/dist/src/integrations/application/delegation-outputs.js +118 -0
  49. package/dist/src/integrations/contracts/provider.d.ts +3 -0
  50. package/dist/src/integrations/fake/external-source.d.ts +1 -0
  51. package/dist/src/integrations/fake/inbound-translator.js +1 -0
  52. package/dist/src/integrations/fake/provider.d.ts +1 -0
  53. package/dist/src/integrations/fake/provider.js +11 -2
  54. package/dist/src/integrations/github/provider.js +7 -1
  55. package/dist/src/integrations/index.d.ts +1 -0
  56. package/dist/src/integrations/index.js +1 -0
  57. package/dist/src/orchestration/application/accept-signal.d.ts +3 -1
  58. package/dist/src/orchestration/application/accept-signal.js +2 -0
  59. package/dist/src/orchestration/application/advance-workflow.d.ts +0 -1
  60. package/dist/src/orchestration/application/advance-workflow.js +0 -4
  61. package/dist/src/orchestration/application/deferred-signals.d.ts +21 -0
  62. package/dist/src/orchestration/application/deferred-signals.js +119 -0
  63. package/dist/src/orchestration/application/delegated-work.d.ts +60 -0
  64. package/dist/src/orchestration/application/delegated-work.js +456 -0
  65. package/dist/src/orchestration/application/delegation-gate.d.ts +17 -0
  66. package/dist/src/orchestration/application/delegation-gate.js +31 -0
  67. package/dist/src/orchestration/application/delegation-ledger.d.ts +28 -0
  68. package/dist/src/orchestration/application/delegation-ledger.js +79 -0
  69. package/dist/src/orchestration/application/delegation-reservation.d.ts +15 -0
  70. package/dist/src/orchestration/application/delegation-reservation.js +77 -0
  71. package/dist/src/orchestration/application/expire-timed-out-waits.d.ts +1 -1
  72. package/dist/src/orchestration/application/expire-timed-out-waits.js +2 -2
  73. package/dist/src/orchestration/application/orchestration-projection.js +5 -1
  74. package/dist/src/orchestration/application/orchestration-repository.d.ts +5 -0
  75. package/dist/src/orchestration/application/orchestration-repository.js +69 -11
  76. package/dist/src/orchestration/application/orchestration-service.d.ts +43 -3
  77. package/dist/src/orchestration/application/orchestration-service.js +73 -20
  78. package/dist/src/orchestration/application/resource-transition-matching.js +11 -6
  79. package/dist/src/orchestration/application/start-workflow.js +4 -2
  80. package/dist/src/orchestration/application/workflow-definition-registry.d.ts +5 -1
  81. package/dist/src/orchestration/application/workflow-definition-registry.js +16 -3
  82. package/dist/src/orchestration/contracts/commands.d.ts +1 -0
  83. package/dist/src/orchestration/contracts/delegation-ports.d.ts +19 -0
  84. package/dist/src/orchestration/contracts/delegation-ports.js +1 -0
  85. package/dist/src/orchestration/contracts/delegation.d.ts +143 -0
  86. package/dist/src/orchestration/contracts/delegation.js +115 -0
  87. package/dist/src/orchestration/contracts/event-decoder.js +19 -0
  88. package/dist/src/orchestration/contracts/event-factory.js +16 -0
  89. package/dist/src/orchestration/contracts/events.d.ts +39 -0
  90. package/dist/src/orchestration/contracts/events.js +8 -0
  91. package/dist/src/orchestration/contracts/views.d.ts +8 -0
  92. package/dist/src/orchestration/contracts/vocabulary.d.ts +3 -0
  93. package/dist/src/orchestration/contracts/vocabulary.js +1 -0
  94. package/dist/src/orchestration/domain/workflow-completion.d.ts +3 -0
  95. package/dist/src/orchestration/domain/workflow-completion.js +9 -0
  96. package/dist/src/orchestration/domain/workflow-instance-events.d.ts +2 -0
  97. package/dist/src/orchestration/domain/workflow-instance-events.js +37 -0
  98. package/dist/src/orchestration/index.d.ts +2 -0
  99. package/dist/src/orchestration/index.js +1 -0
  100. package/dist/src/work/application/work-projection.js +3 -0
  101. package/dist/src/work/application/work-service.js +16 -0
  102. package/dist/src/work/contracts/commands.d.ts +6 -0
  103. package/dist/src/work/contracts/events.d.ts +2 -1
  104. package/dist/src/work/contracts/events.js +8 -0
  105. package/dist/src/work/contracts/views.d.ts +2 -1
  106. package/dist/src/work/domain/work-item.js +3 -0
  107. package/package.json +1 -1
@@ -2,7 +2,8 @@
2
2
  import { execFile } from 'node:child_process';
3
3
  import { access, mkdir, readdir, readFile, realpath, rename, rm, rmdir, unlink, writeFile, } from 'node:fs/promises';
4
4
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
5
- import { promisify } from 'node:util';
5
+ import { isDeepStrictEqual, promisify } from 'node:util';
6
+ import { repositoryAssignmentSchema, } from '../../contracts/repository-assignment.js';
6
7
  import { isActiveRunStatus, RunStatus, WorkspaceMode } from '../../contracts/vocabulary.js';
7
8
  import { prepareWorkspace } from './prepare-workspace.js';
8
9
  const exec = promisify(execFile);
@@ -54,6 +55,10 @@ export class GitWorkspaceProvider {
54
55
  workspaceId: name,
55
56
  path,
56
57
  mode: request.mode,
58
+ readRevision: () => readCheckoutRevision(path, this.git, signal),
59
+ repositoryResourceId: request.repositoryResource.resourceId,
60
+ checkoutRevision: await readCheckoutRevision(path, this.git, signal),
61
+ ...(request.assignment === undefined ? {} : { assignment: request.assignment }),
57
62
  ...(branch === undefined ? {} : { branch }),
58
63
  release: async () => {
59
64
  if (released)
@@ -82,6 +87,7 @@ export class GitWorkspaceProvider {
82
87
  async prepareCheckout(request, locator, name, path, markerPath) {
83
88
  const { signal } = request;
84
89
  const previousMarker = await readMarker(markerPath);
90
+ assertAssignment(previousMarker, request);
85
91
  if (await exists(join(this.markerRoot, `${name}.lock`), signal))
86
92
  throw new Error('Legacy workspace lock requires recovery before acquisition');
87
93
  let initialRevision = previousMarker?.initialRevision;
@@ -95,6 +101,7 @@ export class GitWorkspaceProvider {
95
101
  workspaceId: name,
96
102
  path,
97
103
  checkoutReady,
104
+ ...(request.assignment === undefined ? {} : { assignment: request.assignment }),
98
105
  ...(initialRevision === undefined ? {} : { initialRevision }),
99
106
  }, signal);
100
107
  const existingWorkspace = await this.reuseCheckout(previousMarker, markerPath, path, request.mode, signal);
@@ -113,7 +120,14 @@ export class GitWorkspaceProvider {
113
120
  initialRevision = await readCheckoutRevision(path, this.git, signal);
114
121
  const branch = request.mode === WorkspaceMode.Branch ? request.workItemId : undefined;
115
122
  if (branch !== undefined) {
116
- await this.git(['-C', path, 'switch', ...(existingWorkspace ? [] : ['--create']), branch], signal);
123
+ initialRevision = await initializeBranch({
124
+ path,
125
+ branch,
126
+ // Only repository assignments pin a new branch; direct workflows keep the clone default.
127
+ revision: request.assignment === undefined ? undefined : request.checkoutRevision,
128
+ initialRevision,
129
+ existing: existingWorkspace,
130
+ }, this.git, signal);
117
131
  }
118
132
  checkoutReady = true;
119
133
  await writeMarker();
@@ -344,7 +358,9 @@ function isOwnershipMarker(value) {
344
358
  hasValidCheckoutState(marker));
345
359
  }
346
360
  function hasValidCheckoutState(marker) {
347
- return ((marker.initialRevision === undefined || typeof marker.initialRevision === 'string') &&
361
+ return ((marker.assignment === undefined ||
362
+ repositoryAssignmentSchema.safeParse(marker.assignment).success) &&
363
+ (marker.initialRevision === undefined || typeof marker.initialRevision === 'string') &&
348
364
  (marker.checkoutReady === undefined || typeof marker.checkoutReady === 'boolean'));
349
365
  }
350
366
  async function isOwnedWorkspace(scope, markerPath, marker, fileSystem) {
@@ -486,3 +502,34 @@ function slug(value) {
486
502
  .replace(/[^a-z0-9]+/g, '-')
487
503
  .replace(/^-|-$/g, '');
488
504
  }
505
+ function assertAssignment(previousMarker, request) {
506
+ // Direct workflows legitimately move from an issue to its PR resource in one clone, so
507
+ // resource identity is only binding for assignment-bound workspaces.
508
+ if (previousMarker !== null &&
509
+ (previousMarker.assignment !== undefined || request.assignment !== undefined) &&
510
+ previousMarker.repositoryResourceId !== request.repositoryResource.resourceId)
511
+ throw new Error('Workspace belongs to a different Repository Resource');
512
+ if (previousMarker?.assignment !== undefined &&
513
+ !isDeepStrictEqual(previousMarker.assignment, request.assignment))
514
+ throw new Error('Workspace repository assignment changed; reconcile the existing branch before retrying');
515
+ }
516
+ async function initializeBranch(input, git, signal) {
517
+ const { path, branch, revision, existing } = input;
518
+ let { initialRevision } = input;
519
+ if (!existing && revision !== undefined) {
520
+ await git(['-C', path, 'fetch', 'origin', revision], signal);
521
+ const fetched = await readGitRevision(path, 'FETCH_HEAD^{commit}', git, signal);
522
+ if (/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(revision) && fetched !== revision)
523
+ throw new Error('Fetched source differs from the pinned checkout revision');
524
+ initialRevision = fetched;
525
+ }
526
+ await git([
527
+ '-C',
528
+ path,
529
+ 'switch',
530
+ ...(existing ? [] : ['--create']),
531
+ branch,
532
+ ...(!existing && revision !== undefined ? [initialRevision] : []),
533
+ ], signal);
534
+ return initialRevision;
535
+ }
@@ -10,6 +10,11 @@ interface ArtifactRegistrationDependencies {
10
10
  readonly maxAmbiguityReconciliationAttempts?: number;
11
11
  readonly runs: {
12
12
  list(activationId?: string): Promise<readonly {
13
+ readonly repositoryAssignment?: {
14
+ readonly resourceId: string;
15
+ readonly pullRequestBase: string;
16
+ } | undefined;
17
+ readonly workspaceRevision?: string | undefined;
13
18
  readonly workspace?: {
14
19
  readonly branch?: string | undefined;
15
20
  };
@@ -24,6 +29,7 @@ export declare class ArtifactRegistrationReactor {
24
29
  private register;
25
30
  reconcileOnce(): Promise<void>;
26
31
  private verifyAndRegister;
32
+ private verificationSource;
27
33
  private registerVerified;
28
34
  private recordUnresolved;
29
35
  private branchFor;
@@ -74,25 +74,49 @@ export class ArtifactRegistrationReactor {
74
74
  const provider = this.dependencies.providers.find((candidate) => candidate.adapter === record.artifact.externalKey.adapter);
75
75
  if (provider === undefined)
76
76
  return;
77
- const verified = await provider.verifyArtifact(record.artifact.kind, record.artifact.externalKey, {
78
- workspaceBranch: branch,
79
- });
77
+ const source = await this.verificationSource(record.activationId, branch);
78
+ if (source === null) {
79
+ await this.recordUnresolved(provider, record, ArtifactVerificationResult.NotFound, attempt);
80
+ return;
81
+ }
82
+ const verified = await provider.verifyArtifact(record.artifact.kind, record.artifact.externalKey, source);
80
83
  if (typeof verified === 'string') {
81
84
  await this.recordUnresolved(provider, record, verified, attempt);
82
85
  return;
83
86
  }
84
87
  await this.registerVerified(record, verified, workItemId);
85
88
  }
89
+ async verificationSource(activationId, branch) {
90
+ const run = (await this.dependencies.runs.list(activationId)).at(-1);
91
+ const assignment = run?.repositoryAssignment;
92
+ const repository = assignment === undefined
93
+ ? undefined
94
+ : await this.dependencies.resources.get(resourceId(assignment.resourceId));
95
+ if (repository === null)
96
+ return null;
97
+ // Direct workflows keep branch-only verification; head and base are exact only for assignments.
98
+ if (assignment === undefined)
99
+ return { workspaceBranch: branch };
100
+ if (repository === undefined || run?.workspaceRevision === undefined)
101
+ return null;
102
+ return {
103
+ workspaceBranch: branch,
104
+ repository: repository.externalKey,
105
+ workspaceRevision: run.workspaceRevision,
106
+ pullRequestBase: assignment.pullRequestBase,
107
+ };
108
+ }
86
109
  async registerVerified(record, verified, workItemId) {
87
110
  const existing = await this.dependencies.resources.findByExternalKey(verified.externalKey);
88
- const resource = existing ??
89
- (await this.dependencies.resources.discover({
90
- resourceId: resourceId(this.dependencies.ids.next(ResourceStreamKind.Resource)),
91
- kind: verified.kind,
92
- externalKey: verified.externalKey,
93
- capabilities: verified.capabilities,
94
- ...(verified.revision === undefined ? {} : { revision: verified.revision }),
95
- }, context(record.causationId, record.correlationId, record.occurredAt)));
111
+ // Re-discover an existing resource so a re-report records its newly verified head.
112
+ const resource = await this.dependencies.resources.discover({
113
+ resourceId: existing?.resourceId ??
114
+ resourceId(this.dependencies.ids.next(ResourceStreamKind.Resource)),
115
+ kind: verified.kind,
116
+ externalKey: verified.externalKey,
117
+ capabilities: verified.capabilities,
118
+ ...(verified.revision === undefined ? {} : { revision: verified.revision }),
119
+ }, context(record.causationId, record.correlationId, record.occurredAt));
96
120
  try {
97
121
  await this.dependencies.resources.correlate(resource.resourceId, workItemId, ResourceCorrelationRole.Primary, context(record.causationId, record.correlationId, record.occurredAt), ResourceCorrelationProvenance.AgentReported);
98
122
  }
@@ -0,0 +1,9 @@
1
+ import type { ExternalResourceKey } from '../../resources/index.js';
2
+ import type { ProviderInstance } from '../contracts/provider.js';
3
+ /** Compare typed provider facts with the recorded producing Run. */
4
+ export declare function matchesArtifactSource(externalKey: ExternalResourceKey, observed: {
5
+ readonly repository: string;
6
+ readonly branch: string;
7
+ readonly revision?: string | undefined;
8
+ readonly base?: string | undefined;
9
+ }, context: Parameters<ProviderInstance['verifyArtifact']>[2]): boolean;
@@ -0,0 +1,12 @@
1
+ /** Compare typed provider facts with the recorded producing Run. */
2
+ export function matchesArtifactSource(externalKey, observed, context) {
3
+ if (observed.branch !== context.workspaceBranch)
4
+ return false;
5
+ if (context.repository !== undefined &&
6
+ (context.repository.adapter !== externalKey.adapter ||
7
+ context.repository.key.toLowerCase() !== observed.repository.toLowerCase()))
8
+ return false;
9
+ if (context.workspaceRevision !== undefined && context.workspaceRevision !== observed.revision)
10
+ return false;
11
+ return context.pullRequestBase === undefined || context.pullRequestBase === observed.base;
12
+ }
@@ -0,0 +1,15 @@
1
+ import { type PullRequestService } from '../../activities/index.js';
2
+ import { type RunView } from '../../execution/index.js';
3
+ import type { DelegationArtifacts } from '../../orchestration/index.js';
4
+ import { type ResourceService } from '../../resources/index.js';
5
+ import type { ProviderInstance } from '../contracts/provider.js';
6
+ interface OutputDependencies {
7
+ readonly artifacts: DelegationArtifacts;
8
+ readonly resources: ResourceService;
9
+ readonly pullRequests: PullRequestService;
10
+ readonly runs: () => Promise<readonly RunView[]>;
11
+ readonly providers: () => Promise<readonly ProviderInstance[]>;
12
+ }
13
+ /** Select exact provider-verified results owned by the producing child. */
14
+ export declare function createDelegationOutputs(input: OutputDependencies): DelegationArtifacts;
15
+ export {};
@@ -0,0 +1,118 @@
1
+ import { z } from 'zod';
2
+ import { reportedArtifactSchema } from '../../activities/index.js';
3
+ import { RunStatus, WorkspaceMode } from '../../execution/index.js';
4
+ import { BuiltInResourceKind, ResourceCorrelationProvenance, ResourceCorrelationRole, resourceId, } from '../../resources/index.js';
5
+ import { ArtifactVerificationResult } from '../contracts/artifact-vocabulary.js';
6
+ const reportsSchema = z.object({ reportedArtifacts: z.array(reportedArtifactSchema) });
7
+ /** Select exact provider-verified results owned by the producing child. */
8
+ export function createDelegationOutputs(input) {
9
+ return {
10
+ ...input.artifacts,
11
+ async qualifyingOutputs(child, outputs) {
12
+ const artifacts = outputs.filter((output) => 'path' in output);
13
+ const references = artifacts.length === 0 ? [] : await input.artifacts.qualifyingOutputs(child, artifacts);
14
+ if (references === null)
15
+ return null;
16
+ for (const output of outputs) {
17
+ if (!('kind' in output))
18
+ continue;
19
+ const change = await qualifyingChange(input, child, output);
20
+ if (change === null)
21
+ return null;
22
+ references.push(change);
23
+ }
24
+ return references;
25
+ },
26
+ };
27
+ }
28
+ function reportedChange(runs, name) {
29
+ return runs
30
+ .flatMap((run) => {
31
+ const data = reportsSchema.safeParse(run.outcome?.data);
32
+ return data.success
33
+ ? data.data.reportedArtifacts
34
+ .filter((entry) => entry.name === name && entry.kind === BuiltInResourceKind.PullRequest)
35
+ .map((report) => ({ run, report }))
36
+ : [];
37
+ })
38
+ .at(-1);
39
+ }
40
+ async function verifiedChange(input, report, source) {
41
+ const { assignment, branch, revision } = source;
42
+ const repository = await input.resources.get(resourceId(assignment.resourceId));
43
+ const provider = (await input.providers()).find((entry) => entry.adapter === report.externalKey.adapter);
44
+ if (repository === null || provider === undefined)
45
+ return null;
46
+ const verified = await provider.verifyArtifact(BuiltInResourceKind.PullRequest, report.externalKey, {
47
+ repository: repository.externalKey,
48
+ workspaceBranch: branch,
49
+ workspaceRevision: revision,
50
+ pullRequestBase: assignment.pullRequestBase,
51
+ });
52
+ if (verified === ArtifactVerificationResult.Ambiguous)
53
+ throw new Error('Child PR verification is ambiguous; reconcile provider evidence before selecting the output');
54
+ if (typeof verified === 'string')
55
+ return null;
56
+ const resource = await input.resources.findByExternalKey(verified.externalKey);
57
+ if (resource === null ||
58
+ resource.kind !== BuiltInResourceKind.PullRequest ||
59
+ verified.revision !== revision ||
60
+ resource.primaryCorrelationConflict !== undefined)
61
+ return null;
62
+ return resource;
63
+ }
64
+ async function qualifyingChange(input, child, output) {
65
+ const runs = (await input.runs()).filter((run) => run.workflowInstanceId === child.workflowInstanceId &&
66
+ run.status === RunStatus.Succeeded &&
67
+ child.acceptedOutcomes.includes(run.activationId));
68
+ const latest = reportedChange(runs, output.name);
69
+ if (latest === undefined)
70
+ return null;
71
+ // Judge the PR against the latest implementation head so a revision run need not
72
+ // repeat the report; the provider must confirm the PR now points there.
73
+ const run = runs.filter((entry) => entry.workspace?.mode === WorkspaceMode.Branch).at(-1);
74
+ const source = run === undefined ? undefined : runSource(run);
75
+ if (run === undefined || source === undefined)
76
+ return null;
77
+ const { assignment, branch, revision } = source;
78
+ const resource = await verifiedChange(input, latest.report, source);
79
+ if (resource === null)
80
+ return null;
81
+ if (!(await hasOutputAuthority(input, child, output, resource.resourceId, revision)))
82
+ return null;
83
+ return {
84
+ name: output.name,
85
+ reference: {
86
+ workItemId: child.workItemId,
87
+ resourceId: resource.resourceId,
88
+ repositoryResourceId: assignment.resourceId,
89
+ revision,
90
+ branch,
91
+ pullRequestBase: assignment.pullRequestBase,
92
+ runId: run.runId,
93
+ },
94
+ };
95
+ }
96
+ async function hasOutputAuthority(input, child, output, id, revision) {
97
+ const owner = await input.resources.primaryCorrelation(id);
98
+ if (owner?.workItemId !== child.workItemId ||
99
+ owner.role !== ResourceCorrelationRole.Primary ||
100
+ owner.provenance !== ResourceCorrelationProvenance.AgentReported)
101
+ return false;
102
+ const authority = await input.pullRequests.decideAuthority(child.workItemId, {
103
+ target: { resourceId: id },
104
+ requireAcceptedReview: output.requireReview ?? true,
105
+ requireChecks: output.requireChecks ?? true,
106
+ });
107
+ if (!authority.allowed || authority.revision !== revision)
108
+ return false;
109
+ return true;
110
+ }
111
+ function runSource(run) {
112
+ const assignment = run.repositoryAssignment;
113
+ const branch = run.workspace?.branch;
114
+ const revision = run.workspaceRevision;
115
+ if (assignment === undefined || branch === undefined || revision === undefined)
116
+ return undefined;
117
+ return { assignment, branch, revision };
118
+ }
@@ -76,6 +76,9 @@ export interface ProviderInstance {
76
76
  };
77
77
  verifyArtifact(kind: ResourceKind, externalKey: ExternalResourceKey, context: {
78
78
  readonly workspaceBranch: string;
79
+ readonly repository?: ExternalResourceKey;
80
+ readonly workspaceRevision?: string;
81
+ readonly pullRequestBase?: string;
79
82
  }): Promise<VerifiedArtifact | ArtifactVerificationResult>;
80
83
  readonly checkConnectivity?: () => Promise<void>;
81
84
  readonly health?: () => readonly AdapterHealthCheck[];
@@ -12,6 +12,7 @@ export interface FakeWorkEvidence {
12
12
  readonly tags?: readonly string[] | undefined;
13
13
  readonly kind?: 'issue' | 'pull-request' | undefined;
14
14
  readonly revision?: string | undefined;
15
+ readonly baseBranch?: string | undefined;
15
16
  readonly baseRevision?: string | undefined;
16
17
  readonly checks?: typeof PullRequestCheckState.Unknown | typeof PullRequestCheckState.Pending | typeof PullRequestCheckState.Passing | typeof PullRequestCheckState.Failing | undefined;
17
18
  readonly acceptedReview?: boolean | undefined;
@@ -14,6 +14,7 @@ const evidenceSchema = z
14
14
  kind: z.enum(['issue', 'pull-request']).optional(),
15
15
  revision: z.string().min(1).optional(),
16
16
  branch: z.string().min(1).optional(),
17
+ baseBranch: z.string().min(1).optional(),
17
18
  baseRevision: z.string().min(1).optional(),
18
19
  checks: z.enum(['unknown', 'pending', 'passing', 'failing']).optional(),
19
20
  acceptedReview: z.boolean().optional(),
@@ -11,6 +11,7 @@ declare const configSchema: z.ZodObject<{
11
11
  }>>;
12
12
  revision: z.ZodOptional<z.ZodString>;
13
13
  branch: z.ZodOptional<z.ZodString>;
14
+ baseBranch: z.ZodOptional<z.ZodString>;
14
15
  baseRevision: z.ZodOptional<z.ZodString>;
15
16
  checks: z.ZodOptional<z.ZodEnum<{
16
17
  unknown: "unknown";
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { PullRequestCheckState, ReviewActorKind } from '../../activities/index.js';
3
- import { BuiltInResourceCapability } from '../../resources/index.js';
3
+ import { BuiltInResourceCapability, BuiltInResourceKind } from '../../resources/index.js';
4
+ import { matchesArtifactSource } from '../application/artifact-source.js';
4
5
  import { ArtifactVerificationResult } from '../contracts/artifact-vocabulary.js';
5
6
  import { DurableFakeDeliveryProvider } from './durable-delivery-provider.js';
6
7
  import { FakeEventType, FakeExternalEventSource } from './external-source.js';
@@ -16,6 +17,7 @@ const configSchema = z
16
17
  kind: z.enum(['issue', 'pull-request']).optional(),
17
18
  revision: z.string().min(1).optional(),
18
19
  branch: z.string().min(1).optional(),
20
+ baseBranch: z.string().min(1).optional(),
19
21
  baseRevision: z.string().min(1).optional(),
20
22
  checks: z
21
23
  .enum([
@@ -69,10 +71,17 @@ export const fakeProviderDefinition = {
69
71
  ...(config.effectsFile === undefined ? {} : { effectsFile: config.effectsFile }),
70
72
  }),
71
73
  verifyArtifact: async (kind, externalKey, context) => {
74
+ if (kind !== BuiltInResourceKind.PullRequest)
75
+ return ArtifactVerificationResult.NotFound;
72
76
  const evidence = config.events.find((event) => event.key === externalKey.key);
73
77
  if (evidence === undefined || (evidence.kind ?? 'issue') !== 'pull-request')
74
78
  return ArtifactVerificationResult.NotFound;
75
- if (kind !== 'pull-request' || evidence.branch !== context.workspaceBranch)
79
+ if (!matchesArtifactSource(externalKey, {
80
+ repository: externalKey.key.split('#')[0],
81
+ branch: evidence.branch ?? '',
82
+ revision: evidence.revision,
83
+ base: evidence.baseBranch,
84
+ }, context))
76
85
  return ArtifactVerificationResult.NotFound;
77
86
  return {
78
87
  kind,
@@ -1,6 +1,7 @@
1
1
  import { BuiltInActivityName, PullRequestState } from '../../activities/index.js';
2
2
  import { ConversationSurfaceCapability } from '../../orchestration/index.js';
3
3
  import { BuiltInResourceCapability, BuiltInResourceKind, ResourceCorrelationRole, resourceId, resourceKind, } from '../../resources/index.js';
4
+ import { matchesArtifactSource } from '../application/artifact-source.js';
4
5
  import { ArtifactVerificationResult } from '../contracts/artifact-vocabulary.js';
5
6
  import { AdapterHealthStatus, } from '../contracts/provider.js';
6
7
  import { InboundTranslator } from './application/inbound-translator.js';
@@ -176,7 +177,12 @@ export const gitHubProviderDefinition = {
176
177
  return ArtifactVerificationResult.NotFound;
177
178
  try {
178
179
  const pullRequest = await client.getPullRequest(parsed.owner, parsed.repo, parsed.number);
179
- if (pullRequest.head.ref !== context.workspaceBranch)
180
+ if (!matchesArtifactSource(externalKey, {
181
+ repository: parsed.owner + '/' + parsed.repo,
182
+ branch: pullRequest.head.ref,
183
+ revision: pullRequest.head.sha,
184
+ base: pullRequest.base.ref,
185
+ }, context))
180
186
  return ArtifactVerificationResult.NotFound;
181
187
  return {
182
188
  kind,
@@ -32,3 +32,4 @@ export * from './fake/external-sink.js';
32
32
  export * from './fake/external-source.js';
33
33
  export * from './fake/provider.js';
34
34
  export * from './application/conversation-command-feedback.js';
35
+ export { createDelegationOutputs } from './application/delegation-outputs.js';
@@ -32,3 +32,4 @@ export * from './fake/external-sink.js';
32
32
  export * from './fake/external-source.js';
33
33
  export * from './fake/provider.js';
34
34
  export * from './application/conversation-command-feedback.js';
35
+ export { createDelegationOutputs } from './application/delegation-outputs.js';
@@ -10,5 +10,7 @@ export declare class AcceptSignal {
10
10
  private readonly work;
11
11
  constructor(repository: OrchestrationRepository, workflows: StartWorkflow, work: WorkService);
12
12
  wait(workflowInstanceId: WorkflowInstanceId, expectation: SignalExpectation, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView>;
13
- execute(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView>;
13
+ execute(workflowInstanceId: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext & {
14
+ readonly expectedSequence?: number;
15
+ }): Promise<import("../index.js").WorkflowInstanceView>;
14
16
  }
@@ -21,6 +21,8 @@ export class AcceptSignal {
21
21
  }
22
22
  async execute(workflowInstanceId, signal, context) {
23
23
  const loaded = await this.repository.loadRequired(workflowInstanceId);
24
+ if (context.expectedSequence !== undefined && context.expectedSequence !== loaded.sequence)
25
+ return loaded.view;
24
26
  const expiry = expireTimedOutAwait(loaded.view, {
25
27
  occurredAt: context.occurredAt,
26
28
  causationId: context.commandId,
@@ -22,7 +22,6 @@ export declare class AdvanceWorkflow {
22
22
  markActivationStarted(id: WorkflowInstanceId, activationId: ActivationId, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
23
23
  blockAwaitingActivation(id: WorkflowInstanceId, activationId: ActivationId, reason: string, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
24
24
  block(id: WorkflowInstanceId, reason: string, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
25
- expireTimedOutWaits(context: CommandContext): Promise<import("../index.js").WorkflowInstanceView[]>;
26
25
  resolveExecutionFailure(id: WorkflowInstanceId, input: ExecutionFailureInput, context: CommandContext): Promise<import("../index.js").WorkflowInstanceView | null>;
27
26
  retryRunnerQuotaFailure(id: WorkflowInstanceId, input: {
28
27
  readonly activationId: ActivationId;
@@ -6,7 +6,6 @@ import { workflowEventData } from '../domain/decision-events.js';
6
6
  import { requestChangesResume as decideChangesResume, requestFreshOperatorRetry as decideFreshOperatorRetry, requestOperatorRetry as decideOperatorRetry, requestSupplementalActivity as decideSupplementalActivity, isNeedsClarificationResumeEligible, requestRunnerQuotaRetry, } from '../domain/interpreter.js';
7
7
  import { isAuthorisedActor } from '../domain/supplemental-policy.js';
8
8
  import { appendWithIntentRecovery } from './durable-append.js';
9
- import { expireTimedOutWaits } from './expire-timed-out-waits.js';
10
9
  import { attributeOperatorRetry } from './operator-retry-attribution.js';
11
10
  import { prioritisePendingActivations, } from './pending-activations.js';
12
11
  import { resolveExecutionFailure, } from './resolve-execution-failure.js';
@@ -94,9 +93,6 @@ export class AdvanceWorkflow {
94
93
  await this.repository.append(id, loaded.sequence, [event]);
95
94
  return (await this.repository.load(id)).view;
96
95
  }
97
- async expireTimedOutWaits(context) {
98
- return expireTimedOutWaits(this.repository, context);
99
- }
100
96
  resolveExecutionFailure(id, input, context) {
101
97
  return resolveExecutionFailure(this.repository, this.acceptOutcome, id, input, context);
102
98
  }
@@ -0,0 +1,21 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import type { TransitionTarget } from '../contracts/config.js';
3
+ import { type OrchestrationSignal } from '../contracts/events.js';
4
+ import type { WorkflowInstanceId } from '../contracts/identifiers.js';
5
+ import type { WorkflowInstanceView } from '../contracts/views.js';
6
+ import type { OrchestrationRepository } from './orchestration-repository.js';
7
+ /** Retains authority-bearing inputs while delegation owns advancement; ordinary wait validation replays them. */
8
+ export declare class DeferredSignals {
9
+ private readonly repository;
10
+ private readonly deliver;
11
+ private readonly transition;
12
+ private readonly fenced;
13
+ private readonly ledger;
14
+ constructor(repository: OrchestrationRepository, deliver: (id: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext) => Promise<WorkflowInstanceView>, transition: (id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext) => Promise<WorkflowInstanceView | null>, fenced: (id: WorkflowInstanceId) => Promise<boolean>);
15
+ accept(id: WorkflowInstanceId, signal: OrchestrationSignal, context: CommandContext): Promise<WorkflowInstanceView>;
16
+ applyTransition(id: WorkflowInstanceId, target: TransitionTarget, evidenceId: string, context: CommandContext): Promise<WorkflowInstanceView | null>;
17
+ private record;
18
+ private hasDeferred;
19
+ reconcile(context: CommandContext): Promise<void>;
20
+ reconcileWorkflow(id: WorkflowInstanceId, context: CommandContext): Promise<WorkflowInstanceView>;
21
+ }
@@ -0,0 +1,119 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { DelegationPendingError } from '../contracts/delegation.js';
3
+ import { signalSchema } from '../contracts/event-decoder.js';
4
+ import { OrchestrationEventType, ResourceTransitionSignal, } from '../contracts/events.js';
5
+ import { DelegationLedger } from './delegation-ledger.js';
6
+ /** Retains authority-bearing inputs while delegation owns advancement; ordinary wait validation replays them. */
7
+ export class DeferredSignals {
8
+ repository;
9
+ deliver;
10
+ transition;
11
+ fenced;
12
+ ledger;
13
+ constructor(repository, deliver, transition, fenced) {
14
+ this.repository = repository;
15
+ this.deliver = deliver;
16
+ this.transition = transition;
17
+ this.fenced = fenced;
18
+ this.ledger = new DelegationLedger(repository);
19
+ }
20
+ async accept(id, signal, context) {
21
+ const scope = (await this.repository.loadRequired(id)).view;
22
+ try {
23
+ return await this.deliver(id, signal, context);
24
+ }
25
+ catch (error) {
26
+ if (!(error instanceof DelegationPendingError))
27
+ throw error;
28
+ return this.record(id, signal, context, scope);
29
+ }
30
+ }
31
+ async applyTransition(id, target, evidenceId, context) {
32
+ const scope = (await this.repository.loadRequired(id)).view;
33
+ try {
34
+ return await this.transition(id, target, evidenceId, context);
35
+ }
36
+ catch (error) {
37
+ if (!(error instanceof DelegationPendingError))
38
+ throw error;
39
+ return this.record(id, {
40
+ kind: scope.waitingFor?.signalKind ?? ResourceTransitionSignal,
41
+ actorId: 'resource-transition',
42
+ actorDecision: { authorized: true, evidenceId },
43
+ providerEventId: evidenceId,
44
+ }, context, scope, target);
45
+ }
46
+ }
47
+ async record(id, signal, context, view, target) {
48
+ const parsed = signalSchema.parse(signal);
49
+ await this.ledger.appendOnce(id, context, `defer:${signal.providerEventId}`, {
50
+ eventType: OrchestrationEventType.SignalDeferred,
51
+ payload: {
52
+ stage: view.currentStage,
53
+ ...(view.waitingFor?.intentEventId === undefined
54
+ ? {}
55
+ : { intentEventId: view.waitingFor.intentEventId }),
56
+ ...(view.waitingFor?.resourceId === undefined
57
+ ? {}
58
+ : { resourceId: view.waitingFor.resourceId }),
59
+ ...(view.waitingFor?.revision === undefined ? {} : { revision: view.waitingFor.revision }),
60
+ signal: parsed,
61
+ ...(target === undefined ? {} : { target }),
62
+ },
63
+ });
64
+ return view;
65
+ }
66
+ async hasDeferred() {
67
+ return (await this.repository.events()).some((entry) => entry.event.eventType === OrchestrationEventType.SignalDeferred);
68
+ }
69
+ async reconcile(context) {
70
+ if (!(await this.hasDeferred()))
71
+ return;
72
+ for (const loaded of await this.repository.list()) {
73
+ if (loaded.view !== null)
74
+ await this.reconcileWorkflow(loaded.view.workflowInstanceId, context);
75
+ }
76
+ }
77
+ async reconcileWorkflow(id, context) {
78
+ if ((await this.hasDeferred()) && !(await this.fenced(id))) {
79
+ const { events } = await this.repository.history(id);
80
+ for (const event of events) {
81
+ if (event?.event.eventType !== OrchestrationEventType.SignalDeferred)
82
+ continue;
83
+ const deferred = event.event.payload;
84
+ const loaded = await this.repository.loadRequired(id);
85
+ const view = loaded.view;
86
+ if (!matchesDeferredWait(view, deferred))
87
+ continue;
88
+ const deliveryContext = {
89
+ ...context,
90
+ commandId: `replay:${event.event.eventId}`,
91
+ expectedSequence: loaded.sequence,
92
+ correlationId: event.event.correlationId,
93
+ actor: event.event.actor,
94
+ };
95
+ try {
96
+ if (deferred.target === undefined)
97
+ await this.deliver(id, deferred.signal, deliveryContext);
98
+ else
99
+ await this.transition(id, deferred.target, deferred.signal.providerEventId, deliveryContext);
100
+ }
101
+ catch (error) {
102
+ if (!(error instanceof DelegationPendingError) &&
103
+ !(error instanceof WrongExpectedSequenceError))
104
+ throw error;
105
+ break;
106
+ }
107
+ }
108
+ }
109
+ return (await this.repository.loadRequired(id)).view;
110
+ }
111
+ }
112
+ function matchesDeferredWait(view, deferred) {
113
+ return (!view.acceptedSignalIds.includes(deferred.signal.providerEventId) &&
114
+ view.currentStage === deferred.stage &&
115
+ view.waitingFor !== undefined &&
116
+ view.waitingFor.intentEventId === deferred.intentEventId &&
117
+ view.waitingFor.resourceId === deferred.resourceId &&
118
+ view.waitingFor.revision === deferred.revision);
119
+ }