@atolis-hq/wake 0.4.84 → 0.4.86

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.
@@ -3,9 +3,9 @@ import { createPullRequestService, type ActivityRegistry } from '../activities/i
3
3
  import { OperatorInstructionsService, createArtifactService } from '../artifacts/index.js';
4
4
  import { createControlPlaneService, createRunnerControlService, type ActivationScheduler, type ActivationSchedulerSubscriber, type IntakePipeline, type RunnerPipeline, type TriggerCheckpointStore, type TriggerConfig, type TriggerService } from '../control-plane/index.js';
5
5
  import { createConversationService } from '../conversations/index.js';
6
- import { RecoveryService, TranscriptStore, createExecutionService, type FakeScenarioResolver, type Runner } from '../execution/index.js';
6
+ import { GitWorkspaceProvider, RecoveryService, TranscriptStore, createExecutionService, type FakeScenarioResolver, type Runner } from '../execution/index.js';
7
7
  import type { DeliveryService, DurableFakeDeliveryProvider, ExternalDeliveryAdapter, ProviderCompositionFailure, ProviderInstance } from '../integrations/index.js';
8
- import { type Clock } from '../kernel/index.js';
8
+ import { UlidIdGenerator, type Clock } from '../kernel/index.js';
9
9
  import { createOrchestrationService } from '../orchestration/index.js';
10
10
  import { createResourceLookup, createResourceService, type ResourceLinkResolver } from '../resources/index.js';
11
11
  import { createWorkService } from '../work/index.js';
@@ -41,6 +41,7 @@ export interface CompositionRootOptions {
41
41
  readonly fakeDeliveryProvider?: DurableFakeDeliveryProvider;
42
42
  }
