@atolis-hq/wake 0.3.107 → 0.3.109

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.
@@ -7,7 +7,7 @@ import { promisify } from 'node:util';
7
7
  import { BuiltInActivityName, agentActivityDefinition } from '../activities/index.js';
8
8
  import { IntakeHost, ResidentHost, TickHost } from '../control-plane/index.js';
9
9
  import { ExecutionCancellationReason, ExecutionFailureCode, RunStatus, loadPromptTemplate, } from '../execution/index.js';
10
- import { EventActorKind, correlationId } from '../kernel/index.js';
10
+ import { EventActorKind, JOURNAL_CHANGE_FALLBACK_MS, correlationId } from '../kernel/index.js';
11
11
  import { ResourceCorrelationRole, resourceId } from '../resources/index.js';
12
12
  import { DockerProcessError, createApiDispatcher, createApiHttpServer, createLoggedDockerCli, createPackagedAssetSource, createProcessLogSink, createSandboxDockerPort, drainProcessOutput, runDoctor, runSandbox, runSandboxEntrypoint, runSandboxSetup, runSelfUpdateLatestLoop, runTargetSmoke, verifyResidentStart, waitForActiveRuns, waitForever, } from '../surfaces/index.js';
13
13
  import { WorkStreamKind, workItemId } from '../work/index.js';
@@ -43,7 +43,7 @@ export function createSurfaceCliApplications(root, api, now) {
43
43
  // Genuine idle (no errors): wait for the journal to actually change.
44
44
  return consecutiveIdleTicks === 0
45
45
  ? Promise.resolve()
46
- : root.journal.changeSignal.waitForChange(signal, JOURNAL_WAIT_FALLBACK_MS);
46
+ : root.journal.changeSignal.waitForChange(signal, JOURNAL_CHANGE_FALLBACK_MS);
47
47
  }, reportResidentError('runner'));
48
48
  const intakeResident = new ResidentHost(intakeHost, (signal, { consecutiveIdleTicks }) => sleepUntilAbort(signal, nextPollBackoffMs(root.config.controlPlane.resident, consecutiveIdleTicks)), reportResidentError('intake'));
49
49
  const servers = new Set();
@@ -135,10 +135,6 @@ export function createSurfaceCliApplications(root, api, now) {
135
135
  operational: createOperationalApplications(root),
136
136
  };
137
137
  }
