@atolis-hq/wake 0.4.119 → 0.4.121

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 (41) hide show
  1. package/dist/src/activities/pr/activity-support.js +4 -1
  2. package/dist/src/activities/pr/contracts.d.ts +3 -0
  3. package/dist/src/activities/pr/merge.js +24 -7
  4. package/dist/src/bootstrap/artifact-mcp.js +3 -0
  5. package/dist/src/bootstrap/composition-root.js +23 -2
  6. package/dist/src/bootstrap/version.js +1 -1
  7. package/dist/src/execution/contracts/workspace.d.ts +2 -0
  8. package/dist/src/execution/infrastructure/workspace/git-workspace.js +20 -2
  9. package/dist/src/integrations/application/delegation-outputs.js +3 -0
  10. package/dist/src/integrations/github/application/wake-labels.js +19 -5
  11. package/dist/src/orchestration/application/delegated-work.d.ts +8 -0
  12. package/dist/src/orchestration/application/delegated-work.js +34 -2
  13. package/dist/src/orchestration/application/delegation-ledger.js +10 -5
  14. package/dist/src/orchestration/application/delegation-prerequisites.d.ts +3 -1
  15. package/dist/src/orchestration/application/delegation-prerequisites.js +18 -3
  16. package/dist/src/orchestration/application/delivery-coordinator.d.ts +2 -2
  17. package/dist/src/orchestration/application/delivery-coordinator.js +9 -7
  18. package/dist/src/orchestration/application/delivery-facts-reader.js +6 -7
  19. package/dist/src/orchestration/application/orchestration-service.d.ts +10 -1
  20. package/dist/src/orchestration/application/orchestration-service.js +8 -0
  21. package/dist/src/orchestration/application/prerequisite-readiness.d.ts +3 -6
  22. package/dist/src/orchestration/application/prerequisite-readiness.js +15 -17
  23. package/dist/src/orchestration/application/prerequisite-refresh-inputs.d.ts +27 -0
  24. package/dist/src/orchestration/application/prerequisite-refresh-inputs.js +53 -0
  25. package/dist/src/orchestration/application/prerequisite-review-freshness.d.ts +4 -0
  26. package/dist/src/orchestration/application/prerequisite-review-freshness.js +18 -0
  27. package/dist/src/orchestration/application/prerequisite-revisions.d.ts +15 -0
  28. package/dist/src/orchestration/application/prerequisite-revisions.js +78 -0
  29. package/dist/src/orchestration/application/refresh-prerequisites.d.ts +15 -0
  30. package/dist/src/orchestration/application/refresh-prerequisites.js +64 -0
  31. package/dist/src/orchestration/application/request-child.js +6 -1
  32. package/dist/src/orchestration/contracts/delegation-ports.d.ts +2 -0
  33. package/dist/src/orchestration/contracts/delivery-ports.d.ts +2 -0
  34. package/dist/src/orchestration/contracts/event-decoder.js +1 -0
  35. package/dist/src/orchestration/contracts/event-factory.js +1 -0
  36. package/dist/src/orchestration/contracts/events.d.ts +2 -0
  37. package/dist/src/orchestration/contracts/events.js +1 -0
  38. package/dist/src/orchestration/domain/delivery-replacement-state.d.ts +3 -0
  39. package/dist/src/orchestration/domain/delivery-replacement-state.js +16 -0
  40. package/dist/src/orchestration/domain/workflow-instance-events.js +1 -0
  41. package/package.json +1 -1
@@ -23,7 +23,10 @@ export const pullRequestOutcomeSchema = z.union([
23
23
  z
24
24
  .object({
25
25
  kind: z.literal(ActivityOutcomeKind.Done),
26
- data: z.object({ deliveryEventId: z.string() }).strict(),
26
+ data: z.union([
27
+ z.object({ deliveryEventId: z.string() }).strict(),
28
+ z.object({ resourceId: z.string(), revision: z.string() }).strict(),
29
+ ]),
27
30
  })
28
31
  .strict(),
29
32
  z
@@ -97,6 +97,9 @@ export type PullRequestActivityOutcome = {
97
97
  readonly kind: typeof ActivityOutcomeKind.Done;
98
98
  readonly data: {
99
99
  readonly deliveryEventId: string;
100
+ } | {
101
+ readonly resourceId: string;
102
+ readonly revision: string;
100
103
  };
101
104
  } | {
102
105
  readonly kind: typeof ActivityOutcomeKind.Integrated;
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { ActivityOutcomeKind } from '../contracts/vocabulary.js';
3
3
  import { readMergePolicyDenial } from './merge-policy-denial.js';
4
- import { MergeMethod, PullRequestDenialCode } from './vocabulary.js';
4
+ import { MergeMethod, PullRequestDenialCode, PullRequestState } from './vocabulary.js';
5
5
  import { BuiltInResourceCapability, resourceStream, } from '../../resources/index.js';
6
6
  import { workItemStream } from '../../work/index.js';
7
7
  import { ActivityEventType } from '../contracts/events.js';
@@ -91,6 +91,23 @@ async function denyByAuthority({ journal, appender }, invocation, authority, res
91
91
  factStream: resourceStream(resourceId),
92
92
  });
93
93
  }
94
+ function mergePolicyOf(input) {
95
+ return {
96
+ ...(input.maxFilesChanged === undefined ? {} : { maxFilesChanged: input.maxFilesChanged }),
97
+ blockedPaths: input.blockedPaths,
98
+ };
99
+ }
100
+ function mergedOutcome(authority, resourceId) {
101
+ const merged = authority.pullRequests.find((view) => view.resourceId === resourceId &&
102
+ view.workItemId === authority.work?.workItemId &&
103
+ view.state === PullRequestState.Merged);
104
+ return merged === undefined
105
+ ? null
106
+ : {
107
+ kind: ActivityOutcomeKind.Done,
108
+ data: { resourceId: merged.resourceId, revision: merged.headRevision },
109
+ };
110
+ }
94
111
  async function executeMerge(journal, pullRequests, appender, parentActions, invocation, context) {
95
112
  const requireApproval = invocation.input.requireApproval ?? true;
96
113
  const autoMerge = invocation.input.autoMerge ?? false;
@@ -117,17 +134,17 @@ async function executeMerge(journal, pullRequests, appender, parentActions, invo
117
134
  factStream,
118
135
  });
119
136
  }
137
+ // A merge that landed outside Wake (e.g. GitHub auto-merge) leaves nothing to
138
+ // deliver, so the review/check/file gates that guard Wake's own merge do not apply.
139
+ const alreadyMerged = mergedOutcome(authority, resource.resourceId);
140
+ if (alreadyMerged !== null)
141
+ return alreadyMerged;
120
142
  const decision = decidePullRequestAuthority(authority, {
121
143
  target: { resourceId: resource.resourceId },
122
144
  requireAcceptedReview: requireApproval,
123
145
  requireChecks: invocation.input.requireChecks,
124
146
  allowPendingChecks: autoMerge,
125
- mergePolicy: {
126
- ...(invocation.input.maxFilesChanged === undefined
127
- ? {}
128
- : { maxFilesChanged: invocation.input.maxFilesChanged }),
129
- blockedPaths: invocation.input.blockedPaths,
130
- },
147
+ mergePolicy: mergePolicyOf(invocation.input),
131
148
  });
132
149
  if (!decision.allowed)
133
150
  return denyByAuthority({ journal, appender }, invocation, authority, resource.resourceId, decision, command);
