@arcforge/kernel 2.0.111 → 2.0.112

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcforge/kernel",
3
- "version": "2.0.111",
3
+ "version": "2.0.112",
4
4
  "description": "The Axon kernel — ring 0. Owns resources and execution, enforces policy, and is the only constructor of the unprivileged capsule.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -15,13 +15,13 @@
15
15
  "deploy": "echo \"This package is published ONLY by apps/tui/scripts/release.ts, which pins workspace:* deps to concrete versions first. Publishing it directly ships an unresolvable dependency.\" && exit 1"
16
16
  },
17
17
  "dependencies": {
18
- "@arcforge/cognet": "2.0.111",
19
- "@arcforge/engines": "2.0.111",
20
- "@arcforge/err": "2.0.111",
21
- "@arcforge/session": "2.0.111",
22
- "@arcforge/types": "2.0.111",
23
- "@arclabs/cloud": "2.0.111",
24
- "@axon/capsule": "2.0.111"
18
+ "@arcforge/cognet": "2.0.112",
19
+ "@arcforge/engines": "2.0.112",
20
+ "@arcforge/err": "2.0.112",
21
+ "@arcforge/session": "2.0.112",
22
+ "@arcforge/types": "2.0.112",
23
+ "@arclabs/cloud": "2.0.112",
24
+ "@axon/capsule": "2.0.112"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/bun": "latest",
package/src/kernel.ts CHANGED
@@ -262,6 +262,20 @@ export async function Kernel(opts: KernelOpts) {
262
262
  // persistence surface — private cognitive state + read-only episodic
263
263
  // access, one mediated door like stream/run (see Store())
264
264
  store: store,
265
+
266
+ // The brain's own rhythm. Called from a cognet plugin, never from the
267
+ // body — see KernelAbi.wake for why the body must not drive this.
268
+ // Deliberately NOT awaited into the wake: admission is the contract,
269
+ // so a driver on an interval never serialises the overlap.
270
+ wake: () => scheduler.wake(),
271
+
272
+ clock: () => scheduler.clock(),
273
+
274
+ // Resolved at prepare and carried on the blueprint — the runtime only
275
+ // hands the paths over. Frozen so a brain cannot mutate the map it
276
+ // was given, and empty (never undefined) so a cognet reads it without
277
+ // branching.
278
+ models: Object.freeze({ ...(opts.blueprint.cognet.models ?? {}) }),
265
279
  }
266
280
 
267
281
  // exec(): the kernel is the only loader. ABI compatibility is checked
@@ -310,15 +324,10 @@ export async function Kernel(opts: KernelOpts) {
310
324
  return { ok: true, entries }
311
325
  },
312
326
 
313
- /**
314
- * Advance a continuous cognet by one wake, handing it whatever is on
315
- * the stimulus buffer. Resolves false if a wake was already running
316
- * and this tick was skipped — see scheduler/continuous.ts for why
317
- * skipping is the policy and why it is a return value, not a throw.
318
- */
319
- tick(): Promise<boolean> {
320
- return scheduler.tick()
321
- },
327
+ // No tick() on the public surface. The brain drives its own rhythm
328
+ // through the ABI (KernelAbi.tick, called from a cognet plugin) —
329
+ // exposing it here would let the body wake a mind it knows nothing
330
+ // about, which is the coupling this split exists to remove.
322
331
 
323
332
  /** Abort the active wake, if any. Safe to call when idle. */
324
333
  interrupt(reason: "user" | "shutdown" = "user") {
@@ -3,73 +3,101 @@ import type { AxonSessionT } from "@arcforge/session"
3
3
 
4
4
  type ContinuousOpts = {
5
5
  session: AxonSessionT
6
- reserve: () => string
6
+ reserve: (opts?: { exclusive?: boolean }) => string
7
7
  release: (id?: string) => void
8
8
  runWake: (reservationId: string, input: { stimuli: AxonStimulusEntry[] }) => AsyncGenerator<AxonEntry>
9
9
  }
10
10
 
11
11
  /**
12
- * Continuous trigger: one wake per tick, driven by whoever owns the clock.
12
+ * Continuous trigger: the brain woken on its own rhythm.
13
13
  *
14
- * THE BODY OWNS THE CLOCK, not the cognet and not the kernel. This used to
15
- * hold a `start(tickMs)` that ran its own setInterval off a `tickMs` the
16
- * cognet declared in its config — which had the brain asserting how fast the
17
- * world turns, something it cannot possibly know, and contradicted the rule
18
- * that a cognet learns nothing about its environment. The clock now lives in
19
- * agent code (a plugin driving `axon.tick()`), where the thing that actually
20
- * knows the world's rate can set it.
14
+ * THE BRAIN OWNS THE CLOCK. This has moved twice, and both moves were the
15
+ * same correction. First it was `start(tickMs)` reading a rate the cognet
16
+ * declared in its config — the brain asserting how fast the world turns,
17
+ * which it cannot know. Then it was `axon.tick()` in the body — the body
18
+ * asserting how often a mind should think, which it cannot know either, and
19
+ * which broke the swap test: a body that drives a specific brain has to be
20
+ * rewritten when the brain changes. It also had no answer under composition,
21
+ * where two sensors at 31Hz and 60Hz have equal claim to being "the" rate.
21
22
  *
22
- * What remains here is the one thing a caller must not have to reimplement:
23
- * OVERLAP POLICY. A tick arriving while a wake is still running is SKIPPED,
24
- * reported as `false`, and never throws. Skip rather than queue because a
25
- * late tick is worthless to a controller — the freshest sense data is the
26
- * only useful one, and a queue would put the mind further behind the world
27
- * with every overrun. Rather than concurrent because one session is one log
28
- * with one writer, and two wakes interleaving entries would corrupt the
29
- * record that makes the mind replayable.
23
+ * The resolution is that these are different quantities. How fast frames
24
+ * arrive is the body's. How often it is worth thinking about them is the
25
+ * mind's. So a cognet plugin drives `kernel.wake()`, and the body only ever
26
+ * emits stimuli.
30
27
  *
31
- * That policy is not settled forever — cancelling the in-flight wake in
32
- * favour of the newer sense data is a defensible alternative, and so is
33
- * bounded concurrency. It is settled ENOUGH to ship, and the return value is
34
- * what makes revisiting it cheap: a caller already distinguishes "ran" from
35
- * "skipped", so a future policy change alters what fills the gap, not the
36
- * contract.
28
+ * OVERLAP POLICY: wakes overlap. Every wake starts, always, however long the
29
+ * last one is still taking.
30
+ *
31
+ * This began as skip-on-overlap, which suited a controller whose sensor
32
+ * could be re-read at any moment: a late tick was worthless, so dropping it
33
+ * cost nothing. That reasoning does not survive transient stimuli. A
34
+ * stimulus is delivered once and then dropped, so a skipped tick is not a
35
+ * late tick — it is a tick that never heard, and the frames it would have
36
+ * carried are gone. A mind that stops hearing while it thinks cannot be
37
+ * interrupted, which rules out every conversational workload.
38
+ *
39
+ * Queueing is worse still: two seconds of backlog arrives at one tick, that
40
+ * tick runs long, and the backlog compounds.
41
+ *
42
+ * So wakes run concurrently and share the cognet's module scope, exactly as
43
+ * a brain's regions share one body. Coordinating that — not calling the
44
+ * engine twice, dropping work that arrived while busy — is the cognet
45
+ * author's, through their own state. The kernel supplies no primitive for
46
+ * it, because any primitive would be the runtime having an opinion about
47
+ * how cognition should be organised.
48
+ *
49
+ * The log stays coherent under this: one writer, and `seq` is still a total
50
+ * order. What changes is that spans from different wakes interleave, so
51
+ * nesting is rebuilt per `context.runId` rather than globally.
37
52
  */
38
53
  export function Continuous(opts: ContinuousOpts) {
54
+ let wakes = 0
55
+
39
56
  return {
57
+ /** Wakes admitted since boot — what kernel.clock() reports. */
58
+ get wakes() {
59
+ return wakes
60
+ },
61
+
40
62
  /**
41
63
  * Wake the cognet with whatever is on the stimulus buffer.
42
64
  *
43
- * Resolves `true` once the wake has fully drained, `false` when one
44
- * was already in flight and this tick was skipped. Drives the wake to
45
- * completion internally: a tick has no caller waiting on entries (a
46
- * clock is not asking a question), so unlike invocation there is no
47
- * wire to hand back — the entries reach the log, which is where a
48
- * ticked cognet's output belongs.
65
+ * Resolves with this wake's ordinal AS SOON AS IT IS ADMITTED, not
66
+ * when it finishes. That distinction is the whole point: a driver
67
+ * doing `setInterval(async () => await kernel.wake(), 33)` would
68
+ * otherwise wait for each wake before starting the next, which is
69
+ * skip-on-overlap reintroduced by the back door — the exact behaviour
70
+ * that makes a mind deaf while it thinks.
71
+ *
72
+ * The wake itself runs detached. Its entries reach the log, which is
73
+ * where a ticked cognet's output belongs; there is no caller waiting
74
+ * on a wire, because a clock is not asking a question.
49
75
  */
50
- async tick(): Promise<boolean> {
51
- let reservationId: string
52
- try {
53
- reservationId = opts.reserve()
54
- } catch {
55
- // The one contention path, and the reason this returns a
56
- // boolean instead of throwing: a skipped tick is an ordinary
57
- // steady state for a clock running near capacity, not an
58
- // error. Callers fire this from an interval where a thrown
59
- // RUN_IN_PROGRESS would surface as an unhandled rejection.
60
- return false
61
- }
76
+ async wake(): Promise<number> {
77
+ // Never exclusive: a wake that waited for the previous one would
78
+ // be a wake that did not hear. Stimuli are transient — delivered
79
+ // once, then dropped — so a skipped or delayed tick does not
80
+ // arrive late, it never arrives at all. Overlapping wakes are the
81
+ // point, not the hazard.
82
+ const reservationId = opts.reserve({ exclusive: false })
83
+ const ordinal = ++wakes
62
84
 
63
85
  const stimuli = opts.session.stimuli.drain()
64
86
 
65
- // Drain the wake here rather than yielding it. runWake's finally
66
- // releases the reservation, so the generator MUST be consumed to
67
- // completion or the scheduler stays locked forever.
68
- for await (const _entry of opts.runWake(reservationId, { stimuli })) {
69
- // entries commit as they are produced; nothing to collect
70
- }
87
+ // Drained here rather than yielded: runWake's finally releases the
88
+ // reservation, so the generator MUST be consumed to completion or
89
+ // the reservation leaks. Deliberately NOT awaited — see above.
90
+ // The catch is what keeps a failed wake from surfacing as an
91
+ // unhandled rejection in whatever interval called tick(); the
92
+ // failure is already durable (kernel:run:failed) by the time it
93
+ // reaches here.
94
+ void (async () => {
95
+ for await (const _entry of opts.runWake(reservationId, { stimuli })) {
96
+ // entries commit as they are produced; nothing to collect
97
+ }
98
+ })().catch(() => {})
71
99
 
72
- return true
100
+ return ordinal
73
101
  },
74
102
  }
75
103
  }
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks"
1
2
  import { err } from "@arcforge/err"
2
3
  import type { AxonEntry, AxonStimulusEntry } from "@arcforge/types"
3
4
  import type { KernelBus } from "../contracts"
@@ -23,41 +24,77 @@ type InvokeInput = {
23
24
  * once started (that's wake.ts, unchanged regardless of trigger source).
24
25
  *
25
26
  * Two trigger sources, one mechanism: invocation.ts fires on an admitted
26
- * stimulus, continuous.ts fires when the body ticks it — both call the same
27
- * internal runWake(), which drains session.stimuli and hands the diff to
27
+ * stimulus, continuous.ts fires when the BRAIN wakes itself — both call the
28
+ * same internal runWake(), which drains session.stimuli and hands the diff to
28
29
  * Wake(). Neither trigger source knows the other exists; the cognet's
29
30
  * declared `mode` picks which verb is legal against it.
30
31
  *
31
- * Note the clock is NOT here. A continuous cognet is advanced by agent code
32
- * calling axon.tick(); the scheduler owns what happens on contention, never
33
- * when a tick occurs.
32
+ * Note the clock is NOT here, and not in the body either. A continuous cognet
33
+ * is advanced by a cognet plugin calling kernel.wake(); the scheduler owns
34
+ * what happens on contention, never when a wake occurs.
34
35
  *
35
- * SCHEDULING POLICY (policy, not physics — revisit without contract change):
36
- * one wake at a time, globally. A concurrent invoke throws RUN_IN_PROGRESS;
37
- * a concurrent tick is skipped and reported as false, because a clock
38
- * running near capacity is a steady state rather than a caller error.
36
+ * SCHEDULING POLICY, and it differs by mode because the modes differ:
37
+ *
38
+ * invocation — one wake at a time. An invocation cognet IS one
39
+ * conversation, so a concurrent invoke is a caller error: RUN_IN_PROGRESS.
40
+ *
41
+ * continuous — wakes overlap, always. Every wake starts however long the
42
+ * last one is still taking, because stimuli are transient: a skipped wake
43
+ * is not a late wake, it is one that never heard. See continuous.ts.
44
+ */
45
+ /**
46
+ * The run a syscall belongs to, resolved per async context.
47
+ *
48
+ * Every ABI syscall stamps its commit with the current runId, and that used
49
+ * to be one module-level `active` — which held for a serial scheduler and
50
+ * breaks the moment two wakes overlap: the second overwrites it, so the
51
+ * first's outputs attribute to the wrong run, and when either finishes the
52
+ * other's syscalls throw SYSCALL_OUTSIDE_RUN mid-flight.
53
+ *
54
+ * AsyncLocalStorage binds it to the wake that started the work, so a syscall
55
+ * resolves correctly no matter how the awaits interleave.
39
56
  */
57
+ const runStorage = new AsyncLocalStorage<{ runId: string }>()
58
+
40
59
  export function Scheduler(opts: SchedulerOpts) {
41
60
  let cognet: KernelCognet | null = null
42
- let active: { runId: string } | null = null
61
+ /**
62
+ * Live wakes, by reservation id. A count rather than a single slot: a
63
+ * continuous cognet ticks whether or not the last wake finished, and
64
+ * blocking there is deafness, not backpressure — the stimuli a skipped
65
+ * tick would have carried are already gone.
66
+ */
67
+ const live = new Map<string, { abort: AbortController }>()
43
68
  let reservation: { id: string; abort: AbortController } | null = null
44
69
 
45
70
  /**
46
71
  * Reserve the scheduler SYNCHRONOUSLY, at the true call boundary — an
47
72
  * async generator's body doesn't run until iterated, so locking inside
48
73
  * would leave a window where two callers both mint a wire.
74
+ *
75
+ * `exclusive` is what separates the two modes. An invocation cognet IS
76
+ * one conversation, so a second concurrent invoke is a caller error and
77
+ * still throws RUN_IN_PROGRESS. A continuous cognet is a mind under a
78
+ * clock: wakes overlap by design, because deliberation that outlasts a
79
+ * tick must not stop the next tick from hearing.
49
80
  */
50
- function reserve(): string {
51
- if (reservation) throw err("RUN_IN_PROGRESS")
81
+ function reserve(opts?: { exclusive?: boolean }): string {
82
+ if (opts?.exclusive !== false && reservation) throw err("RUN_IN_PROGRESS")
52
83
  const id = Bun.randomUUIDv7()
53
- reservation = { id, abort: new AbortController() }
84
+ const entry = { id, abort: new AbortController() }
85
+ live.set(id, entry)
86
+ if (opts?.exclusive !== false) reservation = entry
54
87
  return id
55
88
  }
56
89
 
57
90
  function release(id?: string): void {
58
- if (id !== undefined && reservation?.id !== id) return
59
- active = null
60
- reservation = null
91
+ if (id === undefined) {
92
+ live.clear()
93
+ reservation = null
94
+ return
95
+ }
96
+ live.delete(id)
97
+ if (reservation?.id === id) reservation = null
61
98
  }
62
99
 
63
100
  /**
@@ -66,7 +103,8 @@ export function Scheduler(opts: SchedulerOpts) {
66
103
  * stimulus or a clock caused it to be called.
67
104
  */
68
105
  function runWake(reservationId: string, input: { stimuli: AxonStimulusEntry[] }): AsyncGenerator<AxonEntry> {
69
- if (reservation?.id !== reservationId) throw err("RUN_RESERVATION_EXPIRED")
106
+ const reserved = live.get(reservationId)
107
+ if (!reserved) throw err("RUN_RESERVATION_EXPIRED")
70
108
  if (!cognet) {
71
109
  release(reservationId)
72
110
  throw err("NO_COGNET_LOADED")
@@ -77,9 +115,9 @@ export function Scheduler(opts: SchedulerOpts) {
77
115
  stimuli: input.stimuli,
78
116
  bus: opts.bus,
79
117
  session: opts.session,
80
- abort: reservation.abort,
118
+ abort: reserved.abort,
81
119
  })
82
- active = { runId: wake.runId }
120
+ const run = { runId: wake.runId }
83
121
 
84
122
  return (async function* () {
85
123
  try {
@@ -90,9 +128,14 @@ export function Scheduler(opts: SchedulerOpts) {
90
128
  // wake-time err() calls out of attribution. Scoping each
91
129
  // next() means everything the wake executes — cognet code,
92
130
  // engine calls, ABI syscalls — attributes to this session.
131
+ //
132
+ // runStorage wraps it for the same reason one ring in: the
133
+ // run a syscall belongs to must be resolved from the async
134
+ // context that is executing, not from a module variable the
135
+ // next overlapping wake would have overwritten.
93
136
  const inner = wake.stream()
94
137
  while (true) {
95
- const result = await opts.session.scope(() => inner.next())
138
+ const result = await runStorage.run(run, () => opts.session.scope(() => inner.next()))
96
139
  if (result.done) return
97
140
  yield result.value
98
141
  }
@@ -102,10 +145,21 @@ export function Scheduler(opts: SchedulerOpts) {
102
145
  })()
103
146
  }
104
147
 
105
- /** abort the active wake, if any — safe to call when idle */
148
+ /**
149
+ * Abort a wake, or every live wake — safe to call when idle.
150
+ *
151
+ * Without an id this aborts ALL of them, which is what shutdown and a
152
+ * user interrupt both mean: stop thinking. With overlapping wakes there
153
+ * is no single "the active wake" to target, and aborting only the newest
154
+ * would leave older deliberation running past the interrupt that was
155
+ * meant to end it.
156
+ */
106
157
  function interrupt(reason: "user" | "shutdown" = "user", reservationId?: string) {
107
- if (reservationId !== undefined && reservation?.id !== reservationId) return
108
- reservation?.abort.abort(reason)
158
+ if (reservationId !== undefined) {
159
+ live.get(reservationId)?.abort.abort(reason)
160
+ return
161
+ }
162
+ for (const entry of live.values()) entry.abort.abort(reason)
109
163
  }
110
164
 
111
165
  const invocation = Invocation({ session: opts.session, reserve, release, runWake, interrupt })
@@ -136,15 +190,22 @@ export function Scheduler(opts: SchedulerOpts) {
136
190
 
137
191
  /**
138
192
  * Advance a continuous cognet by one wake. The clock belongs to the
139
- * body (a plugin driving `axon.tick()`), never to this scheduler —
140
- * see continuous.ts. Resolves false when a wake was already running.
193
+ * BRAIN — a cognet plugin driving `kernel.wake()` — never to this
194
+ * scheduler and never to the body. See KernelAbi.wake.
195
+ *
196
+ * Resolves with the wake's ordinal on admission, not completion.
141
197
  */
142
- tick() {
198
+ wake() {
143
199
  if (!cognet) throw err("NO_COGNET_LOADED")
144
200
  if (cognet.mode.kind !== "continuous") {
145
- throw err("SCHEDULER_MODE_MISMATCH", { detail: "tick() drives continuous cognets; an invocation cognet wakes on a stimulus via stream()" })
201
+ throw err("SCHEDULER_MODE_MISMATCH", { detail: "wake() drives continuous cognets; an invocation cognet wakes on a stimulus via stream()" })
146
202
  }
147
- return continuous.tick()
203
+ return continuous.wake()
204
+ },
205
+
206
+ /** A snapshot of the scheduler's clock — see KernelClock. */
207
+ clock() {
208
+ return { wakes: continuous.wakes }
148
209
  },
149
210
 
150
211
  /** Invoke on a stimulus admission (invocation mode) — no-op shape for continuous cognets, which never call this. */
@@ -163,13 +224,14 @@ export function Scheduler(opts: SchedulerOpts) {
163
224
  * syscall the ABI exposes (output, run, stream) reads this.
164
225
  */
165
226
  active() {
166
- if (!active) throw err("SYSCALL_OUTSIDE_RUN")
167
- return active
227
+ const run = runStorage.getStore()
228
+ if (!run) throw err("SYSCALL_OUTSIDE_RUN")
229
+ return run
168
230
  },
169
231
 
170
232
  /** Like active(), but null outside a wake instead of throwing — for emitters (cognet telemetry) that legally fire during load/unload. */
171
233
  current() {
172
- return active
234
+ return runStorage.getStore() ?? null
173
235
  },
174
236
 
175
237
  interrupt,