@atolis-hq/wake 0.4.113 → 0.4.115

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 (28) hide show
  1. package/dist/src/activities/review/authorization.d.ts +5 -0
  2. package/dist/src/activities/review/authorization.js +3 -2
  3. package/dist/src/bootstrap/external-ref.d.ts +1 -0
  4. package/dist/src/bootstrap/external-ref.js +14 -3
  5. package/dist/src/bootstrap/surface-api-applications.js +3 -1
  6. package/dist/src/bootstrap/version.js +1 -1
  7. package/dist/src/conversations/contracts/events.js +2 -0
  8. package/dist/src/conversations/contracts/views.d.ts +3 -0
  9. package/dist/src/integrations/delivery/application/delivery-service.js +13 -4
  10. package/dist/src/integrations/delivery/contracts/config.d.ts +2 -0
  11. package/dist/src/integrations/delivery/contracts/events.d.ts +2 -0
  12. package/dist/src/integrations/delivery/contracts/events.js +5 -1
  13. package/dist/src/integrations/github/application/conversation-approval-authorization.d.ts +22 -0
  14. package/dist/src/integrations/github/application/conversation-approval-authorization.js +139 -0
  15. package/dist/src/integrations/github/application/inbound-translator.d.ts +3 -0
  16. package/dist/src/integrations/github/application/inbound-translator.js +18 -12
  17. package/dist/src/integrations/github/infrastructure/delivery.d.ts +1 -1
  18. package/dist/src/integrations/github/infrastructure/delivery.js +12 -6
  19. package/dist/src/integrations/github/provider.js +2 -1
  20. package/dist/src/orchestration/application/conversation-command-reactor.js +2 -0
  21. package/dist/src/orchestration/application/conversation-command.d.ts +6 -0
  22. package/dist/src/orchestration/application/conversation-command.js +31 -2
  23. package/dist/src/orchestration/application/orchestration-service.js +4 -1
  24. package/dist/src/surfaces/api/contracts/board.d.ts +1 -0
  25. package/dist/src/surfaces/web-assets/assets/index-BsP1QXQ3.js +1192 -0
  26. package/dist/src/surfaces/web-assets/index.html +1 -1
  27. package/package.json +1 -1
  28. package/dist/src/surfaces/web-assets/assets/index-BDXgDwPe.js +0 -1192
@@ -7,3 +7,8 @@ export declare function isReviewAuthorized(input: {
7
7
  readonly resourceAuthorId: string;
8
8
  readonly authorization: ReviewerAuthorizationEvidence;
9
9
  }): boolean;