138
- // Safety net for a missed in-process notify() or a cross-process writer the
139
- // EventEmitter can't see; a real append wakes waiters within milliseconds
140
- // regardless, so there's no operational reason to make this configurable.
141
- const JOURNAL_WAIT_FALLBACK_MS = 30_000;
142
138
  export async function runProjectionPump(root, signal) {
143
139
  while (!signal.aborted) {
144
140
  try {
@@ -147,7 +143,7 @@ export async function runProjectionPump(root, signal) {
147
143
  catch (error) {
148
144
  process.stderr.write(`Wake projection pump failed: ${error instanceof Error ? error.message : String(error)}\n`);
149
145
  }
150
- await root.journal.changeSignal.waitForChange(signal, JOURNAL_WAIT_FALLBACK_MS);
146
+ await root.journal.changeSignal.waitForChange(signal, JOURNAL_CHANGE_FALLBACK_MS);
151
147
  }
152
148
  }
153
149
  function nextPollBackoffMs(resident, consecutiveIdleTicks) {
@@ -108,4 +108,4 @@ export function resolveWakeVersion(options = {}) {
108
108
  return `g${headHash.slice(0, 7)}`;
109
109
  return '0.1.0-dev';
110
110
  }
111
- export const wakeVersion = "gb013b4e";
111
+ export const wakeVersion = "g8bb6b08";
@@ -1,4 +1,4 @@
1
- import { createEventDraft, EventActorKind, EventSourceKind, } from '../../kernel/index.js';
1
+ import { createEventDraft, EventActorKind, EventSourceKind, WrongExpectedSequenceError, } from '../../kernel/index.js';
2
2
  import { ExecutionEventType } from '../contracts/events.js';
3
3
  import { runStream } from '../contracts/streams.js';
4
4
  import { RunStatus } from '../contracts/vocabulary.js';
@@ -39,14 +39,27 @@ export async function renewLease(repository, clock, config, currentRunId, owner)
39
39
  return (await repository.load(currentRunId)).view;
40
40
  }
41
41
  export async function requestCancellation(repository, clock, currentRunId, reason, active) {
42
- const loaded = await repository.load(currentRunId);
43
- const run = requireActiveRun(loaded.view);
44
- const requestedAt = clock.now().toISOString();
45
- await repository.append(currentRunId, loaded.sequence, [
46
- livenessEvent(currentRunId, run, ExecutionEventType.RunCancellationRequested, { requestedAt, reason }, requestedAt),
47
- ]);
48
- active.get(currentRunId)?.abort(reason);
49
- return (await repository.load(currentRunId)).view;
42
+ while (true) {
43
+ const loaded = await repository.load(currentRunId);
44
+ const run = requireActiveRun(loaded.view);
45
+ if (run.cancellation !== undefined) {
46
+ active.get(currentRunId)?.abort(reason);
47
+ return run;
48
+ }
49
+ const requestedAt = clock.now().toISOString();
50
+ try {
51
+ await repository.append(currentRunId, loaded.sequence, [
52
+ livenessEvent(currentRunId, run, ExecutionEventType.RunCancellationRequested, { requestedAt, reason }, requestedAt),
53
+ ]);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof WrongExpectedSequenceError)
57
+ continue;
58
+ throw error;
59
+ }
60
+ active.get(currentRunId)?.abort(reason);
61
+ return (await repository.load(currentRunId)).view;
62
+ }
50
63
  }
51
64
  export async function confirmCancellation(repository, clock, currentRunId) {
52
65
  const loaded = await repository.load(currentRunId);
@@ -1,3 +1,4 @@
1
+ export const JOURNAL_CHANGE_FALLBACK_MS = 30_000;
1
2
  // Memoizes a full-journal derivation — a fold, decode, or index built from
2
3
  // every event in history — so a resident loop calling it every tick only
3
4
  // pays that cost when the journal has actually moved since the last call.
@@ -6,15 +7,20 @@
6
7
  // incremental batch. Depends only on the EventJournal port, not on any
7
8
  // concrete persistence implementation, so it lives in kernel rather than
8
9
  // persistence — domain and adapter modules may call it directly.
9
- export function cachedJournalView(journal, derive) {
10
+ export function cachedJournalView(journal, derive, now = Date.now) {
10
11
  let cache;
11
12
  return {
12
13
  async get() {
13
- const position = await journal.latestGlobalPosition();
14
- if (cache !== undefined && cache.position === position)
14
+ const observedRevision = journal.changeSignal.revision();
15
+ const checkedAt = now();
16
+ if (cache !== undefined &&
17
+ cache.observedRevision === observedRevision &&
18
+ checkedAt - cache.checkedAt < JOURNAL_CHANGE_FALLBACK_MS)
15
19
  return cache.value;
16
20
  const value = await derive(await journal.readAll(0));
17
- cache = { position, value };
21
+ // Retain the revision observed before the read. An append that races
22
+ // this derivation must force one more pass instead of being hidden.
23
+ cache = { observedRevision, checkedAt: now(), value };
18
24
  return value;
19
25
  },
20
26
  };
@@ -1,6 +1,11 @@
1
1
  export class InProcessJournalChangeSignal {
2
2
  waiters = [];
3
+ currentRevision = 0;
4
+ revision() {
5
+ return this.currentRevision;
6
+ }
3
7
  notify() {
8
+ this.currentRevision += 1;
4
9
  const waiters = this.waiters;
5
10
  this.waiters = [];
6
11
  for (const resolve of waiters)
@@ -1,3 +1,4 @@
1
+ import { JOURNAL_CHANGE_FALLBACK_MS } from '../../kernel/index.js';
1
2
  async function runImmediately(operation) {
2
3
  return operation();
3
4
  }
@@ -7,13 +8,17 @@ export class ProjectionRunner {
7
8
  checkpoints;
8
9
  registered;
9
10
  serialiseRun;
11
+ now;
10
12
  caughtUpToGlobalPosition;
11
- constructor(journal, projections, checkpoints, registered = [], serialiseRun = runImmediately) {
13
+ caughtUpRevision;
14
+ caughtUpAt;
15
+ constructor(journal, projections, checkpoints, registered = [], serialiseRun = runImmediately, now = Date.now) {
12
16
  this.journal = journal;
13
17
  this.projections = projections;
14
18
  this.checkpoints = checkpoints;
15
19
  this.registered = registered;
16
20
  this.serialiseRun = serialiseRun;
21
+ this.now = now;
17
22
  }
18
23
  // One shared journal read for every registered definition, not one per
19
24
  // definition: readAll ultimately re-derives its content-fingerprint via
@@ -34,11 +39,21 @@ export class ProjectionRunner {
34
39
  return this.serialiseRun(() => this.runRegisteredOnceUnlocked(limit));
35
40
  }
36
41
  async runRegisteredOnceUnlocked(limit) {
42
+ const observedRevision = this.journal.changeSignal.revision();
43
+ const checkedAt = this.now();
44
+ if (this.caughtUpToGlobalPosition !== undefined &&
45
+ this.caughtUpRevision === observedRevision &&
46
+ this.caughtUpAt !== undefined &&
47
+ checkedAt - this.caughtUpAt < JOURNAL_CHANGE_FALLBACK_MS)
48
+ return 0;
37
49
  const allEvents = await this.journal.readAll(0);
38
50
  const latestGlobalPosition = allEvents.at(-1)?.globalPosition ?? 0;
39
51
  if (this.caughtUpToGlobalPosition !== undefined &&
40
- latestGlobalPosition <= this.caughtUpToGlobalPosition)
52
+ latestGlobalPosition <= this.caughtUpToGlobalPosition) {
53
+ this.caughtUpRevision = observedRevision;
54
+ this.caughtUpAt = this.now();
41
55
  return 0;
56
+ }
42
57
  let failed = false;
43
58
  let firstFailure;
44
59
  const counts = await Promise.all(this.registered.map(async (definition) => {
@@ -55,8 +70,13 @@ export class ProjectionRunner {
55
70
  }));
56
71
  if (failed)
57
72
  throw firstFailure;
58
- if (counts.every((count) => count < limit))
73
+ if (counts.every((count) => count < limit)) {
59
74
  this.caughtUpToGlobalPosition = latestGlobalPosition;
75
+ // Keep the revision from before the read so a concurrent append is
76
+ // never mistaken for content already included in this pass.
77
+ this.caughtUpRevision = observedRevision;
78
+ this.caughtUpAt = this.now();
79
+ }
60
80
  return counts.reduce((total, count) => total + count, 0);
61
81
  }
62
82
  async runOnce(definition, limit = 100) {