@atolis-hq/wake 0.4.63 → 0.4.64

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 (36) hide show
  1. package/dist/src/artifacts/application/artifact-context-service.d.ts +30 -0
  2. package/dist/src/artifacts/application/artifact-context-service.js +189 -0
  3. package/dist/src/artifacts/application/artifact-service.d.ts +12 -2
  4. package/dist/src/artifacts/application/artifact-service.js +44 -1
  5. package/dist/src/artifacts/contracts/context-event-factory.d.ts +6 -0
  6. package/dist/src/artifacts/contracts/context-event-factory.js +12 -0
  7. package/dist/src/artifacts/contracts/context-events.d.ts +23 -0
  8. package/dist/src/artifacts/contracts/context-events.js +64 -0
  9. package/dist/src/artifacts/contracts/context.d.ts +56 -0
  10. package/dist/src/artifacts/contracts/context.js +38 -0
  11. package/dist/src/artifacts/contracts/events.d.ts +1 -0
  12. package/dist/src/artifacts/contracts/events.js +2 -0
  13. package/dist/src/artifacts/contracts/streams.d.ts +3 -0
  14. package/dist/src/artifacts/contracts/streams.js +7 -1
  15. package/dist/src/artifacts/contracts/views.d.ts +1 -0
  16. package/dist/src/artifacts/domain/artifact-work-item.js +1 -0
  17. package/dist/src/artifacts/index.d.ts +4 -0
  18. package/dist/src/artifacts/index.js +4 -0
  19. package/dist/src/artifacts/infrastructure/mcp-server.d.ts +5 -1
  20. package/dist/src/artifacts/infrastructure/mcp-server.js +21 -6
  21. package/dist/src/artifacts/infrastructure/mcp-session-store.d.ts +4 -0
  22. package/dist/src/artifacts/infrastructure/mcp-session-store.js +15 -0
  23. package/dist/src/bootstrap/artifact-mcp.d.ts +6 -1
  24. package/dist/src/bootstrap/artifact-mcp.js +5 -7
  25. package/dist/src/bootstrap/artifact-trigger-context.d.ts +30 -0
  26. package/dist/src/bootstrap/artifact-trigger-context.js +99 -0
  27. package/dist/src/bootstrap/canonical-events.js +2 -1
  28. package/dist/src/bootstrap/composition-root.js +13 -1
  29. package/dist/src/bootstrap/config/root-schema.d.ts +1 -0
  30. package/dist/src/bootstrap/integration-runtime.d.ts +1 -0
  31. package/dist/src/bootstrap/integration-runtime.js +1 -0
  32. package/dist/src/bootstrap/version.js +1 -1
  33. package/dist/src/control-plane/application/trigger-service.js +4 -1
  34. package/dist/src/control-plane/contracts/config.d.ts +3 -0
  35. package/dist/src/control-plane/contracts/config.js +5 -0
  36. package/package.json +1 -1
