@godspeedai/cognate-kernel-cordis 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-kernel-cordis
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cordis-backed implementation of `@godspeedai/cognate-kernel-api`. Only this package imports `cordis`; no
4
+ Cordis type crosses an exported signature (spec §3.4). See `docs/decisions/ADR-0001-kernel-engine-cordis.md`.
5
+
6
+ ## Mapping
7
+
8
+ | Cognate concept | Cordis concept |
9
+ | --- | --- |
10
+ | `Scope` | A Cordis `Context` obtained via `ctx.isolate(id)` (`scope.ts`) |
11
+ | Mounted component occurrence | One `ctx.plugin()` call = one Cordis fiber, per attempt (`fiber.ts`) |
12
+ | `effects.register()` | Entries in an adapter-owned stack unwound by a single `ctx.effect()` wrapper |
13
+ | `provide()` / capability publish-withdraw | Committed into `CapabilityRegistry` only after activation succeeds, torn down by the same wrapper effect |
14
+ | `CapabilityLease` | Adapter object bound to one `Publication`, revalidated per invoke (Cordis has no lease type) |
15
+ | `kernel.resolve()` / dependency matching | `CapabilityRegistry.find()` using `isCompatible` over scope-ancestor chain |
16
+
17
+ ## Adapter-owned behaviours (Cordis has none of these; ADR-0001 mitigations)
18
+
19
+ - **Aggregated cleanup errors** — Cordis reports each disposer error to its own logger and never
20
+ aggregates them; the single wrapper effect aggregates into `CleanupError` itself.
21
+ - **Reverse-order disposal** — Cordis's own `Promise.all`-based unload is only reverse-of-completion
22
+ for synchronous disposers; the adapter runs its own effect stack sequentially in reverse.
23
+ - **Cancellation signal** — Cordis never cancels an in-flight `apply()`; the adapter derives its own
24
+ `AbortSignal` per attempt and per active occurrence.
25
+ - **Retry/backoff and permanent failure** — fully adapter-owned state machine (`fiber.ts`).
26
+ - **Activation timeout** — raced against the Cordis fiber promise; a timed-out fiber is abandoned,
27
+ not force-disposed (Cordis's `dispose()` blocks forever on a hung `apply()`).
28
+ - **FAILED/DEACTIVATING vocabulary and fiber-state translation** — Cordis uses
29
+ PENDING/LOADING/ACTIVE/FAILED/DISPOSED/UNLOADING; never exposed.
30
+ - **Dependency eligibility (`isCompatible`, version/attributes)** and **scope visibility**
31
+ (descendant-visible, sibling-invisible) — Cordis's `ctx.provide`/`ctx.get`/`isolate` are
32
+ single-slot-per-name with no version matching and no dynamic per-id isolation; both are
33
+ implemented in `registry.ts`/`scope.ts`.
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-kernel-cordis",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Cordis-backed implementation of @godspeedai/cognate-kernel-api. The only package allowed to import cordis.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/GodSpeedAI/Cognate.git",
10
+ "directory": "packages/kernel-cordis"
11
+ },
12
+ "engines": {
13
+ "bun": ">=1.4.0"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "exports": {
22
+ ".": "./src/index.ts"
23
+ },
24
+ "dependencies": {
25
+ "@godspeedai/cognate-kernel-api": "^0.1.0",
26
+ "cordis": "4.0.0-rc.10"
27
+ }
28
+ }
package/src/fiber.ts ADDED
@@ -0,0 +1,387 @@
1
+ // One mounted Component occurrence. Each activation attempt is a real Cordis plugin/fiber
2
+ // (`scope.cordisCtx.plugin(...)`); the WAITING/ACTIVATING/ACTIVE/FAILED/DEACTIVATING/DISPOSED
3
+ // state machine, retry/backoff, activation timeout, and dependency-loss cascade are adapter-owned
4
+ // because Cordis has none of them (ADR-0001): its own vocabulary is
5
+ // PENDING/LOADING/ACTIVE/FAILED/DISPOSED/UNLOADING with no retry, no timeout, and no cancellation
6
+ // of an in-flight `apply()`.
7
+ import type { Context, Fiber } from "cordis";
8
+ import {
9
+ ActivationTimeoutError,
10
+ CleanupError,
11
+ PermanentActivationError,
12
+ UndeclaredCapabilityError,
13
+ } from "@godspeedai/cognate-kernel-api";
14
+ import type {
15
+ CapabilityContract,
16
+ CapabilityHandler,
17
+ CapabilityLease,
18
+ Component,
19
+ ComponentHandle,
20
+ Disposer,
21
+ EffectHandle,
22
+ FiberContext,
23
+ FiberState,
24
+ KernelEvent,
25
+ Policy,
26
+ } from "@godspeedai/cognate-kernel-api";
27
+ import { createLease } from "./lease.ts";
28
+ import type { CapabilityRegistry, Publication } from "./registry.ts";
29
+ import type { ScopeImpl } from "./scope.ts";
30
+
31
+
32
+ interface EffectEntry {
33
+ readonly label: string;
34
+ readonly disposer: Disposer;
35
+ disposed: boolean;
36
+ }
37
+
38
+ interface Committed {
39
+ readonly pub: Publication;
40
+ readonly unpublish: () => void;
41
+ readonly deactivate: () => void;
42
+ }
43
+
44
+ export class FiberUnit implements ComponentHandle {
45
+ readonly componentId: string;
46
+ readonly scopeId: string;
47
+ lastError: unknown;
48
+
49
+ private _state: FiberState = "WAITING";
50
+ private _fiberId: string | undefined;
51
+ private attempts = 0;
52
+ private terminated = false;
53
+ private registryUnsub: (() => void) | undefined;
54
+ private retryTimer: ReturnType<typeof setTimeout> | undefined;
55
+ private currentAttemptAbort: AbortController | undefined;
56
+ private teardownAbort = new AbortController();
57
+ private cordisFiber: (Fiber & PromiseLike<Fiber>) | undefined;
58
+ private effectStack: EffectEntry[] = [];
59
+ private pendingProvides: Array<{ contract: CapabilityContract; handler: CapabilityHandler }> = [];
60
+ private committed: Committed[] = [];
61
+ private lastCleanupError: CleanupError | undefined;
62
+ private readonly boundUnbind: Array<() => void> = [];
63
+ private readonly stateListeners = new Set<() => void>();
64
+
65
+ constructor(
66
+ private readonly component: Component,
67
+ private readonly scope: ScopeImpl,
68
+ private readonly registry: CapabilityRegistry,
69
+ private readonly policy: Policy,
70
+ private readonly tenant: string,
71
+ private readonly emit: (event: KernelEvent) => void,
72
+ private readonly nextId: () => string,
73
+ ) {
74
+ this.componentId = component.id;
75
+ this.scopeId = scope.id;
76
+ }
77
+
78
+ get state(): FiberState {
79
+ return this._state;
80
+ }
81
+
82
+ get fiberId(): string | undefined {
83
+ return this._fiberId;
84
+ }
85
+
86
+ start(): void {
87
+ this.registryUnsub = this.registry.onChange(() => this.tryActivate());
88
+ this.tryActivate();
89
+ }
90
+
91
+ waitFor(target: FiberState, timeoutMs = 2000): Promise<void> {
92
+ if (this._state === target) return Promise.resolve();
93
+ return new Promise((resolve, reject) => {
94
+ const timer = setTimeout(() => {
95
+ this.stateListeners.delete(listener);
96
+ reject(new Error(`timed out waiting for ${this.componentId} to reach ${target} (was ${this._state})`));
97
+ }, timeoutMs);
98
+ const listener = () => {
99
+ if (this._state !== target) return;
100
+ clearTimeout(timer);
101
+ this.stateListeners.delete(listener);
102
+ resolve();
103
+ };
104
+ this.stateListeners.add(listener);
105
+ });
106
+ }
107
+
108
+ async dispose(reason: string): Promise<void> {
109
+ await this.deactivate(reason, true);
110
+ }
111
+
112
+ async reset(): Promise<void> {
113
+ if (this._state !== "FAILED" || this.terminated) return;
114
+ if (this.retryTimer) {
115
+ clearTimeout(this.retryTimer);
116
+ this.retryTimer = undefined;
117
+ }
118
+ this.setState("WAITING");
119
+ this.tryActivate();
120
+ }
121
+
122
+ // --- dependency watching -------------------------------------------------
123
+
124
+ private tryActivate(): void {
125
+ if (this._state !== "WAITING" || this.terminated) return;
126
+ const requires = this.component.requires ?? {};
127
+ const chain = this.scope.ancestorIds();
128
+ const resolved: Record<string, Publication> = {};
129
+ for (const [key, requirement] of Object.entries(requires)) {
130
+ const pub = this.registry.find(requirement, chain);
131
+ if (!pub) return;
132
+ resolved[key] = pub;
133
+ }
134
+ void this.runAttempt(resolved);
135
+ }
136
+
137
+ // --- activation attempts --------------------------------------------------
138
+
139
+ private async runAttempt(resolved: Record<string, Publication>): Promise<void> {
140
+ this.attempts++;
141
+ this._fiberId = this.nextId();
142
+ this.currentAttemptAbort = new AbortController();
143
+ this.teardownAbort = new AbortController();
144
+ this.effectStack = [];
145
+ this.pendingProvides = [];
146
+ this.setState("ACTIVATING");
147
+
148
+ for (const pub of Object.values(resolved)) {
149
+ this.boundUnbind.push(this.registry.bind(pub, () => this.loseDependency()));
150
+ }
151
+
152
+ const fiberContext = this.buildFiberContext(resolved, this.currentAttemptAbort.signal);
153
+ // Teardown is bound to this attempt's own effect stack: a Cordis fiber abandoned by timeout may be
154
+ // disposed much later, after a retry has started, and must never unwind the newer attempt's effects.
155
+ const stack = this.effectStack;
156
+ const cordisFiber = this.scope.cordisCtx.plugin({
157
+ apply: (ctx: Context) => {
158
+ ctx.effect(() => () => this.teardown(stack));
159
+ return this.component.activate(fiberContext);
160
+ },
161
+ });
162
+ this.cordisFiber = cordisFiber;
163
+
164
+ // Spec §8.4: an activation that never settles fails instead of staying ACTIVATING. Cordis cannot cancel
165
+ // a hung apply() (its dispose() waits for it), so on timeout the adapter unwinds the attempt's effects itself.
166
+ const timeoutMs = this.component.activationTimeoutMs ?? 30000;
167
+ let timedOut = false;
168
+ let timer: ReturnType<typeof setTimeout> | undefined;
169
+ const settled = await Promise.race([
170
+ cordisFiber.then(
171
+ () => ({ ok: true as const }),
172
+ (error: unknown) => ({ ok: false as const, error }),
173
+ ),
174
+ new Promise<{ ok: false; error: unknown }>((resolve) => {
175
+ timer = setTimeout(() => {
176
+ timedOut = true;
177
+ resolve({ ok: false, error: new ActivationTimeoutError(`activation of ${this.component.id} exceeded ${timeoutMs}ms`) });
178
+ }, timeoutMs);
179
+ }),
180
+ ]);
181
+ clearTimeout(timer);
182
+
183
+ if (timedOut) {
184
+ this.currentAttemptAbort.abort();
185
+ await this.teardown(stack);
186
+ cordisFiber.dispose().catch(() => {});
187
+ this.cordisFiber = undefined;
188
+ }
189
+
190
+ if (this.currentAttemptAbort.signal.aborted && !timedOut) {
191
+ // superseded by an explicit dispose()/loseDependency() call already driving the transition.
192
+ return;
193
+ }
194
+
195
+ if (settled.ok) {
196
+ for (const { contract, handler } of this.pendingProvides) this.commitProvide(contract, handler);
197
+ this.pendingProvides = [];
198
+ this.setState("ACTIVE");
199
+ } else {
200
+ this.unbindDependencies();
201
+ this.cordisFiber = undefined;
202
+ this.handleFailure(settled.error);
203
+ }
204
+ }
205
+
206
+ private commitProvide(contract: CapabilityContract, handler: CapabilityHandler): void {
207
+ let active = true;
208
+ const pub: Publication = {
209
+ contract,
210
+ providerId: this._fiberId!,
211
+ scopeId: this.scope.id,
212
+ handler,
213
+ teardownSignal: this.teardownAbort.signal,
214
+ isActive: () => active,
215
+ };
216
+ const unpublish = this.registry.publish(pub);
217
+ this.committed.push({ pub, unpublish, deactivate: () => (active = false) });
218
+ this.emit({ type: "capability.provided", capability: contract, providerId: pub.providerId, scopeId: this.scope.id });
219
+ }
220
+
221
+ private handleFailure(error: unknown): void {
222
+ this.setState("FAILED", error);
223
+ const retry = this.component.retry ?? { maxAttempts: 1, baseDelayMs: 0, maxDelayMs: 0 };
224
+ const permanent = error instanceof PermanentActivationError;
225
+ if (permanent || this.attempts >= retry.maxAttempts) return; // terminal FAILED until reset()
226
+ const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (this.attempts - 1));
227
+ this.retryTimer = setTimeout(() => {
228
+ if (this.terminated) return;
229
+ this.setState("WAITING");
230
+ this.tryActivate();
231
+ }, backoff);
232
+ }
233
+
234
+ // --- teardown: the single Cordis effect every attempt registers -----------
235
+
236
+ /** Registered once via `ctx.effect()` per attempt (ADR mitigation 1 & 3): aggregates cleanup
237
+ * errors ourselves (Cordis reports each to its logger and never aggregates them) and withdraws
238
+ * every capability this occurrence published, cascading to bound dependents first so a
239
+ * dependent always finishes deactivating before the provider's own effects run (spec §8.4/§35). */
240
+ private async teardown(stack: EffectEntry[]): Promise<void> {
241
+ const errors: unknown[] = [];
242
+ // Published capabilities belong to the current occurrence only; an abandoned attempt never published.
243
+ const committed = stack === this.effectStack ? this.committed.splice(0) : [];
244
+ for (const { pub, unpublish, deactivate } of committed) {
245
+ deactivate();
246
+ await this.registry.notifyLoss(pub);
247
+ unpublish();
248
+ this.emit({ type: "capability.withdrawn", capability: pub.contract, providerId: pub.providerId, scopeId: pub.scopeId });
249
+ }
250
+ for (const entry of stack.splice(0).reverse()) {
251
+ if (entry.disposed) continue;
252
+ entry.disposed = true;
253
+ try {
254
+ await entry.disposer();
255
+ } catch (error) {
256
+ errors.push(error);
257
+ }
258
+ }
259
+ if (errors.length) {
260
+ this.lastCleanupError = new CleanupError(this.component.id, errors);
261
+ this.emit({ type: "cleanup.failed", componentId: this.component.id, fiberId: this._fiberId ?? "", errors });
262
+ }
263
+ }
264
+
265
+ private unbindDependencies(): void {
266
+ for (const unbind of this.boundUnbind.splice(0)) unbind();
267
+ }
268
+
269
+ private async loseDependency(): Promise<void> {
270
+ if (this.terminated || (this._state !== "ACTIVE" && this._state !== "ACTIVATING")) return;
271
+ await this.deactivate("dependency lost", false);
272
+ }
273
+
274
+ private async deactivate(reason: string, terminal: boolean): Promise<void> {
275
+ if (this.terminated) return;
276
+
277
+ if (this._state === "WAITING" || this._state === "FAILED") {
278
+ if (this.retryTimer) {
279
+ clearTimeout(this.retryTimer);
280
+ this.retryTimer = undefined;
281
+ }
282
+ if (terminal) this.finalize();
283
+ return;
284
+ }
285
+
286
+ if (this._state === "ACTIVATING") {
287
+ this.currentAttemptAbort?.abort();
288
+ if (this.cordisFiber) {
289
+ await this.cordisFiber.dispose().catch(() => {});
290
+ this.cordisFiber = undefined;
291
+ }
292
+ } else if (this._state === "ACTIVE") {
293
+ this.setState("DEACTIVATING");
294
+ this.teardownAbort.abort();
295
+ if (this.cordisFiber) {
296
+ await this.cordisFiber.dispose().catch(() => {});
297
+ this.cordisFiber = undefined;
298
+ }
299
+ }
300
+
301
+ this.unbindDependencies();
302
+
303
+ if (terminal) {
304
+ this.finalize();
305
+ if (this.lastCleanupError) {
306
+ const error = this.lastCleanupError;
307
+ this.lastCleanupError = undefined;
308
+ throw error;
309
+ }
310
+ } else {
311
+ this._fiberId = undefined;
312
+ this.setState("WAITING");
313
+ this.tryActivate();
314
+ }
315
+ }
316
+
317
+ private finalize(): void {
318
+ this.terminated = true;
319
+ this.registryUnsub?.();
320
+ this.registryUnsub = undefined;
321
+ if (this.retryTimer) {
322
+ clearTimeout(this.retryTimer);
323
+ this.retryTimer = undefined;
324
+ }
325
+ this._fiberId = undefined;
326
+ this.scope.untrack(this);
327
+ this.setState("DISPOSED");
328
+ }
329
+
330
+ private setState(next: FiberState, error?: unknown): void {
331
+ const from = this._state;
332
+ this._state = next;
333
+ if (error !== undefined) this.lastError = error;
334
+ this.emit({ type: "fiber.state", componentId: this.componentId, scopeId: this.scopeId, fiberId: this._fiberId, from, to: next, error });
335
+ for (const listener of [...this.stateListeners]) listener();
336
+ }
337
+
338
+ private buildFiberContext(resolved: Record<string, Publication>, signal: AbortSignal): FiberContext {
339
+ const dependencies: Record<string, CapabilityLease> = {};
340
+ for (const [key, pub] of Object.entries(resolved)) {
341
+ dependencies[key] = createLease(
342
+ { contract: pub.contract, providerId: pub.providerId, scopeId: pub.scopeId, handler: pub.handler, teardownSignal: pub.teardownSignal },
343
+ this.tenant,
344
+ this.policy,
345
+ () => pub.isActive(),
346
+ this.emit,
347
+ );
348
+ }
349
+ const effectStack = this.effectStack;
350
+ return {
351
+ fiberId: this._fiberId!,
352
+ componentId: this.componentId,
353
+ scope: this.scope,
354
+ dependencies,
355
+ signal,
356
+ effects: {
357
+ register: (disposer: Disposer, label = "effect"): EffectHandle => {
358
+ const entry: EffectEntry = { label, disposer, disposed: false };
359
+ if (signal.aborted) {
360
+ // The attempt was abandoned (timeout or concurrent dispose): nothing will unwind it later.
361
+ entry.disposed = true;
362
+ void Promise.resolve().then(disposer).catch(() => {});
363
+ } else effectStack.push(entry);
364
+ return {
365
+ label,
366
+ get disposed() {
367
+ return entry.disposed;
368
+ },
369
+ dispose: async () => {
370
+ if (entry.disposed) return;
371
+ entry.disposed = true;
372
+ const index = effectStack.indexOf(entry);
373
+ if (index >= 0) effectStack.splice(index, 1);
374
+ await Promise.resolve(entry.disposer());
375
+ },
376
+ };
377
+ },
378
+ },
379
+ provide: <I, O>(contract: CapabilityContract, handler: CapabilityHandler<I, O>): void => {
380
+ if (!this.component.provides?.some((c) => c.id === contract.id)) {
381
+ throw new UndeclaredCapabilityError(`component ${this.componentId} did not declare capability ${contract.id}`);
382
+ }
383
+ this.pendingProvides.push({ contract, handler: handler as CapabilityHandler });
384
+ },
385
+ };
386
+ }
387
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ // Public surface of @godspeedai/cognate-kernel-cordis. No Cordis type crosses this boundary (spec §3.4).
2
+ import type { KernelFactory } from "@godspeedai/cognate-kernel-api";
3
+ import { CordisKernel } from "./kernel.ts";
4
+
5
+ export const createCordisKernel: KernelFactory = (options) => new CordisKernel(options);
package/src/kernel.ts ADDED
@@ -0,0 +1,58 @@
1
+ // Framework-owned kernel, backed by Cordis. This is the only file besides scope.ts/fiber.ts that
2
+ // touches the `cordis` package; nothing here appears in any exported signature (spec §3.4).
3
+ import { Context } from "cordis";
4
+ import { ScopeClosedError } from "@godspeedai/cognate-kernel-api";
5
+ import type { CapabilityLease, Component, ComponentHandle, Kernel, KernelEvent, KernelOptions, Requirement, Scope, Unavailable } from "@godspeedai/cognate-kernel-api";
6
+ import { FiberUnit } from "./fiber.ts";
7
+ import { createLease } from "./lease.ts";
8
+ import { CapabilityRegistry } from "./registry.ts";
9
+ import { ScopeImpl } from "./scope.ts";
10
+
11
+ export class CordisKernel implements Kernel {
12
+ readonly root: Scope;
13
+ private readonly registry = new CapabilityRegistry();
14
+ private readonly listeners = new Set<(event: KernelEvent) => void>();
15
+ private readonly rootScope: ScopeImpl;
16
+ private readonly nextId: () => string;
17
+
18
+ constructor(private readonly options: KernelOptions) {
19
+ this.nextId = options.ids ?? (() => crypto.randomUUID());
20
+ this.rootScope = new ScopeImpl(new Context(), options.tenant, options.principal, undefined, "root");
21
+ this.root = this.rootScope;
22
+ }
23
+
24
+ async mount(component: Component, scope: Scope = this.root): Promise<ComponentHandle> {
25
+ const target = scope as ScopeImpl;
26
+ if (target.closed) throw new ScopeClosedError(`cannot mount ${component.id} into closed scope ${target.id}`);
27
+ const fiber = new FiberUnit(component, target, this.registry, this.options.policy, this.options.tenant, (event) => this.emit(event), this.nextId);
28
+ target.track(fiber);
29
+ fiber.start();
30
+ return fiber;
31
+ }
32
+
33
+ resolve(requirement: Requirement, scope: Scope = this.root): CapabilityLease | Unavailable {
34
+ const chain = (scope as ScopeImpl).ancestorIds();
35
+ const pub = this.registry.find(requirement, chain);
36
+ if (!pub) return { unavailable: true, requirement, reason: `no eligible provider for ${requirement.capability}` };
37
+ return createLease(
38
+ { contract: pub.contract, providerId: pub.providerId, scopeId: pub.scopeId, handler: pub.handler, teardownSignal: pub.teardownSignal },
39
+ this.options.tenant,
40
+ this.options.policy,
41
+ () => pub.isActive(),
42
+ (event) => this.emit(event),
43
+ );
44
+ }
45
+
46
+ observe(listener: (event: KernelEvent) => void): () => void {
47
+ this.listeners.add(listener);
48
+ return () => void this.listeners.delete(listener);
49
+ }
50
+
51
+ async shutdown(reason: string): Promise<void> {
52
+ await this.rootScope.close(reason);
53
+ }
54
+
55
+ private emit(event: KernelEvent): void {
56
+ for (const listener of [...this.listeners]) listener(event);
57
+ }
58
+ }
package/src/lease.ts ADDED
@@ -0,0 +1,129 @@
1
+ // Cordis has no first-class lease object (ADR-0001 consequence): a lease here is a Cognate-owned
2
+ // wrapper bound to one resolved provider, revalidated on every invocation against `isValid` (the
3
+ // fiber-owned flag flipped the instant that provider's Cordis fiber leaves ACTIVE), never against
4
+ // Cordis's own service-availability signal directly.
5
+ import type {
6
+ AuthorizationRequest,
7
+ CapabilityContract,
8
+ CapabilityHandler,
9
+ CapabilityLease,
10
+ HandlerContext,
11
+ InvocationContext,
12
+ InvocationFailure,
13
+ InvocationResult,
14
+ KernelEvent,
15
+ Policy,
16
+ } from "@godspeedai/cognate-kernel-api";
17
+
18
+ export interface BoundProvider {
19
+ readonly contract: CapabilityContract;
20
+ readonly providerId: string;
21
+ readonly scopeId: string;
22
+ readonly handler: CapabilityHandler;
23
+ /** Aborted the instant the providing fiber leaves ACTIVE (ADR mitigation: Cordis provides no cancellation signal itself). */
24
+ readonly teardownSignal: AbortSignal;
25
+ }
26
+
27
+ export function createLease(
28
+ provider: BoundProvider,
29
+ tenant: string,
30
+ policy: Policy,
31
+ isValid: () => boolean,
32
+ emit: (event: KernelEvent) => void,
33
+ ): CapabilityLease {
34
+ return {
35
+ contract: provider.contract,
36
+ providerId: provider.providerId,
37
+ get valid() {
38
+ return isValid();
39
+ },
40
+ invoke: (input, context) => invoke(provider, tenant, policy, isValid, emit, input, context),
41
+ };
42
+ }
43
+
44
+ async function invoke(
45
+ provider: BoundProvider,
46
+ tenant: string,
47
+ policy: Policy,
48
+ isValid: () => boolean,
49
+ emit: (event: KernelEvent) => void,
50
+ input: unknown,
51
+ context: InvocationContext,
52
+ ): Promise<InvocationResult<unknown>> {
53
+ if (!isValid()) return unavailable(provider.contract.id);
54
+
55
+ // Spec §32: authorization and handlers see the caller's tenant, not the kernel's.
56
+ const callerTenant = context.tenant ?? tenant;
57
+ const request: AuthorizationRequest = {
58
+ operation: "invoke",
59
+ actor: context.actor,
60
+ tenant: callerTenant,
61
+ scopeId: provider.scopeId,
62
+ capability: provider.contract,
63
+ providerId: provider.providerId,
64
+ correlationId: context.correlationId,
65
+ };
66
+ const decision = await policy.authorize(request);
67
+ emit({ type: "invocation", capability: provider.contract.id, providerId: provider.providerId, correlationId: context.correlationId, decision });
68
+ if (!decision.allow) return { ok: false, failure: { kind: "denied", decision } };
69
+ if (!isValid()) return unavailable(provider.contract.id);
70
+
71
+ const controller = new AbortController();
72
+ let outcome: InvocationFailure | undefined;
73
+ // Registered before any check can fire `abort()`, so a signal already aborted at call time
74
+ // (e.g. the caller aborts synchronously right after invoking) still resolves `settled`.
75
+ const settled = new Promise<InvocationResult<unknown>>((resolve) => {
76
+ controller.signal.addEventListener("abort", () => resolve({ ok: false, failure: outcome! }), { once: true });
77
+ });
78
+ const fail = (failure: InvocationFailure) => {
79
+ if (outcome) return;
80
+ outcome = failure;
81
+ controller.abort();
82
+ };
83
+
84
+ const onTeardown = () => fail({ kind: "unavailable", capability: provider.contract.id, reason: "provider torn down during invocation" });
85
+ provider.teardownSignal.addEventListener("abort", onTeardown, { once: true });
86
+ const onCancel = () => fail({ kind: "cancelled" });
87
+ if (context.signal?.aborted) fail({ kind: "cancelled" });
88
+ else context.signal?.addEventListener("abort", onCancel, { once: true });
89
+
90
+ let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
91
+ if (context.deadline !== undefined) {
92
+ const remaining = Math.max(0, context.deadline - Date.now());
93
+ deadlineTimer = setTimeout(() => fail({ kind: "deadline_exceeded" }), remaining);
94
+ }
95
+
96
+ const handlerContext: HandlerContext = {
97
+ ...context,
98
+ capability: provider.contract,
99
+ providerId: provider.providerId,
100
+ decision,
101
+ tenant: callerTenant,
102
+ scopeId: provider.scopeId,
103
+ signal: controller.signal,
104
+ // Always callable: a handler never needs to guard `ctx.progress?.(...)` even when the caller
105
+ // did not supply a channel (spec: no-op outside a run).
106
+ progress: context.progress ?? (async () => {}),
107
+ };
108
+
109
+ const ran = (async (): Promise<InvocationResult<unknown>> => {
110
+ try {
111
+ const value = await provider.handler(input, handlerContext);
112
+ return { ok: true, value };
113
+ } catch (error) {
114
+ return { ok: false, failure: { kind: "failed", error } };
115
+ }
116
+ })();
117
+
118
+ try {
119
+ return await Promise.race([ran, settled]);
120
+ } finally {
121
+ provider.teardownSignal.removeEventListener("abort", onTeardown);
122
+ context.signal?.removeEventListener("abort", onCancel);
123
+ if (deadlineTimer) clearTimeout(deadlineTimer);
124
+ }
125
+ }
126
+
127
+ function unavailable(capability: string): InvocationResult<never> {
128
+ return { ok: false, failure: { kind: "unavailable", capability, reason: "provider is no longer active" } };
129
+ }
@@ -0,0 +1,80 @@
1
+ // Capability registry: Cognate requires multi-provider resolution keyed by capability id,
2
+ // version and attributes (spec §8.2, isCompatible). Cordis's own service model (`ctx.provide`/
3
+ // `ctx.get`) is a single-slot-per-name singleton with no version/attribute matching, so the
4
+ // eligibility graph itself is adapter-owned (explicitly sanctioned: "dependency eligibility via
5
+ // isCompatible ... implement it in the adapter"). Cordis is still used per-publication: each
6
+ // entry here is only ever created from inside a fiber's committed `ctx.provide()` call and torn
7
+ // down through that same fiber's Cordis effect (see fiber.ts), so the registry is a read model
8
+ // over state whose lifetime Cordis still owns.
9
+ import { isCompatible } from "@godspeedai/cognate-kernel-api";
10
+ import type { CapabilityContract, CapabilityHandler, Requirement } from "@godspeedai/cognate-kernel-api";
11
+
12
+ export interface Publication {
13
+ readonly contract: CapabilityContract;
14
+ readonly providerId: string;
15
+ readonly scopeId: string;
16
+ readonly handler: CapabilityHandler;
17
+ /** Aborted the instant the providing fiber leaves ACTIVE. */
18
+ readonly teardownSignal: AbortSignal;
19
+ isActive(): boolean;
20
+ }
21
+
22
+ type Listener = () => void;
23
+
24
+ /**
25
+ * Scope visibility (spec §8.1): a publication is visible to the scope it was published in and
26
+ * every descendant, never to an ancestor or an unrelated scope. Cordis's `ctx.isolate()` only
27
+ * isolates one named service slot at a time and can't be driven by dynamic, per-mount capability
28
+ * ids, so visibility is computed here from the scope-ancestor chain the caller supplies.
29
+ */
30
+ export class CapabilityRegistry {
31
+ private readonly byScope = new Map<string, Set<Publication>>();
32
+ private readonly consumers = new Map<Publication, Set<() => Promise<void>>>();
33
+ private readonly listeners = new Set<Listener>();
34
+
35
+ publish(pub: Publication): () => void {
36
+ let set = this.byScope.get(pub.scopeId);
37
+ if (!set) this.byScope.set(pub.scopeId, (set = new Set()));
38
+ set.add(pub);
39
+ this.consumers.set(pub, new Set());
40
+ this.notify();
41
+ return () => {
42
+ set!.delete(pub);
43
+ this.consumers.delete(pub);
44
+ this.notify();
45
+ };
46
+ }
47
+
48
+ /** First eligible publication visible from `scopeChain` (self, then ancestors, root last). */
49
+ find(requirement: Requirement, scopeChain: readonly string[]): Publication | undefined {
50
+ for (const scopeId of scopeChain) {
51
+ const set = this.byScope.get(scopeId);
52
+ if (!set) continue;
53
+ for (const pub of set) if (pub.isActive() && isCompatible(requirement, pub.contract)) return pub;
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ /** Bind a dependent so it is asked to react (in registration order) before its provider tears down. */
59
+ bind(pub: Publication, onLost: () => Promise<void>): () => void {
60
+ const set = this.consumers.get(pub);
61
+ set?.add(onLost);
62
+ return () => void set?.delete(onLost);
63
+ }
64
+
65
+ /** Notify bound dependents of `pub`'s loss, awaiting each in turn (spec: dependents deactivate before the provider). */
66
+ async notifyLoss(pub: Publication): Promise<void> {
67
+ const set = this.consumers.get(pub);
68
+ if (!set) return;
69
+ for (const onLost of [...set]) await onLost();
70
+ }
71
+
72
+ onChange(listener: Listener): () => void {
73
+ this.listeners.add(listener);
74
+ return () => void this.listeners.delete(listener);
75
+ }
76
+
77
+ private notify(): void {
78
+ for (const listener of [...this.listeners]) listener();
79
+ }
80
+ }
package/src/scope.ts ADDED
@@ -0,0 +1,86 @@
1
+ // Cognate scopes map to Cordis contexts (ADR-0001): each Scope owns one Cordis `Context` obtained
2
+ // via `isolate()`, giving every scope a genuine, distinct Cordis object to mount component fibers
3
+ // onto. Capability *visibility* itself is not delegated to Cordis (see registry.ts) since Cordis's
4
+ // isolation is per-service-name, not per-subtree, and can't be driven by dynamic capability ids
5
+ // (spec §8.1 requires descendant-visible / sibling-invisible scoping for any capability id).
6
+ import type { Context } from "cordis";
7
+ import type { Principal, Scope, ScopeOptions } from "@godspeedai/cognate-kernel-api";
8
+ import { ScopeClosedError } from "@godspeedai/cognate-kernel-api";
9
+
10
+ let counter = 0;
11
+ const nextId = () => `scope-${++counter}`;
12
+
13
+ export interface Disposable {
14
+ dispose(reason: string): Promise<void>;
15
+ }
16
+
17
+ export class ScopeImpl implements Scope {
18
+ readonly id: string;
19
+ readonly parentId: string | undefined;
20
+ readonly tenant: string;
21
+ readonly principal: Principal;
22
+ readonly cordisCtx: Context;
23
+ private _closed = false;
24
+ private readonly children = new Set<ScopeImpl>();
25
+ private readonly mounts = new Set<Disposable>();
26
+
27
+ constructor(
28
+ cordisCtx: Context,
29
+ tenant: string,
30
+ principal: Principal,
31
+ parent: ScopeImpl | undefined,
32
+ id?: string,
33
+ ) {
34
+ this.cordisCtx = cordisCtx;
35
+ this.tenant = tenant;
36
+ this.principal = principal;
37
+ this.parentId = parent?.id;
38
+ this.id = id ?? nextId();
39
+ }
40
+
41
+ get closed(): boolean {
42
+ return this._closed;
43
+ }
44
+
45
+ /** Ancestor chain starting at this scope, root last — drives registry visibility (spec §8.1). */
46
+ ancestorIds(): readonly string[] {
47
+ const ids: string[] = [];
48
+ let current: ScopeImpl | undefined = this;
49
+ while (current) {
50
+ ids.push(current.id);
51
+ current = current.parent;
52
+ }
53
+ return ids;
54
+ }
55
+
56
+ private parent: ScopeImpl | undefined;
57
+
58
+ child(options?: ScopeOptions): Scope {
59
+ if (this._closed) throw new ScopeClosedError(`cannot create a child of closed scope ${this.id}`);
60
+ const id = options?.id ?? nextId();
61
+ const principal = options?.principal ?? this.principal;
62
+ const childCtx = this.cordisCtx.isolate(`cognate:scope:${id}`);
63
+ const scope = new ScopeImpl(childCtx, this.tenant, principal, this, id);
64
+ scope.parent = this;
65
+ this.children.add(scope);
66
+ return scope;
67
+ }
68
+
69
+ /** Track a component mounted directly in this scope so `close()` can dispose it (spec §8.1: close children first). */
70
+ track(mount: Disposable): void {
71
+ this.mounts.add(mount);
72
+ }
73
+
74
+ untrack(mount: Disposable): void {
75
+ this.mounts.delete(mount);
76
+ }
77
+
78
+ async close(reason: string): Promise<void> {
79
+ if (this._closed) return;
80
+ this._closed = true;
81
+ for (const child of [...this.children]) await child.close(reason);
82
+ this.children.clear();
83
+ for (const mount of [...this.mounts]) await mount.dispose(reason).catch(() => {});
84
+ this.mounts.clear();
85
+ }
86
+ }