@atolis-hq/wake 0.4.85 → 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';
@@ -81,4 +81,65 @@ export interface CompositionRoot {
81
81
  readonly requestImmediatePoll: (adapter: string) => void;
82
82
  readonly resolveResourceLink: ResourceLinkResolver;
83
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
+ }>;
84
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);
@@ -139,6 +137,51 @@ export async function createCompositionRoot(wakeRoot, options = {}) {
139
137
  ids,
140
138
  runners: new Set(Object.values(config.execution.runnerPools).flat()),
141
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);
142
185
  const activationScheduler = createActivationScheduler(orchestration, {
143
186
  ...execution,
144
187
  recoverActive: (owner) => recovery.recoverActive(owner, execution.isLocallyActive),
@@ -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));
@@ -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.85";
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([
@@ -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.85",
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": {