43
43
  export interface CompositionRoot {
44
+ readonly workflowNotices: readonly string[];
44
45
  readonly triggers: TriggerService;
45
46
  readonly config: ResolvedWakeModulesConfig;
46
47
  readonly fakeScenarios: FakeScenarioResolver;
@@ -80,4 +81,65 @@ export interface CompositionRoot {
80
81
  readonly requestImmediatePoll: (adapter: string) => void;
81
82
  readonly resolveResourceLink: ResourceLinkResolver;
82
83
  }
84
+ export declare function createDiagnosticRoot(wakeRoot: string): Promise<{
85
+ providers: readonly ProviderInstance[];
86
+ providerFailures: readonly ProviderCompositionFailure[];
87
+ config: ResolvedWakeModulesConfig;
88
+ fakeScenarios: FakeScenarioResolver;
89
+ workflowNotices: string[];
90
+ paths: WakePaths;
91
+ maintenance: UpdateMaintenanceLease;
92
+ clock: Clock;
93
+ ids: UlidIdGenerator;
94
+ journal: EventJournal;
95
+ projections: ProjectionStore;
96
+ checkpoints: CheckpointStore;
97
+ processorState: ProcessorStateStore;
98
+ subscriptionRunSerialiser: ProcessorRunSerialiser;
99
+ work: import("../work/index.js").WorkService;
100
+ artifacts: import("../artifacts/index.js").ArtifactService;
101
+ operatorInstructions: OperatorInstructionsService;
102
+ conversations: import("../conversations/index.js").ConversationService;
103
+ resources: import("../resources/index.js").ResourceService;
104
+ pullRequests: import("../activities/index.js").PullRequestService;
105
+ lookup: import("../resources/index.js").ResourceLookup;
106
+ orchestration: import("../orchestration/index.js").OrchestrationService;
107
+ execution: {
108
+ attempt: (activation: import("../execution/index.js").ExecutionActivation, context: import("../execution/index.js").ExecutionAttemptContext) => Promise<import("../execution/index.js").RunView>;
109
+ list: (activationId?: import("../execution/index.js").ExecutionActivation["activationId"]) => Promise<readonly import("../execution/index.js").RunView[]>;
110
+ isLocallyActive: (id: string) => boolean;
111
+ claim: (id: string, owner: string) => Promise<import("../execution/index.js").RunView>;
112
+ renewLease: (id: string, owner: string) => Promise<import("../execution/index.js").RunView>;
113
+ requestCancellation: (id: string, reason: NonNullable<import("../execution/index.js").RunView["cancellation"]>["reason"]) => Promise<import("../execution/index.js").RunView>;
114
+ confirmCancellation: (id: string) => Promise<import("../execution/index.js").RunView>;
115
+ cancelActive: (workflowInstanceIds: readonly string[], reason: NonNullable<import("../execution/index.js").RunView["cancellation"]>["reason"]) => Promise<import("../execution/index.js").RunView[]>;
116
+ shutdown: () => Promise<void>;
117
+ };
118
+ recovery: RecoveryService;
119
+ transcriptStore: TranscriptStore | undefined;
120
+ runnerControls: import("../control-plane/index.js").RunnerControlService;
121
+ controlPlane: import("../control-plane/index.js").ControlPlaneService;
122
+ isRuntimePaused: () => Promise<boolean>;
123
+ activities: ActivityRegistry;
124
+ runners: import("../execution/index.js").RunnerRegistry;
125
+ artifactTriggerContext: {
126
+ provision(item: string): Promise<{
127
+ contextScope?: never;
128
+ sharedReferences?: never;
129
+ currentMemory?: never;
130
+ } | {
131
+ contextScope: string;
132
+ sharedReferences: readonly {
133
+ workItemId: import("../work/index.js").WorkItemId;
134
+ revisionId: string;
135
+ }[];
136
+ currentMemory: {
137
+ workItemId: import("../work/index.js").WorkItemId;
138
+ revisionId: string;
139
+ } | null;
140
+ }>;
141
+ reconcile(): Promise<void>;
142
+ };
143
+ workspaces: GitWorkspaceProvider;
144
+ }>;
83
145
  export declare function createCompositionRoot(wakeRoot: string, options?: CompositionRootOptions): Promise<CompositionRoot>;
@@ -16,7 +16,7 @@ import { createArtifactTriggerContext } from './artifact-trigger-context.js';
16
16
  import { loadConfig } from './config/load-config.js';
17
17
  import { EventProcessorRuntime } from './event-processor-runtime.js';
18
18
  import { loadFakeScenarios } from './fake-scenarios.js';
19
- import { composeIntegrationRuntime } from './integration-runtime.js';
19
+ import { composeIntegrationRuntime, composeProviders } from './integration-runtime.js';
20
20
  import { resolveWakePaths } from './paths.js';
21
21
  import { composePersistence } from './persistence-composition.js';
22
22
  import { createRunnerQuotaReporter } from './runner-quota-reporter.js';
@@ -30,8 +30,7 @@ const resourceLinkResolvers = {
30
30
  function resolveResourceLink(externalKey) {
31
31
  return resourceLinkResolvers[externalKey.adapter]?.(externalKey) ?? null;
32
32
  }
33
- // eslint-disable-next-line complexity
34
- export async function createCompositionRoot(wakeRoot, options = {}) {
33
+ async function createApplicationServices(wakeRoot, options = {}) {
35
34
  const config = options.config ?? (await loadConfig(wakeRoot));
36
35
  const fakeScenarios = await loadFakeScenarios(wakeRoot);
37
36
  const paths = resolveWakePaths(wakeRoot);
@@ -39,7 +38,6 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
39
38
  const clock = options.clock ?? new SystemClock();
40
39
  const ids = new UlidIdGenerator();
41
40
  const { journal, projections, checkpoints, processorState, subscriptionRunSerialiser } = composePersistence(paths, clock, options);
42
- const processorRuntime = new EventProcessorRuntime(journal, checkpoints, subscriptionRunSerialiser, clock);
43
41
  const work = createWorkService(journal);
44
42
  const artifacts = createArtifactService(journal, new FileArtifactStore(paths.artifactsRoot), config.artifacts);
45
43
  const artifactContexts = new ArtifactContextService(journal, artifacts);
@@ -54,9 +52,13 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
54
52
  publicUiUrl: config.surfaces.web.publicUrl,
55
53
  githubAdapters: githubAdapters(config),
56
54
  }, conversations));
55
+ const workflowNotices = [];
57
56
  const definitions = Object.fromEntries(Object.entries(config.orchestration.workflows).map(([name, definition]) => [
58
57
  name,
59
- compileWorkflow(name, definition, activities, Object.keys(config.orchestration.workflows)),
58
+ compileWorkflow(name, definition, activities, Object.keys(config.orchestration.workflows), (diagnostic) => {
59
+ workflowNotices.push(diagnostic.message);
60
+ process.stderr.write(`Warning: ${diagnostic.message}\n`);
61
+ }),
60
62
  ]));
61
63
  const orchestration = createOrchestrationService(journal, work, definitions, projections, createAgentActivityClassifier(activities));
62
64
  const workspaces = new GitWorkspaceProvider(paths.workspacesRoot, {
@@ -135,6 +137,51 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
135
137
  ids,
136
138
  runners: new Set(Object.values(config.execution.runnerPools).flat()),
137
139
  });
140
+ return {
141
+ config,
142
+ fakeScenarios,
143
+ workflowNotices,
144
+ paths,
145
+ maintenance,
146
+ clock,
147
+ ids,
148
+ journal,
149
+ projections,
150
+ checkpoints,
151
+ processorState,
152
+ subscriptionRunSerialiser,
153
+ work,
154
+ artifacts,
155
+ operatorInstructions,
156
+ conversations,
157
+ resources,
158
+ pullRequests,
159
+ lookup,
160
+ orchestration,
161
+ execution,
162
+ recovery,
163
+ transcriptStore,
164
+ runnerControls,
165
+ controlPlane,
166
+ isRuntimePaused,
167
+ activities,
168
+ runners,
169
+ artifactTriggerContext,
170
+ workspaces,
171
+ };
172
+ }
173
+ export async function createDiagnosticRoot(wakeRoot) {
174
+ const base = await createApplicationServices(wakeRoot);
175
+ const { instances, failures } = await composeProviders({
176
+ ...base,
177
+ wakeRoot,
178
+ providerDefinitions: [gitHubProviderDefinition],
179
+ });
180
+ return { ...base, providers: instances, providerFailures: failures };
181
+ }
182
+ export async function createCompositionRoot(wakeRoot, options = {}) {
183
+ const { config, fakeScenarios, workflowNotices, paths, maintenance, clock, ids, journal, projections, checkpoints, processorState, subscriptionRunSerialiser, work, artifacts, operatorInstructions, conversations, resources, pullRequests, lookup, orchestration, execution, recovery, transcriptStore, runnerControls, controlPlane, isRuntimePaused, activities, runners, artifactTriggerContext, workspaces, } = await createApplicationServices(wakeRoot, options);
184
+ const processorRuntime = new EventProcessorRuntime(journal, checkpoints, subscriptionRunSerialiser, clock);
138
185
  const activationScheduler = createActivationScheduler(orchestration, {
139
186
  ...execution,
140
187
  recoverActive: (owner) => recovery.recoverActive(owner, execution.isLocallyActive),
@@ -196,6 +243,7 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
196
243
  });
197
244
  processorRuntime.register([activationSchedulerSubscriber.processor, ...runtime.processors]);
198
245
  return {
246
+ workflowNotices,
199
247
  config,
200
248
  fakeScenarios,
201
249
  paths,
@@ -95,12 +95,18 @@ workflows:
95
95
  with: { template: refine }
96
96
  execution: { workspace: read-only, runnerPool: light }
97
97
  on:
98
+ rejected: { then: await-human }
99
+ blocked: { then: await-human }
100
+ failed: { then: await-human }
98
101
  done: { then: implement }
99
102
  implement:
100
103
  activity: agent
101
104
  with: { template: implement }
102
105
  execution: { workspace: branch, runnerPool: standard }
103
106
  on:
107
+ rejected: { then: await-human }
108
+ blocked: { then: await-human }
109
+ failed: { then: await-human }
104
110
  done: { then: done }
105
111
  approval:
106
112
  entry: refine
@@ -110,6 +116,9 @@ workflows:
110
116
  with: { template: refine }
111
117
  execution: { workspace: read-only, runnerPool: light }
112
118
  on:
119
+ rejected: { then: await-human }
120
+ blocked: { then: await-human }
121
+ failed: { then: await-human }
113
122
  done:
114
123
  then: implement
115
124
  await:
@@ -120,6 +129,9 @@ workflows:
120
129
  with: { template: implement }
121
130
  execution: { workspace: branch, runnerPool: standard }
122
131
  on:
132
+ rejected: { then: await-human }
133
+ blocked: { then: await-human }
134
+ failed: { then: await-human }
123
135
  done: { then: done }`;
124
136
  // Frontmatter is limited to model/maxTurns/allowedTools/extraArgs (see
125
137
  // execution/infrastructure/prompt-templates.ts). The scaffold bodies use
@@ -54,3 +54,4 @@ export interface IntegrationRuntimeInput {
54
54
  export declare function composeIntegrationRuntime(input: IntegrationRuntimeInput): Promise<IntegrationRuntime>;
55
55
  /** Coalesces provider webhook requests while retaining the source's durable poll semantics. */
56
56
  export declare function createImmediatePollRequester(providers: readonly ProviderInstance[], journal: EventJournal, wakeRoot: string): (adapter: string) => void;
57
+ export declare function composeProviders(input: Pick<IntegrationRuntimeInput, 'wakeRoot' | 'config' | 'work' | 'conversations' | 'resources' | 'lookup' | 'pullRequests' | 'journal' | 'orchestration' | 'ids' | 'clock' | 'checkpoints' | 'execution' | 'providerDefinitions'>): Promise<import("../integrations/index.js").ProviderCompositionResult>;
@@ -22,27 +22,7 @@ export async function composeIntegrationRuntime(input) {
22
22
  memoryUsage: () => process.memoryUsage(),
23
23
  })
24
24
  : undefined;
25
- const registry = new ProviderRegistry();
26
- registry.register(fakeProviderDefinition);
27
- for (const definition of input.providerDefinitions)
28
- registry.register(definition);
29
- const { instances, failures: providerFailures } = registry.compose(await hydrateFakeProviderEvidence(input.wakeRoot, input.config.integrations), {
30
- publicUiUrl: input.config.surfaces.web.publicUrl,
31
- providerStateRoot: join(input.wakeRoot, '.wake'),
32
- work: input.work,
33
- conversations: input.conversations,
34
- resources: input.resources,
35
- resourceLookup: input.lookup,
36
- pullRequests: input.pullRequests,
37
- runs: new RunRepository(input.journal),
38
- orchestration: input.orchestration,
39
- ids: input.ids,
40
- clock: input.clock,
41
- journal: input.journal,
42
- checkpoints: input.checkpoints,
43
- routing: createWorkflowRouter(input.config.orchestration),
44
- conclusion: createWorkCancellationPolicy(input.work, input.orchestration, input.execution, input.clock, input.ids),
45
- });
25
+ const { instances, failures: providerFailures } = await composeProviders(input);
46
26
  const composedProviders = input.fakeDeliveryProvider === undefined
47
27
  ? instances
48
28
  : instances.map((provider) => provider.adapter === 'fake'
@@ -351,3 +331,26 @@ function createWorkflowRouter(orchestration) {
351
331
  const fallback = workflowName(orchestration.default);
352
332
  return { select: (candidate) => selectWorkflow(candidate, selectors, fallback) };
353
333
  }
334
+ export async function composeProviders(input) {
335
+ const registry = new ProviderRegistry();
336
+ registry.register(fakeProviderDefinition);
337
+ for (const definition of input.providerDefinitions)
338
+ registry.register(definition);
339
+ return registry.compose(await hydrateFakeProviderEvidence(input.wakeRoot, input.config.integrations), {
340
+ publicUiUrl: input.config.surfaces.web.publicUrl,
341
+ providerStateRoot: join(input.wakeRoot, '.wake'),
342
+ work: input.work,
343
+ conversations: input.conversations,
344
+ resources: input.resources,
345
+ resourceLookup: input.lookup,
346
+ pullRequests: input.pullRequests,
347
+ runs: new RunRepository(input.journal),
348
+ orchestration: input.orchestration,
349
+ ids: input.ids,
350
+ clock: input.clock,
351
+ journal: input.journal,
352
+ checkpoints: input.checkpoints,
353
+ routing: createWorkflowRouter(input.config.orchestration),
354
+ conclusion: createWorkCancellationPolicy(input.work, input.orchestration, input.execution, input.clock, input.ids),
355
+ });
356
+ }
@@ -8,3 +8,4 @@ export interface SurfaceApplications {
8
8
  readonly cli: WakeCliApplications;
9
9
  }
10
10
  export declare function createSurfaceApplications(root: CompositionRoot, options?: SurfaceApplicationOptions): SurfaceApplications;
11
+ export { runHostCommand } from './surface-cli-applications.js';
@@ -5,3 +5,4 @@ export function createSurfaceApplications(root, options = {}) {
5
5
  const api = createSurfaceApiApplications(root, now);
6
6
  return { api, cli: createSurfaceCliApplications(root, api, now) };
7
7
  }
8
+ export { runHostCommand } from './surface-cli-applications.js';
@@ -1,7 +1,9 @@
1
1
  import { type HostBudget, type HostResult } from '../control-plane/index.js';
2
- import { type ApiApplications, type WakeCliApplications } from '../surfaces/index.js';
3
- import type { CompositionRoot } from './composition-root.js';
2
+ import { type ApiApplications, type CliOutput, type WakeCliApplications, type WakeCommand } from '../surfaces/index.js';
3
+ import { type CompositionRoot } from './composition-root.js';
4
4
  import { type SelfUpdateQuiescePort } from './self-update-application.js';
5
+ /** Host operations never register processors or establish trigger recovery state. */
6
+ export declare function runHostCommand(command: WakeCommand, wakeRoot: string, output: CliOutput): Promise<boolean>;
5
7
  export declare function createSurfaceCliApplications(root: CompositionRoot, api: ApiApplications, now: () => string): WakeCliApplications;
6
8
  export declare function createRunnerIdleWait(root: Pick<CompositionRoot, 'journal'>, resident: {
7
9
  readonly pollBackoffMs: number;
@@ -9,13 +9,16 @@ import { BuiltInActivityName, agentActivityDefinition } from '../activities/inde
9
9
  import { FileArtifactMcpSessionStore } from '../artifacts/index.js';
10
10
  import { IntakeHost, ResidentHost, TickHost, } from '../control-plane/index.js';
11
11
  import { ExecutionFailureCode, RunStatus, isActiveRunStatus, loadPromptTemplate, } from '../execution/index.js';
12
- import { UlidIdGenerator } from '../kernel/index.js';
12
+ import { SystemClock, UlidIdGenerator } from '../kernel/index.js';
13
13
  import { ResourceCorrelationRole, resourceId } from '../resources/index.js';
14
- import { DockerProcessError, createApiDispatcher, createLoggedDockerCli, createPackagedAssetSource, createPairingGrant, createProcessLogSink, createSandboxDockerPort, createSurfaceHttpServer, describeSandboxStartupFailure, drainProcessOutput, loadOrCreateCredentials, promoteSandboxImage, redeemPairingGrant, replaceAccessKey, runDoctor, runSandbox, runSandboxEntrypoint, runSandboxSetup, runSelfUpdateLatestLoop, runTargetSmoke, serveMcpOverStdio, verifyResidentStart, waitForActiveRuns, waitForever, } from '../surfaces/index.js';
14
+ import { DockerProcessError, WakeOperationalCommand, createApiDispatcher, createLoggedDockerCli, createPackagedAssetSource, createPairingGrant, createProcessLogSink, createSandboxDockerPort, createSurfaceHttpServer, describeSandboxStartupFailure, drainProcessOutput, loadOrCreateCredentials, promoteSandboxImage, redeemPairingGrant, replaceAccessKey, runDoctor, runSandbox, runSandboxEntrypoint, runSandboxSetup, runSelfUpdateLatestLoop, runTargetSmoke, runWakeReadCommand, serveMcpOverStdio, verifyResidentStart, waitForActiveRuns, waitForever, } from '../surfaces/index.js';
15
15
  import { WorkStreamKind, workItemId } from '../work/index.js';
16
16
  import { createArtifactMcpServerForSession } from './artifact-mcp.js';
17
+ import { createDiagnosticRoot } from './composition-root.js';
17
18
  import { loadConfig } from './config/load-config.js';
18
19
  import { createNpmUpdatePort } from './npm-update-port.js';
20
+ import { resolveWakePaths } from './paths.js';
21
+ import { composePersistence } from './persistence-composition.js';
19
22
  import { runtimeProjectionDefinitions } from './projection-runtime.js';
20
23
  import { createRunnerRegistry } from './runner-registry.js';
21
24
  import { createOneShotRunnerAdvance, createResidentRunnerAdvance, withFinalProjectionCatchUp, } from './runner-tick-adapter.js';
@@ -24,9 +27,41 @@ import { createSelfUpdateApplication, } from './self-update-application.js';
24
27
  import { createSelfUpdateFailureLog } from './self-update-failure-log.js';
25
28
  import { createSourceUpdatePort } from './source-update-port.js';
26
29
  import { createUpdateLedger } from './update-ledger.js';
27
- import { UpdateMaintenancePhase } from './update-maintenance-lease.js';
30
+ import { UpdateMaintenancePhase, createUpdateMaintenanceLease, } from './update-maintenance-lease.js';
28
31
  import { resolveWakeVersion, wakePackageVersion } from './version.js';
29
32
  const execFile = promisify(nodeExecFile);
33
+ /** Host operations never register processors or establish trigger recovery state. */
34
+ export async function runHostCommand(command, wakeRoot, output) {
35
+ if (command.kind === 'sandbox') {
36
+ const root = { config: await loadConfig(wakeRoot), paths: resolveWakePaths(wakeRoot) };
37
+ const arguments_ = withoutOperationalWakeRoot(command.arguments);
38
+ await runSandboxManagement(root, arguments_);
39
+ return true;
40
+ }
41
+ if (command.kind === 'doctor' && !command.arguments.includes('--rebuild-projections')) {
42
+ const root = await createDiagnosticRoot(wakeRoot);
43
+ return runWakeReadCommand(command, {
44
+ doctor: async () => runDoctor({
45
+ diagnose: () => doctorDiagnostics(root),
46
+ projections: {
47
+ health: () => projectionHealth(root),
48
+ rebuild: async () => {
49
+ throw new Error('Read-only diagnostics cannot rebuild projections');
50
+ },
51
+ },
52
+ }),
53
+ }, output);
54
+ }
55
+ if (command.kind === 'audit' ||
56
+ (command.kind === 'validate-state' && !command.rebuildProjections)) {
57
+ const stores = composePersistence(resolveWakePaths(wakeRoot), new SystemClock(), {});
58
+ return runWakeReadCommand(command, {
59
+ audit: createAuditApplication(stores),
60
+ validateState: { health: createStateHealth(stores) },
61
+ }, output);
62
+ }
63
+ return false;
64
+ }
30
65
  export function createSurfaceCliApplications(root, api, now) {
31
66
  const artifactMcpSessions = new FileArtifactMcpSessionStore(root.paths.artifactsRoot, now);
32
67
  const artifactMcpIds = new UlidIdGenerator();
@@ -120,20 +155,7 @@ export function createSurfaceCliApplications(root, api, now) {
120
155
  ].join('\n');
121
156
  },
122
157
  },
123
- audit: {
124
- async read(id) {
125
- return (await root.journal.readAll(0))
126
- .filter((event) => event.stream.kind === WorkStreamKind.WorkItem && event.stream.id === id)
127
- .map((event) => ({
128
- eventId: event.event.eventId,
129
- eventType: event.event.eventType,
130
- occurredAt: event.event.occurredAt,
131
- stream: `${event.stream.kind}:${event.stream.id}`,
132
- causationId: event.event.causationId,
133
- correlationId: event.event.correlationId,
134
- }));
135
- },
136
- },
158
+ audit: createAuditApplication(root),
137
159
  correlate: {
138
160
  async correlate(resource, work) {
139
161
  return root.resources.correlate(resourceId(resource), workItemId(work), ResourceCorrelationRole.Primary, commandContext(`correlate:${resource}:${work}`, now()));
@@ -481,6 +503,26 @@ async function rollbackSandboxTag(root, docker, image, development) {
481
503
  await verifyResidentStart(docker, root.config.host.sandbox.containerName, [...wakeInvocation, 'start', '--wake-root', '/wake'].join(' '));
482
504
  await promoteSandboxImage(docker, image, root.config.host.sandbox.image);
483
505
  }
506
+ async function runSandboxManagement(root, arguments_) {
507
+ const docker = await createSandboxDockerForCommand(root, arguments_);
508
+ await runSandbox(arguments_, docker);
509
+ if (arguments_[0] !== 'update')
510
+ return;
511
+ const maintenance = createUpdateMaintenanceLease(root.paths.wakeRoot);
512
+ if ((await maintenance.read())?.phase !== UpdateMaintenancePhase.Failed)
513
+ return;
514
+ // The new container owns runtime writes; clearFailed still refuses a changed active lease.
515
+ await docker.exec([
516
+ ...sandboxWakeInvocation(root),
517
+ WakeOperationalCommand.Maintenance,
518
+ 'clear',
519
+ '--failed',
520
+ '--wake-root',
521
+ '/wake',
522
+ '--no-sandbox',
523
+ ]);
524
+ }
525
+ // Direct facade consumers also use these; production host reads dispatch before full composition.
484
526
  function createOperationalApplications(root) {
485
527
  return {
486
528
  init: async () => unsupportedOperationalCommand('init'),
@@ -511,12 +553,7 @@ function createOperationalApplications(root) {
511
553
  await runSandboxSetup(createSandboxSetupDependencies(root.config.host.sandbox.containerHomeMountPath));
512
554
  },
513
555
  sandbox: async (arguments_) => {
514
- await runSandbox(arguments_, await createSandboxDockerForCommand(root, arguments_));
515
- // A manual sandbox replacement can recover a previously failed update,
516
- // but never clear an in-progress self-update owned by another process.
517
- if (arguments_[0] === 'update' &&
518
- (await root.maintenance.read())?.phase === UpdateMaintenancePhase.Failed)
519
- await root.maintenance.clear();
556
+ await runSandboxManagement(root, withoutOperationalWakeRoot(arguments_));
520
557
  },
521
558
  sandboxEntrypoint: async () => {
522
559
  await runSandboxEntrypoint(createSandboxEntrypointDependencies(root));
@@ -660,7 +697,7 @@ function spawnDocker(arguments_, onChunk, cwd, options) {
660
697
  }
661
698
  async function doctorDiagnostics(root) {
662
699
  const failures = [];
663
- const notices = [];
700
+ const notices = [...root.workflowNotices];
664
701
  const templates = new Map();
665
702
  try {
666
703
  createRunnerRegistry(root.config.execution, root.fakeScenarios).resolve(root.config.execution.defaultRunnerPool);
@@ -732,7 +769,8 @@ async function checkMaintenanceLease(root, failures) {
732
769
  const detail = lease.failure === undefined ? '' : ` (${lease.failure})`;
733
770
  failures.push(`update maintenance lease is held in phase "${lease.phase}" since ${lease.startedAt}${detail} -- ` +
734
771
  'every resident loop stays paused until it is cleared or resumes; run `wake self-update` ' +
735
- 'to retry, or clear the lease manually if the attempt is abandoned');
772
+ 'to retry, or run `wake sandbox exec -- wake maintenance clear --failed --wake-root /wake --no-sandbox` ' +
773
+ 'from the host if abandoning a failed sandbox update (without a sandbox, run `wake maintenance clear --failed` as the runtime-state owner)');
736
774
  }
737
775
  async function checkProviders(root, failures, notices) {
738
776
  for (const provider of root.providers) {
@@ -820,12 +858,16 @@ function selfUpdateLoopInterval(arguments_) {
820
858
  function withoutOperationalWakeRoot(arguments_) {
821
859
  const result = [];
822
860
  for (let index = 0; index < arguments_.length; index += 1) {
861
+ if (arguments_[index] === '--') {
862
+ result.push(...arguments_.slice(index));
863
+ break;
864
+ }
823
865
  if (arguments_[index] !== '--wake-root') {
824
866
  result.push(arguments_[index]);
825
867
  continue;
826
868
  }
827
869
  if (arguments_[index + 1] === undefined)
828
- throw new Error('wake maintenance requires --wake-root <path>');
870
+ throw new Error('wake command requires --wake-root <path>');
829
871
  index += 1;
830
872
  }
831
873
  return result;
@@ -845,14 +887,17 @@ function optionalOperationalOption(arguments_, option) {
845
887
  function unsupportedOperationalCommand(command) {
846
888
  throw new Error(`wake ${command} has not been composed`);
847
889
  }
890
+ function createStateHealth(root) {
891
+ return async () => {
892
+ await root.journal.readAll(0, 1);
893
+ await root.projections.list('work');
894
+ await root.checkpoints.load('surface-health');
895
+ return { journal: 'ok', projections: 'ok', checkpoints: 'ok' };
896
+ };
897
+ }
848
898
  function createValidationApplications(root) {
849
899
  return {
850
- async health() {
851
- await root.journal.readAll(0, 1);
852
- await root.projections.list('work');
853
- await root.checkpoints.load('surface-health');
854
- return { journal: 'ok', projections: 'ok', checkpoints: 'ok' };
855
- },
900
+ health: createStateHealth(root),
856
901
  async rebuildProjections() {
857
902
  for (const definition of runtimeProjectionDefinitions)
858
903
  await root.projectionSubscriptions.rebuild(definition);
@@ -985,3 +1030,19 @@ function runInteractive(command, arguments_) {
985
1030
  });
986
1031
  });
987
1032
  }
1033
+ function createAuditApplication(root) {
1034
+ return {
1035
+ async read(id) {
1036
+ return (await root.journal.readAll(0))
1037
+ .filter((event) => event.stream.kind === WorkStreamKind.WorkItem && event.stream.id === id)
1038
+ .map((event) => ({
1039
+ eventId: event.event.eventId,
1040
+ eventType: event.event.eventType,
1041
+ occurredAt: event.event.occurredAt,
1042
+ stream: `${event.stream.kind}:${event.stream.id}`,
1043
+ causationId: event.event.causationId,
1044
+ correlationId: event.event.correlationId,
1045
+ }));
1046
+ },
1047
+ };
1048
+ }
@@ -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.84";
127
+ export const wakeVersion = "v0.4.86";
128
128
  /** The registry-installable version used by packaged sandbox images. */
129
129
  export const wakePackageVersion = packageVersion(defaultRepoRoot) ?? wakeVersion;
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { type CliOutput, type WakeCliApplications } from './surfaces/index.js';
2
+ import { type CliOutput, type WakeCliApplications, type WakeCommand } from './surfaces/index.js';
3
3
  export interface TargetMainDependencies {
4
4
  readonly compose: (wakeRoot: string) => Promise<WakeCliApplications>;
5
+ readonly runHostCommand?: (command: WakeCommand, wakeRoot: string, output: CliOutput) => Promise<boolean>;
5
6
  readonly initialise?: (wakeRoot: string) => Promise<unknown>;
6
7
  readonly sandboxRuntime?: SandboxRuntimeRouter;
7
8
  readonly output: CliOutput;
package/dist/src/main.js CHANGED
@@ -21,17 +21,10 @@ export async function main(argv = process.argv.slice(2), dependencies) {
21
21
  resolvedDependencies.output.write(`${JSON.stringify(result)}\n`);
22
22
  return;
23
23
  }
24
- if (resolvedDependencies.sandboxRuntime !== undefined) {
25
- const sandboxRuntime = resolvedDependencies.sandboxRuntime;
26
- const ranInSandbox = await runInSandboxIfAvailable({
27
- commandKind: command.kind,
28
- bypassSandbox,
29
- hasDockerfile: () => sandboxRuntime.hasDockerfile(wakeRoot),
30
- exec: () => sandboxRuntime.exec(wakeRoot, rewriteSandboxArguments(suppliedArguments)),
31
- });
32
- if (ranInSandbox)
33
- return;
34
- }
24
+ if (await routeSandboxCommand(command, wakeRoot, suppliedArguments, bypassSandbox, resolvedDependencies.sandboxRuntime))
25
+ return;
26
+ if (await runHostCommandIfAvailable(command, wakeRoot, output, resolvedDependencies))
27
+ return;
35
28
  const applications = await resolvedDependencies.compose(wakeRoot);
36
29
  if (applications.sandboxRuntime !== undefined) {
37
30
  const sandboxRuntime = applications.sandboxRuntime;
@@ -46,6 +39,19 @@ export async function main(argv = process.argv.slice(2), dependencies) {
46
39
  }
47
40
  await runWakeCommand(command, applications, resolvedDependencies.output, resolvedDependencies.signal);
48
41
  }
42
+ async function runHostCommandIfAvailable(command, wakeRoot, output, dependencies) {
43
+ return (await dependencies.runHostCommand?.(command, wakeRoot, output)) ?? false;
44
+ }
45
+ async function routeSandboxCommand(command, wakeRoot, arguments_, bypassSandbox, router) {
46
+ if (router === undefined)
47
+ return false;
48
+ return runInSandboxIfAvailable({
49
+ commandKind: command.kind,
50
+ bypassSandbox,
51
+ hasDockerfile: () => router.hasDockerfile(wakeRoot),
52
+ exec: () => router.exec(wakeRoot, rewriteSandboxArguments(arguments_)),
53
+ });
54
+ }
49
55
  function normalizeDeveloperAlias(arguments_) {
50
56
  if (arguments_[0] !== 'dev' || arguments_[1] !== 'sandbox')
51
57
  return arguments_;
@@ -124,8 +130,10 @@ function rewriteSandboxArguments(arguments_) {
124
130
  return [...rewritten, '--no-sandbox'];
125
131
  }
126
132
  function operationalWakeRoot(arguments_) {
127
- const index = arguments_.indexOf('--wake-root');
128
- return index === -1 ? undefined : arguments_[index + 1];
133
+ const end = arguments_.indexOf('--');
134
+ const options = end === -1 ? arguments_ : arguments_.slice(0, end);
135
+ const index = options.indexOf('--wake-root');
136
+ return index === -1 ? undefined : options[index + 1];
129
137
  }
130
138
  function productionDependencies() {
131
139
  const controller = new AbortController();
@@ -133,6 +141,10 @@ function productionDependencies() {
133
141
  process.once('SIGTERM', () => controller.abort());
134
142
  return {
135
143
  initialise: initialiseWakeRoot,
144
+ async runHostCommand(command, wakeRoot, output) {
145
+ const { runHostCommand } = await import('./bootstrap/surface-applications.js');
146
+ return runHostCommand(command, wakeRoot, output);
147
+ },
136
148
  sandboxRuntime: productionSandboxRuntime(),
137
149
  async compose(wakeRoot) {
138
150
  const [{ createCompositionRoot }, { createSurfaceApplications }] = await Promise.all([
@@ -0,0 +1,4 @@
1
+ import { type ActivityRegistry } from '../../activities/index.js';
2
+ import type { CompiledSupplementalCommand, WorkflowDefinitionConfig } from '../contracts/config.js';
3
+ import { commandName } from '../contracts/identifiers.js';
4
+ export declare function compileCommands(config: WorkflowDefinitionConfig, activities: ActivityRegistry): Record<ReturnType<typeof commandName>, CompiledSupplementalCommand>;
@@ -0,0 +1,12 @@
1
+ import { activityName } from '../../activities/index.js';
2
+ import { commandName } from '../contracts/identifiers.js';
3
+ export function compileCommands(config, activities) {
4
+ return Object.fromEntries(Object.entries(config.commands ?? {}).map(([command, configured]) => [
5
+ commandName(command),
6
+ Object.freeze({
7
+ activity: activityName(configured.activity),
8
+ with: activities.validateInput(activityName(configured.activity), configured.with),
9
+ allowedActors: Object.freeze([...configured.allowedActors]),
10
+ }),
11
+ ]));
12
+ }
@@ -0,0 +1,10 @@
1
+ import type { ActivityRegistry } from '../../activities/index.js';
2
+ import type { CompiledStage } from '../contracts/config.js';
3
+ import type { StageName } from '../contracts/identifiers.js';
4
+ export interface WorkflowCompileDiagnostic {
5
+ readonly workflow: string;
6
+ readonly stage: string;
7
+ readonly outcome: string;
8
+ readonly message: string;
9
+ }
10
+ export declare function reportUnroutedOutcomes(workflow: string, stages: Readonly<Record<StageName, CompiledStage>>, activities: ActivityRegistry, report: (diagnostic: WorkflowCompileDiagnostic) => void): void;
@@ -0,0 +1,14 @@
1
+ export function reportUnroutedOutcomes(workflow, stages, activities, report) {
2
+ for (const [stage, configured] of Object.entries(stages)) {
3
+ for (const outcome of activities.describe(configured.activity).outcomeKinds) {
4
+ if (Object.hasOwn(configured.on, outcome))
5
+ continue;
6
+ report({
7
+ workflow,
8
+ stage,
9
+ outcome,
10
+ message: `Workflow "${workflow}" stage "${stage}": declared outcome "${outcome}" has no route.`,
11
+ });
12
+ }
13
+ }
14
+ }
@@ -1,3 +1,4 @@
1
1
  import { type ActivityRegistry } from '../../activities/index.js';
2
2
  import { type CompiledWorkflow } from '../contracts/config.js';
3
- export declare function compileWorkflow(name: string, input: unknown, activities: ActivityRegistry, knownWorkflowNames?: readonly string[]): CompiledWorkflow;
3
+ import { type WorkflowCompileDiagnostic } from './compile-diagnostics.js';
4
+ export declare function compileWorkflow(name: string, input: unknown, activities: ActivityRegistry, knownWorkflowNames?: readonly string[], reportDiagnostic?: (diagnostic: WorkflowCompileDiagnostic) => void): CompiledWorkflow;
@@ -1,12 +1,14 @@
1
1
  import { ActivityEventType, ActivityExecutionKind, activityName, ActivityOutcomeKind, } from '../../activities/index.js';
2
2
  import { workflowDefinitionConfigSchema, } from '../contracts/config.js';
3
- import { commandName, signalName, stageName, watchId, workflowName, } from '../contracts/identifiers.js';
3
+ import { signalName, stageName, watchId, workflowName, } from '../contracts/identifiers.js';
4
4
  import { ApprovalAuthorityKind, TransitionTargetKind } from '../contracts/vocabulary.js';
5
5
  import { defaultApprovalAwait } from './approval-defaults.js';
6
+ import { compileCommands } from './command-compiler.js';
7
+ import { reportUnroutedOutcomes } from './compile-diagnostics.js';
6
8
  import { compileResourceTransitions } from './resource-transition-compiler.js';
7
9
  import { compileTarget, isReservedRouteTarget, isReservedTerminalTarget, } from './transition-target.js';
8
10
  import { assertCyclesBounded, assertReachable, remainingAgentSteps } from './workflow-graph.js';
9
- export function compileWorkflow(name, input, activities, knownWorkflowNames = [name]) {
11
+ export function compileWorkflow(name, input, activities, knownWorkflowNames = [name], reportDiagnostic = () => { }) {
10
12
  const compiledName = workflowName(name);
11
13
  const config = workflowDefinitionConfigSchema.parse(input);
12
14
  const rawStageNames = Object.keys(config.stages);
@@ -25,6 +27,7 @@ export function compileWorkflow(name, input, activities, knownWorkflowNames = [n
25
27
  const watches = compileWatches(config, rawStageNames, knownWorkflowNames);
26
28
  assertReachable(compiledEntry, stages);
27
29
  assertCyclesBounded(stages);
30
+ reportUnroutedOutcomes(name, stages, activities, reportDiagnostic);
28
31
  return Object.freeze({
29
32
  remainingAgentSteps: Object.freeze(remainingAgentSteps(stages, (activity) => activities.describe(activity).executionKind === ActivityExecutionKind.Agent)),
30
33
  name: compiledName,
@@ -173,13 +176,3 @@ function compileAuthority(workflow, rawStageName, entry, declaredWatchIds) {
173
176
  throw new Error(`Unknown watch reference in workflow "${workflow}" stage "${rawStageName}": "${entry.id}"`);
174
177
  return { kind: ApprovalAuthorityKind.Watch, watch: watchId(entry.id) };
175
178
  }
176
- function compileCommands(config, activities) {
177
- return Object.fromEntries(Object.entries(config.commands ?? {}).map(([command, configured]) => [
178
- commandName(command),
179
- Object.freeze({
180
- activity: activityName(configured.activity),
181
- with: activities.validateInput(activityName(configured.activity), configured.with),
182
- allowedActors: Object.freeze([...configured.allowedActors]),
183
- }),
184
- ]));
185
- }
@@ -31,3 +31,4 @@ export * from './domain/interpreter.js';
31
31
  export * from './domain/workflow-instance.js';
32
32
  export * from './domain/workflow-selector.js';
33
33
  export * from './application/work-completion-summary.js';
34
+ export type { WorkflowCompileDiagnostic } from './domain/compile-diagnostics.js';
@@ -124,4 +124,11 @@ export interface CliOutput {
124
124
  }
125
125
  /** Parses Surface vocabulary only; Bootstrap supplies every application facade. */
126
126
  export declare function parseWakeCommand(arguments_: readonly string[]): WakeCommand;
127
+ export interface WakeReadApplications {
128
+ readonly doctor?: (arguments_: readonly string[]) => Promise<unknown>;
129
+ readonly audit?: WakeCliApplications['audit'];
130
+ readonly validateState?: Pick<WakeCliApplications['validateState'], 'health'>;
131
+ }
132
+ /** Shared presentation for both storage-only reads and fully composed facades. */
133
+ export declare function runWakeReadCommand(command: WakeCommand, applications: WakeReadApplications, output: CliOutput): Promise<boolean>;
127
134
  export declare function runWakeCommand(command: WakeCommand, applications: WakeCliApplications, output: CliOutput, signal: AbortSignal): Promise<void>;
@@ -172,15 +172,37 @@ function requiredArgument(value, label) {
172
172
  throw new Error(`Missing ${label}`);
173
173
  return value;
174
174
  }
175
+ /** Shared presentation for both storage-only reads and fully composed facades. */
176
+ export async function runWakeReadCommand(command, applications, output) {
177
+ if (command.kind === 'doctor' && applications.doctor !== undefined) {
178
+ writeResult(output, await applications.doctor(command.arguments));
179
+ return true;
180
+ }
181
+ if (command.kind === 'audit' && applications.audit !== undefined) {
182
+ for (const record of await applications.audit.read(command.workItemId))
183
+ writeResult(output, record);
184
+ return true;
185
+ }
186
+ if (command.kind === 'validate-state' &&
187
+ !command.rebuildProjections &&
188
+ applications.validateState !== undefined) {
189
+ writeResult(output, await applications.validateState.health());
190
+ return true;
191
+ }
192
+ return false;
193
+ }
175
194
  // eslint-disable-next-line complexity -- each parsed command has one explicit application dispatch.
176
195
  export async function runWakeCommand(command, applications, output, signal) {
177
196
  switch (command.kind) {
197
+ case 'doctor':
198
+ await runWakeReadCommand(command, { doctor: (arguments_) => operational(applications).doctor(arguments_) }, output);
199
+ return;
200
+ case 'audit':
201
+ await runWakeReadCommand(command, { audit: applications.audit }, output);
202
+ return;
178
203
  case 'init':
179
204
  writeResult(output, await operational(applications).init(command.arguments));
180
205
  return;
181
- case 'doctor':
182
- writeResult(output, await operational(applications).doctor(command.arguments));
183
- return;
184
206
  case WakeOperationalCommand.Maintenance:
185
207
  writeResult(output, await operational(applications).maintenance(command.arguments));
186
208
  return;
@@ -220,10 +242,6 @@ export async function runWakeCommand(command, applications, output, signal) {
220
242
  case 'mcp':
221
243
  await mcp(applications).serve(command.sessionPath, process.env.WAKE_MCP_TOKEN ?? '');
222
244
  return;
223
- case 'audit':
224
- for (const record of await applications.audit.read(command.workItemId))
225
- output.write(`${JSON.stringify(record)}\n`);
226
- return;
227
245
  case 'correlate':
228
246
  output.write(`${JSON.stringify(await applications.correlate.correlate(command.resource, command.workItemId))}\n`);
229
247
  return;
@@ -233,7 +251,7 @@ export async function runWakeCommand(command, applications, output, signal) {
233
251
  case 'validate-state': {
234
252
  if (command.rebuildProjections)
235
253
  await applications.validateState.rebuildProjections();
236
- output.write(`${JSON.stringify(await applications.validateState.health())}\n`);
254
+ await runWakeReadCommand({ ...command, rebuildProjections: false }, { validateState: applications.validateState }, output);
237
255
  return;
238
256
  }
239
257
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/wake",
3
- "version": "0.4.84",
3
+ "version": "0.4.86",
4
4
  "description": "Local autonomous agent control plane for software development",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {