@jini-ai/plugins 0.0.0-stage → 0.4.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +201 -0
  3. package/README.md +60 -2
  4. package/dist/glue/attachment-points/content-lifecycle.d.ts +10 -0
  5. package/dist/glue/attachment-points/content-lifecycle.js +5 -0
  6. package/dist/glue/attachment-points/events.d.ts +12 -0
  7. package/dist/glue/attachment-points/events.js +5 -0
  8. package/dist/glue/attachment-points/tool-registration.d.ts +23 -0
  9. package/dist/glue/attachment-points/tool-registration.js +43 -0
  10. package/dist/glue/capability-gate.d.ts +20 -0
  11. package/dist/glue/capability-gate.js +23 -0
  12. package/dist/glue/dispatch.d.ts +20 -0
  13. package/dist/glue/dispatch.js +9 -0
  14. package/dist/glue/index.d.ts +8 -0
  15. package/dist/glue/index.js +8 -0
  16. package/dist/glue/manifest.d.ts +43 -0
  17. package/dist/glue/manifest.js +106 -0
  18. package/dist/glue/ports.d.ts +60 -0
  19. package/dist/glue/ports.js +2 -0
  20. package/dist/host/activation.d.ts +118 -0
  21. package/dist/host/activation.js +104 -0
  22. package/dist/host/attach-loaded-plugin.d.ts +37 -0
  23. package/dist/host/attach-loaded-plugin.js +19 -0
  24. package/dist/host/capability-sdk.d.ts +74 -0
  25. package/dist/host/capability-sdk.js +58 -0
  26. package/dist/host/claim-conflicts.d.ts +101 -0
  27. package/dist/host/claim-conflicts.js +139 -0
  28. package/dist/host/declarative-enable.d.ts +43 -0
  29. package/dist/host/declarative-enable.js +73 -0
  30. package/dist/host/discovery-types.d.ts +52 -0
  31. package/dist/host/discovery-types.js +2 -0
  32. package/dist/host/errors.d.ts +20 -0
  33. package/dist/host/errors.js +22 -0
  34. package/dist/host/hook-registry.d.ts +113 -0
  35. package/dist/host/hook-registry.js +190 -0
  36. package/dist/host/index.d.ts +16 -0
  37. package/dist/host/index.js +16 -0
  38. package/dist/host/manifest.d.ts +149 -0
  39. package/dist/host/manifest.js +407 -0
  40. package/dist/host/node/discovery.d.ts +25 -0
  41. package/dist/host/node/discovery.js +217 -0
  42. package/dist/host/node/index.d.ts +7 -0
  43. package/dist/host/node/index.js +7 -0
  44. package/dist/host/node/install.d.ts +73 -0
  45. package/dist/host/node/install.js +301 -0
  46. package/dist/host/node/loader.d.ts +55 -0
  47. package/dist/host/node/loader.js +146 -0
  48. package/dist/host/node/module-snapshot.d.ts +25 -0
  49. package/dist/host/node/module-snapshot.js +53 -0
  50. package/dist/host/node/package-files.d.ts +52 -0
  51. package/dist/host/node/package-files.js +214 -0
  52. package/dist/host/plugin-claims.d.ts +113 -0
  53. package/dist/host/plugin-claims.js +134 -0
  54. package/dist/host/ports.d.ts +196 -0
  55. package/dist/host/ports.js +2 -0
  56. package/dist/host/quarantine.d.ts +19 -0
  57. package/dist/host/quarantine.js +28 -0
  58. package/dist/host/repo.memory.d.ts +27 -0
  59. package/dist/host/repo.memory.js +33 -0
  60. package/dist/host/sql/index.d.ts +4 -0
  61. package/dist/host/sql/index.js +4 -0
  62. package/dist/host/sql/repo.d.ts +38 -0
  63. package/dist/host/sql/repo.js +50 -0
  64. package/dist/host/sql/repo.rows.d.ts +28 -0
  65. package/dist/host/sql/repo.rows.js +28 -0
  66. package/dist/host/uninstall.d.ts +88 -0
  67. package/dist/host/uninstall.js +112 -0
  68. package/dist/host/worker/import-seam.d.ts +45 -0
  69. package/dist/host/worker/import-seam.js +52 -0
  70. package/dist/host/worker/index.d.ts +5 -0
  71. package/dist/host/worker/index.js +5 -0
  72. package/dist/host/worker/protocol.d.ts +62 -0
  73. package/dist/host/worker/protocol.js +31 -0
  74. package/dist/host/worker/run-call.d.ts +27 -0
  75. package/dist/host/worker/run-call.js +76 -0
  76. package/package.json +102 -3
@@ -0,0 +1,60 @@
1
+ export interface GlueFieldDecl {
2
+ readonly path: string;
3
+ readonly type: 'string' | 'integer' | 'number' | 'boolean';
4
+ }
5
+ export type GlueContentLifecycleFilter = (required: {
6
+ entry: Readonly<Record<string, unknown>>;
7
+ ctx: {
8
+ readonly moduleId: string;
9
+ readonly workspaceId: string;
10
+ };
11
+ }) => Readonly<Record<string, unknown>> | Promise<Readonly<Record<string, unknown>>>;
12
+ export interface GlueToolRegistration {
13
+ readonly toolId: string;
14
+ readonly handler: (required: Readonly<Record<string, unknown>>, optional?: Readonly<Record<string, unknown>>) => unknown;
15
+ }
16
+ export type GlueChangeSetCommand = unknown;
17
+ /** Host implementations own persistence, containment and dispatch. Mounting tools must be atomic. */
18
+ export interface GlueHostPort {
19
+ attachContentLifecycleFilter(required: {
20
+ moduleId: string;
21
+ filter: GlueContentLifecycleFilter;
22
+ declaredFields: readonly GlueFieldDecl[];
23
+ }): void;
24
+ registerTools(required: {
25
+ moduleId: string;
26
+ registrations: readonly GlueToolRegistration[];
27
+ }): void;
28
+ subscribeEvent(required: {
29
+ moduleId: string;
30
+ eventName: string;
31
+ handler: (required: {
32
+ payload: unknown;
33
+ }) => Promise<void> | void;
34
+ }): void;
35
+ registerAdminNav(required: {
36
+ moduleId: string;
37
+ payload: Readonly<Record<string, unknown>>;
38
+ }): void;
39
+ contributeRender(required: {
40
+ moduleId: string;
41
+ payload: Readonly<Record<string, unknown>>;
42
+ }): void;
43
+ registerHttpRoute(required: {
44
+ moduleId: string;
45
+ payload: Readonly<Record<string, unknown>>;
46
+ }): void;
47
+ runChangeSet(required: {
48
+ command: GlueChangeSetCommand;
49
+ }): Promise<unknown>;
50
+ snapshotBlob(required: {
51
+ content: Uint8Array | string;
52
+ }): Promise<{
53
+ readonly hash: string;
54
+ }>;
55
+ restoreBlob(required: {
56
+ hash: string;
57
+ }): Promise<Uint8Array>;
58
+ }
59
+ export type { GlueCallSite, GlueCapability } from './manifest.js';
60
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @file `setPluginEnabled()` / `getActivation()` — gateway-backed enable/disable feature functions
3
+ * (SPEC-005 REQ-07; BR-05; AC-02/AC-13; INV-03/INV-05).
4
+ *
5
+ * Purpose:
6
+ * Mirrors `src/features/presentation/presentation.ts`'s `setActiveTheme`/`getPresentationSettings`
7
+ * shape exactly (Module Map) — a plain feature function, validated and typed-error-throwing, that
8
+ * the ROUTE layer (`src/server/routes/admin/plugins/set-enabled.ts`, C-016) wraps in
9
+ * `executeCommand` (mirrors `admin/posts/update.ts`'s `executeCommand`-wrapped shape, per the
10
+ * ADR's API/Event Contract Summary) — NOT wrapped here. This function itself performs BR-05's
11
+ * three-step precondition evaluation and, on success, upserts the `PluginActivationRecord` and
12
+ * (on enable) invokes the injected load hook / (on disable) the injected unload hook — it does not
13
+ * call the gateway itself.
14
+ *
15
+ * `ext.{pluginId}` data is never touched by either transition (INV-03) — this module has no
16
+ * dependency on `posts.ext` at all, by construction (it only ever touches `plugin_activations`).
17
+ *
18
+ * Architectural role:
19
+ * TDD-certified implementation (implementation outline C-011/C-012). Signatures and JSDoc are
20
+ * design-frozen; `setPluginEnabled()` runs BR-05's three-step evaluation, upserts the activation
21
+ * row, then invokes the injected `onEnabled`/`onDisabled` side effect. If that side effect throws
22
+ * after the row was saved, `restoreOnSideEffectFailure()` compensates — restoring the prior record,
23
+ * or deleting it for a first-time enable/disable — best-effort, before rethrowing the original
24
+ * error unmasked. `getActivation()` is a thin read. Both satisfy
25
+ * `__tests__/integration/activation.integration.test.ts`.
26
+ */
27
+ import type { Clock as ClockPort, UUID } from "@jini-ai/core/primitives";
28
+ import type { PluginDiscoveryRecord } from "./discovery-types.js";
29
+ /** `plugin_activations` row (durable, behind the gateway) — state.spec.md §2. */
30
+ export interface PluginActivationRecord {
31
+ readonly pluginId: string;
32
+ readonly workspaceId: UUID;
33
+ /** The active (enabled) installed version — the "active pointer" (ADR-004). */
34
+ readonly version: string;
35
+ readonly enabled: boolean;
36
+ readonly updatedAt: string;
37
+ /** Present only while automatic quarantine is active. A normal enable/disable save omits these
38
+ * fields, which clears the durable marker and makes re-enable the operator recovery action. */
39
+ readonly quarantinedAt?: string;
40
+ readonly quarantineReason?: string;
41
+ readonly quarantineFailureCount?: number;
42
+ }
43
+ /** Persistence contract — shaped identically to `PresentationSettingsRepoPort` (rule-of-two, two
44
+ * adapters from day one: `repo.memory.ts` / `repo.sqlite.ts`). */
45
+ export interface PluginActivationRepoPort {
46
+ getActivation(required: {
47
+ workspaceId: UUID;
48
+ pluginId: string;
49
+ }, optional?: Record<string, never>): Promise<PluginActivationRecord | null>;
50
+ save(record: PluginActivationRecord, optional?: Record<string, never>): Promise<void>;
51
+ deleteActivation(required: {
52
+ workspaceId: UUID;
53
+ pluginId: string;
54
+ }, optional?: Record<string, never>): Promise<void>;
55
+ /** Every row across every workspace — used by discovery's `enabled` projection and by any
56
+ * future migration, mirrors `PresentationSettingsRepoPort.listAll`. */
57
+ listAll(required?: Record<string, never>, optional?: Record<string, never>): Promise<PluginActivationRecord[]>;
58
+ }
59
+ export declare class PluginNotFoundError extends Error {
60
+ }
61
+ export declare class PluginInvalidError extends Error {
62
+ }
63
+ export declare class PluginIncompatibleError extends Error {
64
+ }
65
+ export interface SetPluginEnabledDeps {
66
+ clock: ClockPort;
67
+ repo: PluginActivationRepoPort;
68
+ /** The current discovery snapshot — used to evaluate BR-05's "id present in discovery" and
69
+ * (when enabling) "status 'valid'" preconditions. Callers pass a fresh `discoverPlugins()`
70
+ * result; this function does not call discovery itself (keeps it a pure state-transition step
71
+ * over an already-known snapshot, easier to test deterministically). */
72
+ discovery: readonly PluginDiscoveryRecord[];
73
+ /** Invoked on a successful enable transition, after the activation row is saved — the actual
74
+ * `loadPlugin()`/hook-attach side effect. Optional so this function stays testable without a
75
+ * real loader; a real composition root always supplies one. */
76
+ onEnabled?: (pluginId: string) => Promise<void>;
77
+ /** Invoked on a successful disable transition — detaches the plugin's hooks
78
+ * (`hook-registry.ts`'s `detach`). Optional for the same testability reason as `onEnabled`. */
79
+ onDisabled?: (pluginId: string) => void;
80
+ }
81
+ export interface SetPluginEnabledInput {
82
+ readonly workspaceId: UUID;
83
+ readonly pluginId: string;
84
+ readonly enabled: boolean;
85
+ }
86
+ export interface SetPluginEnabledRequired {
87
+ deps: SetPluginEnabledDeps;
88
+ input: SetPluginEnabledInput;
89
+ }
90
+ export type SetPluginEnabledOptional = Record<string, never>;
91
+ /**
92
+ * BR-05's three-step evaluation: (1) id present in discovery ⇒ else `PluginNotFoundError`;
93
+ * (2) when enabling, discovered `status` is `"valid"` ⇒ else `PluginInvalidError`/
94
+ * `PluginIncompatibleError`; (3) upsert the activation row and invoke the load/unload side
95
+ * effect. Disable has no validity precondition (BR-05) — a plugin that became invalid after being
96
+ * enabled can always still be disabled.
97
+ *
98
+ * @throws {PluginNotFoundError} the plugin id is not present in the given discovery snapshot.
99
+ * @throws {PluginInvalidError} enabling a plugin whose discovered `status` is `"invalid"`.
100
+ * @throws {PluginIncompatibleError} enabling a plugin whose discovered `status` is `"incompatible"`.
101
+ */
102
+ export declare function setPluginEnabled(required: SetPluginEnabledRequired, _optional?: SetPluginEnabledOptional): Promise<{
103
+ activation: PluginActivationRecord;
104
+ }>;
105
+ export interface GetActivationRequired {
106
+ deps: {
107
+ repo: PluginActivationRepoPort;
108
+ };
109
+ input: {
110
+ workspaceId: UUID;
111
+ pluginId: string;
112
+ };
113
+ }
114
+ export type GetActivationOptional = Record<string, never>;
115
+ /** Reads current activation state for projection into `PLUGINS_LIST` (state.spec.md §5). `null`
116
+ * means "never enabled" (treated as disabled), not an error. */
117
+ export declare function getActivation(required: GetActivationRequired, _optional?: GetActivationOptional): Promise<PluginActivationRecord | null>;
118
+ //# sourceMappingURL=activation.d.ts.map
@@ -0,0 +1,104 @@
1
+ import { nowIso as clockNowIso } from "@jini-ai/core/primitives";
2
+ /**
3
+ * Restores the repo to its pre-transition state after a side-effect hook (`onEnabled`/
4
+ * `onDisabled`) throws: writes back the record that existed before this transition, or — for a
5
+ * first-time enable/disable where no prior record existed — deletes the row `setPluginEnabled`
6
+ * just created. Best-effort: a compensation failure must never mask the original side-effect
7
+ * error, so this swallows its own failure and lets the caller rethrow the original.
8
+ *
9
+ * @complexity O(1) — one repo write.
10
+ */
11
+ async function restoreOnSideEffectFailure(repo, existing, target) {
12
+ try {
13
+ if (existing) {
14
+ await repo.save(existing);
15
+ }
16
+ else {
17
+ await repo.deleteActivation(target);
18
+ }
19
+ }
20
+ catch {
21
+ // Compensation is best-effort; its failure must not mask the original side-effect error.
22
+ }
23
+ }
24
+ export class PluginNotFoundError extends Error {
25
+ }
26
+ export class PluginInvalidError extends Error {
27
+ }
28
+ export class PluginIncompatibleError extends Error {
29
+ }
30
+ /** BR-05 step 2: enabling requires a `"valid"` discovered status — `"incompatible"` gets its own
31
+ * typed error (a fixable-only-by-an-SDK-upgrade condition) distinct from any other non-`"valid"`
32
+ * status. Never called for a disable — BR-05 has no validity precondition on that direction. */
33
+ function assertPluginEnableAllowed(pluginId, status) {
34
+ if (status === "incompatible") {
35
+ throw new PluginIncompatibleError(`plugin '${pluginId}' is incompatible with this runtime's SDK version`);
36
+ }
37
+ if (status !== "valid") {
38
+ throw new PluginInvalidError(`plugin '${pluginId}' failed validation and cannot be enabled`);
39
+ }
40
+ }
41
+ /** The active-version pointer only ever advances on a genuine enable (REQ-02's "active pointer");
42
+ * disabling must not silently re-point it to whatever discovery currently reports as latest — it
43
+ * preserves whichever version was actually active (AC-13: disable's version is unchanged from the
44
+ * enable it inverts). */
45
+ function resolveActivationVersion(enabled, discoveredVersion, existingVersion) {
46
+ if (enabled)
47
+ return discoveredVersion;
48
+ return existingVersion ?? discoveredVersion;
49
+ }
50
+ /** Invokes the enable/disable side effect and, on failure, compensates and rethrows the ORIGINAL
51
+ * error unmasked — one `try`/`catch` instead of the identical pair an enable/disable if/else used
52
+ * to each carry, since both directions need exactly the same failure handling. */
53
+ async function applyActivationSideEffect(deps, input, existing, target) {
54
+ try {
55
+ if (input.enabled) {
56
+ await deps.onEnabled?.(input.pluginId);
57
+ }
58
+ else {
59
+ deps.onDisabled?.(input.pluginId);
60
+ }
61
+ }
62
+ catch (error) {
63
+ await restoreOnSideEffectFailure(deps.repo, existing, target);
64
+ throw error;
65
+ }
66
+ }
67
+ /**
68
+ * BR-05's three-step evaluation: (1) id present in discovery ⇒ else `PluginNotFoundError`;
69
+ * (2) when enabling, discovered `status` is `"valid"` ⇒ else `PluginInvalidError`/
70
+ * `PluginIncompatibleError`; (3) upsert the activation row and invoke the load/unload side
71
+ * effect. Disable has no validity precondition (BR-05) — a plugin that became invalid after being
72
+ * enabled can always still be disabled.
73
+ *
74
+ * @throws {PluginNotFoundError} the plugin id is not present in the given discovery snapshot.
75
+ * @throws {PluginInvalidError} enabling a plugin whose discovered `status` is `"invalid"`.
76
+ * @throws {PluginIncompatibleError} enabling a plugin whose discovered `status` is `"incompatible"`.
77
+ */
78
+ export async function setPluginEnabled(required, _optional = {}) {
79
+ const { deps, input } = required;
80
+ const discovered = deps.discovery.find((record) => record.id === input.pluginId);
81
+ if (!discovered) {
82
+ throw new PluginNotFoundError(`plugin '${input.pluginId}' was not found in the current discovery snapshot`);
83
+ }
84
+ if (input.enabled)
85
+ assertPluginEnableAllowed(input.pluginId, discovered.status);
86
+ const existing = await deps.repo.getActivation({ workspaceId: input.workspaceId, pluginId: input.pluginId });
87
+ const version = resolveActivationVersion(input.enabled, discovered.version, existing?.version);
88
+ const activation = {
89
+ pluginId: input.pluginId,
90
+ workspaceId: input.workspaceId,
91
+ version,
92
+ enabled: input.enabled,
93
+ updatedAt: clockNowIso({ clock: deps.clock }),
94
+ };
95
+ await deps.repo.save(activation);
96
+ await applyActivationSideEffect(deps, input, existing, { workspaceId: input.workspaceId, pluginId: input.pluginId });
97
+ return { activation };
98
+ }
99
+ /** Reads current activation state for projection into `PLUGINS_LIST` (state.spec.md §5). `null`
100
+ * means "never enabled" (treated as disabled), not an error. */
101
+ export async function getActivation(required, _optional = {}) {
102
+ return required.deps.repo.getActivation(required.input);
103
+ }
104
+ //# sourceMappingURL=activation.js.map
@@ -0,0 +1,37 @@
1
+ import type { BeforeSaveFilter } from "./ports.js";
2
+ import type { AttachmentSource, HookRegistry, HookRegistryFieldDecl } from "./hook-registry.js";
3
+ export interface AttachLoadedPluginRequired {
4
+ /** The plugin/glue-module id `hookRegistry.attach()` files this attachment under. */
5
+ readonly pluginId: string;
6
+ /** Who attached this filter — widened by ADR-057 Decision 3 to include `"glue"`, so Site Glue's
7
+ * content-lifecycle attachment point can call this function directly rather than forking it. */
8
+ readonly source: AttachmentSource;
9
+ /** The live registry this load's filter attaches to — one long-lived instance per process
10
+ * (`hook-registry.ts`'s own doc comment), supplied by the caller, never constructed here. */
11
+ readonly hookRegistry: HookRegistry;
12
+ /** The filter obtained from step (4) — i.e. whatever the caller's own `setup()` invocation (with
13
+ * a capability-scoped SDK gating `hooks.attach`) produced. This function does not invoke `setup()`
14
+ * itself: the SDK shape a `setup()` call receives differs by caller (plugin-runtime's own 3-member
15
+ * `PluginCapability` vocabulary for real plugins; Site Glue's 8-member `GlueCapability` vocabulary
16
+ * for glue modules), so building and gating that SDK stays the caller's responsibility. What is
17
+ * genuinely shared — and was genuinely dead before this extraction — is the attach step itself. */
18
+ readonly filter: BeforeSaveFilter;
19
+ readonly declaredFields: readonly HookRegistryFieldDecl[];
20
+ }
21
+ export type AttachLoadedPluginOptional = Record<string, never>;
22
+ /**
23
+ * The real (not stub) extraction of `loadPlugin()`'s dead step (5) — ADR-057 Decision 2.1. Attaches
24
+ * one already-obtained filter to the given hook registry under `(pluginId, source)`, widened beyond
25
+ * `loader.ts`'s original `"built-in" | "site"` scope to also accept `"glue"`. Before ADR-057, no
26
+ * production code ever called `hookRegistry.attach()` at all (verified by grep, see `hook-registry.ts`'s
27
+ * corrected header) — Site Glue's content-lifecycle attachment point is this function's first real
28
+ * caller; a future fix to `loadPlugin()`'s own dead steps (4)-(5) is expected to call this same
29
+ * function from its real activation path rather than re-implementing the attach step a second time.
30
+ *
31
+ * @throws Nothing of its own — propagates whatever `hookRegistry.attach()` itself throws (today,
32
+ * nothing; `attach()` is a plain `Map.set`).
33
+ * @complexity O(1) — a single delegated call, no iteration or I/O of its own.
34
+ * @overallScore 100/100
35
+ */
36
+ export declare function attachLoadedPlugin(required: AttachLoadedPluginRequired, _optional?: AttachLoadedPluginOptional): void;
37
+ //# sourceMappingURL=attach-loaded-plugin.d.ts.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The real (not stub) extraction of `loadPlugin()`'s dead step (5) — ADR-057 Decision 2.1. Attaches
3
+ * one already-obtained filter to the given hook registry under `(pluginId, source)`, widened beyond
4
+ * `loader.ts`'s original `"built-in" | "site"` scope to also accept `"glue"`. Before ADR-057, no
5
+ * production code ever called `hookRegistry.attach()` at all (verified by grep, see `hook-registry.ts`'s
6
+ * corrected header) — Site Glue's content-lifecycle attachment point is this function's first real
7
+ * caller; a future fix to `loadPlugin()`'s own dead steps (4)-(5) is expected to call this same
8
+ * function from its real activation path rather than re-implementing the attach step a second time.
9
+ *
10
+ * @throws Nothing of its own — propagates whatever `hookRegistry.attach()` itself throws (today,
11
+ * nothing; `attach()` is a plain `Map.set`).
12
+ * @complexity O(1) — a single delegated call, no iteration or I/O of its own.
13
+ * @overallScore 100/100
14
+ */
15
+ export function attachLoadedPlugin(required, _optional = {}) {
16
+ const { pluginId, source, hookRegistry, filter, declaredFields } = required;
17
+ hookRegistry.attach({ pluginId, source, filter, declaredFields });
18
+ }
19
+ //# sourceMappingURL=attach-loaded-plugin.js.map
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @file `buildCapabilityScopedSdk()` — builds the per-load `PluginSdk` handle (SPEC-005 REQ-04;
3
+ * CIC U-003, `ESCALATE_SECURITY`).
4
+ *
5
+ * Purpose:
6
+ * REQ-04: "the SDK object handed to the plugin exposes ONLY the granted surface. A plugin
7
+ * invoking a surface it did not declare fails at the SDK boundary (`CAPABILITY_DENIED`)."
8
+ *
9
+ * **CIC U-003 (Binding, ESCALATE_SECURITY):** a naive reading of REQ-04 could satisfy "exposes
10
+ * only the granted surface" by simply OMITTING ungranted properties (`sdk.content = granted ?
11
+ * {...} : undefined`). That is the wrong implementation — AC-05's contract requires a classified,
12
+ * catchable `CAPABILITY_DENIED` error, not a bare `TypeError` from calling a method on
13
+ * `undefined`. This function must therefore always expose a callable at every one of the three
14
+ * v1 capability positions (`content.read`, `content.extend`, `addFilter`) — granted capabilities
15
+ * get the real implementation (delegating to `coreDeps`), ungranted capabilities get a stub that
16
+ * SYNCHRONOUSLY throws a typed `CapabilityDeniedError` naming the missing capability. Any
17
+ * deviation from "always present, never absent" requires a recorded
18
+ * `[CIC_DEVIATION_APPROVED]` entry — see
19
+ * `reports/pipeline/005-plugin-system/critical-internal-constraints.md` U-003.
20
+ *
21
+ * Built fresh per plugin load (never a shared module-level singleton, ADR Decision item 2) — a
22
+ * new `PluginSdk` object is constructed for every `loadPlugin()` call, closing over that one
23
+ * plugin's own `pluginId` and granted capability set only.
24
+ *
25
+ * Architectural role:
26
+ * TDD-certified implementation (implementation outline C-009, CIC U-003). Signature and JSDoc are
27
+ * design-frozen; `buildCapabilityScopedSdk()` returns fresh per-plugin delegates for granted
28
+ * capabilities and present, typed-denial stubs for every ungranted surface.
29
+ */
30
+ import type { BeforeSaveFilter, ContentEntryDraft, PluginSdk, HookPoints, PluginSdkBinding } from "./ports.js";
31
+ import type { PluginCapability } from "./manifest.js";
32
+ /** Thrown synchronously when a plugin invokes an SDK surface it did not declare a capability for
33
+ * (REQ-04, INV-02). Classified so `hook-registry.ts` can catch it specifically and map the
34
+ * containing content operation to `PLUGIN_HOOK_FAILED` (BR-07), distinct from any other thrown
35
+ * error a plugin's own code might raise. */
36
+ export declare class CapabilityDeniedError extends Error {
37
+ readonly pluginId: string;
38
+ readonly capability: PluginCapability;
39
+ constructor(pluginId: string, capability: PluginCapability);
40
+ }
41
+ /** The three real, plugin-instance-scoped callbacks `capability-sdk.ts` wraps with capability
42
+ * gating. Supplied by the caller (the loader, at load time, closing over that specific plugin
43
+ * load's `hook-registry.ts` state) — this module never reaches into `hook-registry.ts` directly. */
44
+ export interface CapabilityScopedSdkCoreDeps {
45
+ /** Backing implementation for the granted `content.read()` surface. */
46
+ getCurrentEntry(): Readonly<ContentEntryDraft>;
47
+ /** Backing implementation for the granted `content.extend()` surface — writes into this
48
+ * plugin's own `ext.{pluginId}.{field}` namespace (validated by BR-06 at the caller). */
49
+ writeExtField(field: string, value: string | number | boolean): void;
50
+ /** Backing implementation for the granted `addFilter()` surface. */
51
+ attachFilter(hookName: string, filter: BeforeSaveFilter): void;
52
+ }
53
+ export interface BuildCapabilityScopedSdkRequired<H extends HookPoints = HookPoints> {
54
+ readonly pluginSdkBinding: PluginSdkBinding<H>;
55
+ readonly pluginId: string;
56
+ /** The manifest's declared capability set (already validated against the v1 vocabulary by
57
+ * `validateManifest()` — this function trusts its input is well-formed capability strings). */
58
+ readonly capabilities: readonly PluginCapability[];
59
+ readonly coreDeps: CapabilityScopedSdkCoreDeps;
60
+ }
61
+ export type BuildCapabilityScopedSdkOptional = Record<string, never>;
62
+ /**
63
+ * Builds one plugin's capability-scoped `PluginSdk` handle. Every one of the three v1 surfaces is
64
+ * always present on the returned object (CIC U-003) — granted surfaces delegate to `coreDeps`,
65
+ * ungranted surfaces are stubs that throw `CapabilityDeniedError` when invoked (never at build
66
+ * time — the stub itself is a normal, present function; only CALLING it throws).
67
+ *
68
+ * @throws Nothing at build time. The returned object's ungranted-surface stubs throw
69
+ * `CapabilityDeniedError` synchronously when invoked by the plugin.
70
+ * @complexity O(1) — three capability checks, trivially small and bounded regardless of
71
+ * plugin-declared array length (the vocabulary itself is fixed-size at exactly three).
72
+ */
73
+ export declare function buildCapabilityScopedSdk<H extends HookPoints>(required: BuildCapabilityScopedSdkRequired<H>, _optional?: BuildCapabilityScopedSdkOptional): PluginSdk<H>;
74
+ //# sourceMappingURL=capability-sdk.d.ts.map
@@ -0,0 +1,58 @@
1
+ /** Thrown synchronously when a plugin invokes an SDK surface it did not declare a capability for
2
+ * (REQ-04, INV-02). Classified so `hook-registry.ts` can catch it specifically and map the
3
+ * containing content operation to `PLUGIN_HOOK_FAILED` (BR-07), distinct from any other thrown
4
+ * error a plugin's own code might raise. */
5
+ export class CapabilityDeniedError extends Error {
6
+ pluginId;
7
+ capability;
8
+ constructor(pluginId, capability) {
9
+ super(`plugin '${pluginId}' invoked '${capability}' without declaring it in its manifest capabilities`);
10
+ this.name = "CapabilityDeniedError";
11
+ this.pluginId = pluginId;
12
+ this.capability = capability;
13
+ }
14
+ }
15
+ /**
16
+ * Builds one plugin's capability-scoped `PluginSdk` handle. Every one of the three v1 surfaces is
17
+ * always present on the returned object (CIC U-003) — granted surfaces delegate to `coreDeps`,
18
+ * ungranted surfaces are stubs that throw `CapabilityDeniedError` when invoked (never at build
19
+ * time — the stub itself is a normal, present function; only CALLING it throws).
20
+ *
21
+ * @throws Nothing at build time. The returned object's ungranted-surface stubs throw
22
+ * `CapabilityDeniedError` synchronously when invoked by the plugin.
23
+ * @complexity O(1) — three capability checks, trivially small and bounded regardless of
24
+ * plugin-declared array length (the vocabulary itself is fixed-size at exactly three).
25
+ */
26
+ export function buildCapabilityScopedSdk(required, _optional = {}) {
27
+ const { pluginId, capabilities, coreDeps } = required;
28
+ const granted = new Set(capabilities);
29
+ /**
30
+ * Wraps one capability-gated surface: returns `real` when `capability` is granted, otherwise a
31
+ * stub that synchronously throws `CapabilityDeniedError` when invoked. CIC U-003's binding
32
+ * property — every surface is always a present, callable function, never an absent property.
33
+ */
34
+ function gate(capability, real) {
35
+ if (granted.has(capability)) {
36
+ return real;
37
+ }
38
+ return ((..._args) => {
39
+ throw new CapabilityDeniedError(pluginId, capability);
40
+ });
41
+ }
42
+ const sdk = {
43
+ content: {
44
+ read: gate("content.read", () => coreDeps.getCurrentEntry()),
45
+ extend: gate("content.extend", (field, value) => coreDeps.writeExtField(field, value)),
46
+ },
47
+ addFilter: gate("hooks.attach", (hookName, filter) => coreDeps.attachFilter(hookName, filter)),
48
+ // `ActionHookName`/`ContributionHookName` (@tovu/sdk hooks.ts) have no catalog members yet
49
+ // (hooks v2 plan §3.3 Waves 1/2 land in a later slice), so no name type-checks as an argument
50
+ // to either surface today -- both are present-but-unreachable, same "always present" contract
51
+ // as `addFilter`, gated on the same `hooks.attach` capability. No `coreDeps` backing exists
52
+ // yet because there is nothing real to delegate to until a hook is cataloged.
53
+ addAction: gate("hooks.attach", (..._args) => undefined),
54
+ addContribution: gate("hooks.attach", (..._args) => undefined),
55
+ };
56
+ return required.pluginSdkBinding.buildSdk({ sdk });
57
+ }
58
+ //# sourceMappingURL=capability-sdk.js.map
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @file `resolveClaimConflicts()` — product-neutral detection of two extensions claiming the same
3
+ * named thing (a route, a tool name, a table, a setting id, a widget id, a permission id, an
4
+ * exclusive hook).
5
+ *
6
+ * JINI CANDIDATE: nothing in this file knows about Tovu, its manifest, its plugins or its storage —
7
+ * it takes owners and their claims as plain data and returns who keeps what. It belongs in
8
+ * `@jini-ai/plugins` (or `@jini-ai/core`) beside the glue capability gates. Not moved yet because
9
+ * Tovu's deploy build resolves `@jini-ai/*` from the published registry, so a Jini-side copy would be
10
+ * unreachable from production until the owner publishes; moving it is a file move plus one import.
11
+ *
12
+ * ## The rules (also in `ADS-memory/specs/005-plugin-system/conflicts.spec.md`)
13
+ *
14
+ * 1. Owners are processed in PRECEDENCE order — the caller's order, first wins. Core goes first;
15
+ * after that the caller decides (Tovu: earliest-enabled first, so the NEWER plugin is the one
16
+ * refused — the plugin that was already working keeps working).
17
+ * 2. A claim is `exclusive` (only one owner may hold it) or `shared` (any number of owners may hold
18
+ * it together — a filter pipeline hook where every filter runs in a fixed order is the example).
19
+ * An exclusive claim conflicts with ANY other owner's claim on the same slot, shared or not; two
20
+ * shared claims never conflict.
21
+ * 3. A REFUSED owner contributes nothing: if A holds `x`, B is refused for `x`, and C claims B's
22
+ * other key `y`, C is accepted. Refusal is all-or-nothing per owner — half a plugin is not a
23
+ * state anyone can reason about, so an owner with any conflict keeps none of its claims.
24
+ * 4. One owner claiming the same slot twice is not a conflict (a manifest repeating itself is a
25
+ * validation concern, not a collision between two parties).
26
+ * 5. Keys are compared after the kind's normalization (see {@link DEFAULT_CLAIM_KIND_RULES}):
27
+ * identifiers are case-insensitive; a route is `METHOD /path` with parameter names erased
28
+ * (`/a/:id` and `/a/{slug}` are the same route) and `*`/`ANY` meaning every method.
29
+ * 6. A key ending in `*` is a PREFIX claim: it holds every key that starts with what precedes the
30
+ * `*`. Core uses this to reserve whole namespaces (`/api/*`, `admin.*`) without listing every
31
+ * name in them; an exact claim inside a held prefix conflicts, and so does a prefix claim that
32
+ * covers a held exact key or overlaps a held prefix.
33
+ *
34
+ * Pure: no I/O, no clock, no mutation of its input.
35
+ */
36
+ /** Whether a claim may be held by several owners at once (see rule 2). */
37
+ export type ClaimMode = "exclusive" | "shared";
38
+ /** One named thing an owner says it provides. `kind` is free text so a host can add kinds without
39
+ * touching this module; {@link DEFAULT_CLAIM_KIND_RULES} only supplies normalization for the
40
+ * common ones. */
41
+ export interface ExtensionClaim {
42
+ readonly kind: string;
43
+ readonly key: string;
44
+ readonly mode: ClaimMode;
45
+ }
46
+ /** One party taking part in conflict resolution — core, a plugin, a module. */
47
+ export interface ClaimOwner {
48
+ readonly id: string;
49
+ readonly claims: readonly ExtensionClaim[];
50
+ }
51
+ /** One refused claim: `ownerId` wanted `kind`/`key`, `heldBy` already had it (`heldKey` is the
52
+ * holder's own spelling — it differs from `key` when a prefix or a normalized route matched). */
53
+ export interface ClaimConflict {
54
+ readonly ownerId: string;
55
+ readonly kind: string;
56
+ readonly key: string;
57
+ readonly heldBy: string;
58
+ readonly heldKey: string;
59
+ }
60
+ /** How one kind's keys are compared: `normalize` turns a key into the slot strings it occupies.
61
+ * Most kinds occupy one slot; a route claimed for every method occupies one per method. */
62
+ export interface ClaimKindRule {
63
+ readonly normalize: (key: string) => readonly string[];
64
+ }
65
+ export interface ResolveClaimConflictsRequired {
66
+ /** Every owner, in precedence order — the first owner to claim a slot keeps it. */
67
+ readonly owners: readonly ClaimOwner[];
68
+ }
69
+ export interface ResolveClaimConflictsOptional {
70
+ /** Per-kind normalization; a kind with no rule uses {@link normalizeIdentifier}. Defaults to
71
+ * {@link DEFAULT_CLAIM_KIND_RULES}. */
72
+ readonly rules?: Readonly<Record<string, ClaimKindRule>>;
73
+ }
74
+ export interface ResolveClaimConflictsResult {
75
+ /** Owner ids that keep all their claims, in precedence order. */
76
+ readonly accepted: readonly string[];
77
+ /** Owner id -> every conflict that refused it (at least one per entry). */
78
+ readonly refused: ReadonlyMap<string, readonly ClaimConflict[]>;
79
+ }
80
+ /** Trimmed, lower-cased — tool names, table names, setting/widget/permission ids. SQLite table
81
+ * names are case-insensitive and the rest are human-typed ids where `Foo` and `foo` side by side
82
+ * would only ever be a mistake, so case never distinguishes two claims. */
83
+ export declare function normalizeIdentifier({ key }: {
84
+ key: string;
85
+ }, _optional?: Record<string, never>): readonly string[];
86
+ /** `"GET /a/:id"` -> `["GET /a/:"]`; `"/a"` or `"* /a"` or `"ANY /a"` -> one slot per method. */
87
+ export declare function normalizeRoute({ key }: {
88
+ key: string;
89
+ }, _optional?: Record<string, never>): readonly string[];
90
+ /** The kinds Tovu (and most hosts) need. A host adds or overrides kinds by spreading this. */
91
+ export declare const DEFAULT_CLAIM_KIND_RULES: Readonly<Record<string, ClaimKindRule>>;
92
+ /**
93
+ * Decides, owner by owner in precedence order, who keeps their claims (see this file's header for
94
+ * the six rules).
95
+ *
96
+ * @complexity O(S²) in the total slot count across all owners — a site has tens of plugins with a
97
+ * handful of claims each, so a linear scan of held slots beats an index that prefix claims would
98
+ * make complicated.
99
+ */
100
+ export declare function resolveClaimConflicts(required: ResolveClaimConflictsRequired, optional?: ResolveClaimConflictsOptional): ResolveClaimConflictsResult;
101
+ //# sourceMappingURL=claim-conflicts.d.ts.map