10
+ export declare function isTrustedReviewer(input: {
11
+ readonly actorId: string;
12
+ readonly actorKind: typeof ReviewActorKind.Human | typeof ReviewActorKind.Bot;
13
+ readonly authorization: ReviewerAuthorizationEvidence;
14
+ }): boolean;
@@ -2,10 +2,11 @@ import { ProviderPermission, ReviewActorKind, ReviewerAuthorizationSource } from
2
2
  export function isReviewAuthorized(input) {
3
3
  if (input.origin === 'provider-native-review')
4
4
  return true;
5
+ return !sameIdentity(input.actorId, input.resourceAuthorId) && isTrustedReviewer(input);
6
+ }
7
+ export function isTrustedReviewer(input) {
5
8
  if (input.actorKind !== ReviewActorKind.Human)
6
9
  return false;
7
- if (sameIdentity(input.actorId, input.resourceAuthorId))
8
- return false;
9
10
  if (input.authorization.source === ReviewerAuthorizationSource.ConfiguredReviewer)
10
11
  return sameIdentity(input.actorId, input.authorization.reviewerId);
11
12
  if (input.authorization.source !== ReviewerAuthorizationSource.ProviderPermission)
@@ -1,3 +1,4 @@
1
1
  import { type ResourceCorrelationView, type ResourceView } from '../resources/index.js';
2
2
  import type { CompositionRoot } from './composition-root.js';
3
3
  export declare function primaryExternalRef(root: CompositionRoot, rawWorkItemId: string, suppliedCorrelations?: readonly ResourceCorrelationView[], suppliedResources?: readonly ResourceView[]): Promise<string | undefined>;
4
+ export declare function primaryRepository(root: CompositionRoot, rawWorkItemId: string): Promise<string | undefined>;
@@ -3,11 +3,22 @@ import { workItemId } from '../work/index.js';
3
3
  // Work items never embed a provider/repo/issue number (see project/adrs/0001); this joins
4
4
  // the primary correlated resource's adapter-formatted key at the presentation layer only.
5
5
  export async function primaryExternalRef(root, rawWorkItemId, suppliedCorrelations, suppliedResources) {
6
+ const resource = await primaryResource(root, rawWorkItemId, suppliedCorrelations, suppliedResources);
7
+ return resource?.externalKey.key;
8
+ }
9
+ // Generic "repository" display field; only adapters that know a repository identity supply one.
10
+ export async function primaryRepository(root, rawWorkItemId) {
11
+ const resource = await primaryResource(root, rawWorkItemId);
12
+ return resource === undefined
13
+ ? undefined
14
+ : root.resolveResourceRepositoryIdentity(resource.externalKey);
15
+ }
16
+ async function primaryResource(root, rawWorkItemId, suppliedCorrelations, suppliedResources) {
6
17
  const correlations = suppliedCorrelations ?? (await root.resources.correlationsForWork(workItemId(rawWorkItemId)));
7
18
  const primary = correlations.find((value) => value.role === ResourceCorrelationRole.Primary);
8
19
  if (primary === undefined)
9
20
  return undefined;
10
- const resource = suppliedResources?.find((value) => value.resourceId === primary.resourceId) ??
11
- (await root.resources.get(primary.resourceId));
12
- return resource?.externalKey.key;
21
+ return (suppliedResources?.find((value) => value.resourceId === primary.resourceId) ??
22
+ (await root.resources.get(primary.resourceId)) ??
23
+ undefined);
13
24
  }
@@ -3,7 +3,7 @@ import { ApiCommandStatus, ApiHealthCheckKind, fromWorkItemKey, presentBoardCard
3
3
  import { analyticsProjection } from './analytics-projection.js';
4
4
  import { createAnalyticsReports } from './analytics-reports.js';
5
5
  import { boardConditionCounts, boardProjection, normalizeBoardActiveRunPhase, } from './board-projection.js';
6
- import { primaryExternalRef } from './external-ref.js';
6
+ import { primaryExternalRef, primaryRepository } from './external-ref.js';
7
7
  import { createSelfUpdateFailureLog, describeSelfUpdateFailure, } from './self-update-failure-log.js';
8
8
  import { createExecutionApplications } from './surface-api-execution-applications.js';
9
9
  import { projectionMeta, sampledMeta } from './surface-api-metadata.js';
@@ -41,6 +41,7 @@ function createBoardApplications(root, now) {
41
41
  const page = cards.slice(offset, offset + query.limit);
42
42
  const items = await Promise.all(page.map(async (card) => {
43
43
  const externalRef = await primaryExternalRef(root, card.workItemId);
44
+ const repository = await primaryRepository(root, card.workItemId);
44
45
  const { activeRun: _legacyActiveRun, activeRuns: _activeRuns, ...withoutActiveRuns } = card;
45
46
  const activeRuns = activeBoardRuns(board, card);
46
47
  return presentBoardCard({
@@ -51,6 +52,7 @@ function createBoardApplications(root, now) {
51
52
  { ...activeRun, elapsedMs: elapsedSince(activeRun.startedAt, nowMs) },
52
53
  ])),
53
54
  ...(externalRef === undefined ? {} : { externalRef }),
55
+ ...(repository === undefined ? {} : { repository }),
54
56
  ...(card.lastRunAt === undefined
55
57
  ? {}
56
58
  : { lastRunAgeMs: elapsedSince(card.lastRunAt, nowMs) }),
@@ -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.113";
127
+ export const wakeVersion = "v0.4.115";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -41,6 +41,8 @@ const origin = z.discriminatedUnion('kind', [
41
41
  messageId: z.string().min(1),
42
42
  authorized: z.boolean().optional(),
43
43
  reviewAuthorized: z.boolean().optional(),
44
+ approvalRejectionReason: z.string().min(1).optional(),
45
+ approvalSubjects: z.array(z.string().min(1)).readonly().optional(),
44
46
  canClarify: z.boolean().optional(),
45
47
  capabilities: z.array(z.string().min(1)).readonly().optional(),
46
48
  location: z
@@ -20,6 +20,9 @@ export type ConversationEntryOrigin = {
20
20
  readonly authorized?: boolean | undefined;
21
21
  /** Independent-review authority, separate from work control. */
22
22
  readonly reviewAuthorized?: boolean | undefined;
23
+ /** Surface attribution decision and opaque wait subjects for approval commands. */
24
+ readonly approvalRejectionReason?: string | undefined;
25
+ readonly approvalSubjects?: readonly string[] | undefined;
23
26
  /** Whether this participant may answer a clarification without control authority. */
24
27
  readonly canClarify?: boolean | undefined;
25
28
  /** Commands available to this entry's receiving surface. */
@@ -79,7 +79,7 @@ export class DeliveryService {
79
79
  const result = await adapter.deliver(intent, signal);
80
80
  switch (result.kind) {
81
81
  case DeliveryResultKind.Confirmed:
82
- await this.append(intent, this.confirmed(intent, occurrence, result.externalId));
82
+ await this.append(intent, this.confirmed(intent, occurrence, result.externalId, result.producerId));
83
83
  break;
84
84
  case DeliveryResultKind.Failed:
85
85
  await this.append(intent, this.failed(intent, occurrence, result.code, result.message));
@@ -134,11 +134,15 @@ export class DeliveryService {
134
134
  payload: this.correlation(intent, occurrence),
135
135
  };
136
136
  }
137
- confirmed(intent, occurrence, externalId) {
137
+ confirmed(intent, occurrence, externalId, producerId) {
138
138
  return {
139
139
  ...this.metadata(intent, occurrence, DeliveryEventType.Confirmed),
140
140
  eventType: DeliveryEventType.Confirmed,
141
- payload: { ...this.correlation(intent, occurrence), externalId },
141
+ payload: {
142
+ ...this.correlation(intent, occurrence),
143
+ externalId,
144
+ ...(producerId === undefined ? {} : { producerId }),
145
+ },
142
146
  };
143
147
  }
144
148
  failed(intent, occurrence, code, message) {
@@ -173,7 +177,12 @@ export class DeliveryService {
173
177
  return {
174
178
  ...metadata,
175
179
  eventType: DeliveryEventType.Reconciled,
176
- payload: { ...correlation, result: result.kind, externalId: result.externalId },
180
+ payload: {
181
+ ...correlation,
182
+ result: result.kind,
183
+ externalId: result.externalId,
184
+ ...(result.producerId === undefined ? {} : { producerId: result.producerId }),
185
+ },
177
186
  };
178
187
  case DeliveryResultKind.NotFound:
179
188
  case DeliveryResultKind.Unknown:
@@ -7,6 +7,7 @@ export interface ExternalDeliveryAdapter {
7
7
  export type DeliveryResult = {
8
8
  readonly kind: typeof DeliveryResultKind.Confirmed;
9
9
  readonly externalId: string;
10
+ readonly producerId?: string;
10
11
  } | {
11
12
  readonly kind: typeof DeliveryResultKind.Failed;
12
13
  readonly code: string;
@@ -18,6 +19,7 @@ export type DeliveryResult = {
18
19
  export type ReconciliationResult = {
19
20
  readonly kind: typeof DeliveryResultKind.Confirmed;
20
21
  readonly externalId: string;
22
+ readonly producerId?: string;
21
23
  } | {
22
24
  readonly kind: typeof DeliveryResultKind.NotFound;
23
25
  } | {
@@ -21,6 +21,7 @@ export interface DeliveryEventPayloads {
21
21
  readonly [DeliveryEventType.AttemptStarted]: DeliveryEventCorrelation;
22
22
  readonly [DeliveryEventType.Confirmed]: DeliveryEventCorrelation & {
23
23
  readonly externalId: string;
24
+ readonly producerId?: string | undefined;
24
25
  };
25
26
  readonly [DeliveryEventType.Failed]: DeliveryEventCorrelation & {
26
27
  readonly code: string;
@@ -35,6 +36,7 @@ export interface DeliveryEventPayloads {
35
36
  readonly [DeliveryEventType.Reconciled]: DeliveryEventCorrelation & ({
36
37
  readonly result: typeof DeliveryResultKind.Confirmed;
37
38
  readonly externalId: string;
39
+ readonly producerId?: string | undefined;
38
40
  } | {
39
41
  readonly result: typeof DeliveryResultKind.NotFound | typeof DeliveryResultKind.Unknown;
40
42
  readonly externalId?: never;
@@ -31,6 +31,7 @@ const reconciledPayloadSchema = z.discriminatedUnion('result', [
31
31
  correlationSchema.extend({
32
32
  result: z.literal(DeliveryResultKind.Confirmed),
33
33
  externalId: z.string().min(1),
34
+ producerId: z.string().min(1).optional(),
34
35
  }),
35
36
  correlationSchema.extend({ result: z.literal(DeliveryResultKind.NotFound) }),
36
37
  correlationSchema.extend({ result: z.literal(DeliveryResultKind.Unknown) }),
@@ -47,7 +48,10 @@ const eventSchema = z
47
48
  eventEnvelopeSchema.extend({
48
49
  event: eventDataSchema.extend({
49
50
  eventType: z.literal(DeliveryEventType.Confirmed),
50
- payload: correlationSchema.extend({ externalId: z.string().min(1) }),
51
+ payload: correlationSchema.extend({
52
+ externalId: z.string().min(1),
53
+ producerId: z.string().min(1).optional(),
54
+ }),
51
55
  }),
52
56
  stream: deliveryStreamSchema,
53
57
  }),
@@ -0,0 +1,22 @@
1
+ import type { EventJournal } from '@atolis-hq/eventing';
2
+ import { type OrchestrationService } from '../../../orchestration/index.js';
3
+ import { type ResourceService, type ResourceView } from '../../../resources/index.js';
4
+ import type { WorkItemId } from '../../../work/index.js';
5
+ import type { AdapterId } from '../../contracts/identifiers.js';
6
+ import { GitHubEventType, type GitHubAdapterEventOf } from '../contracts/events.js';
7
+ interface Authorization {
8
+ readonly reviewAuthorized: boolean;
9
+ readonly approvalRejectionReason?: string;
10
+ readonly approvalSubjects?: readonly string[];
11
+ }
12
+ export declare function conversationReviewAuthorization(input: {
13
+ readonly event: GitHubAdapterEventOf<typeof GitHubEventType.CommentObserved>;
14
+ readonly journal: EventJournal;
15
+ readonly resources: ResourceService;
16
+ readonly resource: ResourceView;
17
+ readonly workItemId: WorkItemId;
18
+ readonly adapter: AdapterId;
19
+ readonly orchestration?: OrchestrationService | undefined;
20
+ readonly authenticatedLogin?: (() => Promise<string>) | undefined;
21
+ }): Promise<Authorization>;
22
+ export {};
@@ -0,0 +1,139 @@
1
+ import { isReviewAuthorized, isTrustedReviewer, ReviewerAuthorizationSource, } from '../../../activities/index.js';
2
+ import { conversationApprovalSubject, isHumanConversationApprovalWait, } from '../../../orchestration/index.js';
3
+ import { BuiltInResourceKind, resourceId, resourceStream, } from '../../../resources/index.js';
4
+ import { deliveryStream, integrationStream } from '../../contracts/streams.js';
5
+ import { DeliveryEventType, selectDeliveryEvent } from '../../delivery/contracts/events.js';
6
+ import { DeliveryIntentEventType, selectDeliveryIntentEvent, } from '../../delivery/contracts/intents.js';
7
+ import { DeliveryResultKind } from '../../delivery/contracts/vocabulary.js';
8
+ import { GitHubEventType, selectGitHubAdapterEvent, } from '../contracts/events.js';
9
+ import { GitHubBuiltInCommand, UnknownGitHubIdentity } from '../contracts/vocabulary.js';
10
+ import { formatAgentRunComment } from './agent-run-comment.js';
11
+ import { isHumanNonWakeReply, recognizedCommand } from './inbound-comment-syntax.js';
12
+ export async function conversationReviewAuthorization(input) {
13
+ const reviewAuthorized = trustedConversationReviewer(input.event);
14
+ if (!isApproval(input.event.event.payload.body) || !reviewAuthorized)
15
+ return { reviewAuthorized };
16
+ const workflows = ((await input.orchestration?.listAll()) ?? []).filter((workflow) => workflow.workItemId === input.workItemId && isHumanConversationApprovalWait(workflow));
17
+ const approvalSubjects = workflows.map(conversationApprovalSubject);
18
+ for (const workflow of workflows) {
19
+ const approvalRejectionReason = await artifactRejection(input, workflow);
20
+ if (approvalRejectionReason !== undefined)
21
+ return { reviewAuthorized, approvalSubjects, approvalRejectionReason };
22
+ }
23
+ return { reviewAuthorized, approvalSubjects };
24
+ }
25
+ function isApproval(body) {
26
+ const command = recognizedCommand(body);
27
+ return command === GitHubBuiltInCommand.Approved || command === GitHubBuiltInCommand.Accepted;
28
+ }
29
+ function trustedConversationReviewer(event) {
30
+ const { actor, authorization, resourceAuthorId, body } = event.event.payload;
31
+ if (!isHumanNonWakeReply(actor.kind, body))
32
+ return false;
33
+ const reviewer = {
34
+ actorId: actor.id,
35
+ actorKind: actor.kind,
36
+ authorization: authorization ?? { source: ReviewerAuthorizationSource.None },
37
+ };
38
+ return isApproval(body)
39
+ ? isTrustedReviewer(reviewer)
40
+ : isReviewAuthorized({
41
+ ...reviewer,
42
+ resourceAuthorId: resourceAuthorId ?? UnknownGitHubIdentity,
43
+ });
44
+ }
45
+ async function artifactRejection(input, workflow) {
46
+ const target = workflow.waitingFor?.resourceId === undefined
47
+ ? input.resource
48
+ : await input.resources.get(resourceId(workflow.waitingFor.resourceId));
49
+ if (target === null)
50
+ return unknownAttribution;
51
+ const pr = target.kind === BuiltInResourceKind.PullRequest;
52
+ const author = pr ? await pullRequestAuthor(input, target) : await planProducer(input, workflow);
53
+ if (author === undefined || author.toLowerCase() === UnknownGitHubIdentity)
54
+ return unknownAttribution;
55
+ if (input.event.event.payload.actor.id.toLowerCase() !== author.toLowerCase())
56
+ return undefined;
57
+ return pr
58
+ ? 'Self-approval denied: the approver is the PR author.'
59
+ : 'Self-approval denied: the approver is the artifact producer.';
60
+ }
61
+ const unknownAttribution = 'Approval attribution is unknown or ambiguous for the artifact under review.';
62
+ async function pullRequestAuthor(input, target) {
63
+ if (target.externalKey.adapter !== input.adapter)
64
+ return undefined;
65
+ if (target.resourceId === input.resource.resourceId)
66
+ return input.event.event.payload.resourceAuthorId;
67
+ const observations = (await input.journal.readStream(integrationStream(input.adapter))).map(selectGitHubAdapterEvent);
68
+ const latest = observations
69
+ .reverse()
70
+ .find((event) => event?.event.eventType === GitHubEventType.WorkObserved &&
71
+ event.event.payload.externalKey === target.externalKey.key);
72
+ return latest?.event.eventType === GitHubEventType.WorkObserved &&
73
+ latest.event.payload.kind === BuiltInResourceKind.PullRequest
74
+ ? latest.event.payload.resourceAuthorId
75
+ : undefined;
76
+ }
77
+ async function planProducer(input, workflow) {
78
+ if (workflow.pendingActivation === undefined)
79
+ return undefined;
80
+ const producers = new Set();
81
+ for (const correlation of await input.resources.correlationsForWork(input.workItemId)) {
82
+ const resource = await input.resources.get(correlation.resourceId);
83
+ if (resource?.externalKey.adapter !== input.adapter)
84
+ continue;
85
+ const facts = await input.journal.readStream(resourceStream(resource.resourceId));
86
+ for (const fact of facts) {
87
+ const intent = selectDeliveryIntentEvent(fact);
88
+ if (intent === null)
89
+ continue;
90
+ const accounts = await publicationProducers(input, workflow, intent);
91
+ if (accounts === undefined)
92
+ return undefined;
93
+ for (const account of accounts)
94
+ producers.add(account.toLowerCase());
95
+ }
96
+ }
97
+ return producers.size === 1 ? [...producers][0] : undefined;
98
+ }
99
+ async function publicationProducers(input, workflow, intent) {
100
+ if (intent.event.eventType !== DeliveryIntentEventType.AgentRunPublishRequested ||
101
+ intent.event.payload.workflowInstanceId !== workflow.workflowInstanceId ||
102
+ intent.event.payload.activationId !== workflow.pendingActivation?.activationId)
103
+ return [];
104
+ const producers = [];
105
+ const facts = await input.journal.readStream(deliveryStream(intent.event.eventId));
106
+ for (const fact of facts) {
107
+ const confirmation = confirmedPublication(selectDeliveryEvent(fact));
108
+ if (confirmation === null)
109
+ continue;
110
+ let producer = confirmation.producerId;
111
+ // GitHub agent publications carry the Wake marker in their delivered representation.
112
+ if (producer === undefined &&
113
+ formatAgentRunComment({
114
+ ...intent.event.payload.report,
115
+ idempotencyKey: intent.event.eventId,
116
+ }).includes('<!-- wake:agent -->'))
117
+ producer = await legacyProducer(input.authenticatedLogin);
118
+ if (producer === undefined || producer.trim() === '')
119
+ return undefined;
120
+ producers.push(producer);
121
+ }
122
+ return producers;
123
+ }
124
+ function confirmedPublication(fact) {
125
+ if (fact?.event.eventType === DeliveryEventType.Confirmed)
126
+ return fact.event.payload;
127
+ if (fact?.event.eventType === DeliveryEventType.Reconciled &&
128
+ fact.event.payload.result === DeliveryResultKind.Confirmed)
129
+ return fact.event.payload;
130
+ return null;
131
+ }
132
+ async function legacyProducer(authenticatedLogin) {
133
+ try {
134
+ return await authenticatedLogin?.();
135
+ }
136
+ catch {
137
+ return undefined;
138
+ }
139
+ }
@@ -45,6 +45,7 @@ interface InboundTranslatorDependencies {
45
45
  readonly conclusion?: WorkConclusion;
46
46
  readonly conversations?: ConversationService;
47
47
  readonly conversationCapabilities?: readonly ConversationSurfaceCapability[];
48
+ readonly authenticatedLogin?: () => Promise<string>;
48
49
  }
49
50
  export declare class InboundTranslator {
50
51
  private readonly journal?;
@@ -55,6 +56,7 @@ export declare class InboundTranslator {
55
56
  readonly reconciler: ProviderReconciler;
56
57
  translate(payload: ExternalWorkObservedPayload): readonly InboundCommandCandidate[];
57
58
  constructor(journal?: EventJournal | undefined, work?: WorkService | undefined, resources?: ResourceService | undefined, dependencies?: InboundTranslatorDependencies);
59
+ private readonly authenticatedLogin;
58
60
  private readonly pullRequests;
59
61
  private readonly ids;
60
62
  private readonly lookup;
@@ -82,6 +84,7 @@ export declare class InboundTranslator {
82
84
  private recordConversationDeferred;
83
85
  private appendConversationRecordFact;
84
86
  private recordConversationEntry;
87
+ private reviewAuthorization;
85
88
  private failureRecorded;
86
89
  private retryRecorded;
87
90
  private recordTranslationRecovery;
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable max-lines */
2
2
  import { correlationId, defineEventProcessor, EventActorKind, EventProcessorCategory, EventProcessorReplayPolicy, EventSourceKind, WrongExpectedSequenceError, } from '@atolis-hq/eventing';
3
- import { ActivityEventType, createPullRequestService, isReviewAuthorized, ReviewerAuthorizationSource, selectActivityEvent, } from '../../../activities/index.js';
3
+ import { ActivityEventType, createPullRequestService, ReviewerAuthorizationSource, selectActivityEvent, } from '../../../activities/index.js';
4
4
  import { conversationIdForWorkItem, ConversationOriginKind, } from '../../../conversations/index.js';
5
5
  import { UlidIdGenerator } from '../../../kernel/index.js';
6
6
  import { BuiltInResourceCapability, BuiltInResourceKind, ResourceCorrelationRole, ResourceEventType, resourceId, resourceStream, selectResourceEvent, } from '../../../resources/index.js';
@@ -12,7 +12,8 @@ import { deliveryStream, integrationStream } from '../../contracts/streams.js';
12
12
  import { DeliveryEventType, selectDeliveryEvent } from '../../delivery/contracts/events.js';
13
13
  import { createGitHubEventData } from '../contracts/event-factory.js';
14
14
  import { GitHubEventType, selectGitHubAdapterEvent } from '../contracts/events.js';
15
- import { GitHubAdapter, UnknownGitHubIdentity } from '../contracts/vocabulary.js';
15
+ import { GitHubAdapter } from '../contracts/vocabulary.js';
16
+ import { conversationReviewAuthorization } from './conversation-approval-authorization.js';
16
17
  import { isHumanNonWakeReply } from './inbound-comment-syntax.js';
17
18
  import { commandContext } from './inbound-context.js';
18
19
  import { applyReviewSignal } from './inbound-review-signals.js';
@@ -54,6 +55,7 @@ export class InboundTranslator {
54
55
  this.journal = journal;
55
56
  this.work = work;
56
57
  this.resources = resources;
58
+ this.authenticatedLogin = dependencies.authenticatedLogin;
57
59
  this.pullRequests = dependencies.pullRequests;
58
60
  this.ids = dependencies.ids ?? new UlidIdGenerator();
59
61
  this.lookup = dependencies.lookup;
@@ -76,6 +78,7 @@ export class InboundTranslator {
76
78
  });
77
79
  this.reconciler = { reconcileOnce: () => this.reconcileOnce() };
78
80
  }
81
+ authenticatedLogin;
79
82
  pullRequests;
80
83
  ids;
81
84
  lookup;
@@ -297,7 +300,7 @@ export class InboundTranslator {
297
300
  threadId: resource.externalKey.key,
298
301
  messageId: externalId,
299
302
  authorized: isAuthorizedWorkControlActor(event),
300
- reviewAuthorized: isAuthorizedConversationActor(event),
303
+ ...(await this.reviewAuthorization(event, resource, correlation.workItemId)),
301
304
  canClarify: isHumanNonWakeReply(event.event.payload.actor.kind, event.event.payload.body),
302
305
  capabilities: this.conversationCapabilities,
303
306
  ...(event.event.payload.reviewKind !== 'issue' ||
@@ -307,6 +310,18 @@ export class InboundTranslator {
307
310
  },
308
311
  }, commandContext(event));
309
312
  }
313
+ reviewAuthorization(event, resource, workItemId) {
314
+ return conversationReviewAuthorization({
315
+ event,
316
+ journal: this.journal,
317
+ resources: this.resources,
318
+ resource,
319
+ workItemId,
320
+ adapter: this.adapter,
321
+ orchestration: this.orchestration,
322
+ authenticatedLogin: this.authenticatedLogin,
323
+ });
324
+ }
310
325
  async failureRecorded(sourceEventId) {
311
326
  return (await this.journal.readStream(integrationStream(this.adapter))).some((event) => {
312
327
  const owned = selectGitHubAdapterEvent(event);
@@ -764,15 +779,6 @@ export class InboundTranslator {
764
779
  }
765
780
  }
766
781
  }
767
- function isAuthorizedConversationActor(event) {
768
- const { actor, authorization, resourceAuthorId } = event.event.payload;
769
- return isReviewAuthorized({
770
- actorId: actor.id,
771
- actorKind: actor.kind,
772
- resourceAuthorId: resourceAuthorId ?? UnknownGitHubIdentity,
773
- authorization: authorization ?? { source: ReviewerAuthorizationSource.None },
774
- });
775
- }
776
782
  function observedCommentExternalId(event) {
777
783
  const id = event.event.payload.raw.id;
778
784
  return typeof id === 'string' || typeof id === 'number' ? String(id) : event.event.eventId;
@@ -3,4 +3,4 @@ import type { DeliveryIntentView } from '../../delivery/contracts/views.js';
3
3
  export declare function createGitHubDelivery(deliver: (intent: DeliveryIntentView, idempotencyKey: string) => Promise<string>, reconcileIssue?: (intent: DeliveryIntentView) => Promise<string | null>, precondition?: (intent: DeliveryIntentView) => Promise<{
4
4
  readonly allowed: boolean;
5
5
  readonly reason?: string;
6
- }>, mergedTarget?: (intent: DeliveryIntentView) => Promise<string | null>): ExternalDeliveryAdapter;
6
+ }>, mergedTarget?: (intent: DeliveryIntentView) => Promise<string | null>, authenticatedLogin?: () => Promise<string>): ExternalDeliveryAdapter;
@@ -1,13 +1,22 @@
1
1
  import { BuiltInActivityName } from '../../../activities/index.js';
2
- import { DeliveryResultKind } from '../../delivery/contracts/vocabulary.js';
2
+ import { DeliveryIntentKind, DeliveryResultKind } from '../../delivery/contracts/vocabulary.js';
3
3
  const GitHubDeliveryFailureCode = 'github-error';
4
- export function createGitHubDelivery(deliver, reconcileIssue, precondition, mergedTarget) {
4
+ export function createGitHubDelivery(deliver, reconcileIssue, precondition, mergedTarget, authenticatedLogin) {
5
5
  async function confirmedMerge(intent) {
6
6
  if (intent.kind !== BuiltInActivityName.PullRequestMerge)
7
7
  return null;
8
8
  const externalId = await mergedTarget?.(intent);
9
9
  return externalId == null ? null : { kind: DeliveryResultKind.Confirmed, externalId };
10
10
  }
11
+ async function publish(intent) {
12
+ // Resolve identity before publishing so an identity failure cannot lose a successful delivery.
13
+ const producerId = intent.kind === DeliveryIntentKind.AgentRunPublish ? await authenticatedLogin?.() : undefined;
14
+ return {
15
+ kind: DeliveryResultKind.Confirmed,
16
+ externalId: await deliver(intent, intent.intentEventId),
17
+ ...(producerId === undefined ? {} : { producerId }),
18
+ };
19
+ }
11
20
  return {
12
21
  async deliver(intent) {
13
22
  try {
@@ -21,10 +30,7 @@ export function createGitHubDelivery(deliver, reconcileIssue, precondition, merg
21
30
  if (result !== undefined && !result.allowed)
22
31
  throw new Error(result.reason ?? 'auto-merge precondition failed');
23
32
  }
24
- return {
25
- kind: DeliveryResultKind.Confirmed,
26
- externalId: await deliver(intent, intent.intentEventId),
27
- };
33
+ return await publish(intent);
28
34
  }
29
35
  catch (error) {
30
36
  try {
@@ -45,6 +45,7 @@ export const gitHubProviderDefinition = {
45
45
  conclusion: services.conclusion,
46
46
  conversations: services.conversations,
47
47
  conversationCapabilities,
48
+ authenticatedLogin: () => requests.run(() => client.authenticatedLogin()),
48
49
  });
49
50
  return {
50
51
  adapter,
@@ -168,7 +169,7 @@ export const gitHubProviderDefinition = {
168
169
  return null;
169
170
  const pr = await client.getPullRequest(parsed.owner, parsed.repo, parsed.number);
170
171
  return pr.merged && pr.head.sha === intent.payload.revision ? String(pr.id) : null;
171
- }),
172
+ }, () => requests.run(() => client.authenticatedLogin())),
172
173
  verifyArtifact: async (kind, externalKey, context) => {
173
174
  if (kind !== resourceKind('pull-request'))
174
175
  return ArtifactVerificationResult.NotFound;
@@ -36,6 +36,8 @@ export function createConversationCommandReactor(orchestration, feedback) {
36
36
  authorized: entry.origin.authorized === true,
37
37
  // Legacy entries authorized commands only after enforcing review independence.
38
38
  reviewAuthorized: entry.origin.reviewAuthorized ?? entry.origin.authorized === true,
39
+ approvalRejectionReason: entry.origin.approvalRejectionReason,
40
+ approvalSubjects: entry.origin.approvalSubjects,
39
41
  };
40
42
  const context = {
41
43
  commandId: `${event.eventId}:conversation-command`,
@@ -16,6 +16,8 @@ export interface ConversationCommandInput {
16
16
  readonly authorized: boolean;
17
17
  /** Independent-review authority must be supplied explicitly. */
18
18
  readonly reviewAuthorized?: boolean;
19
+ readonly approvalRejectionReason?: string | undefined;
20
+ readonly approvalSubjects?: readonly string[] | undefined;
19
21
  /** Explicit continuation reenters the agent stage without a review decision. */
20
22
  readonly continuation?: boolean;
21
23
  }
@@ -42,4 +44,8 @@ interface BuiltInConversationCommandInput {
42
44
  }
43
45
  export declare function applyBuiltInConversationCommand(input: BuiltInConversationCommandInput): Promise<ConversationCommandResult>;
44
46
  export declare function continuationCommandRejection(input: ConversationCommandInput, command: string): string | null;
47
+ /** Binds surface approval evidence to the exact wait observed at intake. */
48
+ export declare function conversationApprovalSubject(workflow: WorkflowInstanceView): string;
49
+ export declare function conversationApprovalRejection(command: string, input: ConversationCommandInput, workflows: readonly WorkflowInstanceView[]): string | undefined;
50
+ export declare function isHumanConversationApprovalWait(workflow: WorkflowInstanceView): boolean;
45
51
  export {};
@@ -1,5 +1,5 @@
1
1
  import { ActivityOutcomeKind } from '../../activities/index.js';
2
- import { ConversationBuiltInCommand, ConversationSurfaceCapability, } from '../contracts/vocabulary.js';
2
+ import { ApprovalAuthorityKind, ConversationBuiltInCommand, ConversationSurfaceCapability, } from '../contracts/vocabulary.js';
3
3
  import { isGroupBudgetExtensionEligible, isOperatorRetryEligible, selectChangesResumeTargets, selectOperatorRetryTarget, } from '../domain/operator-retry-policy.js';
4
4
  export const BuiltInConversationCommands = Object.values(ConversationBuiltInCommand);
5
5
  export function conversationCommand(body) {
@@ -34,7 +34,7 @@ export async function applyBuiltInConversationCommand(input) {
34
34
  if (input.command === ConversationBuiltInCommand.Approved ||
35
35
  input.command === ConversationBuiltInCommand.Accepted) {
36
36
  if (!input.reviewAuthorized)
37
- return denied('Independent-review authority is required. An author cannot approve their own work; clarification uses /changes with instructions.');
37
+ return denied('Independent-review authority is required: the approver must be a trusted human reviewer.');
38
38
  let applied = false;
39
39
  for (const workflow of input.workflows)
40
40
  if (workflow.waitingFor !== undefined)
@@ -82,3 +82,32 @@ export function continuationCommandRejection(input, command) {
82
82
  return 'Supply instructions after /changes to continue the blocked stage.';
83
83
  return null;
84
84
  }
85
+ /** Binds surface approval evidence to the exact wait observed at intake. */
86
+ export function conversationApprovalSubject(workflow) {
87
+ return JSON.stringify([
88
+ workflow.workflowInstanceId,
89
+ workflow.pendingActivation?.activationId,
90
+ workflow.waitingFor?.signalKind,
91
+ workflow.waitingFor?.waitStartedAt,
92
+ workflow.waitingFor?.resourceId,
93
+ workflow.waitingFor?.revision,
94
+ ]);
95
+ }
96
+ export function conversationApprovalRejection(command, input, workflows) {
97
+ if (command !== ConversationBuiltInCommand.Approved &&
98
+ command !== ConversationBuiltInCommand.Accepted)
99
+ return undefined;
100
+ if (input.approvalRejectionReason !== undefined)
101
+ return input.approvalRejectionReason;
102
+ if (input.approvalSubjects !== undefined &&
103
+ workflows.some((workflow) => isHumanConversationApprovalWait(workflow) &&
104
+ !input.approvalSubjects.includes(conversationApprovalSubject(workflow))))
105
+ return 'Approval attribution is unknown for the current wait; the reviewed subject changed.';
106
+ return undefined;
107
+ }
108
+ export function isHumanConversationApprovalWait(workflow) {
109
+ const wait = workflow.waitingFor;
110
+ return (wait !== undefined &&
111
+ (wait.from === undefined ||
112
+ wait.from.some((authority) => authority.kind === ApprovalAuthorityKind.Human)));
113
+ }
@@ -16,7 +16,7 @@ import { isGroupBudgetExtensionEligible, isNeedsClarificationResumeEligible, isP
16
16
  import { AcceptActivityOutcome } from './accept-activity-outcome.js';
17
17
  import { AcceptSignal } from './accept-signal.js';
18
18
  import { AdvanceWorkflow } from './advance-workflow.js';
19
- import { applyBuiltInConversationCommand, continuationCommandRejection, conversationCommand, } from './conversation-command.js';
19
+ import { applyBuiltInConversationCommand, continuationCommandRejection, conversationApprovalRejection, conversationCommand, } from './conversation-command.js';
20
20
  import { CoordinationClaims } from './coordination-claims.js';
21
21
  import { attentionVerdict } from './delegation-attention-state.js';
22
22
  import { GroupBudgetRecorder } from './group-budget-recorder.js';
@@ -255,6 +255,9 @@ export class OrchestrationService {
255
255
  const workflows = (await this.advanceWorkflow.listAll()).filter((workflow) => workflow.workItemId === workItemId);
256
256
  if (conversationCommandAlreadyApplied(workflows, context.commandId))
257
257
  return { applied: true };
258
+ const approvalRejection = conversationApprovalRejection(command, input, workflows);
259
+ if (approvalRejection !== undefined)
260
+ return { applied: false, reason: approvalRejection };
258
261
  const work = await this.work.get(workItemId);
259
262
  if (!isWorkControllable(work))
260
263
  return { applied: false, reason: 'Work item must be open, unfrozen, and not deleted.' };
@@ -46,6 +46,7 @@ export interface BoardCardResponse {
46
46
  readonly totalCostUsd: number;
47
47
  readonly totalDurationMs: number;
48
48
  readonly externalRef?: string;
49
+ readonly repository?: string;
49
50
  }
50
51
  export interface BoardResponse {
51
52
  readonly conditionCounts: Partial<Record<BoardCardCondition, number>>;