@@ -0,0 +1,30 @@
1
+ import { type CommandContext, type EventJournal } from '@atolis-hq/eventing';
2
+ import type { WorkItemId } from '../../work/index.js';
3
+ import { type ArtifactContextProvenance, type ArtifactContextPublication, type ArtifactContextView, type ArtifactDelegationGrant, type ArtifactRevisionReference } from '../contracts/context.js';
4
+ import type { ArtifactService } from './artifact-service.js';
5
+ export type ArtifactAcceptance = (activationId: string, workItemId?: string) => Promise<boolean>;
6
+ /** Trusted host commands only. MCP never receives enrollment/publication methods. */
7
+ export declare class ArtifactContextService {
8
+ private readonly journal;
9
+ private readonly artifacts;
10
+ constructor(journal: EventJournal, artifacts: ArtifactService);
11
+ get(contextScope: string): Promise<ArtifactContextView>;
12
+ enroll(contextScope: string, workItemId: WorkItemId, provenance: ArtifactContextProvenance, context: CommandContext): Promise<void>;
13
+ references(contextScope: string, workItemId: WorkItemId): Promise<readonly ArtifactRevisionReference[]>;
14
+ /** One context-stream append records exports, memory CAS and reconciliation receipt. */
15
+ publish(input: {
16
+ readonly contextScope: string;
17
+ readonly workItemId: WorkItemId;
18
+ readonly publicationId: string;
19
+ readonly successful: boolean;
20
+ readonly exports: readonly ArtifactRevisionReference[];
21
+ readonly expectedMemory: ArtifactRevisionReference | null;
22
+ }, accepted: ArtifactAcceptance, context: CommandContext): Promise<ArtifactContextPublication>;
23
+ registerChild(grant: ArtifactDelegationGrant, accepted: ArtifactAcceptance, context: CommandContext): Promise<void>;
24
+ childReferences(parentWorkItemId: WorkItemId, childWorkItemId: WorkItemId): Promise<readonly ArtifactRevisionReference[]>;
25
+ parentReferences(parentWorkItemId: WorkItemId, accepted: ArtifactAcceptance): Promise<readonly ArtifactRevisionReference[]>;
26
+ private requireAccepted;
27
+ private delegations;
28
+ private events;
29
+ private append;
30
+ }
@@ -0,0 +1,189 @@
1
+ import { EventSourceKind } from '@atolis-hq/eventing';
2
+ import { createArtifactContextEventData, } from '../contracts/context-event-factory.js';
3
+ import { ArtifactContextEventType, selectArtifactContextEvent, } from '../contracts/context-events.js';
4
+ import { artifactContextNameSchema, ArtifactMemoryPublicationReason, artifactSharedContextNameSchema, } from '../contracts/context.js';
5
+ import { artifactContextStream } from '../contracts/streams.js';
6
+ /** Trusted host commands only. MCP never receives enrollment/publication methods. */
7
+ export class ArtifactContextService {
8
+ journal;
9
+ artifacts;
10
+ constructor(journal, artifacts) {
11
+ this.journal = journal;
12
+ this.artifacts = artifacts;
13
+ }
14
+ async get(contextScope) {
15
+ return foldContext(contextScope, await this.events(contextScope));
16
+ }
17
+ async enroll(contextScope, workItemId, provenance, context) {
18
+ artifactSharedContextNameSchema.parse(contextScope);
19
+ const events = await this.events(contextScope);
20
+ const view = foldContext(contextScope, events);
21
+ const member = view.members.find((candidate) => candidate.workItemId === workItemId);
22
+ if (member !== undefined) {
23
+ if (JSON.stringify(member.provenance) !== JSON.stringify(provenance))
24
+ throw new Error('Artifact enrollment provenance conflict');
25
+ return;
26
+ }
27
+ await this.append(events.length, {
28
+ eventType: ArtifactContextEventType.Enrolled,
29
+ payload: { contextScope, workItemId, provenance, expectedMemory: view.memory },
30
+ }, context, `enroll:${workItemId}`);
31
+ }
32
+ async references(contextScope, workItemId) {
33
+ const view = await this.get(contextScope);
34
+ if (!view.members.some((member) => member.workItemId === workItemId))
35
+ throw new Error('Work item is not enrolled in artifact context');
36
+ return uniqueReferences(view.publications.flatMap((publication) => publication.references));
37
+ }
38
+ /** One context-stream append records exports, memory CAS and reconciliation receipt. */
39
+ async publish(input, accepted, context) {
40
+ artifactSharedContextNameSchema.parse(input.contextScope);
41
+ const events = await this.events(input.contextScope);
42
+ const view = foldContext(input.contextScope, events);
43
+ const receipt = view.publications.find((publication) => publication.publicationId === input.publicationId);
44
+ if (receipt !== undefined) {
45
+ if (receipt.workItemId !== input.workItemId)
46
+ throw new Error('Artifact publication ownership conflict');
47
+ return receipt;
48
+ }
49
+ if (!view.members.some((member) => member.workItemId === input.workItemId))
50
+ throw new Error('Work item is not enrolled in artifact context');
51
+ for (const reference of input.exports) {
52
+ if (reference.workItemId !== input.workItemId)
53
+ throw new Error('Cannot publish another work item artifact');
54
+ await this.requireAccepted(reference, accepted);
55
+ }
56
+ const memories = (await this.artifacts.latestPublished(input.workItemId, (id) => accepted(id, input.workItemId))).filter((revision) => revision.path === 'memory.md');
57
+ let reason = memoryReason(input.successful, memories.length);
58
+ let memory = reason === ArtifactMemoryPublicationReason.Advanced
59
+ ? { workItemId: input.workItemId, revisionId: memories[0].revisionId }
60
+ : null;
61
+ if (memory !== null && !sameReference(view.memory, input.expectedMemory)) {
62
+ reason = ArtifactMemoryPublicationReason.Conflict;
63
+ memory = null;
64
+ }
65
+ const publication = {
66
+ publicationId: input.publicationId,
67
+ workItemId: input.workItemId,
68
+ references: uniqueReferences([...input.exports, ...(memory === null ? [] : [memory])]),
69
+ memory,
70
+ reason,
71
+ };
72
+ await this.append(events.length, {
73
+ eventType: ArtifactContextEventType.Published,
74
+ payload: { contextScope: input.contextScope, ...publication },
75
+ }, context, `publish:${input.publicationId}`);
76
+ return publication;
77
+ }
78
+ async registerChild(grant, accepted, context) {
79
+ const contextScope = delegationScope(grant.parentWorkItemId);
80
+ const events = await this.events(contextScope);
81
+ const existing = events.find((event) => event.event.eventType === ArtifactContextEventType.Delegated &&
82
+ event.event.payload.delegationId === grant.delegationId);
83
+ if (existing !== undefined) {
84
+ if (JSON.stringify(existing.event.payload) !== JSON.stringify({ contextScope, ...grant }))
85
+ throw new Error('Artifact delegation conflict');
86
+ return;
87
+ }
88
+ if (grant.parentWorkItemId === grant.childWorkItemId)
89
+ throw new Error('Artifact delegation requires distinct work items');
90
+ for (const reference of grant.childReferences)
91
+ await this.requireAccepted(reference, accepted);
92
+ await this.append(events.length, { eventType: ArtifactContextEventType.Delegated, payload: { contextScope, ...grant } }, context, `delegate:${grant.delegationId}`);
93
+ }
94
+ async childReferences(parentWorkItemId, childWorkItemId) {
95
+ return uniqueReferences((await this.delegations(parentWorkItemId))
96
+ .filter((grant) => grant.childWorkItemId === childWorkItemId)
97
+ .flatMap((grant) => grant.childReferences));
98
+ }
99
+ async parentReferences(parentWorkItemId, accepted) {
100
+ const references = [];
101
+ for (const grant of await this.delegations(parentWorkItemId)) {
102
+ const revisions = await this.artifacts.latestPublished(grant.childWorkItemId, (id) => accepted(id, grant.childWorkItemId));
103
+ references.push(...revisions.map((revision) => ({
104
+ workItemId: grant.childWorkItemId,
105
+ revisionId: revision.revisionId,
106
+ })));
107
+ }
108
+ return uniqueReferences(references);
109
+ }
110
+ async requireAccepted(reference, accepted) {
111
+ const revision = (await this.artifacts.get(reference.workItemId))?.revisions.find((candidate) => candidate.revisionId === reference.revisionId);
112
+ if (revision === undefined ||
113
+ revision.deleted ||
114
+ !(await accepted(revision.activationId, reference.workItemId)))
115
+ throw new Error('Artifact reference is not an accepted revision');
116
+ }
117
+ async delegations(parentWorkItemId) {
118
+ return (await this.events(delegationScope(parentWorkItemId))).flatMap((event) => event.event.eventType === ArtifactContextEventType.Delegated ? [event.event.payload] : []);
119
+ }
120
+ async events(contextScope) {
121
+ artifactContextNameSchema.parse(contextScope);
122
+ return (await this.journal.readStream(artifactContextStream(contextScope))).flatMap((event) => {
123
+ const owned = selectArtifactContextEvent(event);
124
+ return owned === null ? [] : [owned];
125
+ });
126
+ }
127
+ async append(sequence, input, context, id) {
128
+ const data = createArtifactContextEventData({
129
+ ...input,
130
+ eventId: `${input.payload.contextScope}:${id}`,
131
+ occurredAt: context.occurredAt,
132
+ correlationId: context.correlationId,
133
+ causationId: context.commandId,
134
+ actor: context.actor,
135
+ source: { kind: EventSourceKind.Internal, id: 'artifact-context-service' },
136
+ });
137
+ await this.journal.appendToStream(artifactContextStream(input.payload.contextScope), sequence, [
138
+ data,
139
+ ]);
140
+ }
141
+ }
142
+ function foldContext(contextScope, events) {
143
+ let view = { contextScope, members: [], publications: [], memory: null };
144
+ for (const event of events) {
145
+ switch (event.event.eventType) {
146
+ case ArtifactContextEventType.Enrolled: {
147
+ const { contextScope: _scope, ...member } = event.event.payload;
148
+ view = { ...view, members: [...view.members, member] };
149
+ break;
150
+ }
151
+ case ArtifactContextEventType.Published: {
152
+ const { contextScope: _scope, ...publication } = event.event.payload;
153
+ view = {
154
+ ...view,
155
+ publications: [...view.publications, publication],
156
+ memory: publication.memory ?? view.memory,
157
+ };
158
+ break;
159
+ }
160
+ case ArtifactContextEventType.Delegated:
161
+ break;
162
+ }
163
+ }
164
+ return view;
165
+ }
166
+ function memoryReason(successful, memoryCount) {
167
+ if (!successful)
168
+ return ArtifactMemoryPublicationReason.Failed;
169
+ if (memoryCount === 0)
170
+ return ArtifactMemoryPublicationReason.Missing;
171
+ return memoryCount > 1
172
+ ? ArtifactMemoryPublicationReason.Ambiguous
173
+ : ArtifactMemoryPublicationReason.Advanced;
174
+ }
175
+ function uniqueReferences(references) {
176
+ return [
177
+ ...new Map(references.map((reference) => [`${reference.workItemId}:${reference.revisionId}`, reference])).values(),
178
+ ];
179
+ }
180
+ function sameReference(left, right) {
181
+ return left === null
182
+ ? right === null
183
+ : right !== null &&
184
+ left.workItemId === right.workItemId &&
185
+ left.revisionId === right.revisionId;
186
+ }
187
+ function delegationScope(parentWorkItemId) {
188
+ return `delegation:${parentWorkItemId}`;
189
+ }
@@ -1,6 +1,7 @@
1
1
  import { type CommandContext } from '@atolis-hq/eventing';
2
2
  import type { WorkItemId } from '../../work/index.js';
3
3
  import type { ArtifactsConfig } from '../contracts/config.js';
4
+ import { type ArtifactRevisionReference } from '../contracts/context.js';
4
5
  import { type ArtifactPath } from '../contracts/paths.js';
5
6
  import type { ArtifactWorkItemView } from '../contracts/views.js';
6
7
  import type { FileArtifactStore } from '../infrastructure/file-artifact-store.js';
@@ -9,19 +10,25 @@ export interface ArtifactService {
9
10
  stageRevision(command: StageArtifactRevision, scope: ArtifactWriteScope, context: CommandContext): Promise<ArtifactWorkItemView>;
10
11
  stageTombstone(command: StageArtifactTombstone, scope: ArtifactWriteScope, context: CommandContext): Promise<ArtifactWorkItemView>;
11
12
  get(workItemId: string): Promise<ArtifactWorkItemView | null>;
12
- latestPublished(workItemId: string, acceptedActivation: (activationId: string) => Promise<boolean>): Promise<ReadonlyArray<ArtifactWorkItemView['revisions'][number]>>;
13
+ latestPublished(workItemId: string, acceptedActivation: (activationId: string, workItemId?: string) => Promise<boolean>): Promise<ReadonlyArray<ArtifactWorkItemView['revisions'][number]>>;
13
14
  readAcceptedRevision(workItemId: string, revisionId: string, acceptedActivation: (activationId: string) => Promise<boolean>): Promise<{
14
15
  readonly revision: ArtifactWorkItemView['revisions'][number];
15
16
  readonly bytes: Uint8Array;
16
17
  } | null>;
17
- visibleTo(scope: ArtifactReadScope, acceptedActivation: (activationId: string) => Promise<boolean>): Promise<ReadonlyArray<ArtifactWorkItemView['revisions'][number]>>;
18
+ visibleTo(scope: ArtifactReadScope, acceptedActivation: (activationId: string, workItemId?: string) => Promise<boolean>): Promise<ReadonlyArray<ArtifactVisibleRevision>>;
18
19
  read(location: string): Promise<Uint8Array>;
19
20
  }