@@ -45,6 +45,9 @@ export function createArtifactMcpProvisioner(input) {
45
45
  prompt: [
46
46
  artifactPrompt(manifest),
47
47
  attentionPrompt(await input.orchestration.openDelegationAttention(workflowInstanceId(context.workflowInstanceId), activation.activationId)),
48
+ context.repositoryAssignment === undefined
49
+ ? ''
50
+ : await input.orchestration.prerequisiteRefreshPrompt(workflowInstanceId(context.workflowInstanceId), activation.activationId),
48
51
  operatorInstructionsPrompt(instructions),
49
52
  ]
50
53
  .filter(Boolean)
@@ -7,7 +7,7 @@ import { ExecutionCancellationReason, GitWorkspaceProvider, RecoveryService, Run
7
7
  import { createGitHubAgentContextReader, gitHubProviderDefinition, gitHubRepositoryIdentity, resolveGitHubResourceUrl, } from '../integrations/github/index.js';
8
8
  import { createDelegationOutputs, createDeliveryIntegrationVerification, } from '../integrations/index.js';
9
9
  import { SystemClock, UlidIdGenerator } from '../kernel/index.js';
10
- import { compileWorkflow, createAgentActivityClassifier, createOrchestrationService, } from '../orchestration/index.js';
10
+ import { compileWorkflow, createAgentActivityClassifier, createOrchestrationService, workflowInstanceId, } from '../orchestration/index.js';
11
11
  import { ResourceCorrelationProvenance, ResourceCorrelationRole, createResourceLookup, createResourceService, resourceId, } from '../resources/index.js';
12
12
  import { createWorkService } from '../work/index.js';
13
13
  import { createFileActivationSchedulerSerialiser } from './activation-scheduler-serialiser.js';
@@ -106,6 +106,20 @@ async function createApplicationServices(wakeRoot, options = {}) {
106
106
  await resources.correlate(primary.resourceId, childWorkItemId, ResourceCorrelationRole.Secondary, context, ResourceCorrelationProvenance.Delegated);
107
107
  },
108
108
  },
109
+ childRunsEnded: async (id) => {
110
+ const child = await orchestration.get(workflowInstanceId(id));
111
+ if (child === null)
112
+ return false;
113
+ return (await execution.list())
114
+ .filter((run) => run.orchestrationGroupId === child.orchestrationGroupId)
115
+ .every((run) => !isActiveRunStatus(run.status) &&
116
+ run.status !== RunStatus.Ambiguous &&
117
+ !execution.isLocallyActive(run.runId));
118
+ },
119
+ hasUnresolvedRuns: async (id) => (await execution.list()).some((run) => run.workflowInstanceId === id &&
120
+ (isActiveRunStatus(run.status) ||
121
+ run.status === RunStatus.Ambiguous ||
122
+ execution.isLocallyActive(run.runId))),
109
123
  runHasEnded: async (runId) => {
110
124
  const run = (await execution.list()).find((entry) => entry.runId === runId);
111
125
  return (run !== undefined &&
@@ -168,7 +182,14 @@ async function createApplicationServices(wakeRoot, options = {}) {
168
182
  },
169
183
  }
170
184
  : {}),
171
- workspaces,
185
+ workspaces: {
186
+ acquire: async (request) => workspaces.acquire({
187
+ ...request,
188
+ assignmentHistory: request.assignment === undefined
189
+ ? []
190
+ : await orchestration.workspaceAssignmentHistory(request.workItemId),
191
+ }),
192
+ },
172
193
  });
173
194
  orchestration.setWatchChildCancellation({
174
195
  cancelSupersededWatchChildren: (workflowInstanceIds) => execution.cancelActive(workflowInstanceIds, ExecutionCancellationReason.WorkflowSuperseded),
@@ -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.119";
127
+ export const wakeVersion = "v0.4.121";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -18,6 +18,8 @@ export interface WorkspaceRequest {
18
18
  readonly checkoutRevision?: string;
19
19
  readonly requiredSourceRef?: string;
20
20
  readonly assignment?: RepositoryAssignment;
21
+ /** Prior pins authorized by durable upstream-refresh receipts; checkout contents are retained. */
22
+ readonly assignmentHistory?: readonly RepositoryAssignment[];
21
23
  }
22
24
  export interface WorkspaceLease {
23
25
  readonly changeOutputs?: readonly ChangeOutputWorkspace[];
@@ -66,7 +66,21 @@ export class GitWorkspaceProvider {
66
66
  workspaceId: name,
67
67
  path,
68
68
  mode: request.mode,
69
- readRevision: () => readCheckoutRevision(path, this.git, signal),
69
+ readRevision: async () => {
70
+ const revision = await readCheckoutRevision(path, this.git, signal);
71
+ if (request.mode === WorkspaceMode.Branch &&
72
+ request.assignment !== undefined &&
73
+ (request.assignmentHistory?.length ?? 0) > 0)
74
+ await this.git([
75
+ '-C',
76
+ path,
77
+ 'merge-base',
78
+ '--is-ancestor',
79
+ request.assignment.sourceRevision,
80
+ revision,
81
+ ], signal);
82
+ return revision;
83
+ },
70
84
  repositoryResourceId: request.repositoryResource.resourceId,
71
85
  checkoutRevision: await readCheckoutRevision(path, this.git, signal),
72
86
  ...(request.assignment === undefined ? {} : { assignment: request.assignment }),
@@ -525,7 +539,11 @@ function assertAssignment(previousMarker, request) {
525
539
  throw new Error('Workspace belongs to a different Repository Resource');
526
540
  if (request.mode === WorkspaceMode.Branch &&
527
541
  previousMarker?.assignment !== undefined &&
528
- !isDeepStrictEqual(previousMarker.assignment, request.assignment))
542
+ !isDeepStrictEqual(previousMarker.assignment, request.assignment) &&
543
+ !request.assignmentHistory?.some((assignment) => isDeepStrictEqual(assignment, previousMarker.assignment) &&
544
+ assignment.resourceId === request.assignment?.resourceId &&
545
+ assignment.sourceRef === request.assignment.sourceRef &&
546
+ assignment.pullRequestBase === request.assignment.pullRequestBase))
529
547
  throw new Error('Workspace repository assignment changed; reconcile the existing branch before retrying');
530
548
  }
531
549
  async function initializeBranch(input, git, signal) {
@@ -9,6 +9,9 @@ const reportsSchema = z.object({ reportedArtifacts: z.array(reportedArtifactSche
9
9
  export function createDelegationOutputs(input) {
10
10
  return {
11
11
  ...input.artifacts,
12
+ async runActivation(runId) {
13
+ return (await input.runs()).find((run) => run.runId === runId)?.activationId;
14
+ },
12
15
  async prerequisiteOutput(child, output, condition) {
13
16
  if ('path' in output &&
14
17
  (condition === Condition.AcceptedOutput || condition === Condition.DeliveryReady)) {
@@ -1,4 +1,5 @@
1
- import { WorkflowStatus } from '../../../orchestration/index.js';
1
+ import { ActivityOutcomeKind } from '../../../activities/index.js';
2
+ import { isApprovalAwaitingSignalKind, WorkflowStatus, } from '../../../orchestration/index.js';
2
3
  import { WorkStatus } from '../../../work/index.js';
3
4
  import { GitHubWakeStatusLabel, isGitHubWakeMarker, } from '../contracts/vocabulary.js';
4
5
  export function reconcileGitHubWakeLabels(current, desired) {
@@ -82,18 +83,18 @@ function defaultOnError(failure, error) {
82
83
  }
83
84
  function desiredWakeLabels(workflow, watching) {
84
85
  return [
85
- `wake:status.${statusLabel(workflow.status)}`,
86
+ `wake:status.${statusLabel(workflow)}`,
86
87
  `wake:stage.${workflow.currentStage}`,
87
88
  `wake:workflow.${workflow.workflowName}`,
88
89
  ...(watching ? ['wake:watching'] : []),
89
90
  ];
90
91
  }
91
- function statusLabel(status) {
92
- switch (status) {
92
+ function statusLabel(workflow) {
93
+ switch (workflow.status) {
93
94
  case WorkflowStatus.Active:
94
95
  return GitHubWakeStatusLabel.Working;
95
96
  case WorkflowStatus.Waiting:
96
- return GitHubWakeStatusLabel.AwaitingApproval;
97
+ return waitStatusLabel(workflow.waitingFor);
97
98
  case WorkflowStatus.Blocked:
98
99
  return GitHubWakeStatusLabel.Blocked;
99
100
  case WorkflowStatus.Completed:
@@ -102,6 +103,19 @@ function statusLabel(status) {
102
103
  return GitHubWakeStatusLabel.Failed;
103
104
  }
104
105
  }
106
+ // Only approval-style waits are "awaiting approval"; other waits (delivery
107
+ // results, resource transitions) are Wake-side progress.
108
+ function waitStatusLabel(wait) {
109
+ if (wait === undefined)
110
+ return GitHubWakeStatusLabel.Working;
111
+ if (isApprovalAwaitingSignalKind(wait.signalKind))
112
+ return GitHubWakeStatusLabel.AwaitingApproval;
113
+ if (wait.signalKind === ActivityOutcomeKind.Blocked)
114
+ return GitHubWakeStatusLabel.Blocked;
115
+ if (wait.signalKind === ActivityOutcomeKind.Failed)
116
+ return GitHubWakeStatusLabel.Failed;
117
+ return GitHubWakeStatusLabel.Working;
118
+ }
105
119
  function parseGitHubIssueKey(key) {
106
120
  const match = /^(?<owner>[^/]+)\/(?<repo>[^#]+)#(?<number>[1-9]\d*)$/.exec(key);
107
121
  if (match?.groups === undefined)
@@ -34,6 +34,7 @@ export declare class DelegatedWork {
34
34
  readonly artifacts: DelegationArtifacts;
35
35
  readonly repositories?: DelegationRepositories | undefined;
36
36
  readonly runHasEnded: (runId: string) => Promise<boolean>;
37
+ readonly childRunsEnded?: ((id: string) => Promise<boolean>) | undefined;
37
38
  readonly authority?: DelegationAuthority | undefined;
38
39
  readonly supportsAttention?: ((activity: ActivityName) => boolean) | undefined;
39
40
  readonly resumeChild?: DelegationAttentionDependencies['resumeChild'] | undefined;
@@ -152,6 +153,13 @@ export declare class DelegatedWork {
152
153
  pullRequestBase: string;
153
154
  };
154
155
  }[] | undefined>;
156
+ refreshPrompt(id: WorkflowInstanceId, activation: string): Promise<string>;
157
+ assignmentHistory(workItemId: string): Promise<{
158
+ resourceId: string;
159
+ sourceRef: string;
160
+ pullRequestBase: string;
161
+ sourceRevision: string;
162
+ }[]>;
155
163
  repositoryFor(workItemId: string): Promise<{
156
164
  resourceId: string;
157
165
  sourceRef: string;
@@ -18,6 +18,7 @@ import { DelegationPrerequisites } from './delegation-prerequisites.js';
18
18
  import { assertWithinRootLimits, buildReservation, matchesAssignments, } from './delegation-reservation.js';
19
19
  import { resolvePrerequisites } from './delegation-wait-graph.js';
20
20
  import { readDeliveryFacts } from './delivery-facts-reader.js';
21
+ import { prerequisiteRefreshPrompt } from './refresh-prerequisites.js';
21
22
  const defaultLimits = { maxDepth: 1, maxDescendants: 8 };
22
23
  /** How long completed-child outputs may stay invisible before the child is blocked. */
23
24
  const OUTPUT_VISIBILITY_GRACE_MS = 120_000;
@@ -55,7 +56,12 @@ export class DelegatedWork {
55
56
  canContinue: (reservation) => this.canJoin(reservation),
56
57
  messages: dependencies.messages,
57
58
  });
58
- this.prerequisites = new DelegationPrerequisites(repository, this.ledger, dependencies.artifacts, dependencies.repositories, work);
59
+ this.prerequisites = new DelegationPrerequisites(repository, this.ledger, dependencies.artifacts, dependencies.repositories, work, {
60
+ workflows,
61
+ messages: dependencies.messages,
62
+ supportsAttention: dependencies.supportsAttention,
63
+ childRunsEnded: dependencies.childRunsEnded,
64
+ });
59
65
  this.repositories = dependencies.repositories;
60
66
  this.runHasEnded = dependencies.runHasEnded;
61
67
  }
@@ -127,6 +133,32 @@ export class DelegatedWork {
127
133
  ]
128
134
  : []);
129
135
  }
136
+ async refreshPrompt(id, activation) {
137
+ const history = await this.repository.history(id);
138
+ let inputs;
139
+ for (const { event } of history.events) {
140
+ if (event.eventType === OrchestrationEventType.DelegationInputsRefreshed)
141
+ inputs = event.payload;
142
+ if (event.eventType === OrchestrationEventType.ActivityRequested) {
143
+ if (event.payload.activationId === activation && inputs !== undefined)
144
+ return prerequisiteRefreshPrompt(inputs);
145
+ inputs = undefined;
146
+ }
147
+ }
148
+ return '';
149
+ }
150
+ async assignmentHistory(workItemId) {
151
+ const events = await this.ledger.events();
152
+ if (!events.some(({ event }) => event.eventType === OrchestrationEventType.DelegationInputsRefreshed &&
153
+ event.payload.childWorkItemId === workItemId))
154
+ return [];
155
+ return events.flatMap(({ event }) => (event.eventType === OrchestrationEventType.DelegationInputsResolved ||
156
+ event.eventType === OrchestrationEventType.DelegationInputsRefreshed) &&
157
+ event.payload.childWorkItemId === workItemId &&
158
+ event.payload.repository !== undefined
159
+ ? [event.payload.repository]
160
+ : []);
161
+ }
130
162
  async repositoryFor(workItemId) {
131
163
  const inputs = await this.prerequisites.inputs(workItemId);
132
164
  if (inputs?.repository !== undefined)
@@ -590,7 +622,7 @@ export class DelegatedWork {
590
622
  await this.failChild(reservation, child, 'Invalid qualifying output contract', context);
591
623
  return;
592
624
  }
593
- await this.ledger.appendOnce(root, context, `result:${child.grantId}`, {
625
+ await this.ledger.appendOnce(root, context, `result:${child.grantId}:${workflow.acceptedOutcomes.at(-1)}`, {
594
626
  eventType: OrchestrationEventType.DelegationResultSelected,
595
627
  payload: { cohortId: reservation.cohortId, childWorkItemId: child.workItemId, outputs },
596
628
  });
@@ -63,11 +63,16 @@ export function isSettled(events, reservation) {
63
63
  }
64
64
  export function selectedResults(events, reservation) {
65
65
  const children = new Set(reservation.children.map((child) => child.workItemId));
66
- return events.flatMap((event) => event.event.eventType === OrchestrationEventType.DelegationResultSelected &&
67
- event.event.payload.cohortId === reservation.cohortId &&
68
- children.has(event.event.payload.childWorkItemId)
69
- ? [event.event.payload]
70
- : []);
66
+ const selected = new Map();
67
+ for (const { event } of events) {
68
+ if (event.eventType === OrchestrationEventType.DelegationInputsRefreshed)
69
+ selected.delete(event.payload.childWorkItemId);
70
+ if (event.eventType === OrchestrationEventType.DelegationResultSelected &&
71
+ event.payload.cohortId === reservation.cohortId &&
72
+ children.has(event.payload.childWorkItemId))
73
+ selected.set(event.payload.childWorkItemId, event.payload);
74
+ }
75
+ return [...selected.values()];
71
76
  }
72
77
  export function reservedEvent(events, reservation) {
73
78
  const found = events.find((entry) => entry.event.eventType === OrchestrationEventType.DelegationReserved &&
@@ -5,6 +5,7 @@ import type { DelegationInputs, DelegationReservation } from '../contracts/deleg
5
5
  import type { DelegationLedger } from './delegation-ledger.js';
6
6
  import type { OrchestrationRepository } from './orchestration-repository.js';
7
7
  import { PrerequisiteReadiness, type PrerequisiteAdmission } from './prerequisite-readiness.js';
8
+ import { type PrerequisiteRefreshDependencies } from './refresh-prerequisites.js';
8
9
  type Child = DelegationReservation['children'][number];
9
10
  /** Immutable consumption receipts and live eligibility; never chooses a repair. */
10
11
  export declare class DelegationPrerequisites {
@@ -13,7 +14,8 @@ export declare class DelegationPrerequisites {
13
14
  private readonly artifacts;
14
15
  private readonly repositories;
15
16
  private readonly work;
16
- constructor(repository: OrchestrationRepository, ledger: DelegationLedger, artifacts: DelegationArtifacts, repositories: DelegationRepositories | undefined, work: WorkService);
17
+ private readonly refresh?;
18
+ constructor(repository: OrchestrationRepository, ledger: DelegationLedger, artifacts: DelegationArtifacts, repositories: DelegationRepositories | undefined, work: WorkService, refresh?: PrerequisiteRefreshDependencies | undefined);
17
19
  inputs(id: string): Promise<DelegationInputs | undefined>;
18
20
  read(workSnapshot?: DeliverySnapshot): Promise<PrerequisiteReadiness>;
19
21
  reasons(ids: readonly string[], workSnapshot?: DeliverySnapshot): Promise<ReadonlyMap<string, PrerequisiteAdmission>>;
@@ -1,6 +1,7 @@
1
1
  import { OrchestrationEventType } from '../contracts/events.js';
2
2
  import { PrerequisiteBlockCode } from '../contracts/vocabulary.js';
3
3
  import { PrerequisiteReadiness } from './prerequisite-readiness.js';
4
+ import { refreshPrerequisites, } from './refresh-prerequisites.js';
4
5
  /** Immutable consumption receipts and live eligibility; never chooses a repair. */
5
6
  export class DelegationPrerequisites {
6
7
  repository;
@@ -8,18 +9,23 @@ export class DelegationPrerequisites {
8
9
  artifacts;
9
10
  repositories;
10
11
  work;
11
- constructor(repository, ledger, artifacts, repositories, work) {
12
+ refresh;
13
+ constructor(repository, ledger, artifacts, repositories, work, refresh) {
12
14
  this.repository = repository;
13
15
  this.ledger = ledger;
14
16
  this.artifacts = artifacts;
15
17
  this.repositories = repositories;
16
18
  this.work = work;
19
+ this.refresh = refresh;
17
20
  }
18
21
  async inputs(id) {
19
- return (await this.ledger.events()).flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationInputsResolved &&
22
+ return (await this.ledger.events())
23
+ .flatMap(({ event }) => (event.eventType === OrchestrationEventType.DelegationInputsResolved ||
24
+ event.eventType === OrchestrationEventType.DelegationInputsRefreshed) &&
20
25
  event.payload.childWorkItemId === id
21
26
  ? [event.payload]
22
- : [])[0];
27
+ : [])
28
+ .at(-1);
23
29
  }
24
30
  async read(workSnapshot) {
25
31
  const snapshot = await this.repository.snapshot();
@@ -97,6 +103,15 @@ export class DelegationPrerequisites {
97
103
  const blocked = await read.block(child.workItemId);
98
104
  if (blocked === undefined)
99
105
  return true;
106
+ if (blocked.refresh !== undefined && this.refresh !== undefined) {
107
+ const repository = await this.resolveBase(reservation, child, blocked.refresh);
108
+ await refreshPrerequisites(this.repository, this.refresh, child, {
109
+ childWorkItemId: child.workItemId,
110
+ consumed: blocked.refresh,
111
+ ...(repository === undefined ? {} : { repository }),
112
+ }, context);
113
+ return false;
114
+ }
100
115
  await this.diagnostic(reservation, child, blocked.reason, context);
101
116
  if (blocked.code === PrerequisiteBlockCode.Changed ||
102
117
  blocked.code === PrerequisiteBlockCode.Failed)
@@ -316,8 +316,8 @@ export declare class DeliveryCoordinator {
316
316
  };
317
317
  }>;
318
318
  /**
319
- * Replacement children keep the original acceptance criteria and repository; a terminal original
320
- * is replaced by a new child, while correcting a still-running one is not supported.
319
+ * Replacements preserve the original requirements. Missing instances need durable failed
320
+ * settlement; live workflows and unresolved runs remain ineligible.
321
321
  */
322
322
  assertReplacements(caller: DelegationCaller, input: unknown): Promise<void>;
323
323
  completionBlock(id: string): Promise<import("../contracts/delivery.js").DeliveryCompletionBlock | undefined>;
@@ -1,15 +1,16 @@
1
1
  import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
- import { DelegationConflictError, delegationSubmissionSchema, } from '../contracts/delegation.js';
2
+ import { delegationSubmissionSchema } from '../contracts/delegation.js';
3
3
  import { DeliveryRejectionError, deliveryCandidateCommandSchema, deliveryMaintenanceCommandSchema, deliveryQaCommandSchema, deliverySelectionCommandSchema, } from '../contracts/delivery.js';
4
4
  import { OrchestrationEventType } from '../contracts/events.js';
5
5
  import { stageName } from '../contracts/identifiers.js';
6
- import { DelegationConflictCode, DeliveryCompletion, DeliveryRejection, QaVerdict, WorkflowStatus, } from '../contracts/vocabulary.js';
6
+ import { DeliveryCompletion, DeliveryRejection, QaVerdict, WorkflowStatus, } from '../contracts/vocabulary.js';
7
7
  import { planCandidate } from '../domain/delivery-candidate.js';
8
8
  import { currentSelection, requirements } from '../domain/delivery-facts.js';
9
9
  import { assertQa, completionDecision, deliveryState } from '../domain/delivery-qa.js';
10
+ import { assertReplacementState } from '../domain/delivery-replacement-state.js';
10
11
  import { originalOf } from '../domain/delivery-replacement.js';
11
12
  import { reviseSelection } from '../domain/delivery-selection.js';
12
- import { delegationDraft } from './delegation-ledger.js';
13
+ import { delegationDraft, isJoined, isSettled } from './delegation-ledger.js';
13
14
  import { readDeliveryFacts } from './delivery-facts-reader.js';
14
15
  import { DeliveryIntegrationService } from './delivery-integration-service.js';
15
16
  import { DeliveryPreparation } from './delivery-preparation.js';
@@ -163,8 +164,8 @@ export class DeliveryCoordinator {
163
164
  };
164
165
  }
165
166
  /**
166
- * Replacement children keep the original acceptance criteria and repository; a terminal original
167
- * is replaced by a new child, while correcting a still-running one is not supported.
167
+ * Replacements preserve the original requirements. Missing instances need durable failed
168
+ * settlement; live workflows and unresolved runs remain ineligible.
168
169
  */
169
170
  async assertReplacements(caller, input) {
170
171
  const parent = (await this.repository.loadRequired(caller.workflowInstanceId)).view;
@@ -177,11 +178,12 @@ export class DeliveryCoordinator {
177
178
  return;
178
179
  await this.dependencies.authority.assertCaller(caller, parent);
179
180
  const facts = await this.facts(parent);
181
+ const { events } = await this.repository.history(parent.workflowInstanceId);
180
182
  for (const assignment of replacements) {
181
183
  const original = originalOf(facts, assignment.replaces);
182
184
  const view = (await this.repository.load(original.workflowInstanceId)).view;
183
- if (view?.status !== WorkflowStatus.Completed && view?.status !== WorkflowStatus.Superseded)
184
- throw new DelegationConflictError(DelegationConflictCode.ReplacementUnsupported, 'Correcting a child that is still running is not supported; replace it once it is complete or superseded');
185
+ const cohort = facts.reservations.find((entry) => entry.cohortId === assignment.replaces.cohortId);
186
+ assertReplacementState(view?.status, isSettled(events, cohort) && !isJoined(events, cohort), (await this.dependencies.hasUnresolvedRuns?.(original.workflowInstanceId)) ?? false);
185
187
  }
186
188
  }
187
189
  completionBlock(id) {
@@ -1,4 +1,5 @@
1
1
  import { OrchestrationEventType } from '../contracts/events.js';
2
+ import { selectedResults } from './delegation-ledger.js';
2
3
  /**
3
4
  * Journal-derived facts for one parent delivery: its cohorts and their selected results, what each
4
5
  * child consumed, and the parent's own selection, candidate and QA facts.
@@ -10,19 +11,17 @@ export async function readDeliveryFacts(repository, parent, own) {
10
11
  ? [event.payload]
11
12
  : []));
12
13
  const instances = new Map(reservations.flatMap((reservation) => reservation.children.map((child) => [child.workflowInstanceId, child.workItemId])));
13
- const results = all.flatMap(({ event }) => event.eventType === OrchestrationEventType.DelegationResultSelected &&
14
- [...instances.values()].includes(event.payload.childWorkItemId)
15
- ? [event.payload]
16
- : []);
14
+ const results = reservations.flatMap((reservation) => selectedResults(all, reservation));
17
15
  const consumed = new Map();
18
16
  for (const { event } of all) {
19
- if (event.eventType !== OrchestrationEventType.DelegationInputsResolved)
17
+ if (event.eventType !== OrchestrationEventType.DelegationInputsResolved &&
18
+ event.eventType !== OrchestrationEventType.DelegationInputsRefreshed)
20
19
  continue;
21
- // Consumption receipts belong to the parent stream and identify their child in the payload.
20
+ // Receipts identify their child; a refresh replaces the effective basis, not its history.
22
21
  const child = event.payload.childWorkItemId;
23
22
  if (![...instances.values()].includes(child))
24
23
  continue;
25
- consumed.set(child, [...(consumed.get(child) ?? []), ...event.payload.consumed]);
24
+ consumed.set(child, [...event.payload.consumed]);
26
25
  }
27
26
  const mine = own.map(({ event }) => event);
28
27
  return {
@@ -1,6 +1,6 @@
1
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
- import type { DeliveryIntegration } from '../contracts/delivery-ports.js';
3
+ import type { DeliveryDependencies, DeliveryIntegration } from '../contracts/delivery-ports.js';
4
4
  import type { DeliveryCandidateCommand, DeliveryMaintenanceCommand, DeliveryQaCommand, DeliverySelectionCommand } from '../contracts/delivery.js';
5
5
  import { retryObservedState } from './observed-state-retry.js';
6
6
  import type { ResourceTransitionEvidence } from './resource-transition-evidence.js';
@@ -164,6 +164,13 @@ export declare class OrchestrationService {
164
164
  pullRequestBase: string;
165
165
  };
166
166
  }[] | undefined>;
167
+ prerequisiteRefreshPrompt(id: WorkflowInstanceId, activation: string): Promise<string>;
168
+ workspaceAssignmentHistory(workItemId: string): Promise<{
169
+ resourceId: string;
170
+ sourceRef: string;
171
+ pullRequestBase: string;
172
+ sourceRevision: string;
173
+ }[]>;
167
174
  repositoryAssignment(workItemId: string): Promise<{
168
175
  resourceId: string;
169
176
  sourceRef: string;
@@ -772,5 +779,7 @@ type DelegationDependenciesFactory = (queries: {
772
779
  resources?: DelegationResources;
773
780
  integration?: DeliveryIntegration;
774
781
  runHasEnded: (runId: string) => Promise<boolean>;
782
+ childRunsEnded?: (id: string) => Promise<boolean>;
783
+ hasUnresolvedRuns?: DeliveryDependencies['hasUnresolvedRuns'];
775
784
  };
776
785
  export {};
@@ -88,6 +88,12 @@ export class OrchestrationService {
88
88
  changeOutputAssignments(workItemId) {
89
89
  return this.delegatedWork.changeOutputAssignments(workItemId);
90
90
  }
91
+ prerequisiteRefreshPrompt(id, activation) {
92
+ return this.delegatedWork.refreshPrompt(id, activation);
93
+ }
94
+ workspaceAssignmentHistory(workItemId) {
95
+ return this.delegatedWork.assignmentHistory(workItemId);
96
+ }
91
97
  repositoryAssignment(workItemId) {
92
98
  return this.delegatedWork.repositoryFor(workItemId);
93
99
  }
@@ -507,6 +513,7 @@ function delegatedWorkDependencies(dependencies, supportsAttention, resumeChild)
507
513
  artifacts: dependencies?.artifacts ?? unavailableArtifacts,
508
514
  repositories: dependencies?.repositories,
509
515
  runHasEnded: dependencies?.runHasEnded ?? unavailableRunCompletion,
516
+ childRunsEnded: dependencies?.childRunsEnded,
510
517
  supportsAttention,
511
518
  resumeChild,
512
519
  messages: dependencies?.messages,
@@ -521,6 +528,7 @@ function deliveryDependencies(dependencies, definitionFor, work) {
521
528
  authority: dependencies?.authority ?? unavailableDelegationAuthority,
522
529
  repositories: dependencies?.repositories,
523
530
  integration: dependencies?.integration,
531
+ hasUnresolvedRuns: dependencies?.hasUnresolvedRuns,
524
532
  // A finished producing workflow (a Closed child) is deliberately not a hold.
525
533
  unavailable: async (ids) => {
526
534
  const snapshot = await work.deliverySnapshot();
@@ -2,17 +2,14 @@ import type { DeliverySnapshot } from '../../work/index.js';
2
2
  import type { DelegationArtifacts, DelegationRepositories } from '../contracts/delegation-ports.js';
3
3
  import type { DelegationInputs, DelegationReservation } from '../contracts/delegation.js';
4
4
  import type { WorkflowInstanceView } from '../contracts/views.js';
5
- import { PrerequisiteBlockCode as Code } from '../contracts/vocabulary.js';
6
5
  import type { OrchestrationRepository } from './orchestration-repository.js';
6
+ import { type PrerequisiteBlock } from './prerequisite-refresh-inputs.js';
7
7
  type Child = DelegationReservation['children'][number];
8
8
  export interface PrerequisiteAdmission {
9
9
  readonly reason: string | undefined;
10
10
  readonly abandoned: boolean;
11
11
  }
12
- export interface PrerequisiteBlock {
13
- readonly code: Code;
14
- readonly reason: string;
15
- }
12
+ export type { PrerequisiteBlock } from './prerequisite-refresh-inputs.js';
16
13
  /** A bounded read pass: one journal/Work snapshot and one lookup per declared input. */
17
14
  export declare class PrerequisiteReadiness {
18
15
  private readonly work;
@@ -26,6 +23,7 @@ export declare class PrerequisiteReadiness {
26
23
  private readonly blockers;
27
24
  private readonly evaluated;
28
25
  private readonly selected;
26
+ private readonly revisionEvidence;
29
27
  private readonly bases;
30
28
  constructor(snapshot: Awaited<ReturnType<OrchestrationRepository['snapshot']>>, work: DeliverySnapshot, artifacts: DelegationArtifacts, repositories: DelegationRepositories | undefined);
31
29
  abandoned(id: string): boolean;
@@ -73,4 +71,3 @@ export declare class PrerequisiteReadiness {
73
71
  private upstreamAvailability;
74
72
  private verifyBase;
75
73
  }
76
- export {};
@@ -4,6 +4,8 @@ import { OrchestrationEventType } from '../contracts/events.js';
4
4
  import { PrerequisiteBlockCode as Code, DelegationPrerequisiteCondition as Condition, WorkflowStatus, } from '../contracts/vocabulary.js';
5
5
  import { isSuccessfulWorkflowCompletion } from '../domain/workflow-completion.js';
6
6
  import { reservationsOf } from './delegation-ledger.js';
7
+ import { changedInputsBlock, freshness, inheritedBlock, } from './prerequisite-refresh-inputs.js';
8
+ import { prerequisiteRevisions, revisionOutputPending, revisionPending, } from './prerequisite-revisions.js';
7
9
  /** A bounded read pass: one journal/Work snapshot and one lookup per declared input. */
8
10
  export class PrerequisiteReadiness {
9
11
  work;
@@ -17,11 +19,13 @@ export class PrerequisiteReadiness {
17
19
  blockers = new Map();
18
20
  evaluated = new Map();
19
21
  selected = new Map();
22
+ revisionEvidence;
20
23
  bases = new Map();
21
24
  constructor(snapshot, work, artifacts, repositories) {
22
25
  this.work = work;
23
26
  this.artifacts = artifacts;
24
27
  this.repositories = repositories;
28
+ this.revisionEvidence = prerequisiteRevisions(snapshot.events);
25
29
  const failures = new Set(snapshot.events.flatMap(({ event, stream }) => event.eventType === OrchestrationEventType.DelegationFailed
26
30
  ? [JSON.stringify([stream.id, event.payload.cohortId])]
27
31
  : []));
@@ -37,7 +41,8 @@ export class PrerequisiteReadiness {
37
41
  if (view !== null)
38
42
  this.workflows.set(view.workflowInstanceId, view);
39
43
  for (const { event } of snapshot.events) {
40
- if (event.eventType === OrchestrationEventType.DelegationInputsResolved)
44
+ if (event.eventType === OrchestrationEventType.DelegationInputsResolved ||
45
+ event.eventType === OrchestrationEventType.DelegationInputsRefreshed)
41
46
  this.receipts.set(event.payload.childWorkItemId, event.payload);
42
47
  if (event.eventType === OrchestrationEventType.DelegationChildBlocked)
43
48
  this.blockers.set(event.payload.childWorkItemId, {
@@ -110,14 +115,14 @@ export class PrerequisiteReadiness {
110
115
  async evaluate(id, seen) {
111
116
  const blocked = this.blockers.get(id);
112
117
  if (blocked !== undefined)
113
- return blocked;
118
+ return inheritedBlock(blocked);
114
119
  const child = this.children.get(id);
115
120
  if (child === undefined || (child.prerequisites?.length ?? 0) === 0)
116
121
  return undefined;
117
122
  for (const upstream of child.prerequisiteWorkItemIds ?? []) {
118
123
  const block = await this.block(upstream, seen);
119
124
  if (block !== undefined)
120
- return block;
125
+ return inheritedBlock(block);
121
126
  }
122
127
  const current = await this.select(child, seen);
123
128
  if (!Array.isArray(current))
@@ -126,10 +131,7 @@ export class PrerequisiteReadiness {
126
131
  if (stored === undefined)
127
132
  return { code: Code.Waiting, reason: 'Prerequisite inputs have not been pinned' };
128
133
  if (!isDeepStrictEqual(freshness(stored.consumed), freshness(current)))
129
- return {
130
- code: Code.Changed,
131
- reason: 'Consumed upstream output or base changed; agent assessment required',
132
- };
134
+ return changedInputsBlock(stored.consumed, current, this.children, this.artifacts, this.revisionEvidence.revisions);
133
135
  return undefined;
134
136
  }
135
137
  async select(child, seen) {
@@ -183,13 +185,15 @@ export class PrerequisiteReadiness {
183
185
  const statusReason = workflowReason(workflow, edge);
184
186
  if (statusReason !== undefined)
185
187
  return {
186
- code: workflow.status === WorkflowStatus.Completed ||
187
- workflow.status === WorkflowStatus.Superseded
188
+ code: [WorkflowStatus.Completed, WorkflowStatus.Superseded].some((status) => status === workflow.status)
188
189
  ? Code.Failed
189
190
  : Code.Waiting,
190
191
  reason: statusReason,
191
192
  };
192
193
  const output = upstream.outputs.find((entry) => entry.name === edge.output);
194
+ const evidence = this.revisionEvidence;
195
+ if (revisionPending(workflow, evidence.pending))
196
+ return { code: Code.Waiting, reason: 'Waiting for upstream review revision' };
193
197
  const selected = await this.artifacts.prerequisiteOutput?.(workflow, output, edge.condition);
194
198
  if (selected == null ||
195
199
  selected.name !== edge.output ||
@@ -198,6 +202,8 @@ export class PrerequisiteReadiness {
198
202
  code: Code.Waiting,
199
203
  reason: `Waiting for ${edge.condition} output ${upstream.assignmentId}/${edge.output}`,
200
204
  };
205
+ if (await revisionOutputPending(workflow, selected.reference, this.artifacts, evidence))
206
+ return { code: Code.Waiting, reason: 'Waiting for verified upstream review revision' };
201
207
  return selected;
202
208
  }
203
209
  async upstreamAvailability(workflow) {
@@ -242,11 +248,3 @@ function workflowReason(workflow, edge) {
242
248
  return 'Upstream workflow was superseded';
243
249
  return undefined;
244
250
  }
245
- function freshness(outputs) {
246
- return outputs.map(({ name, reference }) => {
247
- if (!('runId' in reference))
248
- return { name, reference };
249
- const { runId: _run, baseRevision: _base, merged: _merged, pullRequestBase: _baseBranch, ...revision } = reference;
250
- return { name, reference: revision };
251
- });
252
- }
@@ -0,0 +1,27 @@
1
+ import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
2
+ import type { DelegationInputs, DelegationReservation } from '../contracts/delegation.js';
3
+ import { PrerequisiteBlockCode as Code } from '../contracts/vocabulary.js';
4
+ export interface PrerequisiteBlock {
5
+ readonly code: Code;
6
+ readonly reason: string;
7
+ readonly refresh?: DelegationInputs['consumed'];
8
+ }
9
+ export declare function canRefreshInputs(stored: DelegationInputs['consumed'], current: DelegationInputs['consumed'], children: ReadonlyMap<string, DelegationReservation['children'][number]>, artifacts: DelegationArtifacts, revisions: ReadonlyMap<string, ReadonlySet<string>>): Promise<boolean>;
10
+ export declare function freshness(outputs: DelegationInputs['consumed']): ({
11
+ name: string;
12
+ reference: {
13
+ workItemId: import("../../work/index.js").WorkItemId;
14
+ revisionId: string;
15
+ };
16
+ } | {
17
+ name: string;
18
+ reference: {
19
+ workItemId: import("../../work/index.js").WorkItemId;
20
+ resourceId: string;
21
+ repositoryResourceId: string;
22
+ revision: string;
23
+ branch: string;
24
+ };
25
+ })[];
26
+ export declare function changedInputsBlock(...args: Parameters<typeof canRefreshInputs>): Promise<PrerequisiteBlock>;
27
+ export declare function inheritedBlock(block: PrerequisiteBlock): PrerequisiteBlock;
@@ -0,0 +1,53 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { PrerequisiteBlockCode as Code } from '../contracts/vocabulary.js';
3
+ export async function canRefreshInputs(stored, current, children, artifacts, revisions) {
4
+ if (stored.length !== current.length)
5
+ return false;
6
+ for (const [index, next] of current.entries()) {
7
+ const previous = stored[index];
8
+ if (isDeepStrictEqual(freshness([previous]), freshness([next])))
9
+ continue;
10
+ if (!('runId' in previous.reference) || !('runId' in next.reference))
11
+ return false;
12
+ const old = previous.reference;
13
+ const fresh = next.reference;
14
+ if (!sameChange(previous.name, next.name, old, fresh))
15
+ return false;
16
+ const upstream = children.get(fresh.workItemId);
17
+ const activation = await artifacts.runActivation?.(fresh.runId);
18
+ if (upstream === undefined ||
19
+ activation === undefined ||
20
+ !revisions.get(upstream.workflowInstanceId)?.has(activation))
21
+ return false;
22
+ }
23
+ return true;
24
+ }
25
+ export function freshness(outputs) {
26
+ return outputs.map(({ name, reference }) => {
27
+ if (!('runId' in reference))
28
+ return { name, reference };
29
+ const { runId: _run, baseRevision: _base, merged: _merged, pullRequestBase: _baseBranch, ...revision } = reference;
30
+ return { name, reference: revision };
31
+ });
32
+ }
33
+ export async function changedInputsBlock(...args) {
34
+ const refresh = await canRefreshInputs(...args);
35
+ return {
36
+ code: Code.Changed,
37
+ reason: 'Consumed upstream output or base changed; agent assessment required',
38
+ ...(refresh ? { refresh: args[1] } : {}),
39
+ };
40
+ }
41
+ export function inheritedBlock(block) {
42
+ return block.refresh === undefined
43
+ ? block
44
+ : { code: Code.Waiting, reason: 'Waiting for upstream prerequisite refresh' };
45
+ }
46
+ function sameChange(oldName, name, old, fresh) {
47
+ return (oldName === name &&
48
+ old.workItemId === fresh.workItemId &&
49
+ old.resourceId === fresh.resourceId &&
50
+ old.repositoryResourceId === fresh.repositoryResourceId &&
51
+ old.branch === fresh.branch &&
52
+ old.revision !== fresh.revision);
53
+ }
@@ -0,0 +1,4 @@
1
+ import type { WorkflowInstanceView } from '../contracts/views.js';
2
+ import type { OrchestrationRepository } from './orchestration-repository.js';
3
+ /** A review of the old basis cannot approve a new wait with the same watch name. */
4
+ export declare function watchPredatesPrerequisiteRefresh(repository: OrchestrationRepository, child: WorkflowInstanceView): Promise<boolean>;
@@ -0,0 +1,18 @@
1
+ import { OrchestrationEventType as Event } from '../contracts/events.js';
2
+ /** A review of the old basis cannot approve a new wait with the same watch name. */
3
+ export async function watchPredatesPrerequisiteRefresh(repository, child) {
4
+ if (child.parentWorkflowInstanceId === undefined)
5
+ return false;
6
+ const parent = await repository.history(child.parentWorkflowInstanceId);
7
+ const refresh = parent.events
8
+ .filter(({ event }) => event.eventType === Event.DelegationInputsRefreshed)
9
+ .at(-1);
10
+ if (refresh === undefined)
11
+ return false;
12
+ const trigger = parent.events.find(({ event }) => event.eventId === child.triggerId);
13
+ if (trigger !== undefined && trigger.globalPosition < refresh.globalPosition)
14
+ return true;
15
+ const own = await repository.history(child.workflowInstanceId);
16
+ const start = own.events.find(({ event }) => event.eventType === Event.InstanceStarted);
17
+ return start === undefined || start.globalPosition < refresh.globalPosition;
18
+ }
@@ -0,0 +1,15 @@
1
+ import type { DelegationArtifacts } from '../contracts/delegation-ports.js';
2
+ import type { DelegationInputs } from '../contracts/delegation.js';
3
+ import { type WorkflowOrchestrationEvent } from '../contracts/events.js';
4
+ import type { WorkflowInstanceView } from '../contracts/views.js';
5
+ /**
6
+ * Only an accepted watch rejection with an explicit configured stage route opens a revision
7
+ * episode. Every branch activation requested while it is open (retries, quota retries, follow-on
8
+ * stages) belongs to it; the next wait closes it.
9
+ */
10
+ export declare function prerequisiteRevisions(events: readonly WorkflowOrchestrationEvent[]): {
11
+ revisions: Map<string, Set<string>>;
12
+ pending: Map<string, string | undefined>;
13
+ };
14
+ export declare function revisionPending(workflow: WorkflowInstanceView, pending: ReadonlyMap<string, string | undefined>): boolean;
15
+ export declare function revisionOutputPending(workflow: WorkflowInstanceView, reference: DelegationInputs['consumed'][number]['reference'], artifacts: DelegationArtifacts, { pending, revisions }: ReturnType<typeof prerequisiteRevisions>): Promise<boolean>;
@@ -0,0 +1,78 @@
1
+ import { ActivityOutcomeKind } from '../../activities/index.js';
2
+ import { WorkspaceMode } from '../../execution/index.js';
3
+ import { OrchestrationEventType as Event, WatchGateVerdictSignal, } from '../contracts/events.js';
4
+ import { ApprovalAuthorityKind, TransitionTargetKind } from '../contracts/vocabulary.js';
5
+ /**
6
+ * Only an accepted watch rejection with an explicit configured stage route opens a revision
7
+ * episode. Every branch activation requested while it is open (retries, quota retries, follow-on
8
+ * stages) belongs to it; the next wait closes it.
9
+ */
10
+ export function prerequisiteRevisions(events) {
11
+ const waits = new Map();
12
+ const targets = new Map();
13
+ const open = new Set();
14
+ const revisions = new Map();
15
+ const pending = new Map();
16
+ for (const { stream, event } of events) {
17
+ const id = stream.id;
18
+ if (event.eventType === Event.SignalWaitStarted) {
19
+ waits.set(id, event.payload);
20
+ open.delete(id);
21
+ }
22
+ if (event.eventType === Event.SignalAccepted) {
23
+ const target = rejectedRoute(waits.get(id), event.payload);
24
+ if (target !== undefined) {
25
+ targets.set(id, target);
26
+ open.delete(id);
27
+ pending.set(id, undefined);
28
+ }
29
+ waits.delete(id);
30
+ }
31
+ if (event.eventType === Event.DelegationInputsRefreshed) {
32
+ targets.set(id, null);
33
+ open.delete(id);
34
+ }
35
+ if (event.eventType !== Event.ActivityRequested)
36
+ continue;
37
+ if (!inEpisode(id, event.payload, targets, open))
38
+ continue;
39
+ const activation = event.payload.activationId;
40
+ revisions.set(id, new Set(revisions.get(id)).add(activation));
41
+ pending.set(id, activation);
42
+ }
43
+ return { revisions, pending };
44
+ }
45
+ /** The first branch request must hit the configured target; later ones follow the open episode. */
46
+ function inEpisode(id, request, targets, open) {
47
+ const branch = request.execution?.workspace === WorkspaceMode.Branch;
48
+ if (!targets.has(id))
49
+ return open.has(id) && branch;
50
+ const target = targets.get(id);
51
+ targets.delete(id);
52
+ if (!branch || (target !== null && request.stage !== target))
53
+ return false;
54
+ open.add(id);
55
+ return true;
56
+ }
57
+ function rejectedRoute(wait, signal) {
58
+ const acceptedAuthority = signal.authority;
59
+ if (wait?.signalKind === WatchGateVerdictSignal &&
60
+ wait.onRejectResume?.kind === TransitionTargetKind.Stage &&
61
+ signal.kind === WatchGateVerdictSignal &&
62
+ signal.outcome === ActivityOutcomeKind.Rejected &&
63
+ acceptedAuthority?.kind === ApprovalAuthorityKind.Watch &&
64
+ wait.from?.some((authority) => authority.kind === ApprovalAuthorityKind.Watch &&
65
+ authority.watch === acceptedAuthority.watch))
66
+ return wait.onRejectResume.stage;
67
+ return undefined;
68
+ }
69
+ export function revisionPending(workflow, pending) {
70
+ return (pending.has(workflow.workflowInstanceId) &&
71
+ !workflow.acceptedOutcomes.some((id) => id === pending.get(workflow.workflowInstanceId)));
72
+ }
73
+ export async function revisionOutputPending(workflow, reference, artifacts, { pending, revisions }) {
74
+ if (!('runId' in reference) || !pending.has(workflow.workflowInstanceId))
75
+ return false;
76
+ const activation = await artifacts.runActivation?.(reference.runId);
77
+ return activation === undefined || !revisions.get(workflow.workflowInstanceId)?.has(activation);
78
+ }
@@ -0,0 +1,15 @@
1
+ import { type CommandContext } from '@atolis-hq/eventing';
2
+ import type { ActivityName } from '../../activities/index.js';
3
+ import type { DelegationMessages } from '../contracts/delegation-ports.js';
4
+ import type { DelegationInputs, DelegationReservation } from '../contracts/delegation.js';
5
+ import type { OrchestrationRepository } from './orchestration-repository.js';
6
+ import type { StartWorkflow } from './start-workflow.js';
7
+ export interface PrerequisiteRefreshDependencies {
8
+ readonly workflows: StartWorkflow;
9
+ readonly messages?: DelegationMessages | undefined;
10
+ readonly supportsAttention?: ((activity: ActivityName) => boolean) | undefined;
11
+ readonly childRunsEnded?: ((id: string) => Promise<boolean>) | undefined;
12
+ }
13
+ /** Re-enter the child's own branch activity; the agent assesses and performs all Git repairs. */
14
+ export declare function refreshPrerequisites(repository: OrchestrationRepository, dependencies: PrerequisiteRefreshDependencies, child: DelegationReservation['children'][number], inputs: DelegationInputs, context: CommandContext): Promise<void>;
15
+ export declare function prerequisiteRefreshPrompt(inputs: DelegationInputs): string;
@@ -0,0 +1,64 @@
1
+ import { WrongExpectedSequenceError } from '@atolis-hq/eventing';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { WorkspaceMode } from '../../execution/index.js';
4
+ import { OrchestrationEventType as Event } from '../contracts/events.js';
5
+ import { WorkflowStatus } from '../contracts/vocabulary.js';
6
+ import { activation } from '../domain/decision-events.js';
7
+ import { delegationDraft } from './delegation-ledger.js';
8
+ /** Re-enter the child's own branch activity; the agent assesses and performs all Git repairs. */
9
+ export async function refreshPrerequisites(repository, dependencies, child, inputs, context) {
10
+ const loaded = await repository.loadRequired(child.workflowInstanceId);
11
+ const view = loaded.view;
12
+ if (!(await canRefresh(view, dependencies)))
13
+ return;
14
+ const history = await repository.history(child.workflowInstanceId);
15
+ if (history.events.some(({ event }) => event.eventType === Event.DelegationInputsRefreshed &&
16
+ isDeepStrictEqual(event.payload, inputs)))
17
+ return;
18
+ const stageName = branchStage(history.events);
19
+ const definition = await dependencies.workflows.definitionFor(view);
20
+ const stage = definition.stages[stageName];
21
+ if (!dependencies.supportsAttention?.(stage.activity) || dependencies.messages === undefined)
22
+ throw new Error('Prerequisite refresh requires an agent activity and conversation adapter');
23
+ const request = activation(view.workflowInstanceId, history.events.reduce((ordinal, { event }) => event.eventType === Event.ActivityRequested
24
+ ? Math.max(ordinal, event.payload.ordinal + 1)
25
+ : ordinal, 1), stage.activity, stage.with ?? {}, {
26
+ execution: stage.execution,
27
+ stage: stageName,
28
+ sessionPolicy: 'fresh',
29
+ });
30
+ const key = `refresh:${request.activationId}`;
31
+ await dependencies.messages.post({
32
+ workItemId: child.workItemId,
33
+ entryId: key,
34
+ authorId: 'delegation-prerequisites',
35
+ body: prerequisiteRefreshPrompt(inputs),
36
+ }, context);
37
+ try {
38
+ await repository.append(child.workflowInstanceId, loaded.sequence, [
39
+ delegationDraft(context, key, { eventType: Event.DelegationInputsRefreshed, payload: inputs }, child.workflowInstanceId),
40
+ delegationDraft(context, key + ':stage', { eventType: Event.StageEntered, payload: { stage: stageName } }, child.workflowInstanceId),
41
+ delegationDraft(context, key + ':activity', { eventType: Event.ActivityRequested, payload: request }, child.workflowInstanceId),
42
+ ]);
43
+ }
44
+ catch (error) {
45
+ if (!(error instanceof WrongExpectedSequenceError))
46
+ throw error;
47
+ }
48
+ }
49
+ export function prerequisiteRefreshPrompt(inputs) {
50
+ return `An upstream review revision changed your consumed inputs. Assess and refresh your existing work onto the exact verified inputs below. You own all Git operations, including rebase, push and PR updates. Preserve your assignment and run its checks again. Report BLOCKED if you cannot safely refresh. Completion requires a new successful branch run and the configured review gates.\n\n${JSON.stringify(inputs, null, 2)}`;
51
+ }
52
+ async function canRefresh(view, dependencies) {
53
+ return (view.status !== WorkflowStatus.Superseded &&
54
+ view.status !== WorkflowStatus.Blocked &&
55
+ view.delegationFence === undefined &&
56
+ (await dependencies.childRunsEnded?.(view.workflowInstanceId)) === true);
57
+ }
58
+ function branchStage(events) {
59
+ const first = events.find(({ event }) => event.eventType === Event.ActivityRequested &&
60
+ event.payload.execution?.workspace === WorkspaceMode.Branch)?.event;
61
+ if (first?.eventType !== Event.ActivityRequested || first.payload.stage === undefined)
62
+ throw new Error('No branch activity available for prerequisite refresh');
63
+ return first.payload.stage;
64
+ }
@@ -7,6 +7,7 @@ import { childMetadata, childRequestId, coordinationMetadata } from '../domain/c
7
7
  import { coordinationDraft } from '../domain/coordination-events.js';
8
8
  import { stateDraft } from '../domain/decision-events.js';
9
9
  import { acceptSignal as decideSignal } from '../domain/interpreter.js';
10
+ import { watchPredatesPrerequisiteRefresh } from './prerequisite-review-freshness.js';
10
11
  export class RequestChild {
11
12
  repository;
12
13
  claims;
@@ -94,7 +95,9 @@ export class RequestChild {
94
95
  if (child.view.parentWorkflowInstanceId === undefined)
95
96
  return true;
96
97
  const parent = await this.repository.loadRequired(child.view.parentWorkflowInstanceId);
97
- if (child.view.watchId !== undefined && parentWaitsForWatch(parent.view, child.view.watchId))
98
+ if (child.view.watchId !== undefined &&
99
+ parentWaitsForWatch(parent.view, child.view.watchId) &&
100
+ !(await watchPredatesPrerequisiteRefresh(this.repository, child.view)))
98
101
  return true;
99
102
  if (child.view.status !== WorkflowStatus.Superseded)
100
103
  await this.repository.append(childWorkflowInstanceId, child.sequence, [
@@ -125,6 +128,8 @@ export class RequestChild {
125
128
  const parent = await this.repository.loadRequired(metadata.parentWorkflowInstanceId);
126
129
  if (parent.view.acceptedChildCompletionIds.includes(child.workflowInstanceId))
127
130
  return;
131
+ if (await watchPredatesPrerequisiteRefresh(this.repository, child))
132
+ return;
128
133
  const watchGateOutcome = watchGateVerdictOutcome(parent.view, child);
129
134
  const signal = {
130
135
  kind: watchGateOutcome === undefined
@@ -1,9 +1,11 @@
1
1
  import type { CommandContext } from '@atolis-hq/eventing';
2
+ import type { ActivationId } from '../../activities/index.js';
2
3
  import type { RepositoryAssignment } from '../../execution/index.js';
3
4
  import type { DelegatedAssignment, DelegationCaller, DelegationPrerequisite, DelegationReservation, DelegationResult, DelegationRevisionReference, RepositoryAssignmentRequest } from './delegation.js';
4
5
  import type { WorkflowInstanceView } from './views.js';
5
6
  /** Trusted Bootstrap adapters; no provider, Run or session authority is supplied by assignments. */
6
7
  export interface DelegationArtifacts {
8
+ runActivation?(runId: string): Promise<ActivationId | undefined>;
7
9
  prerequisiteOutput?(child: WorkflowInstanceView, output: DelegatedAssignment['outputs'][number], condition: DelegationPrerequisite['condition']): Promise<DelegationResult['outputs'][number] | null>;
8
10
  validateInputs(parent: WorkflowInstanceView, references: readonly DelegationRevisionReference[]): Promise<void>;
9
11
  registerChild(grant: {
@@ -41,6 +41,8 @@ export interface DeliveryIntegration {
41
41
  }
42
42
  export interface DeliveryDependencies {
43
43
  readonly authority: DelegationAuthority;
44
+ /** Execution authority includes active, ambiguous and locally running work. */
45
+ readonly hasUnresolvedRuns?: ((workflowInstanceId: string) => Promise<boolean>) | undefined;
44
46
  /** Resolves a repository source through the parent's own repository authority. */
45
47
  readonly repositories?: DelegationRepositories | undefined;
46
48
  readonly integration?: DeliveryIntegration | undefined;
@@ -226,6 +226,7 @@ const eventSchemas = {
226
226
  [OrchestrationEventType.DelegationChildBlocked]: workflowEnvelope(OrchestrationEventType.DelegationChildBlocked, z
227
227
  .object({ childWorkItemId: brandedStringSchema(workItemId), reason: z.string().min(1) })
228
228
  .strict()),
229
+ [OrchestrationEventType.DelegationInputsRefreshed]: workflowEnvelope(OrchestrationEventType.DelegationInputsRefreshed, delegationInputsSchema),
229
230
  [OrchestrationEventType.DelegationInputsResolved]: workflowEnvelope(OrchestrationEventType.DelegationInputsResolved, delegationInputsSchema),
230
231
  [OrchestrationEventType.DelegationPrerequisiteBlocked]: workflowEnvelope(OrchestrationEventType.DelegationPrerequisiteBlocked, z
231
232
  .object({ childWorkItemId: brandedStringSchema(workItemId), reason: z.string().min(1) })
@@ -4,6 +4,7 @@ import { OrchestrationEventType, } from './events.js';
4
4
  // eslint-disable-next-line complexity, max-lines-per-function
5
5
  export function createOrchestrationEventData(input) {
6
6
  switch (input.eventType) {
7
+ case OrchestrationEventType.DelegationInputsRefreshed:
7
8
  case OrchestrationEventType.DelegationInputsResolved:
8
9
  return createEventData(input);
9
10
  case OrchestrationEventType.DelegationPrerequisiteBlocked:
@@ -10,6 +10,7 @@ import type { ChildOrchestrationGroupStreamId, ChildOrchestrationGroupStreamRef,
10
10
  export declare const OrchestrationEventType: {
11
11
  readonly DelegationReserved: "orchestration.delegation-reserved";
12
12
  readonly DelegationInputsResolved: "orchestration.delegation-inputs-resolved";
13
+ readonly DelegationInputsRefreshed: "orchestration.delegation-inputs-refreshed";
13
14
  readonly DelegationChildBlocked: "orchestration.delegation-child-blocked";
14
15
  readonly DelegationPrerequisiteBlocked: "orchestration.delegation-prerequisite-blocked";
15
16
  readonly DelegationRegistered: "orchestration.delegation-registered";
@@ -70,6 +71,7 @@ export interface OrchestrationEventPayloads {
70
71
  readonly reason: string;
71
72
  };
72
73
  readonly [OrchestrationEventType.DelegationInputsResolved]: DelegationInputs;
74
+ readonly [OrchestrationEventType.DelegationInputsRefreshed]: DelegationInputs;
73
75
  readonly [OrchestrationEventType.DelegationPrerequisiteBlocked]: {
74
76
  readonly childWorkItemId: WorkItemId;
75
77
  readonly reason: string;
@@ -2,6 +2,7 @@ import { signalName } from './identifiers.js';
2
2
  export const OrchestrationEventType = {
3
3
  DelegationReserved: 'orchestration.delegation-reserved',
4
4
  DelegationInputsResolved: 'orchestration.delegation-inputs-resolved',
5
+ DelegationInputsRefreshed: 'orchestration.delegation-inputs-refreshed',
5
6
  DelegationChildBlocked: 'orchestration.delegation-child-blocked',
6
7
  DelegationPrerequisiteBlocked: 'orchestration.delegation-prerequisite-blocked',
7
8
  DelegationRegistered: 'orchestration.delegation-registered',
@@ -0,0 +1,3 @@
1
+ import { WorkflowStatus } from '../contracts/vocabulary.js';
2
+ /** Absence proves eligibility only with durable unsuccessful cohort settlement. */
3
+ export declare function assertReplacementState(status: WorkflowStatus | undefined, unsuccessfullySettled: boolean, hasUnresolvedRuns: boolean): void;
@@ -0,0 +1,16 @@
1
+ import { DelegationConflictError } from '../contracts/delegation.js';
2
+ import { DelegationConflictCode, WorkflowStatus } from '../contracts/vocabulary.js';
3
+ /** Absence proves eligibility only with durable unsuccessful cohort settlement. */
4
+ export function assertReplacementState(status, unsuccessfullySettled, hasUnresolvedRuns) {
5
+ const reject = (message) => {
6
+ throw new DelegationConflictError(DelegationConflictCode.ReplacementUnsupported, message);
7
+ };
8
+ if (status === undefined && !unsuccessfullySettled)
9
+ reject('The child workflow instance is missing; replacement requires an unsuccessfully settled cohort');
10
+ if (status !== undefined &&
11
+ status !== WorkflowStatus.Completed &&
12
+ status !== WorkflowStatus.Superseded)
13
+ reject('Correcting a child that is still running is not supported; replace it once it is complete or superseded');
14
+ if (hasUnresolvedRuns)
15
+ reject('The child has an unresolved run; reconcile it before submitting replacement work');
16
+ }
@@ -214,6 +214,7 @@ function applyCoordinationFact(state, event) {
214
214
  };
215
215
  return;
216
216
  case OrchestrationEventType.DelegationRegistered:
217
+ case OrchestrationEventType.DelegationInputsRefreshed:
217
218
  case OrchestrationEventType.DelegationInputsResolved:
218
219
  case OrchestrationEventType.DelegationPrerequisiteBlocked:
219
220
  case OrchestrationEventType.DelegationChildBlocked:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/wake",
3
- "version": "0.4.119",
3
+ "version": "0.4.121",
4
4
  "description": "Local autonomous agent control plane for software development",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {