@godspeedai/cognate-kernel-api 0.0.0-stage → 0.1.1

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,14 @@
1
- # Temporary Holding Version
1
+ # @godspeedai/cognate-kernel-api
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
+ Framework-owned kernel contract (spec §8, §8.5, §9.1, §32): `Kernel`, `Scope`, `Component`, `FiberContext`, `CapabilityLease`, `Effects`, `Policy`.
4
+ No engine type appears here; engines (e.g. `@godspeedai/cognate-kernel-cordis`) implement `KernelFactory`.
5
+
6
+ - `@godspeedai/cognate-kernel-api` — types, `isCompatible` (deterministic eligibility), policies (`denyAll` default), typed errors.
7
+ - `@godspeedai/cognate-kernel-api/conformance` — the executable contract. Every engine runs all six suites unchanged.
8
+
9
+ Semantics that the suites pin down:
10
+ - resolution never consults policy; every invocation does (default deny) and emits an `invocation` audit event;
11
+ - invocation never throws: it returns `InvocationResult` (`unavailable | denied | deadline_exceeded | cancelled | failed`);
12
+ - activation is all-or-nothing; failed setup disposes that attempt's effects in reverse order and publishes nothing;
13
+ - dispose is idempotent, runs every disposer in reverse order, and rejects once with `CleanupError`;
14
+ - a provider is visible in its scope and descendants only; closing a scope closes children first.
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@godspeedai/cognate-kernel-api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Framework-owned kernel contract: contexts, scopes, capabilities, components, fibers, effects. No engine types.",
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-api"
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
+ "./conformance": "./src/conformance/index.ts"
24
+ },
25
+ "peerDependencies": {}
26
+ }
package/src/compat.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { CapabilityContract, Requirement } from "./types.ts";
2
+
3
+ function parse(version: string): [number, number, number] {
4
+ const match = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(version);
5
+ if (!match) throw new TypeError(`Invalid capability version: ${version}`);
6
+ return [Number(match[1]), Number(match[2] ?? 0), Number(match[3] ?? 0)];
7
+ }
8
+
9
+ /**
10
+ * Deterministic eligibility of a contract for a requirement (spec §8.2): same identity,
11
+ * same major version with minor/patch >= required, and every required attribute equal.
12
+ */
13
+ export function isCompatible(requirement: Requirement, contract: CapabilityContract): boolean {
14
+ if (requirement.capability !== contract.id) return false;
15
+ if (requirement.version !== undefined) {
16
+ const [rMajor, rMinor, rPatch] = parse(requirement.version);
17
+ const [cMajor, cMinor, cPatch] = parse(contract.version);
18
+ if (rMajor !== cMajor) return false;
19
+ if (cMinor < rMinor || (cMinor === rMinor && cPatch < rPatch)) return false;
20
+ }
21
+ for (const [key, value] of Object.entries(requirement.attributes ?? {})) {
22
+ if (contract.attributes?.[key] !== value) return false;
23
+ }
24
+ return true;
25
+ }
@@ -0,0 +1,80 @@
1
+ import { allowCapabilities } from "../policy.ts";
2
+ import type {
3
+ CapabilityContract,
4
+ Component,
5
+ InvocationContext,
6
+ Kernel,
7
+ KernelEvent,
8
+ KernelFactory,
9
+ Policy,
10
+ Principal,
11
+ } from "../types.ts";
12
+
13
+ export const system: Principal = { id: "system", kind: "system" };
14
+ export const alice: Principal = { id: "alice", kind: "user" };
15
+
16
+ export function contract(id: string, version = "1.0.0", attributes?: CapabilityContract["attributes"]): CapabilityContract {
17
+ return attributes ? { id, version, attributes } : { id, version };
18
+ }
19
+
20
+ export function invocation(overrides: Partial<InvocationContext> = {}): InvocationContext {
21
+ return { actor: alice, correlationId: "corr-1", ...overrides };
22
+ }
23
+
24
+ /** A kernel plus a recorded event log, closed after each test by the suite. */
25
+ export interface Harness {
26
+ kernel: Kernel;
27
+ events: KernelEvent[];
28
+ /** Ordered record of side effects performed by test components (setup/teardown markers). */
29
+ log: string[];
30
+ }
31
+
32
+ export async function harness(factory: KernelFactory, policy: Policy = allowCapabilities("test-allow", ["*"])): Promise<Harness> {
33
+ const kernel = await factory({ tenant: "tenant-a", principal: system, policy });
34
+ const events: KernelEvent[] = [];
35
+ kernel.observe((event) => events.push(event));
36
+ return { kernel, events, log: [] };
37
+ }
38
+
39
+ /** Policy that allows every capability (tests that are not about authority). */
40
+ export const allowAll: Policy = {
41
+ authorize: () => ({ allow: true, policyId: "allow-all", reason: "test" }),
42
+ };
43
+
44
+ /** A pure provider: provides `id` and records setup/teardown in the log. */
45
+ export function provider(h: Harness, name: string, capability: CapabilityContract, handler: (input: unknown) => unknown = (input) => ({ from: name, input })): Component {
46
+ return {
47
+ id: name,
48
+ provides: [capability],
49
+ activate(fiber) {
50
+ h.log.push(`${name}:up`);
51
+ fiber.effects.register(() => void h.log.push(`${name}:down`), `${name}-marker`);
52
+ fiber.provide(capability, (input) => handler(input));
53
+ },
54
+ };
55
+ }
56
+
57
+ /** A consumer requiring the given capabilities under `dep0..n` names. */
58
+ export function consumer(h: Harness, name: string, requires: Component["requires"], provides: CapabilityContract[] = []): Component {
59
+ return {
60
+ id: name,
61
+ requires,
62
+ provides,
63
+ activate(fiber) {
64
+ h.log.push(`${name}:up`);
65
+ fiber.effects.register(() => void h.log.push(`${name}:down`), `${name}-marker`);
66
+ for (const capability of provides) fiber.provide(capability, () => name);
67
+ },
68
+ };
69
+ }
70
+
71
+ export const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
72
+
73
+ /** Wait until `predicate` holds or fail after `timeoutMs`. */
74
+ export async function until(predicate: () => boolean, timeoutMs = 2000, what = "condition"): Promise<void> {
75
+ const start = Date.now();
76
+ while (!predicate()) {
77
+ if (Date.now() - start > timeoutMs) throw new Error(`Timed out waiting for ${what}`);
78
+ await delay(2);
79
+ }
80
+ }
@@ -0,0 +1,3 @@
1
+ // Executable kernel contract. Engine adapters call every suite from their own tests.
2
+ export { contractSuite, lifecycleSuite, effectsSuite, dependenciesSuite, scopesSuite, authoritySuite } from "./suites.ts";
3
+ export * as fixtures from "./harness.ts";
@@ -0,0 +1,645 @@
1
+ // Kernel conformance kit. Every kernel engine adapter must pass every suite unchanged.
2
+ import { afterEach, describe, expect, test } from "bun:test";
3
+ import { CleanupError, PermanentActivationError, UndeclaredCapabilityError } from "../errors.ts";
4
+ import { isUnavailable } from "../index.ts";
5
+ import { denyAll } from "../policy.ts";
6
+ import type { CapabilityLease, ComponentHandle, KernelFactory, Policy } from "../types.ts";
7
+ import { alice, allowAll, consumer, contract, delay, type Harness, harness, invocation, provider, until } from "./harness.ts";
8
+
9
+ function lifecycleOf(factory: KernelFactory, policy: Policy = allowAll) {
10
+ const open: Harness[] = [];
11
+ afterEach(async () => {
12
+ for (const h of open.splice(0)) await h.kernel.shutdown("test end").catch(() => {});
13
+ });
14
+ return async (p: Policy = policy) => {
15
+ const h = await harness(factory, p);
16
+ open.push(h);
17
+ return h;
18
+ };
19
+ }
20
+
21
+ const lease = (value: unknown): CapabilityLease => {
22
+ if (isUnavailable(value as never)) throw new Error("expected a lease");
23
+ return value as CapabilityLease;
24
+ };
25
+
26
+ /** §8.5 operations and failure semantics. Gate: CG-KRN-001. */
27
+ export function contractSuite(name: string, factory: KernelFactory): void {
28
+ describe(`${name}: kernel contract (§8.5)`, () => {
29
+ const make = lifecycleOf(factory);
30
+
31
+ test("a component without requirements activates and exposes a fiber", async () => {
32
+ const h = await make();
33
+ const handle = await h.kernel.mount(provider(h, "a", contract("x.read")));
34
+ await handle.waitFor("ACTIVE");
35
+ expect(handle.state).toBe("ACTIVE");
36
+ expect(handle.fiberId).toBeString();
37
+ expect(h.log).toEqual(["a:up"]);
38
+ });
39
+
40
+ test("missing dependencies keep a component WAITING with no fiber", async () => {
41
+ const h = await make();
42
+ const handle = await h.kernel.mount(consumer(h, "b", { dep: { capability: "x.read" } }));
43
+ await delay(20);
44
+ expect(handle.state).toBe("WAITING");
45
+ expect(handle.fiberId).toBeUndefined();
46
+ expect(h.log).toEqual([]);
47
+ });
48
+
49
+ test("resolve returns Unavailable, then a lease once provided, without consulting policy", async () => {
50
+ let consulted = 0;
51
+ const h = await make({ authorize: () => (consulted++, { allow: true, policyId: "p", reason: "r" }) });
52
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.read" }))).toBe(true);
53
+ await (await h.kernel.mount(provider(h, "a", contract("x.read")))).waitFor("ACTIVE");
54
+ const resolved = lease(h.kernel.resolve({ capability: "x.read" }));
55
+ expect(resolved.valid).toBe(true);
56
+ expect(resolved.contract.id).toBe("x.read");
57
+ expect(consulted).toBe(0);
58
+ });
59
+
60
+ test("invoke passes input and full handler context and returns an ok result", async () => {
61
+ const h = await make();
62
+ let seen: Record<string, unknown> = {};
63
+ await (
64
+ await h.kernel.mount({
65
+ id: "a",
66
+ provides: [contract("x.read")],
67
+ activate(fiber) {
68
+ fiber.provide(contract("x.read"), (input, ctx) => {
69
+ seen = { actor: ctx.actor.id, correlationId: ctx.correlationId, providerId: ctx.providerId, tenant: ctx.tenant, allow: ctx.decision.allow, aborted: ctx.signal.aborted };
70
+ return { echo: input };
71
+ });
72
+ },
73
+ })
74
+ ).waitFor("ACTIVE");
75
+ const result = await lease(h.kernel.resolve({ capability: "x.read" })).invoke({ n: 1 }, invocation());
76
+ expect(result).toEqual({ ok: true, value: { echo: { n: 1 } } });
77
+ expect(seen).toMatchObject({ actor: "alice", correlationId: "corr-1", tenant: "tenant-a", allow: true, aborted: false });
78
+ expect(seen.providerId).toBeString();
79
+ });
80
+
81
+ test("a handler error is a typed failed result, not a thrown exception", async () => {
82
+ const h = await make();
83
+ await (await h.kernel.mount(provider(h, "a", contract("x.read"), () => { throw new Error("boom"); }))).waitFor("ACTIVE");
84
+ const result = await lease(h.kernel.resolve({ capability: "x.read" })).invoke(null, invocation());
85
+ expect(result.ok).toBe(false);
86
+ if (!result.ok) {
87
+ expect(result.failure.kind).toBe("failed");
88
+ }
89
+ });
90
+
91
+ test("a deadline yields deadline_exceeded and aborts the handler signal", async () => {
92
+ const h = await make();
93
+ let aborted = false;
94
+ await (
95
+ await h.kernel.mount({
96
+ id: "slow",
97
+ provides: [contract("x.slow")],
98
+ activate(fiber) {
99
+ fiber.provide(contract("x.slow"), async (_input, ctx) => {
100
+ await delay(200);
101
+ aborted = ctx.signal.aborted;
102
+ return "late";
103
+ });
104
+ },
105
+ })
106
+ ).waitFor("ACTIVE");
107
+ const result = await lease(h.kernel.resolve({ capability: "x.slow" })).invoke(null, invocation({ deadline: Date.now() + 20 }));
108
+ expect(result).toEqual({ ok: false, failure: { kind: "deadline_exceeded" } });
109
+ await until(() => aborted, 1000, "handler to observe abort");
110
+ });
111
+
112
+ test("caller cancellation yields cancelled", async () => {
113
+ const h = await make();
114
+ await (await h.kernel.mount(provider(h, "a", contract("x.wait"), () => delay(200)))).waitFor("ACTIVE");
115
+ const controller = new AbortController();
116
+ const pending = lease(h.kernel.resolve({ capability: "x.wait" })).invoke(null, invocation({ signal: controller.signal }));
117
+ controller.abort();
118
+ expect(await pending).toEqual({ ok: false, failure: { kind: "cancelled" } });
119
+ });
120
+
121
+ test("providing an undeclared capability fails activation and publishes nothing", async () => {
122
+ const h = await make();
123
+ const handle = await h.kernel.mount({
124
+ id: "liar",
125
+ provides: [contract("x.declared")],
126
+ retry: { maxAttempts: 1, baseDelayMs: 1, maxDelayMs: 1 },
127
+ activate(fiber) {
128
+ fiber.provide(contract("x.undeclared"), () => 1);
129
+ },
130
+ });
131
+ await handle.waitFor("FAILED");
132
+ expect(handle.lastError).toBeInstanceOf(UndeclaredCapabilityError);
133
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.undeclared" }))).toBe(true);
134
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.declared" }))).toBe(true);
135
+ });
136
+
137
+ test("dispose is idempotent and ends DISPOSED; the lease becomes unavailable", async () => {
138
+ const h = await make();
139
+ const handle = await h.kernel.mount(provider(h, "a", contract("x.read")));
140
+ await handle.waitFor("ACTIVE");
141
+ const held = lease(h.kernel.resolve({ capability: "x.read" }));
142
+ await handle.dispose("done");
143
+ await handle.dispose("again");
144
+ expect(handle.state).toBe("DISPOSED");
145
+ expect(h.log).toEqual(["a:up", "a:down"]);
146
+ expect(held.valid).toBe(false);
147
+ const result = await held.invoke(null, invocation());
148
+ expect(result.ok).toBe(false);
149
+ if (!result.ok) expect(result.failure.kind).toBe("unavailable");
150
+ });
151
+
152
+ test("an effect handle can be disposed early exactly once", async () => {
153
+ const h = await make();
154
+ let runs = 0;
155
+ let handleRef: { dispose(): Promise<void>; disposed: boolean } | undefined;
156
+ const handle = await h.kernel.mount({
157
+ id: "e",
158
+ activate(fiber) {
159
+ handleRef = fiber.effects.register(() => void runs++, "counter");
160
+ },
161
+ });
162
+ await handle.waitFor("ACTIVE");
163
+ await handleRef!.dispose();
164
+ await handleRef!.dispose();
165
+ expect(handleRef!.disposed).toBe(true);
166
+ await handle.dispose("done");
167
+ expect(runs).toBe(1);
168
+ });
169
+
170
+ test("closing a scope disposes its components", async () => {
171
+ const h = await make();
172
+ const scope = h.kernel.root.child({ id: "s1" });
173
+ const handle = await h.kernel.mount(provider(h, "a", contract("x.read")), scope);
174
+ await handle.waitFor("ACTIVE");
175
+ await scope.close("done");
176
+ expect(scope.closed).toBe(true);
177
+ expect(handle.state).toBe("DISPOSED");
178
+ expect(h.log).toEqual(["a:up", "a:down"]);
179
+ });
180
+
181
+ test("a component definition is independent of its occurrences (§8.3)", async () => {
182
+ const h1 = await make();
183
+ const h2 = await make();
184
+ const registry: string[] = [];
185
+ let activations = 0;
186
+ const definition: import("../types.ts").Component = {
187
+ id: "shared-definition",
188
+ provides: [contract("x.shared")],
189
+ activate(fiber) {
190
+ activations++;
191
+ registry.push(fiber.fiberId);
192
+ fiber.effects.register(() => void registry.splice(registry.indexOf(fiber.fiberId), 1), "entry");
193
+ fiber.provide(contract("x.shared"), () => fiber.fiberId);
194
+ },
195
+ };
196
+ const a = h1.kernel.root.child({ id: "a" });
197
+ const b = h1.kernel.root.child({ id: "b" });
198
+ const occurrences = [await h1.kernel.mount(definition, a), await h1.kernel.mount(definition, b), await h2.kernel.mount(definition)];
199
+ for (const o of occurrences) await o.waitFor("ACTIVE");
200
+ expect(activations).toBe(3);
201
+ expect(new Set(occurrences.map((o) => o.fiberId)).size).toBe(3);
202
+ await occurrences[0]!.dispose("one occurrence");
203
+ expect(occurrences.slice(1).map((o) => o.state)).toEqual(["ACTIVE", "ACTIVE"]);
204
+ expect(registry).toEqual([occurrences[1]!.fiberId!, occurrences[2]!.fiberId!]);
205
+ const fromB = lease(h1.kernel.resolve({ capability: "x.shared" }, b));
206
+ expect(await fromB.invoke(null, invocation())).toEqual({ ok: true, value: occurrences[1]!.fiberId });
207
+ expect(isUnavailable(h1.kernel.resolve({ capability: "x.shared" }, a))).toBe(true);
208
+ });
209
+
210
+ test("mounting into a closed scope is rejected", async () => {
211
+ const h = await make();
212
+ const scope = h.kernel.root.child();
213
+ await scope.close("done");
214
+ await expect(h.kernel.mount(provider(h, "a", contract("x.read")), scope)).rejects.toThrow();
215
+ });
216
+ });
217
+ }
218
+
219
+ /** §8.4 lifecycle: FAILED, bounded retry, permanent failure, activation races. Gate: CG-KRN-002. */
220
+ export function lifecycleSuite(name: string, factory: KernelFactory): void {
221
+ describe(`${name}: fiber lifecycle (§8.4)`, () => {
222
+ const make = lifecycleOf(factory);
223
+
224
+ test("a transient activation failure passes through FAILED and retries to ACTIVE", async () => {
225
+ const h = await make();
226
+ let attempts = 0;
227
+ const handle = await h.kernel.mount({
228
+ id: "flaky",
229
+ retry: { maxAttempts: 3, baseDelayMs: 5, maxDelayMs: 20 },
230
+ activate() {
231
+ attempts++;
232
+ if (attempts === 1) throw new Error("transient");
233
+ },
234
+ });
235
+ await handle.waitFor("ACTIVE");
236
+ expect(attempts).toBe(2);
237
+ const states = h.events.filter((e) => e.type === "fiber.state").map((e) => (e.type === "fiber.state" ? e.to : ""));
238
+ expect(states).toEqual(["ACTIVATING", "FAILED", "WAITING", "ACTIVATING", "ACTIVE"]);
239
+ });
240
+
241
+ test("a permanent failure stays FAILED until reset", async () => {
242
+ const h = await make();
243
+ let attempts = 0;
244
+ const handle = await h.kernel.mount({
245
+ id: "broken",
246
+ retry: { maxAttempts: 5, baseDelayMs: 1, maxDelayMs: 5 },
247
+ activate() {
248
+ attempts++;
249
+ if (attempts === 1) throw new PermanentActivationError("bad config");
250
+ },
251
+ });
252
+ await handle.waitFor("FAILED");
253
+ await delay(30);
254
+ expect(handle.state).toBe("FAILED");
255
+ expect(attempts).toBe(1);
256
+ expect(handle.lastError).toBeInstanceOf(PermanentActivationError);
257
+ await handle.reset();
258
+ await handle.waitFor("ACTIVE");
259
+ expect(attempts).toBe(2);
260
+ });
261
+
262
+ test("retries are bounded: exhausting maxAttempts leaves the component FAILED", async () => {
263
+ const h = await make();
264
+ let attempts = 0;
265
+ const handle = await h.kernel.mount({
266
+ id: "always",
267
+ retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 4 },
268
+ activate() {
269
+ attempts++;
270
+ throw new Error("nope");
271
+ },
272
+ });
273
+ await until(() => attempts === 3, 1000, "three attempts");
274
+ await handle.waitFor("FAILED");
275
+ await delay(30);
276
+ expect(attempts).toBe(3);
277
+ expect(handle.state).toBe("FAILED");
278
+ });
279
+
280
+ test("an activation that never settles fails by timeout instead of staying ACTIVATING", async () => {
281
+ const h = await make();
282
+ const handle = await h.kernel.mount({
283
+ id: "hang",
284
+ activationTimeoutMs: 30,
285
+ retry: { maxAttempts: 1, baseDelayMs: 1, maxDelayMs: 1 },
286
+ activate: () => new Promise<void>(() => {}),
287
+ });
288
+ await handle.waitFor("FAILED", 1000);
289
+ expect(handle.state).toBe("FAILED");
290
+ });
291
+
292
+ test("a timed-out activation still disposes the effects it registered before hanging", async () => {
293
+ const h = await make();
294
+ const handle = await h.kernel.mount({
295
+ id: "hang-after-effect",
296
+ activationTimeoutMs: 30,
297
+ retry: { maxAttempts: 1, baseDelayMs: 1, maxDelayMs: 1 },
298
+ async activate(fiber) {
299
+ fiber.effects.register(() => void h.log.push("partial:down"), "partial");
300
+ await new Promise<void>(() => {});
301
+ },
302
+ });
303
+ await handle.waitFor("FAILED", 1000);
304
+ await until(() => h.log.includes("partial:down"), 1000, "partial effect disposal after timeout");
305
+ expect(h.log).toEqual(["partial:down"]);
306
+ });
307
+
308
+ test("dispose during a pending activation wins, cleans partial effects, and publishes nothing", async () => {
309
+ const h = await make();
310
+ let release!: () => void;
311
+ const gate = new Promise<void>((resolve) => (release = resolve));
312
+ let aborted = false;
313
+ const handle = await h.kernel.mount({
314
+ id: "racy",
315
+ provides: [contract("x.racy")],
316
+ async activate(fiber) {
317
+ fiber.effects.register(() => void h.log.push("partial:down"), "partial");
318
+ await gate;
319
+ aborted = fiber.signal.aborted;
320
+ fiber.provide(contract("x.racy"), () => 1);
321
+ },
322
+ });
323
+ await handle.waitFor("ACTIVATING");
324
+ const disposing = handle.dispose("race");
325
+ release();
326
+ await disposing.catch(() => {});
327
+ await delay(10);
328
+ expect(handle.state).toBe("DISPOSED");
329
+ expect(aborted).toBe(true);
330
+ expect(h.log).toEqual(["partial:down"]);
331
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.racy" }))).toBe(true);
332
+ expect(h.events.some((e) => e.type === "fiber.state" && e.to === "ACTIVE")).toBe(false);
333
+ });
334
+
335
+ test("repeated dependency notifications never create duplicate active instances", async () => {
336
+ const h = await make();
337
+ let activations = 0;
338
+ const handle = await h.kernel.mount({
339
+ id: "dependent",
340
+ requires: { dep: { capability: "x.read" } },
341
+ activate() {
342
+ activations++;
343
+ },
344
+ });
345
+ await Promise.all([
346
+ h.kernel.mount(provider(h, "p1", contract("x.read"))),
347
+ h.kernel.mount(provider(h, "p2", contract("x.read"))),
348
+ h.kernel.mount(provider(h, "p3", contract("x.read"))),
349
+ ]);
350
+ await handle.waitFor("ACTIVE");
351
+ await delay(30);
352
+ expect(activations).toBe(1);
353
+ expect(handle.state).toBe("ACTIVE");
354
+ });
355
+ });
356
+ }
357
+
358
+ /** §9.1 / §31.1 reversible effects. Gate: CG-KRN-003. */
359
+ export function effectsSuite(name: string, factory: KernelFactory): void {
360
+ describe(`${name}: reversible effects (§9.1)`, () => {
361
+ const make = lifecycleOf(factory);
362
+
363
+ test("disposers run in reverse registration order", async () => {
364
+ const h = await make();
365
+ const handle = await h.kernel.mount({
366
+ id: "ordered",
367
+ activate(fiber) {
368
+ for (const label of ["listener", "tool", "renderer", "timer"]) fiber.effects.register(() => void h.log.push(label), label);
369
+ },
370
+ });
371
+ await handle.waitFor("ACTIVE");
372
+ await handle.dispose("done");
373
+ expect(h.log).toEqual(["timer", "renderer", "tool", "listener"]);
374
+ });
375
+
376
+ test("a failing disposer does not stop the others; errors are aggregated once", async () => {
377
+ const h = await make();
378
+ const handle = await h.kernel.mount({
379
+ id: "messy",
380
+ activate(fiber) {
381
+ fiber.effects.register(() => void h.log.push("first"), "first");
382
+ fiber.effects.register(() => { throw new Error("second failed"); }, "second");
383
+ fiber.effects.register(() => void h.log.push("third"), "third");
384
+ },
385
+ });
386
+ await handle.waitFor("ACTIVE");
387
+ const error = await handle.dispose("done").then(() => undefined, (e: unknown) => e);
388
+ expect(error).toBeInstanceOf(CleanupError);
389
+ expect((error as CleanupError).errors).toHaveLength(1);
390
+ expect(h.log).toEqual(["third", "first"]);
391
+ await handle.dispose("again");
392
+ expect(h.log).toEqual(["third", "first"]);
393
+ });
394
+
395
+ test("failed setup disposes every effect from that attempt in reverse order", async () => {
396
+ const h = await make();
397
+ const handle = await h.kernel.mount({
398
+ id: "half",
399
+ provides: [contract("x.half")],
400
+ retry: { maxAttempts: 1, baseDelayMs: 1, maxDelayMs: 1 },
401
+ activate(fiber) {
402
+ fiber.effects.register(() => void h.log.push("a"), "a");
403
+ fiber.effects.register(() => void h.log.push("b"), "b");
404
+ fiber.provide(contract("x.half"), () => 1);
405
+ throw new Error("setup failed");
406
+ },
407
+ });
408
+ await handle.waitFor("FAILED");
409
+ expect(h.log).toEqual(["b", "a"]);
410
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.half" }))).toBe(true);
411
+ expect(h.events.some((e) => e.type === "capability.provided")).toBe(false);
412
+ });
413
+
414
+ test("cleanup errors during dependency loss are observable as cleanup.failed", async () => {
415
+ const h = await make();
416
+ const p = await h.kernel.mount(provider(h, "p", contract("x.read")));
417
+ const c = await h.kernel.mount({
418
+ id: "c",
419
+ requires: { dep: { capability: "x.read" } },
420
+ activate(fiber) {
421
+ fiber.effects.register(() => { throw new Error("teardown bug"); }, "bad");
422
+ },
423
+ });
424
+ await c.waitFor("ACTIVE");
425
+ await p.dispose("gone");
426
+ await c.waitFor("WAITING");
427
+ expect(h.events.some((e) => e.type === "cleanup.failed" && e.componentId === "c")).toBe(true);
428
+ });
429
+
430
+ test("mount then unmount returns owned observable state to its initial value", async () => {
431
+ const h = await make();
432
+ const registry = new Set<string>();
433
+ const before = [...registry];
434
+ const handle = await h.kernel.mount({
435
+ id: "reg",
436
+ activate(fiber) {
437
+ for (const key of ["listener", "tool", "timer"]) {
438
+ registry.add(key);
439
+ fiber.effects.register(() => void registry.delete(key), key);
440
+ }
441
+ },
442
+ });
443
+ await handle.waitFor("ACTIVE");
444
+ expect(registry.size).toBe(3);
445
+ await handle.dispose("done");
446
+ expect([...registry]).toEqual(before);
447
+ });
448
+ });
449
+ }
450
+
451
+ /** §8.4 / §29.2 / §35 dependency closure and replacement. Gate: CG-KRN-004. */
452
+ export function dependenciesSuite(name: string, factory: KernelFactory): void {
453
+ describe(`${name}: dependency closure (§8.4, §35)`, () => {
454
+ const make = lifecycleOf(factory);
455
+
456
+ test("provide → activate, remove → deactivate, restore compatible → reactivate on the new provider", async () => {
457
+ const h = await make();
458
+ const b = await h.kernel.mount(consumer(h, "b", { dep: { capability: "customer.read", version: "1.0" } }));
459
+ expect(b.state).toBe("WAITING");
460
+ const a1 = await h.kernel.mount(provider(h, "a1", contract("customer.read", "1.2.0")));
461
+ await b.waitFor("ACTIVE");
462
+ const firstFiber = b.fiberId;
463
+ await a1.dispose("removed");
464
+ await b.waitFor("WAITING");
465
+ expect(b.fiberId).toBeUndefined();
466
+ const a2 = await h.kernel.mount(provider(h, "a2", contract("customer.read", "1.5.0")));
467
+ await b.waitFor("ACTIVE");
468
+ expect(b.fiberId).not.toBe(firstFiber);
469
+ expect(lease(h.kernel.resolve({ capability: "customer.read" })).providerId).toBeString();
470
+ expect(h.log).toEqual(["b:up".replace("b", "a1"), "b:up", "b:down", "a1:down", "a2:up", "b:up"]);
471
+ await a2.dispose("end");
472
+ });
473
+
474
+ test("incompatible versions and attributes are not eligible", async () => {
475
+ const h = await make();
476
+ const b = await h.kernel.mount(consumer(h, "b", { dep: { capability: "m.gen", version: "1.2", attributes: { structured_output: true } } }));
477
+ await h.kernel.mount(provider(h, "old", contract("m.gen", "1.1.0", { structured_output: true })));
478
+ await h.kernel.mount(provider(h, "next", contract("m.gen", "2.0.0", { structured_output: true })));
479
+ await h.kernel.mount(provider(h, "plain", contract("m.gen", "1.3.0")));
480
+ await delay(20);
481
+ expect(b.state).toBe("WAITING");
482
+ await h.kernel.mount(provider(h, "good", contract("m.gen", "1.3.0", { structured_output: true })));
483
+ await b.waitFor("ACTIVE");
484
+ });
485
+
486
+ test("loss propagates transitively through dependent chains", async () => {
487
+ const h = await make();
488
+ const a = await h.kernel.mount(provider(h, "a", contract("x.a")));
489
+ const b = await h.kernel.mount(consumer(h, "b", { dep: { capability: "x.a" } }, [contract("x.b")]));
490
+ const c = await h.kernel.mount(consumer(h, "c", { dep: { capability: "x.b" } }));
491
+ await c.waitFor("ACTIVE");
492
+ await a.dispose("gone");
493
+ await b.waitFor("WAITING");
494
+ await c.waitFor("WAITING");
495
+ expect(h.log.slice(-3)).toEqual(["c:down", "b:down", "a:down"]);
496
+ });
497
+
498
+ test("losing the bound provider while another compatible one remains rebinds to it", async () => {
499
+ const h = await make();
500
+ const p1 = await h.kernel.mount(provider(h, "p1", contract("x.read")));
501
+ await p1.waitFor("ACTIVE");
502
+ const p2 = await h.kernel.mount(provider(h, "p2", contract("x.read")));
503
+ await p2.waitFor("ACTIVE");
504
+ let bound: CapabilityLease | undefined;
505
+ const b = await h.kernel.mount({
506
+ id: "b",
507
+ requires: { dep: { capability: "x.read" } },
508
+ activate(fiber) {
509
+ bound = fiber.dependencies.dep;
510
+ },
511
+ });
512
+ await b.waitFor("ACTIVE");
513
+ const first = bound!;
514
+ const firstResult = await first.invoke(null, invocation());
515
+ const firstFrom = firstResult.ok ? (firstResult.value as { from: string }).from : "";
516
+ await (firstFrom === "p1" ? p1 : p2).dispose("gone");
517
+ await until(() => b.state === "ACTIVE" && bound !== first, 1000, "rebinding");
518
+ const second = await bound!.invoke(null, invocation());
519
+ expect(second.ok).toBe(true);
520
+ if (second.ok) expect((second.value as { from: string }).from).toBe(firstFrom === "p1" ? "p2" : "p1");
521
+ });
522
+ });
523
+ }
524
+
525
+ /** §8.1 / §32 scope isolation. Gate: CG-KRN-005. */
526
+ export function scopesSuite(name: string, factory: KernelFactory): void {
527
+ describe(`${name}: scope isolation (§8.1)`, () => {
528
+ const make = lifecycleOf(factory);
529
+
530
+ test("a child-provided capability is invisible to parent and siblings, visible to descendants", async () => {
531
+ const h = await make();
532
+ const child = h.kernel.root.child({ id: "child" });
533
+ const sibling = h.kernel.root.child({ id: "sibling" });
534
+ const grandchild = child.child({ id: "grandchild" });
535
+ await (await h.kernel.mount(provider(h, "p", contract("x.secret")), child)).waitFor("ACTIVE");
536
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.secret" }, h.kernel.root))).toBe(true);
537
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.secret" }, sibling))).toBe(true);
538
+ expect(isUnavailable(h.kernel.resolve({ capability: "x.secret" }, grandchild))).toBe(false);
539
+ const siblingConsumer = await h.kernel.mount(consumer(h, "s", { dep: { capability: "x.secret" } }), sibling);
540
+ await delay(20);
541
+ expect(siblingConsumer.state).toBe("WAITING");
542
+ });
543
+
544
+ test("parent-provided capabilities are visible in children", async () => {
545
+ const h = await make();
546
+ await (await h.kernel.mount(provider(h, "p", contract("x.shared")))).waitFor("ACTIVE");
547
+ const child = h.kernel.root.child();
548
+ const c = await h.kernel.mount(consumer(h, "c", { dep: { capability: "x.shared" } }), child);
549
+ await c.waitFor("ACTIVE");
550
+ });
551
+
552
+ test("a child may narrow its principal without changing the parent", async () => {
553
+ const h = await make();
554
+ const child = h.kernel.root.child({ principal: alice });
555
+ expect(child.principal.id).toBe("alice");
556
+ expect(h.kernel.root.principal.id).toBe("system");
557
+ expect(child.tenant).toBe(h.kernel.root.tenant);
558
+ expect(child.parentId).toBe(h.kernel.root.id);
559
+ });
560
+
561
+ test("closing a parent closes children before parent effects", async () => {
562
+ const h = await make();
563
+ const parent = h.kernel.root.child({ id: "parent" });
564
+ const child = parent.child({ id: "child" });
565
+ await (await h.kernel.mount(provider(h, "outer", contract("x.outer")), parent)).waitFor("ACTIVE");
566
+ await (await h.kernel.mount(provider(h, "inner", contract("x.inner")), child)).waitFor("ACTIVE");
567
+ await parent.close("done");
568
+ expect(child.closed).toBe(true);
569
+ expect(h.log).toEqual(["outer:up", "inner:up", "inner:down", "outer:down"]);
570
+ });
571
+
572
+ test("closing a child leaves the parent's components active", async () => {
573
+ const h = await make();
574
+ const outer = await h.kernel.mount(provider(h, "outer", contract("x.outer")));
575
+ await outer.waitFor("ACTIVE");
576
+ const child = h.kernel.root.child();
577
+ await (await h.kernel.mount(provider(h, "inner", contract("x.inner")), child)).waitFor("ACTIVE");
578
+ await child.close("done");
579
+ expect(outer.state).toBe("ACTIVE");
580
+ });
581
+ });
582
+ }
583
+
584
+ /** §8.5 / §32 authority. Gate: CG-KRN-006. */
585
+ export function authoritySuite(name: string, factory: KernelFactory): void {
586
+ describe(`${name}: authority (§32)`, () => {
587
+ const make = lifecycleOf(factory);
588
+
589
+ test("default-deny policy denies invocation without calling the handler", async () => {
590
+ const h = await make(denyAll);
591
+ let called = false;
592
+ await (await h.kernel.mount(provider(h, "p", contract("x.pay"), () => (called = true)))).waitFor("ACTIVE");
593
+ const result = await lease(h.kernel.resolve({ capability: "x.pay" })).invoke(null, invocation());
594
+ expect(result.ok).toBe(false);
595
+ if (!result.ok) {
596
+ expect(result.failure.kind).toBe("denied");
597
+ }
598
+ expect(called).toBe(false);
599
+ });
600
+
601
+ test("policy receives actor, tenant, scope, capability, and provider for each invocation", async () => {
602
+ const requests: unknown[] = [];
603
+ const h = await make({ authorize: (r) => (requests.push(r), { allow: true, policyId: "p", reason: "ok" }) });
604
+ const scope = h.kernel.root.child({ id: "ws" });
605
+ await (await h.kernel.mount(provider(h, "p", contract("x.read")), scope)).waitFor("ACTIVE");
606
+ const l = lease(h.kernel.resolve({ capability: "x.read" }, scope));
607
+ await l.invoke(null, invocation());
608
+ await l.invoke(null, invocation({ correlationId: "corr-2" }));
609
+ expect(requests).toHaveLength(2);
610
+ expect(requests[0]).toMatchObject({ operation: "invoke", actor: { id: "alice" }, tenant: "tenant-a", scopeId: "ws", capability: { id: "x.read" }, providerId: l.providerId, correlationId: "corr-1" });
611
+ });
612
+
613
+ test("the caller's tenant reaches both the policy and the handler", async () => {
614
+ const seen: string[] = [];
615
+ const h = await make({ authorize: (r) => (seen.push(`policy:${r.tenant}`), { allow: true, policyId: "p", reason: "ok" }) });
616
+ await (
617
+ await h.kernel.mount({ id: "t", provides: [contract("x.tenant")], activate: (f) => f.provide(contract("x.tenant"), (_i, ctx) => void seen.push(`handler:${ctx.tenant}`)) })
618
+ ).waitFor("ACTIVE");
619
+ const l = lease(h.kernel.resolve({ capability: "x.tenant" }));
620
+ await l.invoke(null, invocation({ tenant: "tenant-b" }));
621
+ await l.invoke(null, invocation());
622
+ expect(seen).toEqual(["policy:tenant-b", "handler:tenant-b", "policy:tenant-a", "handler:tenant-a"]);
623
+ });
624
+
625
+ test("every invocation emits an auditable decision event", async () => {
626
+ const h = await make(denyAll);
627
+ await (await h.kernel.mount(provider(h, "p", contract("x.pay")))).waitFor("ACTIVE");
628
+ await lease(h.kernel.resolve({ capability: "x.pay" })).invoke(null, invocation({ correlationId: "audit-1" }));
629
+ const audit = h.events.find((e) => e.type === "invocation");
630
+ expect(audit).toMatchObject({ type: "invocation", capability: "x.pay", correlationId: "audit-1", decision: { allow: false, policyId: "deny-all" } });
631
+ });
632
+
633
+ test("a revoked lease yields unavailable before any policy check", async () => {
634
+ let consulted = 0;
635
+ const h = await make({ authorize: () => (consulted++, { allow: true, policyId: "p", reason: "r" }) });
636
+ const handle: ComponentHandle = await h.kernel.mount(provider(h, "p", contract("x.read")));
637
+ await handle.waitFor("ACTIVE");
638
+ const l = lease(h.kernel.resolve({ capability: "x.read" }));
639
+ await handle.dispose("revoked");
640
+ const result = await l.invoke(null, invocation());
641
+ expect(result).toMatchObject({ ok: false, failure: { kind: "unavailable" } });
642
+ expect(consulted).toBe(0);
643
+ });
644
+ });
645
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,29 @@
1
+ /** Aggregated disposer failures from one teardown (spec §8.5, §31.1). */
2
+ export class CleanupError extends AggregateError {
3
+ override readonly name = "CleanupError";
4
+ constructor(
5
+ readonly componentId: string,
6
+ errors: readonly unknown[],
7
+ ) {
8
+ super(errors, `${errors.length} disposer(s) failed while tearing down ${componentId}`);
9
+ }
10
+ }
11
+
12
+ /** Throw from `activate` to mark a failure that retrying cannot fix; requires `reset()`. */
13
+ export class PermanentActivationError extends Error {
14
+ override readonly name = "PermanentActivationError";
15
+ }
16
+
17
+ /** Activation exceeded its timeout; treated as a transient failure. */
18
+ export class ActivationTimeoutError extends Error {
19
+ override readonly name = "ActivationTimeoutError";
20
+ }
21
+
22
+ /** A component tried to provide a capability it did not declare. */
23
+ export class UndeclaredCapabilityError extends Error {
24
+ override readonly name = "UndeclaredCapabilityError";
25
+ }
26
+
27
+ export class ScopeClosedError extends Error {
28
+ override readonly name = "ScopeClosedError";
29
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export type * from "./types.ts";
2
+ export { isCompatible } from "./compat.ts";
3
+ export { denyAll, rulePolicy, allowCapabilities, type Rule } from "./policy.ts";
4
+ export { CleanupError, PermanentActivationError, ActivationTimeoutError, UndeclaredCapabilityError, ScopeClosedError } from "./errors.ts";
5
+
6
+ /** Type guard distinguishing an unavailable resolution from a lease. */
7
+ export function isUnavailable(value: import("./types.ts").CapabilityLease | import("./types.ts").Unavailable): value is import("./types.ts").Unavailable {
8
+ return "unavailable" in value && value.unavailable === true;
9
+ }
package/src/policy.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { AuthorizationRequest, Policy, PolicyDecision } from "./types.ts";
2
+
3
+ /** Default policy: no authority (spec §32). */
4
+ export const denyAll: Policy = {
5
+ authorize: () => ({ allow: false, policyId: "deny-all", reason: "no policy grants this invocation" }),
6
+ };
7
+
8
+ export type Rule = (request: AuthorizationRequest) => PolicyDecision | undefined;
9
+
10
+ /** First matching rule decides; no match denies. */
11
+ export function rulePolicy(policyId: string, rules: readonly Rule[]): Policy {
12
+ return {
13
+ authorize(request) {
14
+ for (const rule of rules) {
15
+ const decision = rule(request);
16
+ if (decision) return decision;
17
+ }
18
+ return { allow: false, policyId, reason: "no rule matched" };
19
+ },
20
+ };
21
+ }
22
+
23
+ /** Allow invocations of the listed capability ids by any actor. Intended for tests and profiles that state it explicitly. */
24
+ export function allowCapabilities(policyId: string, capabilities: readonly string[]): Policy {
25
+ const allowed = new Set(capabilities);
26
+ return rulePolicy(policyId, [
27
+ (request) => (allowed.has(request.capability.id) ? { allow: true, policyId, reason: `capability ${request.capability.id} allowed` } : undefined),
28
+ ]);
29
+ }
package/src/types.ts ADDED
@@ -0,0 +1,233 @@
1
+ // Framework-owned kernel contract (spec §8, §8.5, §9.1, §32). No engine types may appear here.
2
+
3
+ /**
4
+ * Structurally identical to `@godspeedai/cognate-events`' `Json`, declared locally: `@godspeedai/cognate-events` itself
5
+ * depends on this package (for `SemanticRef`), so importing it here would cycle the package graph
6
+ * (spec §28). Any JSON value satisfies both structurally.
7
+ */
8
+ export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
9
+
10
+ /** Opaque reference to an existing semantic object (spec §7.1). Produced by semantic adapters. */
11
+ export interface SemanticRef {
12
+ readonly namespace: string;
13
+ /** DomainForge object identity (e.g. `namespace::name`). */
14
+ readonly id: string;
15
+ readonly kind?: string;
16
+ /** Model URI plus immutable source digest, or SemanticPack identity/version. */
17
+ readonly source: { readonly uri: string; readonly digest: string };
18
+ /** Cognate-owned adapter projection schema version. */
19
+ readonly projectionVersion: string;
20
+ }
21
+
22
+ export interface Principal {
23
+ readonly id: string;
24
+ readonly kind: "user" | "agent" | "service" | "system";
25
+ }
26
+
27
+ export type AttributeValue = string | number | boolean;
28
+ export type Attributes = Readonly<Record<string, AttributeValue>>;
29
+
30
+ /** A capability contract a provider publishes (spec §8.2). */
31
+ export interface CapabilityContract {
32
+ /** Stable capability identity, e.g. `customer.read`. */
33
+ readonly id: string;
34
+ /** Semantic version of the contract, `MAJOR.MINOR.PATCH`. */
35
+ readonly version: string;
36
+ readonly attributes?: Attributes;
37
+ readonly semanticRef?: SemanticRef;
38
+ }
39
+
40
+ /** What a consumer requires (deterministic eligibility input, spec §8.2). */
41
+ export interface Requirement {
42
+ readonly capability: string;
43
+ /** Required major version; any provider with the same major and >= minor is compatible. */
44
+ readonly version?: string;
45
+ /** Every listed attribute must equal the provider's attribute. */
46
+ readonly attributes?: Attributes;
47
+ }
48
+
49
+ export interface InvocationContext {
50
+ readonly actor: Principal;
51
+ /** The caller's tenant. Defaults to the kernel's tenant; policy and handlers see this value (spec §32). */
52
+ readonly tenant?: string;
53
+ readonly correlationId: string;
54
+ readonly causationId?: string;
55
+ readonly runId?: string;
56
+ /** Required for durable commands (spec §10). */
57
+ readonly idempotencyKey?: string;
58
+ /** Absolute deadline in epoch milliseconds. */
59
+ readonly deadline?: number;
60
+ readonly signal?: AbortSignal;
61
+ /**
62
+ * Durable progress channel into the invoking run, when there is one (e.g. streamed model token
63
+ * deltas). Absent, or a no-op, outside a run — e.g. `RuntimeService.invoke` from a client. Never
64
+ * affects step/emit/artifact replay accounting.
65
+ */
66
+ readonly progress?: (payload: Json) => Promise<void>;
67
+ }
68
+
69
+ export interface AuthorizationRequest {
70
+ readonly operation: "invoke";
71
+ readonly actor: Principal;
72
+ readonly tenant: string;
73
+ readonly scopeId: string;
74
+ readonly capability: CapabilityContract;
75
+ readonly providerId: string;
76
+ readonly correlationId: string;
77
+ }
78
+
79
+ export interface PolicyDecision {
80
+ readonly allow: boolean;
81
+ readonly policyId: string;
82
+ readonly reason: string;
83
+ }
84
+
85
+ /** Server-side policy consulted at every invocation. The default is deny (spec §32). */
86
+ export interface Policy {
87
+ authorize(request: AuthorizationRequest): PolicyDecision | Promise<PolicyDecision>;
88
+ }
89
+
90
+ /** Context passed to a capability handler. */
91
+ export interface HandlerContext extends InvocationContext {
92
+ readonly capability: CapabilityContract;
93
+ readonly providerId: string;
94
+ readonly decision: PolicyDecision;
95
+ readonly tenant: string;
96
+ readonly scopeId: string;
97
+ /** Aborted on caller cancellation, deadline expiry, or provider teardown. */
98
+ readonly signal: AbortSignal;
99
+ }
100
+
101
+ export type CapabilityHandler<I = unknown, O = unknown> = (input: I, context: HandlerContext) => O | Promise<O>;
102
+
103
+ export type InvocationFailure =
104
+ | { readonly kind: "unavailable"; readonly capability: string; readonly reason: string }
105
+ | { readonly kind: "denied"; readonly decision: PolicyDecision }
106
+ | { readonly kind: "deadline_exceeded" }
107
+ | { readonly kind: "cancelled" }
108
+ | { readonly kind: "failed"; readonly error: unknown };
109
+
110
+ export type InvocationResult<O> =
111
+ | { readonly ok: true; readonly value: O }
112
+ | { readonly ok: false; readonly failure: InvocationFailure };
113
+
114
+ /** A resolved, revocable reference to one active provider. Resolution grants no permission. */
115
+ export interface CapabilityLease<I = unknown, O = unknown> {
116
+ readonly contract: CapabilityContract;
117
+ readonly providerId: string;
118
+ /** False once the providing fiber leaves ACTIVE or its scope closes. */
119
+ readonly valid: boolean;
120
+ invoke(input: I, context: InvocationContext): Promise<InvocationResult<O>>;
121
+ }
122
+
123
+ export interface Unavailable {
124
+ readonly unavailable: true;
125
+ readonly requirement: Requirement;
126
+ readonly reason: string;
127
+ }
128
+
129
+ export interface EffectHandle {
130
+ readonly label: string;
131
+ readonly disposed: boolean;
132
+ /** Dispose this single effect early; idempotent. */
133
+ dispose(): Promise<void>;
134
+ }
135
+
136
+ export type Disposer = () => void | Promise<void>;
137
+
138
+ export interface Effects {
139
+ /** Register a reversible effect owned by the current fiber (spec §9.1). */
140
+ register(disposer: Disposer, label?: string): EffectHandle;
141
+ }
142
+
143
+ export type FiberState = "WAITING" | "ACTIVATING" | "ACTIVE" | "FAILED" | "DEACTIVATING" | "DISPOSED";
144
+
145
+ /** What an activation function receives: one live fiber (spec §8.4). */
146
+ export interface FiberContext {
147
+ readonly fiberId: string;
148
+ readonly componentId: string;
149
+ readonly scope: Scope;
150
+ /** Leases for every declared requirement, keyed by requirement name. */
151
+ readonly dependencies: Readonly<Record<string, CapabilityLease>>;
152
+ readonly effects: Effects;
153
+ /** Aborted when a concurrent disposal or dependency loss wins over this activation. */
154
+ readonly signal: AbortSignal;
155
+ /** Publish a declared capability; becomes visible only after activation succeeds. */
156
+ provide<I, O>(contract: CapabilityContract, handler: CapabilityHandler<I, O>): void;
157
+ }
158
+
159
+ export interface RetryPolicy {
160
+ /** Attempts before the component becomes permanently FAILED. */
161
+ readonly maxAttempts: number;
162
+ readonly baseDelayMs: number;
163
+ readonly maxDelayMs: number;
164
+ }
165
+
166
+ /** A declarative unit of composition, independent from any running occurrence (spec §8.3). */
167
+ export interface Component {
168
+ readonly id: string;
169
+ readonly requires?: Readonly<Record<string, Requirement>>;
170
+ readonly provides?: readonly CapabilityContract[];
171
+ readonly semanticRef?: SemanticRef;
172
+ readonly retry?: RetryPolicy;
173
+ /** Activation longer than this fails transiently instead of staying ACTIVATING (spec §8.4). Default 30000. */
174
+ readonly activationTimeoutMs?: number;
175
+ activate(fiber: FiberContext): void | Promise<void>;
176
+ }
177
+
178
+ export interface ComponentHandle {
179
+ readonly componentId: string;
180
+ readonly scopeId: string;
181
+ readonly state: FiberState;
182
+ /** The id of the current ACTIVE fiber, if any. */
183
+ readonly fiberId: string | undefined;
184
+ readonly lastError: unknown;
185
+ /** Resolve when the handle reaches a state (rejects on timeout). */
186
+ waitFor(state: FiberState, timeoutMs?: number): Promise<void>;
187
+ /** Permanently dispose; idempotent. Rejects once with CleanupError if any disposer failed. */
188
+ dispose(reason: string): Promise<void>;
189
+ /** Clear a permanent FAILED state and re-enter WAITING. */
190
+ reset(): Promise<void>;
191
+ }
192
+
193
+ export interface ScopeOptions {
194
+ readonly id?: string;
195
+ /** A child may narrow its principal; it never gains authority by inheritance. */
196
+ readonly principal?: Principal;
197
+ }
198
+
199
+ export interface Scope {
200
+ readonly id: string;
201
+ readonly parentId: string | undefined;
202
+ readonly tenant: string;
203
+ readonly principal: Principal;
204
+ readonly closed: boolean;
205
+ child(options?: ScopeOptions): Scope;
206
+ /** Close children first, then dispose this scope's components. */
207
+ close(reason: string): Promise<void>;
208
+ }
209
+
210
+ export type KernelEvent =
211
+ | { readonly type: "fiber.state"; readonly componentId: string; readonly scopeId: string; readonly fiberId: string | undefined; readonly from: FiberState; readonly to: FiberState; readonly error?: unknown }
212
+ | { readonly type: "capability.provided" | "capability.withdrawn"; readonly capability: CapabilityContract; readonly providerId: string; readonly scopeId: string }
213
+ | { readonly type: "cleanup.failed"; readonly componentId: string; readonly fiberId: string; readonly errors: readonly unknown[] }
214
+ | { readonly type: "invocation"; readonly capability: string; readonly providerId: string; readonly correlationId: string; readonly decision: PolicyDecision };
215
+
216
+ export interface KernelOptions {
217
+ readonly tenant: string;
218
+ readonly principal: Principal;
219
+ readonly policy: Policy;
220
+ /** Deterministic id source for tests; defaults to crypto.randomUUID. */
221
+ readonly ids?: () => string;
222
+ }
223
+
224
+ export interface Kernel {
225
+ readonly root: Scope;
226
+ mount(component: Component, scope?: Scope): Promise<ComponentHandle>;
227
+ resolve(requirement: Requirement, scope?: Scope): CapabilityLease | Unavailable;
228
+ observe(listener: (event: KernelEvent) => void): () => void;
229
+ /** Close the root scope and release the engine. */
230
+ shutdown(reason: string): Promise<void>;
231
+ }
232
+
233
+ export type KernelFactory = (options: KernelOptions) => Kernel | Promise<Kernel>;