21
+ export type ArtifactVisibleRevision = ArtifactWorkItemView['revisions'][number] & {
22
+ readonly workItemId: WorkItemId;
23
+ readonly access: 'local' | 'shared';
24
+ readonly currentMemory?: true;
25
+ };
20
26
  export interface StageArtifactRevision {
21
27
  readonly revisionId: string;
22
28
  readonly path: ArtifactPath | string;
23
29
  readonly bytes: Uint8Array;
24
30
  readonly mediaType?: string;
31
+ readonly share?: boolean;
25
32
  }
26
33
  export interface StageArtifactTombstone {
27
34
  readonly revisionId: string;
@@ -33,8 +40,11 @@ export interface ArtifactWriteScope {
33
40
  readonly producer: string;
34
41
  readonly runId: string;
35
42
  readonly activationId: string;
43
+ readonly contextScope?: string;
36
44
  }
37
45
  export interface ArtifactReadScope extends ArtifactWriteScope {
38
46
  readonly readableProducers: ReadonlySet<string>;
47
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
48
+ readonly currentMemory?: ArtifactRevisionReference | null;
39
49
  }
40
50
  export declare function createArtifactService(journal: ConstructorParameters<typeof ArtifactRepository>[0], store: FileArtifactStore, config: ArtifactsConfig): ArtifactService;
@@ -1,4 +1,5 @@
1
1
  import { EventSourceKind } from '@atolis-hq/eventing';
2
+ import { artifactSharedContextNameSchema, } from '../contracts/context.js';
2
3
  import { createArtifactEventData } from '../contracts/event-factory.js';
3
4
  import { ArtifactEventType } from '../contracts/events.js';
4
5
  import { artifactWorkItemIdForWorkItem } from '../contracts/identifiers.js';
@@ -8,6 +9,33 @@ import { ArtifactRepository } from './artifact-repository.js';
8
9
  // eslint-disable-next-line max-lines-per-function
9
10
  export function createArtifactService(journal, store, config) {
10
11
  const repository = new ArtifactRepository(journal);
12
+ // A shared reference resolves only to a live revision whose owner's activation was accepted.
13
+ async function sharedRevision(reference, currentMemory, acceptedActivation) {
14
+ const owner = await repository.load(artifactWorkItemIdForWorkItem(reference.workItemId));
15
+ const revision = owner.view?.revisions.find((candidate) => candidate.revisionId === reference.revisionId);
16
+ if (revision === undefined ||
17
+ revision.deleted ||
18
+ !(await acceptedActivation(revision.activationId, reference.workItemId)))
19
+ return null;
20
+ return {
21
+ ...revision,
22
+ workItemId: reference.workItemId,
23
+ access: 'shared',
24
+ ...(currentMemory !== null &&
25
+ currentMemory !== undefined &&
26
+ sameRevision(currentMemory, reference)
27
+ ? { currentMemory: true }
28
+ : {}),
29
+ };
30
+ }
31
+ async function appendShared(local, scope, acceptedActivation) {
32
+ for (const reference of scope.sharedReferences ?? []) {
33
+ const shared = await sharedRevision(reference, scope.currentMemory, acceptedActivation);
34
+ if (shared !== null && !local.some((candidate) => sameRevision(candidate, reference)))
35
+ local.push(shared);
36
+ }
37
+ return local;
38
+ }
11
39
  return {
12
40
  async stageRevision(command, scope, context) {
13
41
  const id = artifactWorkItemIdForWorkItem(scope.workItemId);
@@ -20,6 +48,7 @@ export function createArtifactService(journal, store, config) {
20
48
  0;
21
49
  if (retained + command.bytes.byteLength > config.maxWorkItemBytes)
22
50
  throw new Error(`Artifact work item exceeds ${config.maxWorkItemBytes} byte limit`);
51
+ const selectedExport = contextExport(command.share, scope.contextScope);
23
52
  const path = artifactPath(String(command.path));
24
53
  const stored = await store.write({
25
54
  workItemId: scope.workItemId,
@@ -44,6 +73,7 @@ export function createArtifactService(journal, store, config) {
44
73
  runId: scope.runId,
45
74
  activationId: scope.activationId,
46
75
  ...stored,
76
+ ...selectedExport,
47
77
  ...(command.mediaType === undefined ? {} : { mediaType: command.mediaType }),
48
78
  },
49
79
  }),
@@ -111,7 +141,10 @@ export function createArtifactService(journal, store, config) {
111
141
  if (published || ownStaged)
112
142
  latest.set(`${revision.producer}\u0000${revision.path}`, revision);
113
143
  }
114
- return [...latest.values()].filter((revision) => !revision.deleted);
144
+ const local = [...latest.values()]
145
+ .filter((revision) => !revision.deleted)
146
+ .map((revision) => ({ ...revision, workItemId: scope.workItemId, access: 'local' }));
147
+ return appendShared(local, scope, acceptedActivation);
115
148
  },
116
149
  async readAcceptedRevision(workItemId, revisionId, acceptedActivation) {
117
150
  const view = await repository.load(artifactWorkItemIdForWorkItem(workItemId));
@@ -126,3 +159,13 @@ export function createArtifactService(journal, store, config) {
126
159
  read: (location) => store.read(location),
127
160
  };
128
161
  }
162
+ function sameRevision(left, right) {
163
+ return left.workItemId === right.workItemId && left.revisionId === right.revisionId;
164
+ }
165
+ function contextExport(share, contextScope) {
166
+ if (share !== true)
167
+ return {};
168
+ if (contextScope === undefined)
169
+ throw new Error('This run has no trusted shared context');
170
+ return { contextExport: artifactSharedContextNameSchema.parse(contextScope) };
171
+ }
@@ -0,0 +1,6 @@
1
+ import { type EventDataInput } from '@atolis-hq/eventing';
2
+ import { type ArtifactContextEventData, type ArtifactContextEventPayloads } from './context-events.js';
3
+ export type ArtifactContextEventInput = {
4
+ [Type in keyof ArtifactContextEventPayloads]: EventDataInput<Type, ArtifactContextEventPayloads[Type]>;
5
+ }[keyof ArtifactContextEventPayloads];
6
+ export declare function createArtifactContextEventData(input: ArtifactContextEventInput): ArtifactContextEventData;
@@ -0,0 +1,12 @@
1
+ import { createEventData } from '@atolis-hq/eventing';
2
+ import { ArtifactContextEventType, } from './context-events.js';
3
+ export function createArtifactContextEventData(input) {
4
+ switch (input.eventType) {
5
+ case ArtifactContextEventType.Enrolled:
6
+ return createEventData(input);
7
+ case ArtifactContextEventType.Published:
8
+ return createEventData(input);
9
+ case ArtifactContextEventType.Delegated:
10
+ return createEventData(input);
11
+ }
12
+ }
@@ -0,0 +1,23 @@
1
+ import { type EventDataUnion, type EventEnvelope, type EventUnion } from '@atolis-hq/eventing';
2
+ import { type ArtifactContextEnrollment, type ArtifactContextPublication, type ArtifactDelegationGrant } from './context.js';
3
+ import { type ArtifactContextStreamRef } from './streams.js';
4
+ export declare const ArtifactContextEventType: {
5
+ readonly Enrolled: "artifact-context.enrolled";
6
+ readonly Published: "artifact-context.published";
7
+ readonly Delegated: "artifact-context.delegated";
8
+ };
9
+ export interface ArtifactContextEventPayloads {
10
+ readonly [ArtifactContextEventType.Enrolled]: {
11
+ readonly contextScope: string;
12
+ } & ArtifactContextEnrollment;
13
+ readonly [ArtifactContextEventType.Published]: {
14
+ readonly contextScope: string;
15
+ } & ArtifactContextPublication;
16
+ readonly [ArtifactContextEventType.Delegated]: {
17
+ readonly contextScope: string;
18
+ } & ArtifactDelegationGrant;
19
+ }
20
+ export type ArtifactContextEvent = EventUnion<ArtifactContextEventPayloads, ArtifactContextStreamRef>;
21
+ export type ArtifactContextEventData = EventDataUnion<ArtifactContextEventPayloads>;
22
+ export declare function decodeArtifactContextEvent(event: EventEnvelope): ArtifactContextEvent;
23
+ export declare function selectArtifactContextEvent(event: EventEnvelope): ArtifactContextEvent | null;
@@ -0,0 +1,64 @@
1
+ import { eventDataSchema, eventEnvelopeSchema, } from '@atolis-hq/eventing';
2
+ import { z } from 'zod';
3
+ import { brandedStringSchema } from '../../kernel/index.js';
4
+ import { workItemId } from '../../work/index.js';
5
+ import { artifactContextNameSchema, artifactContextProvenanceSchema, ArtifactMemoryPublicationReason, artifactRevisionReferenceSchema, } from './context.js';
6
+ import { ArtifactStreamKind } from './streams.js';
7
+ export const ArtifactContextEventType = {
8
+ Enrolled: 'artifact-context.enrolled',
9
+ Published: 'artifact-context.published',
10
+ Delegated: 'artifact-context.delegated',
11
+ };
12
+ const common = z.object({ contextScope: artifactContextNameSchema }).strict();
13
+ const stream = z
14
+ .object({ kind: z.literal(ArtifactStreamKind.Context), id: artifactContextNameSchema })
15
+ .strict();
16
+ const schema = z.union([
17
+ eventEnvelopeSchema.extend({
18
+ stream,
19
+ event: eventDataSchema.extend({
20
+ eventType: z.literal(ArtifactContextEventType.Enrolled),
21
+ payload: common.extend({
22
+ workItemId: brandedStringSchema(workItemId),
23
+ provenance: artifactContextProvenanceSchema,
24
+ expectedMemory: artifactRevisionReferenceSchema.nullable(),
25
+ }),
26
+ }),
27
+ }),
28
+ eventEnvelopeSchema.extend({
29
+ stream,
30
+ event: eventDataSchema.extend({
31
+ eventType: z.literal(ArtifactContextEventType.Published),
32
+ payload: common.extend({
33
+ publicationId: z.string().min(1),
34
+ workItemId: brandedStringSchema(workItemId),
35
+ references: z.array(artifactRevisionReferenceSchema),
36
+ memory: artifactRevisionReferenceSchema.nullable(),
37
+ reason: z.enum(Object.values(ArtifactMemoryPublicationReason)),
38
+ }),
39
+ }),
40
+ }),
41
+ eventEnvelopeSchema.extend({
42
+ stream,
43
+ event: eventDataSchema.extend({
44
+ eventType: z.literal(ArtifactContextEventType.Delegated),
45
+ payload: common.extend({
46
+ delegationId: z.string().min(1),
47
+ parentWorkItemId: brandedStringSchema(workItemId),
48
+ childWorkItemId: brandedStringSchema(workItemId),
49
+ childReferences: z.array(artifactRevisionReferenceSchema),
50
+ }),
51
+ }),
52
+ }),
53
+ ]);
54
+ export function decodeArtifactContextEvent(event) {
55
+ const decoded = schema.parse(event);
56
+ if (decoded.stream.id !== decoded.event.payload.contextScope)
57
+ throw new Error('Artifact context event belongs to another scope');
58
+ return decoded;
59
+ }
60
+ export function selectArtifactContextEvent(event) {
61
+ return event.event.eventType.startsWith('artifact-context.')
62
+ ? decodeArtifactContextEvent(event)
63
+ : null;
64
+ }
@@ -0,0 +1,56 @@
1
+ import { z } from 'zod';
2
+ import { workItemId } from '../../work/index.js';
3
+ export declare const artifactContextNameSchema: z.ZodString;
4
+ export declare const artifactSharedContextNameSchema: z.ZodString;
5
+ export declare const artifactRevisionReferenceSchema: z.ZodObject<{
6
+ workItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
7
+ revisionId: z.ZodString;
8
+ }, z.core.$strict>;
9
+ export type ArtifactRevisionReference = z.infer<typeof artifactRevisionReferenceSchema>;
10
+ export declare const ArtifactContextProvenanceKind: {
11
+ readonly Trigger: "trigger";
12
+ readonly Delegation: "delegation";
13
+ };
14
+ export declare const artifactContextProvenanceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
15
+ kind: z.ZodLiteral<"trigger">;
16
+ triggerId: z.ZodString;
17
+ invocationId: z.ZodString;
18
+ }, z.core.$strict>, z.ZodObject<{
19
+ kind: z.ZodLiteral<"delegation">;
20
+ delegationId: z.ZodString;
21
+ parentWorkItemId: z.ZodPipe<z.ZodString, z.ZodTransform<import("../../work/index.js").WorkItemId, string>>;
22
+ }, z.core.$strict>], "kind">;
23
+ export type ArtifactContextProvenance = z.infer<typeof artifactContextProvenanceSchema>;
24
+ export declare const ArtifactMemoryPublicationReason: {
25
+ readonly Advanced: "advanced";
26
+ readonly Conflict: "stale-memory-pointer";
27
+ readonly Failed: "invocation-unsuccessful";
28
+ readonly Missing: "missing";
29
+ readonly Ambiguous: "multiple-memory-producers";
30
+ };
31
+ export type ArtifactMemoryPublicationReason = (typeof ArtifactMemoryPublicationReason)[keyof typeof ArtifactMemoryPublicationReason];
32
+ export interface ArtifactContextEnrollment {
33
+ readonly workItemId: ReturnType<typeof workItemId>;
34
+ readonly provenance: ArtifactContextProvenance;
35
+ readonly expectedMemory: ArtifactRevisionReference | null;
36
+ }
37
+ export interface ArtifactContextPublication {
38
+ readonly publicationId: string;
39
+ readonly workItemId: ReturnType<typeof workItemId>;
40
+ readonly references: readonly ArtifactRevisionReference[];
41
+ readonly memory: ArtifactRevisionReference | null;
42
+ readonly reason: ArtifactMemoryPublicationReason;
43
+ }
44
+ export interface ArtifactContextView {
45
+ readonly contextScope: string;
46
+ readonly members: readonly ArtifactContextEnrollment[];
47
+ readonly publications: readonly ArtifactContextPublication[];
48
+ readonly memory: ArtifactRevisionReference | null;
49
+ }
50
+ /** Issued only from validated delegation; no ancestry-derived or sibling access. */
51
+ export interface ArtifactDelegationGrant {
52
+ readonly delegationId: string;
53
+ readonly parentWorkItemId: ReturnType<typeof workItemId>;
54
+ readonly childWorkItemId: ReturnType<typeof workItemId>;
55
+ readonly childReferences: readonly ArtifactRevisionReference[];
56
+ }
@@ -0,0 +1,38 @@
1
+ import { z } from 'zod';
2
+ import { brandedStringSchema } from '../../kernel/index.js';
3
+ import { workItemId } from '../../work/index.js';
4
+ export const artifactContextNameSchema = z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
5
+ export const artifactSharedContextNameSchema = artifactContextNameSchema.refine((name) => !name.startsWith('delegation:'), 'The delegation: prefix is reserved for trusted delegation grants');
6
+ export const artifactRevisionReferenceSchema = z
7
+ .object({
8
+ workItemId: brandedStringSchema(workItemId),
9
+ revisionId: z.string().min(1),
10
+ })
11
+ .strict();
12
+ export const ArtifactContextProvenanceKind = {
13
+ Trigger: 'trigger',
14
+ Delegation: 'delegation',
15
+ };
16
+ export const artifactContextProvenanceSchema = z.discriminatedUnion('kind', [
17
+ z
18
+ .object({
19
+ kind: z.literal(ArtifactContextProvenanceKind.Trigger),
20
+ triggerId: z.string().min(1),
21
+ invocationId: z.string().min(1),
22
+ })
23
+ .strict(),
24
+ z
25
+ .object({
26
+ kind: z.literal(ArtifactContextProvenanceKind.Delegation),
27
+ delegationId: z.string().min(1),
28
+ parentWorkItemId: brandedStringSchema(workItemId),
29
+ })
30
+ .strict(),
31
+ ]);
32
+ export const ArtifactMemoryPublicationReason = {
33
+ Advanced: 'advanced',
34
+ Conflict: 'stale-memory-pointer',
35
+ Failed: 'invocation-unsuccessful',
36
+ Missing: 'missing',
37
+ Ambiguous: 'multiple-memory-producers',
38
+ };
@@ -17,6 +17,7 @@ export interface ArtifactEventPayloads {
17
17
  readonly digest: string;
18
18
  readonly byteLength: number;
19
19
  readonly mediaType?: string | undefined;
20
+ readonly contextExport?: string | undefined;
20
21
  };
21
22
  readonly [ArtifactEventType.TombstoneStaged]: {
22
23
  readonly workItemId: WorkItemId;
@@ -2,6 +2,7 @@ import { eventDataSchema, eventEnvelopeSchema, } from '@atolis-hq/eventing';
2
2
  import { z } from 'zod';
3
3
  import { brandedStringSchema } from '../../kernel/index.js';
4
4
  import { workItemId } from '../../work/index.js';
5
+ import { artifactSharedContextNameSchema } from './context.js';
5
6
  import { artifactWorkItemId, artifactWorkItemIdForWorkItem } from './identifiers.js';
6
7
  import { artifactPath } from './paths.js';
7
8
  import { ArtifactStreamKind } from './streams.js';
@@ -34,6 +35,7 @@ const schema = z.union([
34
35
  digest: z.string().regex(/^[a-f0-9]{64}$/),
35
36
  byteLength: z.number().int().nonnegative(),
36
37
  mediaType: z.string().min(1).optional(),
38
+ contextExport: artifactSharedContextNameSchema.optional(),
37
39
  }),
38
40
  }),
39
41
  stream,
@@ -2,6 +2,9 @@ import type { EntityRef } from '../../kernel/index.js';
2
2
  import type { ArtifactWorkItemId } from './identifiers.js';
3
3
  export declare const ArtifactStreamKind: {
4
4
  readonly WorkItem: "artifact-work-item";
5
+ readonly Context: "artifact-context";
5
6
  };
6
7
  export type ArtifactWorkItemStreamRef = EntityRef<typeof ArtifactStreamKind.WorkItem, ArtifactWorkItemId>;
7
8
  export declare function artifactWorkItemStream(id: ArtifactWorkItemId): ArtifactWorkItemStreamRef;
9
+ export type ArtifactContextStreamRef = EntityRef<typeof ArtifactStreamKind.Context>;
10
+ export declare function artifactContextStream(contextScope: string): ArtifactContextStreamRef;
@@ -1,4 +1,10 @@
1
- export const ArtifactStreamKind = { WorkItem: 'artifact-work-item' };
1
+ export const ArtifactStreamKind = {
2
+ WorkItem: 'artifact-work-item',
3
+ Context: 'artifact-context',
4
+ };
2
5
  export function artifactWorkItemStream(id) {
3
6
  return { kind: ArtifactStreamKind.WorkItem, id };
4
7
  }
8
+ export function artifactContextStream(contextScope) {
9
+ return { kind: ArtifactStreamKind.Context, id: contextScope };
10
+ }
@@ -12,6 +12,7 @@ export interface ArtifactRevisionView {
12
12
  readonly digest?: string;
13
13
  readonly byteLength?: number;
14
14
  readonly mediaType?: string;
15
+ readonly contextExport?: string;
15
16
  }
16
17
  export interface ArtifactWorkItemView {
17
18
  readonly artifactWorkItemId: ArtifactWorkItemId;
@@ -35,6 +35,7 @@ export function applyArtifactEvent(view, event) {
35
35
  location: revision.location,
36
36
  digest: revision.digest,
37
37
  byteLength: revision.byteLength,
38
+ ...(revision.contextExport === undefined ? {} : { contextExport: revision.contextExport }),
38
39
  ...(revision.mediaType === undefined ? {} : { mediaType: revision.mediaType }),
39
40
  },
40
41
  ],
@@ -12,3 +12,7 @@ export * from './domain/artifact-work-item.js';
12
12
  export * from './infrastructure/file-artifact-store.js';
13
13
  export * from './infrastructure/mcp-server.js';
14
14
  export * from './infrastructure/mcp-session-store.js';
15
+ export * from './application/artifact-context-service.js';
16
+ export * from './contracts/context-event-factory.js';
17
+ export * from './contracts/context-events.js';
18
+ export * from './contracts/context.js';
@@ -12,3 +12,7 @@ export * from './domain/artifact-work-item.js';
12
12
  export * from './infrastructure/file-artifact-store.js';
13
13
  export * from './infrastructure/mcp-server.js';
14
14
  export * from './infrastructure/mcp-session-store.js';
15
+ export * from './application/artifact-context-service.js';
16
+ export * from './contracts/context-event-factory.js';
17
+ export * from './contracts/context-events.js';
18
+ export * from './contracts/context.js';
@@ -2,6 +2,7 @@ import type { CommandContext } from '@atolis-hq/eventing';
2
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
3
  import type { WorkItemId } from '../../work/index.js';
4
4
  import type { ArtifactService } from '../application/artifact-service.js';
5
+ import type { ArtifactRevisionReference } from '../contracts/context.js';
5
6
  /** A capability token is resolved into this server-side scope by Execution. */
6
7
  export interface ArtifactMcpSession {
7
8
  readonly workItemId: WorkItemId;
@@ -9,9 +10,12 @@ export interface ArtifactMcpSession {
9
10
  readonly runId: string;
10
11
  readonly activationId: string;
11
12
  readonly readableProducers: ReadonlySet<string>;
13
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
14
+ readonly currentMemory?: ArtifactRevisionReference | null;
15
+ readonly contextScope?: string;
12
16
  readonly nextRevisionId: () => string;
13
17
  readonly commandContext: () => CommandContext;
14
- readonly acceptedActivation: (activationId: string) => Promise<boolean>;
18
+ readonly acceptedActivation: (activationId: string, workItemId?: string) => Promise<boolean>;
15
19
  /** Revalidates the run-bound credential for every tool request. */
16
20
  readonly assertActive: () => Promise<void>;
17
21
  }
@@ -9,13 +9,14 @@ export function createArtifactMcpServer(artifacts, session) {
9
9
  description: 'Read a visible artifact revision as UTF-8 text or base64 bytes.',
10
10
  inputSchema: {
11
11
  revisionId: z.string().min(1),
12
+ workItemId: z.string().min(1).optional(),
12
13
  encoding: z.enum(['utf8', 'base64']).default('utf8'),
13
14
  offset: z.number().int().nonnegative().default(0),
14
15
  length: z.number().int().positive().optional(),
15
16
  },
16
- }, async ({ revisionId, encoding, offset, length }) => {
17
+ }, async ({ revisionId, workItemId, encoding, offset, length }) => {
17
18
  await session.assertActive();
18
- const artifact = await visibleArtifact(artifacts, session, revisionId);
19
+ const artifact = await visibleArtifact(artifacts, session, revisionId, workItemId);
19
20
  if (artifact.location === undefined)
20
21
  throw new Error('Artifact revision has no content');
21
22
  const bytes = (await artifacts.read(artifact.location)).slice(offset, length === undefined ? undefined : offset + length);
@@ -51,7 +52,7 @@ export function createArtifactMcpServer(artifacts, session) {
51
52
  }, async ({ revisionId, find, replace }) => {
52
53
  await session.assertActive();
53
54
  const artifact = await visibleArtifact(artifacts, session, revisionId);
54
- if (artifact.producer !== session.producer)
55
+ if (artifact.producer !== session.producer || artifact.workItemId !== session.workItemId)
55
56
  throw new Error('Only the owning producer may patch an artifact');
56
57
  if (artifact.location === undefined)
57
58
  throw new Error('Artifact revision has no content');
@@ -76,14 +77,19 @@ export function createArtifactMcpServer(artifacts, session) {
76
77
  content: z.string(),
77
78
  encoding: z.enum(['utf8', 'base64']).default('utf8'),
78
79
  mediaType: z.string().min(1).optional(),
80
+ share: z
81
+ .boolean()
82
+ .optional()
83
+ .describe("Select this revision for export to the run's trusted context after successful acceptance."),
79
84
  },
80
- }, async ({ path, content, encoding, mediaType }) => {
85
+ }, async ({ path, content, encoding, mediaType, share }) => {
81
86
  await session.assertActive();
82
87
  const revisionId = session.nextRevisionId();
83
88
  await artifacts.stageRevision({
84
89
  revisionId,
85
90
  path: artifactPath(path),
86
91
  bytes: decodeContent(content, encoding),
92
+ ...(share === undefined ? {} : { share }),
87
93
  ...(mediaType === undefined ? {} : { mediaType }),
88
94
  }, writeScope(session), session.commandContext());
89
95
  return { content: [{ type: 'text', text: JSON.stringify({ revisionId }) }] };
@@ -102,8 +108,12 @@ export function createArtifactMcpServer(artifacts, session) {
102
108
  });
103
109
  return server;
104
110
  }
105
- async function visibleArtifact(artifacts, session, revisionId) {
106
- const artifact = (await visibleArtifacts(artifacts, session)).find((candidate) => candidate.revisionId === revisionId && session.readableProducers.has(candidate.producer));
111
+ async function visibleArtifact(artifacts, session, revisionId, workItemId) {
112
+ const matches = (await visibleArtifacts(artifacts, session)).filter((candidate) => candidate.revisionId === revisionId &&
113
+ (workItemId === undefined || candidate.workItemId === workItemId));
114
+ if (matches.length > 1)
115
+ throw new Error('Artifact revision is ambiguous; specify workItemId');
116
+ const artifact = matches[0];
107
117
  if (artifact === undefined)
108
118
  throw new Error('Artifact revision is not visible to this activation');
109
119
  return artifact;
@@ -115,6 +125,10 @@ function visibleArtifacts(artifacts, session) {
115
125
  runId: session.runId,
116
126
  activationId: session.activationId,
117
127
  readableProducers: session.readableProducers,
128
+ ...(session.sharedReferences === undefined
129
+ ? {}
130
+ : { sharedReferences: session.sharedReferences }),
131
+ ...(session.currentMemory === undefined ? {} : { currentMemory: session.currentMemory }),
118
132
  }, session.acceptedActivation);
119
133
  }
120
134
  function writeScope(session) {
@@ -123,6 +137,7 @@ function writeScope(session) {
123
137
  producer: session.producer,
124
138
  runId: session.runId,
125
139
  activationId: session.activationId,
140
+ ...(session.contextScope === undefined ? {} : { contextScope: session.contextScope }),
126
141
  };
127
142
  }
128
143
  function decodeContent(content, encoding) {
@@ -1,4 +1,5 @@
1
1
  import type { WorkItemId } from '../../work/index.js';
2
+ import { type ArtifactRevisionReference } from '../contracts/context.js';
2
3
  export interface ArtifactMcpSessionDescriptor {
3
4
  readonly workItemId: WorkItemId;
4
5
  readonly producer: string;
@@ -6,6 +7,9 @@ export interface ArtifactMcpSessionDescriptor {
6
7
  readonly activationId: string;
7
8
  readonly readableProducers: readonly string[];
8
9
  readonly expiresAt: string;
10
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
11
+ readonly currentMemory?: ArtifactRevisionReference | null;
12
+ readonly contextScope?: string;
9
13
  }
10
14
  /**
11
15
  * Ephemeral run-scoped descriptors are intentionally outside a Git workspace.
@@ -1,6 +1,8 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
2
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { artifactRevisionReferenceSchema, artifactSharedContextNameSchema, } from '../contracts/context.js';
4
6
  /**
5
7
  * Ephemeral run-scoped descriptors are intentionally outside a Git workspace.
6
8
  * The unpredictable filename is the capability presented by the configured MCP
@@ -35,6 +37,7 @@ export class FileArtifactMcpSessionStore {
35
37
  typeof descriptor.activationId !== 'string' ||
36
38
  !Array.isArray(descriptor.readableProducers) ||
37
39
  typeof descriptor.expiresAt !== 'string' ||
40
+ !validSharedContext(descriptor) ||
38
41
  !Number.isFinite(Date.parse(descriptor.expiresAt)) ||
39
42
  Date.parse(descriptor.expiresAt) <= Date.parse(this.now()))
40
43
  throw new Error('Invalid artifact MCP session');
@@ -51,6 +54,18 @@ export class FileArtifactMcpSessionStore {
51
54
  }
52
55
  }
53
56
  }
57
+ const sharedContextSchema = z.object({
58
+ contextScope: artifactSharedContextNameSchema.optional(),
59
+ sharedReferences: z.array(artifactRevisionReferenceSchema).optional(),
60
+ currentMemory: artifactRevisionReferenceSchema.nullable().optional(),
61
+ });
62
+ function validSharedContext(descriptor) {
63
+ return sharedContextSchema.safeParse({
64
+ contextScope: descriptor.contextScope,
65
+ sharedReferences: descriptor.sharedReferences,
66
+ currentMemory: descriptor.currentMemory,
67
+ }).success;
68
+ }
54
69
  function digest(value) {
55
70
  return createHash('sha256').update(value).digest('hex');
56
71
  }
@@ -1,5 +1,5 @@
1
1
  import type { FileArtifactMcpSessionStore } from '../artifacts/index.js';
2
- import { type ArtifactService } from '../artifacts/index.js';
2
+ import { type ArtifactRevisionReference, type ArtifactService } from '../artifacts/index.js';
3
3
  import { type ExecutionDependencies } from '../execution/index.js';
4
4
  import type { OrchestrationService } from '../orchestration/index.js';
5
5
  /** Bootstrap binds Artifact's generic policy to verified Execution and Orchestration facts. */
@@ -10,6 +10,11 @@ export declare function createArtifactMcpProvisioner(input: {
10
10
  readonly wakeRoot: string;
11
11
  readonly now: () => string;
12
12
  readonly nextId: () => string;
13
+ readonly sharedContext?: (workItemId: string) => Promise<{
14
+ readonly sharedReferences?: readonly ArtifactRevisionReference[];
15
+ readonly currentMemory?: ArtifactRevisionReference | null;
16
+ readonly contextScope?: string;
17
+ }>;
13
18
  }): NonNullable<ExecutionDependencies['mcp']>;
14
19
  /** Creates the transport-neutral Wake MCP server for the run-bound CLI command. */
15
20
  export declare function createArtifactMcpServerForSession(root: ArtifactMcpRoot, sessions: FileArtifactMcpSessionStore, path: string, token: string, options: {
@@ -20,6 +20,7 @@ export function createArtifactMcpProvisioner(input) {
20
20
  activationId: activation.activationId,
21
21
  readableProducers: [...readableProducers],
22
22
  expiresAt,
23
+ ...(await input.sharedContext?.(context.workItemId)),
23
24
  };
24
25
  const issued = await input.sessions.issue(descriptor);
25
26
  try {
@@ -68,13 +69,10 @@ function commandContext(occurredAt, descriptor) {
68
69
  }
69
70
  function acceptedActivation(orchestration, workItemId) {
70
71
  let accepted;
71
- return async (activationId) => {
72
- accepted ??= orchestration
73
- .listAll()
74
- .then((workflows) => new Set(workflows
75
- .filter((workflow) => workflow.workItemId === workItemId)
76
- .flatMap((workflow) => workflow.acceptedOutcomes)));
77
- return (await accepted).has(activationId);
72
+ return async (activationId, sourceWorkItemId = workItemId) => {
73
+ accepted ??= orchestration.listAll();
74
+ return (await accepted).some((workflow) => workflow.workItemId === sourceWorkItemId &&
75
+ workflow.acceptedOutcomes.includes(activationId));
78
76
  };
79
77
  }
80
78
  function producerFor(workflowInstanceId, stage, activity) {
@@ -0,0 +1,30 @@
1
+ import { type EventJournal } from '@atolis-hq/eventing';
2
+ import { type ArtifactContextService, type ArtifactService } from '../artifacts/index.js';
3
+ import { type TriggerConfig } from '../control-plane/index.js';
4
+ import { type OrchestrationService } from '../orchestration/index.js';
5
+ /** Only durable claims matching the operator binding authorize named enrollment. */
6
+ export declare function createArtifactTriggerContext(input: {
7
+ readonly journal: EventJournal;
8
+ readonly contexts: ArtifactContextService;
9
+ readonly artifacts: ArtifactService;
10
+ readonly orchestration: OrchestrationService;
11
+ readonly triggers: readonly TriggerConfig[];
12
+ readonly now: () => string;
13
+ }): {
14
+ provision(item: string): Promise<{
15
+ contextScope?: never;
16
+ sharedReferences?: never;
17
+ currentMemory?: never;
18
+ } | {
19
+ contextScope: string;
20
+ sharedReferences: readonly {
21
+ workItemId: import("../work/index.js").WorkItemId;
22
+ revisionId: string;
23
+ }[];
24
+ currentMemory: {
25
+ workItemId: import("../work/index.js").WorkItemId;
26
+ revisionId: string;
27
+ } | null;
28
+ }>;
29
+ reconcile(): Promise<void>;
30
+ };
@@ -0,0 +1,99 @@
1
+ import { EventActorKind, correlationId } from '@atolis-hq/eventing';
2
+ import { ActivityOutcomeKind } from '../activities/index.js';
3
+ import { ArtifactContextProvenanceKind, } from '../artifacts/index.js';
4
+ import { ControlEventType, artifactContextCoordinationKey, selectControlEvent, triggerInvocationStream, } from '../control-plane/index.js';
5
+ import { WorkflowStatus } from '../orchestration/index.js';
6
+ import { workItemId } from '../work/index.js';
7
+ /** Only durable claims matching the operator binding authorize named enrollment. */
8
+ export function createArtifactTriggerContext(input) {
9
+ // Completed receipts and immutable claim bindings need no repeated stream reads in a resident host.
10
+ const reconciled = new Set();
11
+ const bindings = new Map();
12
+ async function binding(item) {
13
+ if (bindings.has(item))
14
+ return bindings.get(item) ?? null;
15
+ for (const envelope of await input.journal.readStream(triggerInvocationStream(item))) {
16
+ const event = selectControlEvent(envelope);
17
+ if (event?.event.eventType !== ControlEventType.TriggerInvocationClaimed)
18
+ continue;
19
+ const claimed = event.event.payload;
20
+ const config = input.triggers.find((trigger) => trigger.id === claimed.triggerId);
21
+ if (config?.contextScope === undefined ||
22
+ claimed.coordinationKey !== artifactContextCoordinationKey(config.contextScope))
23
+ break;
24
+ const result = {
25
+ contextScope: config.contextScope,
26
+ workflowInstanceId: claimed.workflowInstanceId,
27
+ };
28
+ await input.contexts.enroll(config.contextScope, workItemId(item), {
29
+ kind: ArtifactContextProvenanceKind.Trigger,
30
+ triggerId: config.id,
31
+ invocationId: claimed.workflowInstanceId,
32
+ }, context(item));
33
+ bindings.set(item, result);
34
+ return result;
35
+ }
36
+ bindings.set(item, null);
37
+ return null;
38
+ }
39
+ function context(item) {
40
+ return {
41
+ commandId: `artifact-trigger:${item}`,
42
+ correlationId: correlationId(item),
43
+ occurredAt: input.now(),
44
+ actor: { kind: EventActorKind.System, id: 'artifact-trigger-context' },
45
+ };
46
+ }
47
+ return {
48
+ async provision(item) {
49
+ const bound = await binding(item);
50
+ if (bound === null)
51
+ return {};
52
+ const view = await input.contexts.get(bound.contextScope);
53
+ return {
54
+ contextScope: bound.contextScope,
55
+ sharedReferences: await input.contexts.references(bound.contextScope, workItemId(item)),
56
+ currentMemory: view.memory,
57
+ };
58
+ },
59
+ async reconcile() {
60
+ for (const workflow of await input.orchestration.listAll()) {
61
+ if (reconciled.has(workflow.workflowInstanceId) ||
62
+ (workflow.status !== WorkflowStatus.Completed &&
63
+ workflow.status !== WorkflowStatus.Superseded))
64
+ continue;
65
+ try {
66
+ const bound = await binding(workflow.workItemId);
67
+ // A trigger claim authorizes its invocation, not every workflow on its WorkItem.
68
+ if (bound !== null && bound.workflowInstanceId === workflow.workflowInstanceId) {
69
+ const view = await input.contexts.get(bound.contextScope);
70
+ const member = view.members.find((candidate) => candidate.workItemId === workflow.workItemId);
71
+ const accepted = async (id, item) => item === workflow.workItemId &&
72
+ workflow.acceptedOutcomes.some((acceptedId) => acceptedId === id);
73
+ const revisions = await input.artifacts.latestPublished(workflow.workItemId, (id) => accepted(id, workflow.workItemId));
74
+ const successful = workflow.status === WorkflowStatus.Completed &&
75
+ workflow.lastOutcome?.kind !== ActivityOutcomeKind.Failed;
76
+ await input.contexts.publish({
77
+ contextScope: bound.contextScope,
78
+ workItemId: workflow.workItemId,
79
+ publicationId: workflow.workflowInstanceId,
80
+ successful,
81
+ exports: revisions
82
+ .filter((revision) => successful && revision.contextExport === bound.contextScope)
83
+ .map((revision) => ({
84
+ workItemId: workflow.workItemId,
85
+ revisionId: revision.revisionId,
86
+ })),
87
+ expectedMemory: member.expectedMemory,
88
+ }, accepted, context(workflow.workItemId));
89
+ }
90
+ reconciled.add(workflow.workflowInstanceId);
91
+ }
92
+ catch (error) {
93
+ // Retry this invocation next pass without starving other scopes or trigger admission.
94
+ console.error(`Artifact context publication failed for ${workflow.workflowInstanceId}`, error);
95
+ }
96
+ }
97
+ },
98
+ };
99
+ }
@@ -1,5 +1,5 @@
1
1
  import { ActivityEventType, selectActivityEvent } from '../activities/index.js';
2
- import { ArtifactEventType, selectArtifactEvent } from '../artifacts/index.js';
2
+ import { ArtifactContextEventType, ArtifactEventType, selectArtifactContextEvent, selectArtifactEvent, } from '../artifacts/index.js';
3
3
  import { ControlEventType, selectControlEvent } from '../control-plane/index.js';
4
4
  import { ConversationEventType, selectConversationEvent } from '../conversations/index.js';
5
5
  import { ExecutionEventType, selectExecutionEvent } from '../execution/index.js';
@@ -12,6 +12,7 @@ import { WorkEventType, selectWorkEvent } from '../work/index.js';
12
12
  const registrations = [
13
13
  { types: Object.values(ActivityEventType), decode: selectActivityEvent },
14
14
  { types: Object.values(ArtifactEventType), decode: selectArtifactEvent },
15
+ { types: Object.values(ArtifactContextEventType), decode: selectArtifactContextEvent },
15
16
  { types: Object.values(ControlEventType), decode: selectControlEvent },
16
17
  { types: Object.values(ConversationEventType), decode: selectConversationEvent },
17
18
  { types: Object.values(ExecutionEventType), decode: selectExecutionEvent },
@@ -1,6 +1,6 @@
1
1
  import { acquireFileLock } from '@atolis-hq/eventing-filesystem';
2
2
  import { createPullRequestService } from '../activities/index.js';
3
- import { FileArtifactMcpSessionStore, FileArtifactStore, createArtifactService, } from '../artifacts/index.js';
3
+ import { ArtifactContextService, FileArtifactMcpSessionStore, FileArtifactStore, createArtifactService, } from '../artifacts/index.js';
4
4
  import { DispatchPolicy, createActivationScheduler, createActivationSchedulerSubscriber, createControlPlaneService, createDurableRunnerIneligibility, createRunnerControlService, } from '../control-plane/index.js';
5
5
  import { createConversationService } from '../conversations/index.js';
6
6
  import { ExecutionCancellationReason, ExternalExecutionState, GitWorkspaceProvider, RecoveryService, TranscriptStore, createExecutionService, createRunnerMemoryProfileDecorator, } from '../execution/index.js';
@@ -12,6 +12,7 @@ import { createWorkService } from '../work/index.js';
12
12
  import { createFileActivationSchedulerSerialiser } from './activation-scheduler-serialiser.js';
13
13
  import { createBuiltInActivityRegistry } from './activity-registry.js';
14
14
  import { createArtifactMcpProvisioner } from './artifact-mcp.js';
15
+ import { createArtifactTriggerContext } from './artifact-trigger-context.js';
15
16
  import { loadConfig } from './config/load-config.js';
16
17
  import { EventProcessorRuntime } from './event-processor-runtime.js';
17
18
  import { loadFakeScenarios } from './fake-scenarios.js';
@@ -41,6 +42,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
41
42
  const processorRuntime = new EventProcessorRuntime(journal, checkpoints, subscriptionRunSerialiser, clock);
42
43
  const work = createWorkService(journal);
43
44
  const artifacts = createArtifactService(journal, new FileArtifactStore(paths.artifactsRoot), config.artifacts);
45
+ const artifactContexts = new ArtifactContextService(journal, artifacts);
44
46
  const artifactMcpSessions = new FileArtifactMcpSessionStore(paths.artifactsRoot, () => clock.now().toISOString());
45
47
  const conversations = createConversationService(journal);
46
48
  const lookup = createResourceLookup({ journal, projections });
@@ -86,6 +88,14 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
86
88
  ? profileDecorator
87
89
  : (runner, name) => profileDecorator(options.decorateRunner(runner, name), name);
88
90
  const runners = createRunnerRegistry(config.execution, fakeScenarios, decorateRunner);
91
+ const artifactTriggerContext = createArtifactTriggerContext({
92
+ journal,
93
+ contexts: artifactContexts,
94
+ artifacts,
95
+ orchestration,
96
+ triggers: config.controlPlane.triggers,
97
+ now: () => clock.now().toISOString(),
98
+ });
89
99
  const execution = createExecutionService(journal, activities, config.execution, {
90
100
  clock,
91
101
  ids,
@@ -97,6 +107,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
97
107
  wakeRoot: paths.wakeRoot,
98
108
  now: () => clock.now().toISOString(),
99
109
  nextId: () => ids.next('artifact'),
110
+ sharedContext: artifactTriggerContext.provision,
100
111
  }),
101
112
  reportRunnerQuota: createRunnerQuotaReporter(journal, clock, ids),
102
113
  ...(transcriptStore !== undefined
@@ -174,6 +185,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
174
185
  processorRuntime,
175
186
  activities,
176
187
  runners,
188
+ reconcileArtifactContext: artifactTriggerContext.reconcile,
177
189
  triggerCheckpoints: options.triggerCheckpoints ?? new ProcessorTriggerCheckpointStore(processorState),
178
190
  ...(options.triggerCoordinationKey === undefined
179
191
  ? {}
@@ -341,6 +341,7 @@ export declare const rootConfigSchema: z.ZodObject<{
341
341
  triggers: z.ZodDefault<z.ZodArray<z.ZodObject<{
342
342
  id: z.ZodString;
343
343
  workflow: z.ZodString;
344
+ contextScope: z.ZodOptional<z.ZodString>;
344
345
  on: z.ZodObject<{
345
346
  events: z.ZodOptional<z.ZodArray<z.ZodString>>;
346
347
  cron: z.ZodOptional<z.ZodString>;
@@ -45,6 +45,7 @@ export interface IntegrationRuntimeInput {
45
45
  readonly subscriptionRunSerialiser: ProcessorRunSerialiser;
46
46
  readonly processorRuntime: EventProcessorRuntime;
47
47
  readonly triggerCheckpoints: TriggerCheckpointStore;
48
+ readonly reconcileArtifactContext?: () => Promise<void>;
48
49
  readonly triggerCoordinationKey?: (config: TriggerConfig) => string;
49
50
  readonly decorateDeliveryAdapter?: (adapter: ExternalDeliveryAdapter, provider: ProviderInstance) => ExternalDeliveryAdapter;
50
51
  readonly fakeDeliveryProvider?: DurableFakeDeliveryProvider;
@@ -232,6 +232,7 @@ export async function composeIntegrationRuntime(input) {
232
232
  const runnerPipeline = createRunnerPipeline({
233
233
  isPaused: input.isPaused,
234
234
  runTriggers: () => observeMemory(memoryProfile, 'runner.triggers', async () => {
235
+ await input.reconcileArtifactContext?.();
235
236
  await triggers.reconcile({
236
237
  commandId: input.ids.next('command'),
237
238
  correlationId: correlationId('trigger-recovery'),
@@ -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.63";
127
+ export const wakeVersion = "v0.4.64";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -1,3 +1,4 @@
1
+ import { artifactContextCoordinationKey } from '../contracts/config.js';
1
2
  import { ControlEventType, TriggerRequestDisposition, TriggerSourceKind, } from '../contracts/events.js';
2
3
  import { TriggerSkipReason } from '../contracts/trigger-diagnostics.js';
3
4
  import { CronTriggerPolicy } from '../domain/cron-trigger-policy.js';
@@ -87,7 +88,9 @@ export class TriggerService {
87
88
  return this.dependencies.serialise(triggerCriticalSectionConsumer, new AbortController().signal, operation);
88
89
  }
89
90
  key(config) {
90
- return this.dependencies.coordinationKey?.(config) ?? config.id;
91
+ return config.contextScope === undefined
92
+ ? (this.dependencies.coordinationKey?.(config) ?? config.id)
93
+ : artifactContextCoordinationKey(config.contextScope);
91
94
  }
92
95
  commandKey(triggerId) {
93
96
  const config = this.configured(triggerId);
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  export interface TriggerConfig {
3
3
  readonly id: string;
4
4
  readonly workflow: string;
5
+ readonly contextScope?: string;
5
6
  readonly on: {
6
7
  readonly events?: readonly string[];
7
8
  readonly cron?: string;
@@ -25,6 +26,7 @@ export declare const controlPlaneConfigSchema: z.ZodDefault<z.ZodObject<{
25
26
  triggers: z.ZodDefault<z.ZodArray<z.ZodObject<{
26
27
  id: z.ZodString;
27
28
  workflow: z.ZodString;
29
+ contextScope: z.ZodOptional<z.ZodString>;
28
30
  on: z.ZodObject<{
29
31
  events: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
32
  cron: z.ZodOptional<z.ZodString>;
@@ -38,3 +40,4 @@ export declare const controlPlaneConfigSchema: z.ZodDefault<z.ZodObject<{
38
40
  maxPollBackoffMs: z.ZodOptional<z.ZodNumber>;
39
41
  }, z.core.$strict>>;
40
42
  }, z.core.$strict>>;
43
+ export declare function artifactContextCoordinationKey(contextScope: string): string;
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { artifactSharedContextNameSchema } from '../../artifacts/index.js';
2
3
  import { CronTriggerPolicy } from '../domain/cron-trigger-policy.js';
3
4
  const triggerSchema = z
4
5
  .object({
@@ -8,6 +9,7 @@ const triggerSchema = z
8
9
  .min(1)
9
10
  .refine((id) => !/[\\/]/.test(id), 'Trigger id must not contain path separators'),
10
11
  workflow: z.string().trim().min(1),
12
+ contextScope: artifactSharedContextNameSchema.optional(),
11
13
  on: z
12
14
  .object({
13
15
  events: z.array(z.string().trim().min(1)).min(1).optional(),
@@ -59,3 +61,6 @@ export const controlPlaneConfigSchema = z
59
61
  triggers: [],
60
62
  resident: { pollBackoffMs: 1000 },
61
63
  });
64
+ export function artifactContextCoordinationKey(contextScope) {
65
+ return `context:${contextScope}`;
66
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/wake",
3
- "version": "0.4.63",
3
+ "version": "0.4.64",
4
4
  "description": "Local autonomous agent control plane for software development",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {