@h-rig/kernel-seed 0.0.6-alpha.157 → 0.0.6-alpha.158

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.
@@ -0,0 +1,687 @@
1
+ // @bun
2
+ // packages/kernel-seed/src/pluginAbi.ts
3
+ function loadedPluginId(plugin) {
4
+ return plugin.name;
5
+ }
6
+
7
+ // packages/kernel-seed/src/resolveCapability.ts
8
+ function replacementMatches(spec, capability, providerId) {
9
+ if (typeof spec === "string")
10
+ return spec === `${capability}@${providerId}`;
11
+ return spec.capability === capability && spec.providerPluginId === providerId;
12
+ }
13
+
14
+ class AmbiguousCapabilityError extends Error {
15
+ capability;
16
+ providers;
17
+ name = "AmbiguousCapabilityError";
18
+ constructor(capability, providers) {
19
+ super(`Ambiguous capability provider for ${capability}: ${providers.join(", ")}`);
20
+ this.capability = capability;
21
+ this.providers = providers;
22
+ }
23
+ }
24
+
25
+ class CapabilityProviderMissingError extends Error {
26
+ capability;
27
+ name = "CapabilityProviderMissingError";
28
+ constructor(capability) {
29
+ super(`No provider resolved for capability ${capability}`);
30
+ this.capability = capability;
31
+ }
32
+ }
33
+ function capabilityValue(plugin, capability) {
34
+ return plugin.capabilityProviders?.[capability];
35
+ }
36
+ function capabilityProviders(plugins, capability) {
37
+ return plugins.filter((plugin) => (plugin.provides ?? []).includes(capability));
38
+ }
39
+ function byPrecedence(providers, precedence) {
40
+ if (!precedence || precedence.length === 0)
41
+ return null;
42
+ const byId = new Map(providers.map((provider) => [loadedPluginId(provider), provider]));
43
+ for (const id of precedence) {
44
+ const provider = byId.get(id);
45
+ if (provider)
46
+ return provider;
47
+ }
48
+ return null;
49
+ }
50
+ function providersAfterReplacement(capability, providers) {
51
+ const providerIds = new Set(providers.map(loadedPluginId));
52
+ const replaced = new Set;
53
+ for (const provider of providers) {
54
+ for (const replacement of provider.replaces ?? []) {
55
+ for (const candidateId of providerIds) {
56
+ if (replacementMatches(replacement, capability, candidateId)) {
57
+ replaced.add(candidateId);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ return {
63
+ providers: providers.filter((provider) => !replaced.has(loadedPluginId(provider))),
64
+ replaced: [...replaced].sort()
65
+ };
66
+ }
67
+ function resolveCapability(plugins, capability, config = {}) {
68
+ const providers = capabilityProviders(plugins, capability);
69
+ if (providers.length === 0)
70
+ return null;
71
+ const precedenceProvider = byPrecedence(providers, config.capabilityPrecedence?.[capability]);
72
+ if (precedenceProvider) {
73
+ return {
74
+ capability,
75
+ plugin: precedenceProvider,
76
+ value: capabilityValue(precedenceProvider, capability),
77
+ selectedBy: "precedence",
78
+ replacedProviders: []
79
+ };
80
+ }
81
+ const afterReplacement = providersAfterReplacement(capability, providers);
82
+ if (afterReplacement.providers.length === 1) {
83
+ const [provider] = afterReplacement.providers;
84
+ if (!provider)
85
+ throw new CapabilityProviderMissingError(capability);
86
+ return {
87
+ capability,
88
+ plugin: provider,
89
+ value: capabilityValue(provider, capability),
90
+ selectedBy: afterReplacement.replaced.length > 0 ? "replaces" : "sole-provider",
91
+ replacedProviders: afterReplacement.replaced
92
+ };
93
+ }
94
+ throw new AmbiguousCapabilityError(capability, afterReplacement.providers.map(loadedPluginId).sort());
95
+ }
96
+
97
+ // packages/kernel-seed/src/loaderPolicy.ts
98
+ function createLoaderPolicyCapability() {
99
+ return {
100
+ resolveCapability(plugins, capability, grants) {
101
+ const candidatePluginIds = plugins.filter((plugin) => (plugin.provides ?? []).includes(capability)).map((plugin) => plugin.name).sort();
102
+ const providers = plugins.map((plugin) => ({
103
+ name: plugin.name,
104
+ ...plugin.provides ? { provides: plugin.provides } : {},
105
+ ...plugin.replaces ? { replaces: plugin.replaces } : {}
106
+ }));
107
+ try {
108
+ const resolution = resolveCapability(providers, capability, {
109
+ ...grants?.capabilityPrecedence ? { capabilityPrecedence: grants.capabilityPrecedence } : {}
110
+ });
111
+ if (!resolution) {
112
+ return {
113
+ capability,
114
+ status: "missing",
115
+ selectedPluginId: null,
116
+ candidatePluginIds,
117
+ precedenceUsed: false,
118
+ error: `No provider for ${capability}`
119
+ };
120
+ }
121
+ return {
122
+ capability,
123
+ status: "resolved",
124
+ selectedPluginId: resolution.plugin.name,
125
+ candidatePluginIds,
126
+ precedenceUsed: resolution.selectedBy === "precedence",
127
+ ...resolution.replacedProviders.length > 0 ? { error: `Replaced providers: ${resolution.replacedProviders.join(", ")}` } : {}
128
+ };
129
+ } catch (error) {
130
+ if (error instanceof AmbiguousCapabilityError) {
131
+ return {
132
+ capability,
133
+ status: "ambiguous",
134
+ selectedPluginId: null,
135
+ candidatePluginIds,
136
+ precedenceUsed: false,
137
+ error: `Ambiguous providers for ${capability}`
138
+ };
139
+ }
140
+ throw error;
141
+ }
142
+ }
143
+ };
144
+ }
145
+
146
+ // packages/kernel-seed/src/stageResolve.ts
147
+ class PipelineUnresolvableError extends Error {
148
+ cycles;
149
+ contributors;
150
+ constructor(message, cycles, contributors) {
151
+ super(message);
152
+ this.name = "PipelineUnresolvableError";
153
+ this.cycles = cycles;
154
+ this.contributors = contributors;
155
+ }
156
+ }
157
+ function uniqueSorted(values) {
158
+ return Array.from(new Set(values)).sort((left, right) => left.localeCompare(right));
159
+ }
160
+ function wrapperForMutation(mutation) {
161
+ return "wrapper" in mutation ? mutation.wrapper : mutation.around;
162
+ }
163
+ function contributorOf(mutation) {
164
+ if (mutation.contributedBy?.trim())
165
+ return mutation.contributedBy;
166
+ if (mutation.op === "wrap") {
167
+ const wrapper = wrapperForMutation(mutation);
168
+ if (wrapper.id?.trim())
169
+ return wrapper.id;
170
+ }
171
+ return "anonymous";
172
+ }
173
+ function stableMutationCompare(left, right) {
174
+ const leftTarget = left.op === "insert" ? left.stage.id : left.id;
175
+ const rightTarget = right.op === "insert" ? right.stage.id : right.id;
176
+ const targetDelta = leftTarget.localeCompare(rightTarget);
177
+ if (targetDelta !== 0)
178
+ return targetDelta;
179
+ return contributorOf(left).localeCompare(contributorOf(right));
180
+ }
181
+ function ensureUniqueStageIds(stages) {
182
+ const seen = new Set;
183
+ for (const stage of stages) {
184
+ if (seen.has(stage.id)) {
185
+ throw new PipelineUnresolvableError(`Duplicate stage id: ${stage.id}`, [], []);
186
+ }
187
+ seen.add(stage.id);
188
+ }
189
+ }
190
+ function assertNoDuplicateMutationTargets(mutations, op) {
191
+ const seen = new Map;
192
+ for (const mutation of mutations.filter((entry) => entry.op === op)) {
193
+ const id = mutation.op === "insert" ? mutation.stage.id : mutation.id;
194
+ const previous = seen.get(id);
195
+ if (previous) {
196
+ throw new PipelineUnresolvableError(`Duplicate ${op} mutation for stage ${id}: ${previous}, ${contributorOf(mutation)}`, [], uniqueSorted([previous, contributorOf(mutation)]));
197
+ }
198
+ seen.set(id, contributorOf(mutation));
199
+ }
200
+ }
201
+ function mergeAnchors(current, incoming) {
202
+ return uniqueSorted([...current, ...incoming ?? []]);
203
+ }
204
+ function stagePriority(stage) {
205
+ return typeof stage.priority === "number" && Number.isFinite(stage.priority) ? stage.priority : 0;
206
+ }
207
+ function readyCompare(states) {
208
+ return (left, right) => {
209
+ const leftState = states.get(left);
210
+ const rightState = states.get(right);
211
+ const priorityDelta = stagePriority(rightState?.stage ?? { id: right }) - stagePriority(leftState?.stage ?? { id: left });
212
+ if (priorityDelta !== 0)
213
+ return priorityDelta;
214
+ if (leftState?.baseIndex !== null && rightState?.baseIndex !== null && leftState?.baseIndex !== rightState?.baseIndex) {
215
+ return (leftState?.baseIndex ?? 0) - (rightState?.baseIndex ?? 0);
216
+ }
217
+ if (leftState?.baseIndex !== null && rightState?.baseIndex === null)
218
+ return -1;
219
+ if (leftState?.baseIndex === null && rightState?.baseIndex !== null)
220
+ return 1;
221
+ return left.localeCompare(right);
222
+ };
223
+ }
224
+ function findCycles(nodes, edges) {
225
+ const adjacency = new Map;
226
+ for (const node of nodes)
227
+ adjacency.set(node, []);
228
+ for (const edge of edges)
229
+ adjacency.get(edge.from)?.push(edge.to);
230
+ for (const targets of adjacency.values())
231
+ targets.sort((left, right) => left.localeCompare(right));
232
+ let nextIndex = 0;
233
+ const indexByNode = new Map;
234
+ const lowByNode = new Map;
235
+ const stack = [];
236
+ const onStack = new Set;
237
+ const cycles = [];
238
+ const visit = (node) => {
239
+ indexByNode.set(node, nextIndex);
240
+ lowByNode.set(node, nextIndex);
241
+ nextIndex += 1;
242
+ stack.push(node);
243
+ onStack.add(node);
244
+ for (const target of adjacency.get(node) ?? []) {
245
+ if (!indexByNode.has(target)) {
246
+ visit(target);
247
+ lowByNode.set(node, Math.min(lowByNode.get(node) ?? 0, lowByNode.get(target) ?? 0));
248
+ } else if (onStack.has(target)) {
249
+ lowByNode.set(node, Math.min(lowByNode.get(node) ?? 0, indexByNode.get(target) ?? 0));
250
+ }
251
+ }
252
+ if (lowByNode.get(node) !== indexByNode.get(node))
253
+ return;
254
+ const component = [];
255
+ let current;
256
+ do {
257
+ current = stack.pop();
258
+ if (current) {
259
+ onStack.delete(current);
260
+ component.push(current);
261
+ }
262
+ } while (current && current !== node);
263
+ const hasSelfLoop = edges.some((edge) => edge.from === node && edge.to === node);
264
+ if (component.length > 1 || hasSelfLoop) {
265
+ cycles.push(component.sort((left, right) => left.localeCompare(right)));
266
+ }
267
+ };
268
+ for (const node of [...nodes].sort((left, right) => left.localeCompare(right))) {
269
+ if (!indexByNode.has(node))
270
+ visit(node);
271
+ }
272
+ return cycles.sort((left, right) => left.join("\x00").localeCompare(right.join("\x00")));
273
+ }
274
+ function topologicalOrder(states, edges) {
275
+ const nodes = [...states.keys()];
276
+ const outgoing = new Map;
277
+ const indegree = new Map;
278
+ for (const node of nodes) {
279
+ outgoing.set(node, []);
280
+ indegree.set(node, 0);
281
+ }
282
+ for (const edge of edges) {
283
+ outgoing.get(edge.from)?.push(edge.to);
284
+ indegree.set(edge.to, (indegree.get(edge.to) ?? 0) + 1);
285
+ }
286
+ for (const targets of outgoing.values())
287
+ targets.sort((left, right) => left.localeCompare(right));
288
+ const compare = readyCompare(states);
289
+ const ready = nodes.filter((node) => (indegree.get(node) ?? 0) === 0).sort(compare);
290
+ const order = [];
291
+ while (ready.length > 0) {
292
+ const node = ready.shift();
293
+ if (!node)
294
+ break;
295
+ order.push(node);
296
+ for (const target of outgoing.get(node) ?? []) {
297
+ const next = (indegree.get(target) ?? 0) - 1;
298
+ indegree.set(target, next);
299
+ if (next === 0) {
300
+ ready.push(target);
301
+ ready.sort(compare);
302
+ }
303
+ }
304
+ }
305
+ if (order.length === nodes.length)
306
+ return order;
307
+ const cycles = findCycles(nodes, edges);
308
+ const cycleMembers = new Set(cycles.flat());
309
+ const contributors = uniqueSorted(edges.filter((edge) => cycleMembers.has(edge.from) && cycleMembers.has(edge.to)).flatMap((edge) => edge.contributors));
310
+ throw new PipelineUnresolvableError(`Stage pipeline has unresolved cycle: ${cycles.map((cycle) => cycle.join(" -> ")).join("; ")}`, cycles, contributors);
311
+ }
312
+ function composeStageWrappers(state) {
313
+ const wrappers = state.wrappers.toSorted((left, right) => {
314
+ const priorityDelta = (right.wrapper.priority ?? 0) - (left.wrapper.priority ?? 0);
315
+ if (priorityDelta !== 0)
316
+ return priorityDelta;
317
+ return left.contributedBy.localeCompare(right.contributedBy);
318
+ });
319
+ let stage = state.stage;
320
+ for (const wrapper of wrappers.toReversed()) {
321
+ if (wrapper.wrapper.apply)
322
+ stage = wrapper.wrapper.apply(stage);
323
+ }
324
+ return stage;
325
+ }
326
+ function resolveStagePipeline(input) {
327
+ ensureUniqueStageIds(input.defaultStages);
328
+ const mutations = [...input.mutations ?? []];
329
+ assertNoDuplicateMutationTargets(mutations, "insert");
330
+ assertNoDuplicateMutationTargets(mutations, "replace");
331
+ const states = new Map;
332
+ const removedStates = new Map;
333
+ for (const [index, stage] of input.defaultStages.entries()) {
334
+ states.set(stage.id, {
335
+ stage: { ...stage, protected: false },
336
+ before: [...stage.before ?? []],
337
+ after: [...stage.after ?? []],
338
+ baseIndex: index,
339
+ contributedBy: "default",
340
+ wrappers: [],
341
+ droppedAnchors: [],
342
+ isProtected: false
343
+ });
344
+ }
345
+ for (const mutation of mutations.filter((entry) => entry.op === "remove").sort(stableMutationCompare)) {
346
+ const state = states.get(mutation.id);
347
+ const contributor = contributorOf(mutation);
348
+ if (!state)
349
+ continue;
350
+ const removedState = {
351
+ ...state,
352
+ removedBy: contributor
353
+ };
354
+ removedStates.set(mutation.id, removedState);
355
+ states.delete(mutation.id);
356
+ }
357
+ for (const mutation of mutations.filter((entry) => entry.op === "replace").sort(stableMutationCompare)) {
358
+ const state = states.get(mutation.id);
359
+ const contributor = contributorOf(mutation);
360
+ if (!state)
361
+ continue;
362
+ const replacement = { ...mutation.stage, id: mutation.id, protected: false };
363
+ states.set(mutation.id, {
364
+ ...state,
365
+ stage: replacement,
366
+ before: mutation.stage.before ? [...mutation.stage.before] : state.before,
367
+ after: mutation.stage.after ? [...mutation.stage.after] : state.after,
368
+ replacedBy: contributor,
369
+ contributedBy: state.contributedBy,
370
+ isProtected: false
371
+ });
372
+ }
373
+ for (const mutation of mutations.filter((entry) => entry.op === "insert").sort(stableMutationCompare)) {
374
+ const contributor = contributorOf(mutation);
375
+ if (states.has(mutation.stage.id)) {
376
+ throw new PipelineUnresolvableError(`Inserted stage ${mutation.stage.id} conflicts with an existing stage`, [], [contributor]);
377
+ }
378
+ states.set(mutation.stage.id, {
379
+ stage: { ...mutation.stage, protected: false },
380
+ before: [...mutation.stage.before ?? []],
381
+ after: [...mutation.stage.after ?? []],
382
+ baseIndex: null,
383
+ contributedBy: contributor,
384
+ wrappers: [],
385
+ droppedAnchors: [],
386
+ isProtected: false
387
+ });
388
+ }
389
+ for (const mutation of mutations.filter((entry) => entry.op === "reorder").sort(stableMutationCompare)) {
390
+ const state = states.get(mutation.id);
391
+ if (!state)
392
+ continue;
393
+ states.set(mutation.id, {
394
+ ...state,
395
+ before: mergeAnchors(state.before, mutation.before),
396
+ after: mergeAnchors(state.after, mutation.after)
397
+ });
398
+ }
399
+ for (const mutation of mutations.filter((entry) => entry.op === "wrap").sort(stableMutationCompare)) {
400
+ const state = states.get(mutation.id);
401
+ const contributor = contributorOf(mutation);
402
+ const wrapper = wrapperForMutation(mutation);
403
+ if (!state)
404
+ continue;
405
+ states.set(mutation.id, {
406
+ ...state,
407
+ wrappers: [...state.wrappers, { contributedBy: contributor, wrapper }]
408
+ });
409
+ }
410
+ const contributorsForAnchor = (stageId, direction, anchor, state) => {
411
+ const contributors = new Set;
412
+ if (state.replacedBy)
413
+ contributors.add(state.replacedBy);
414
+ for (const mutation of mutations) {
415
+ if (mutation.op === "reorder" && mutation.id === stageId && (direction === "before" ? mutation.before : mutation.after)?.includes(anchor)) {
416
+ contributors.add(contributorOf(mutation));
417
+ }
418
+ if (mutation.op === "insert" && mutation.stage.id === stageId && (direction === "before" ? mutation.stage.before : mutation.stage.after)?.includes(anchor)) {
419
+ contributors.add(contributorOf(mutation));
420
+ }
421
+ }
422
+ if (contributors.size === 0)
423
+ contributors.add(state.contributedBy);
424
+ return uniqueSorted(contributors);
425
+ };
426
+ const edges = [];
427
+ for (const [stageId, state] of states) {
428
+ const before = [];
429
+ const after = [];
430
+ for (const anchor of state.before) {
431
+ if (states.has(anchor))
432
+ before.push(anchor);
433
+ else {
434
+ const removed = removedStates.get(anchor);
435
+ state.droppedAnchors.push({
436
+ stageId,
437
+ anchor,
438
+ direction: "before",
439
+ reason: removed ? "removed" : "missing",
440
+ ...removed?.removedBy ? { removedBy: removed.removedBy } : {}
441
+ });
442
+ }
443
+ }
444
+ for (const anchor of state.after) {
445
+ if (states.has(anchor))
446
+ after.push(anchor);
447
+ else {
448
+ const removed = removedStates.get(anchor);
449
+ state.droppedAnchors.push({
450
+ stageId,
451
+ anchor,
452
+ direction: "after",
453
+ reason: removed ? "removed" : "missing",
454
+ ...removed?.removedBy ? { removedBy: removed.removedBy } : {}
455
+ });
456
+ }
457
+ }
458
+ state.before = uniqueSorted(before);
459
+ state.after = uniqueSorted(after);
460
+ for (const target of state.before)
461
+ edges.push({ from: stageId, to: target, contributors: contributorsForAnchor(stageId, "before", target, state) });
462
+ for (const source of state.after)
463
+ edges.push({ from: source, to: stageId, contributors: contributorsForAnchor(stageId, "after", source, state) });
464
+ }
465
+ const order = topologicalOrder(states, edges);
466
+ const stages = [];
467
+ const record = [];
468
+ for (const id of order) {
469
+ const state = states.get(id);
470
+ if (!state)
471
+ continue;
472
+ stages.push(composeStageWrappers(state));
473
+ const wrappedBy = state.wrappers.toSorted((left, right) => {
474
+ const priorityDelta = (right.wrapper.priority ?? 0) - (left.wrapper.priority ?? 0);
475
+ if (priorityDelta !== 0)
476
+ return priorityDelta;
477
+ return left.contributedBy.localeCompare(right.contributedBy);
478
+ }).map((wrapper) => wrapper.contributedBy);
479
+ record.push({
480
+ stageId: id,
481
+ contributedBy: state.contributedBy,
482
+ ...state.replacedBy ? { replacedBy: state.replacedBy } : {},
483
+ ...wrappedBy.length > 0 ? { wrappedBy } : {},
484
+ ...state.droppedAnchors.length > 0 ? { droppedAnchors: state.droppedAnchors.toSorted((left, right) => left.anchor.localeCompare(right.anchor)) } : {},
485
+ isProtected: state.isProtected
486
+ });
487
+ }
488
+ record.push(...[...removedStates.entries()].toSorted((left, right) => {
489
+ const leftIndex = left[1].baseIndex ?? Number.MAX_SAFE_INTEGER;
490
+ const rightIndex = right[1].baseIndex ?? Number.MAX_SAFE_INTEGER;
491
+ if (leftIndex !== rightIndex)
492
+ return leftIndex - rightIndex;
493
+ return left[0].localeCompare(right[0]);
494
+ }).map(([stageId, state]) => ({
495
+ stageId,
496
+ contributedBy: state.contributedBy,
497
+ ...state.removedBy ? { removedBy: state.removedBy } : {},
498
+ isProtected: state.isProtected
499
+ })));
500
+ return { stages, order, record, cycles: [] };
501
+ }
502
+
503
+ // packages/kernel-seed/src/resolver.ts
504
+ function toCoreStage(stage) {
505
+ return {
506
+ id: String(stage.id),
507
+ kind: stage.kind,
508
+ priority: stage.priority,
509
+ protected: false,
510
+ ...stage.before !== undefined ? { before: stage.before.map(String) } : {},
511
+ ...stage.after !== undefined ? { after: stage.after.map(String) } : {}
512
+ };
513
+ }
514
+ function coreMutation(mutation) {
515
+ const contributedBy = typeof mutation.contributedBy === "string" && mutation.contributedBy.length > 0 ? mutation.contributedBy : "anonymous";
516
+ switch (mutation.op) {
517
+ case "insert":
518
+ return { op: "insert", stage: toCoreStage(mutation.stage), contributedBy };
519
+ case "remove":
520
+ return { op: "remove", id: String(mutation.id), contributedBy };
521
+ case "replace":
522
+ return { op: "replace", id: String(mutation.id), stage: toCoreStage(mutation.stage), contributedBy };
523
+ case "wrap":
524
+ return { op: "wrap", id: String(mutation.id), wrapper: { priority: mutation.around.priority }, contributedBy };
525
+ case "reorder":
526
+ return {
527
+ op: "reorder",
528
+ id: String(mutation.id),
529
+ contributedBy,
530
+ ...mutation.before !== undefined ? { before: mutation.before.map(String) } : {},
531
+ ...mutation.after !== undefined ? { after: mutation.after.map(String) } : {}
532
+ };
533
+ }
534
+ }
535
+ function resolutionRecordEntry(entry) {
536
+ return {
537
+ stageId: entry.stageId,
538
+ contributedBy: entry.contributedBy,
539
+ ...entry.removedBy !== undefined ? { removedBy: entry.removedBy } : {},
540
+ ...entry.replacedBy !== undefined ? { replacedBy: entry.replacedBy } : {},
541
+ ...entry.wrappedBy !== undefined ? { wrappedBy: [...entry.wrappedBy] } : {},
542
+ ...entry.droppedAnchors !== undefined ? { droppedAnchors: entry.droppedAnchors.map((anchor) => anchor.anchor) } : {},
543
+ isProtected: entry.isProtected
544
+ };
545
+ }
546
+ function resolvedPipeline(input) {
547
+ const mutations = input.mutations ?? [];
548
+ const resolved = resolveStagePipeline({
549
+ defaultStages: input.defaultStages.map(toCoreStage),
550
+ mutations: mutations.map(coreMutation)
551
+ });
552
+ return {
553
+ order: resolved.order.map((stageId) => stageId),
554
+ record: resolved.record.map(resolutionRecordEntry),
555
+ cycles: resolved.cycles.map((cycle) => cycle.map((stageId) => stageId)),
556
+ grantUses: [],
557
+ resolvedAt: new Date().toISOString()
558
+ };
559
+ }
560
+ function resolveKernelStages(defaultStages, mutations = [], grants = {}) {
561
+ return resolvedPipeline({ defaultStages, mutations, grants });
562
+ }
563
+
564
+ // packages/kernel-seed/src/defaultKernel.ts
565
+ var DEFAULT_KERNEL_PLUGIN_ID = "@rig/kernel-seed/default";
566
+ function createInMemoryJournalProvider(runId) {
567
+ const records = [];
568
+ const eventRunId = (event) => {
569
+ if (event !== null && typeof event === "object") {
570
+ const candidate = event.runId;
571
+ if (typeof candidate === "string" && candidate.length > 0)
572
+ return candidate;
573
+ }
574
+ return runId;
575
+ };
576
+ return {
577
+ async append(event) {
578
+ records.push({ runId: eventRunId(event), event });
579
+ },
580
+ async recordPipeline(targetRunId, pipeline) {
581
+ records.push({ runId: targetRunId, event: { type: "pipeline-resolved", pipeline } });
582
+ },
583
+ async recordStageOutcome(targetRunId, outcome) {
584
+ records.push({ runId: targetRunId, event: { type: "stage-outcome", outcome } });
585
+ },
586
+ async read(targetRunId) {
587
+ return records.filter((record) => record.runId === targetRunId).map((record) => record.event);
588
+ }
589
+ };
590
+ }
591
+ function createDefaultTransport() {
592
+ return {
593
+ async dispatch() {
594
+ throw new Error("Default kernel transport is not bound to a live OMP/collab dispatcher yet.");
595
+ }
596
+ };
597
+ }
598
+ function createDefaultKernel(options = {}) {
599
+ const journal = options.journal ?? createInMemoryJournalProvider("default-kernel-bootstrap");
600
+ const stageRunner = {
601
+ resolve(defaultStages, mutations, grants) {
602
+ return resolveKernelStages(defaultStages, mutations, grants ?? {});
603
+ },
604
+ async runPipeline(runId, resolved, ctx) {
605
+ await journal.recordPipeline(runId, resolved);
606
+ const outcomes = [];
607
+ let currentCtx = ctx;
608
+ for (const stageId of resolved.order) {
609
+ const startedAt = new Date().toISOString();
610
+ const executor = options.stageExecutors?.[stageId];
611
+ const result = executor ? await executor(currentCtx) : { kind: "continue", ctx: currentCtx };
612
+ const stageOutcome = { stageId, result, startedAt, finishedAt: new Date().toISOString() };
613
+ outcomes.push(stageOutcome);
614
+ await journal.recordStageOutcome?.(runId, stageOutcome);
615
+ if (result.kind === "continue") {
616
+ currentCtx = result.ctx;
617
+ } else if (result.kind === "block") {
618
+ break;
619
+ }
620
+ }
621
+ return outcomes;
622
+ }
623
+ };
624
+ const boundTransport = options.transport ?? createDefaultTransport();
625
+ const transport = {
626
+ dispatch: (task, opts) => boundTransport.dispatch(task, opts),
627
+ attach: (runId) => boundTransport.attach ? boundTransport.attach(runId) : Promise.reject(new Error("transport.attach not supported")),
628
+ serve: () => boundTransport.serve ? boundTransport.serve() : Promise.resolve()
629
+ };
630
+ return {
631
+ id: DEFAULT_KERNEL_PLUGIN_ID,
632
+ stageRunner,
633
+ journal,
634
+ transport,
635
+ loaderPolicy: createLoaderPolicyCapability(),
636
+ async start(_plugins) {}
637
+ };
638
+ }
639
+ var LOCAL_TRANSPORT_PLUGIN_ID = "@rig/kernel-seed/local-transport";
640
+ var PLACEMENT_TRANSPORT_PLUGIN_ID = "@rig/kernel-seed/placement-transport";
641
+ function createTransportProviderPlugin(input) {
642
+ return {
643
+ name: input.id,
644
+ version: "0.0.0-alpha.1",
645
+ provides: ["transport"],
646
+ replaces: input.replaces,
647
+ capabilityProviders: { transport: input.transport }
648
+ };
649
+ }
650
+ function createLocalTransportPlugin(transport) {
651
+ return createTransportProviderPlugin({
652
+ id: LOCAL_TRANSPORT_PLUGIN_ID,
653
+ transport,
654
+ replaces: [`transport@${DEFAULT_KERNEL_PLUGIN_ID}`]
655
+ });
656
+ }
657
+ function createPlacementTransportPlugin(transport, _options = {}) {
658
+ return createTransportProviderPlugin({
659
+ id: PLACEMENT_TRANSPORT_PLUGIN_ID,
660
+ transport,
661
+ replaces: [`transport@${DEFAULT_KERNEL_PLUGIN_ID}`, `transport@${LOCAL_TRANSPORT_PLUGIN_ID}`]
662
+ });
663
+ }
664
+ function createDefaultKernelPlugin(options = {}) {
665
+ const kernel = createDefaultKernel(options);
666
+ return {
667
+ name: DEFAULT_KERNEL_PLUGIN_ID,
668
+ version: "0.0.0-alpha.1",
669
+ provides: ["kernel", "stage-runner", "journal", "transport", "loader-policy"],
670
+ capabilityProviders: {
671
+ kernel,
672
+ "stage-runner": kernel.stageRunner,
673
+ journal: kernel.journal,
674
+ transport: kernel.transport,
675
+ "loader-policy": kernel.loaderPolicy
676
+ }
677
+ };
678
+ }
679
+ export {
680
+ createPlacementTransportPlugin,
681
+ createLocalTransportPlugin,
682
+ createDefaultKernelPlugin,
683
+ createDefaultKernel,
684
+ PLACEMENT_TRANSPORT_PLUGIN_ID,
685
+ LOCAL_TRANSPORT_PLUGIN_ID,
686
+ DEFAULT_KERNEL_PLUGIN_ID
687
+ };
@@ -1,4 +1,9 @@
1
1
  export * from "./journalConformance";
2
+ export * from "./loaderPolicy";
2
3
  export * from "./pluginAbi";
3
4
  export * from "./resolveCapability";
4
5
  export * from "./seed";
6
+ export * from "./bootDefault";
7
+ export * from "./defaultKernel";
8
+ export * from "./stageResolve";
9
+ export * from "./resolver";