@jini-ai/plugins 0.0.0-stage → 0.4.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.
Files changed (84) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +201 -0
  3. package/README.md +60 -2
  4. package/dist/glue/attachment-points/content-lifecycle.d.ts +52 -0
  5. package/dist/glue/attachment-points/content-lifecycle.js +15 -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 +73 -0
  11. package/dist/glue/capability-gate.js +41 -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 +94 -0
  26. package/dist/host/claim-conflicts.d.ts +101 -0
  27. package/dist/host/claim-conflicts.js +139 -0
  28. package/dist/host/contributions.d.ts +129 -0
  29. package/dist/host/contributions.js +167 -0
  30. package/dist/host/declarative-enable.d.ts +43 -0
  31. package/dist/host/declarative-enable.js +73 -0
  32. package/dist/host/discovery-types.d.ts +55 -0
  33. package/dist/host/discovery-types.js +2 -0
  34. package/dist/host/errors.d.ts +20 -0
  35. package/dist/host/errors.js +22 -0
  36. package/dist/host/hook-registry.d.ts +113 -0
  37. package/dist/host/hook-registry.js +190 -0
  38. package/dist/host/index.d.ts +19 -0
  39. package/dist/host/index.js +19 -0
  40. package/dist/host/manifest.d.ts +159 -0
  41. package/dist/host/manifest.js +417 -0
  42. package/dist/host/node/discovery.d.ts +32 -0
  43. package/dist/host/node/discovery.js +241 -0
  44. package/dist/host/node/index.d.ts +8 -0
  45. package/dist/host/node/index.js +8 -0
  46. package/dist/host/node/install.d.ts +118 -0
  47. package/dist/host/node/install.js +431 -0
  48. package/dist/host/node/loader.d.ts +55 -0
  49. package/dist/host/node/loader.js +146 -0
  50. package/dist/host/node/module-snapshot.d.ts +25 -0
  51. package/dist/host/node/module-snapshot.js +53 -0
  52. package/dist/host/node/package-files.d.ts +52 -0
  53. package/dist/host/node/package-files.js +214 -0
  54. package/dist/host/node/source-drafts.d.ts +98 -0
  55. package/dist/host/node/source-drafts.js +323 -0
  56. package/dist/host/plugin-claims.d.ts +75 -0
  57. package/dist/host/plugin-claims.js +182 -0
  58. package/dist/host/ports.d.ts +208 -0
  59. package/dist/host/ports.js +2 -0
  60. package/dist/host/quarantine.d.ts +19 -0
  61. package/dist/host/quarantine.js +28 -0
  62. package/dist/host/repo.memory.d.ts +27 -0
  63. package/dist/host/repo.memory.js +33 -0
  64. package/dist/host/source-policy.d.ts +18 -0
  65. package/dist/host/source-policy.js +13 -0
  66. package/dist/host/sql/index.d.ts +4 -0
  67. package/dist/host/sql/index.js +4 -0
  68. package/dist/host/sql/repo.d.ts +38 -0
  69. package/dist/host/sql/repo.js +50 -0
  70. package/dist/host/sql/repo.rows.d.ts +28 -0
  71. package/dist/host/sql/repo.rows.js +28 -0
  72. package/dist/host/tool-contributions.d.ts +26 -0
  73. package/dist/host/tool-contributions.js +42 -0
  74. package/dist/host/uninstall.d.ts +88 -0
  75. package/dist/host/uninstall.js +112 -0
  76. package/dist/host/worker/import-seam.d.ts +45 -0
  77. package/dist/host/worker/import-seam.js +52 -0
  78. package/dist/host/worker/index.d.ts +5 -0
  79. package/dist/host/worker/index.js +5 -0
  80. package/dist/host/worker/protocol.d.ts +62 -0
  81. package/dist/host/worker/protocol.js +31 -0
  82. package/dist/host/worker/run-call.d.ts +27 -0
  83. package/dist/host/worker/run-call.js +76 -0
  84. package/package.json +107 -3
@@ -0,0 +1,55 @@
1
+ import type { PluginManifest, PluginValidationError } from "./manifest.js";
2
+ /** A built-in plugin's in-code manifest-equivalent (ADR Decision item 4) — no tarball, no
3
+ * integrity file (compiled-in code is definitionally not tampered), but still validated through
4
+ * the same `validateManifest()` path as a site-installed plugin. */
5
+ export interface BuiltInPluginSource {
6
+ readonly manifest: PluginManifest;
7
+ }
8
+ /** In-memory, rebuilt each discovery pass — NOT persisted (state.spec.md §2). Feeds `PLUGINS_LIST`
9
+ * once activation state is projected onto it by the caller (the HTTP route layer, C-016/C-017 —
10
+ * discovery itself does not know about `plugin_activations`). */
11
+ export interface PluginDiscoveryRecord {
12
+ readonly warnings?: readonly string[];
13
+ readonly id: string;
14
+ readonly name: string;
15
+ readonly version: string;
16
+ readonly source: "built-in" | "site";
17
+ /** (1.1.2, REQ-10/REQ-18) The plugin's trust tier, projected verbatim from the already-required
18
+ * `PluginManifest.tier` (REQ-01/ADR-024 §1) — mirrors how `source` already passes through
19
+ * unchanged. Optional on this stub type only so pre-existing fixtures in unrelated test files
20
+ * (`activation.integration.test.ts`, `loader.integration.test.ts`) that construct
21
+ * `PluginDiscoveryRecord` literals for concerns unrelated to REQ-10/`PLUGINS_LIST` are not forced
22
+ * to retrofit it; the real `discoverPlugins()` implementation must always populate it (a
23
+ * discovered plugin's manifest always has a validated `tier` by the time a record exists),
24
+ * enforced behaviorally by the dedicated REQ-10 pass-through tests in `plugins-dto.unit.test.ts`
25
+ * / `plugins-http.integration.test.ts`, not by widening this field to non-optional everywhere. */
26
+ readonly tier?: "tier-1" | "tier-2" | "tier-3";
27
+ readonly status: "valid" | "invalid" | "incompatible";
28
+ readonly errors: readonly PluginValidationError[];
29
+ /**
30
+ * (Milestone 1b, 2026-08-20) The already-parsed, already-`validateManifest()`-checked manifest
31
+ * this record was built from — present after manifest validation (`undefined` otherwise:
32
+ * an invalid/incompatible candidate's raw JSON may not conform to `PluginManifest`'s shape at
33
+ * all, so this field never claims a validated type for a manifest that failed validation).
34
+ * A later whole-set publisher collision omits the losing manifest and marks its record invalid.
35
+ * The incumbent keeps its reservation; the rejected claim must not reappear in host lookup.
36
+ *
37
+ * Exists so a composition root's enable path (`server/plugin-runtime.ts`'s `onPluginEnabled()`)
38
+ * can hand `loadPlugin()` the SAME manifest object this discovery pass already parsed, instead of
39
+ * re-reading `tovu.plugin.json` a second time. This matters beyond avoiding duplicate I/O: every
40
+ * real caller of `onPluginEnabled` (`activation.ts`'s `setPluginEnabled`, BR-05 step 1) already
41
+ * calls `discoverPlugins()` fresh, in the SAME request, immediately before invoking it (see
42
+ * `routes/admin/plugins/set-enabled.ts`) — so reusing that record's manifest is not a staleness
43
+ * risk, it is the one-and-only read for this attempt. A second, independent load-time re-read
44
+ * would instead open a narrow TOCTOU window: an attacker who can write to `installDir` between
45
+ * the discovery read and a second load-time read could swap in a self-consistent tampered
46
+ * manifest+entry pair that the discovery pass never actually validated. Reusing this field closes
47
+ * that window by construction — there is only one read to race against, not two.
48
+ *
49
+ * Built-in records also carry it (trivially, from `BuiltInPluginSource.manifest`) for type
50
+ * uniformity, but `onPluginEnabled`'s built-in branch does not need it — it already has the
51
+ * composition root's own static `PluginRuntimeSource.manifest`, unchanged from before this slice.
52
+ */
53
+ readonly manifest?: PluginManifest | undefined;
54
+ }
55
+ //# sourceMappingURL=discovery-types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=discovery-types.js.map
@@ -0,0 +1,20 @@
1
+ /** Host adapters must re-export this shared class to preserve instanceof identity; product
2
+ * refusal copy stays host-owned. */
3
+ /**
4
+ * @file Shared plugin save-hook refusal. Callers handling saves and the plugin runtime import
5
+ * this neutral error contract to avoid a dependency cycle or making the save domain plugin-aware.
6
+ */
7
+ /** Thrown (and caught by the caller, mapped to 500 `PLUGIN_HOOK_FAILED`) when a filter throws,
8
+ * triggers `CapabilityDeniedError`, or returns an invalid `ext` write (BR-07/EC-10). */
9
+ export declare class PluginHookFailedError extends Error {
10
+ readonly pluginId: string;
11
+ /** The item a multi-item apply was writing when the hook refused (e.g. `post:<id>`), set only by
12
+ * an apply that is NOT all-or-nothing (`publish-content/apply-loop.ts`), so items applied before
13
+ * it stay saved. `null` for a single save, where the refusal means nothing was saved. */
14
+ readonly refusedItemRef: string | null;
15
+ constructor(pluginId: string, message: string, options?: {
16
+ cause?: unknown;
17
+ refusedItemRef?: string;
18
+ });
19
+ }
20
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,22 @@
1
+ /** Host adapters must re-export this shared class to preserve instanceof identity; product
2
+ * refusal copy stays host-owned. */
3
+ /**
4
+ * @file Shared plugin save-hook refusal. Callers handling saves and the plugin runtime import
5
+ * this neutral error contract to avoid a dependency cycle or making the save domain plugin-aware.
6
+ */
7
+ /** Thrown (and caught by the caller, mapped to 500 `PLUGIN_HOOK_FAILED`) when a filter throws,
8
+ * triggers `CapabilityDeniedError`, or returns an invalid `ext` write (BR-07/EC-10). */
9
+ export class PluginHookFailedError extends Error {
10
+ pluginId;
11
+ /** The item a multi-item apply was writing when the hook refused (e.g. `post:<id>`), set only by
12
+ * an apply that is NOT all-or-nothing (`publish-content/apply-loop.ts`), so items applied before
13
+ * it stay saved. `null` for a single save, where the refusal means nothing was saved. */
14
+ refusedItemRef;
15
+ constructor(pluginId, message, options) {
16
+ super(message, options);
17
+ this.name = "PluginHookFailedError";
18
+ this.pluginId = pluginId;
19
+ this.refusedItemRef = options?.refusedItemRef ?? null;
20
+ }
21
+ }
22
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @file `createHookRegistry()` / `runBeforeSave()` — composes enabled plugins' `content.entry.
3
+ * beforeSave` filters, merges `ext`, fail-closed (SPEC-005 REQ-05/REQ-06; BR-04/BR-06/BR-07;
4
+ * CIC U-004, no escalation marker).
5
+ *
6
+ * Purpose:
7
+ * The concrete adapter for `BeforeSaveHookPort` (`src/features/post/post.ts`'s contract). Keeping
8
+ * this composition logic here — not in `post.ts` — is what keeps `post.ts` plugin-ignorant
9
+ * (Module Map). `activation.ts` calls `.detach()` on disable.
10
+ *
11
+ * **Corrected 2026-08-04 (ADR-057 Decision 2.1):** this comment previously claimed `loader.ts`
12
+ * calls `.attach()` on this registry as each plugin's `setup()` runs. That was false — `loadPlugin()`
13
+ * (`loader.ts`) has never called `.attach()`; steps 4-5 of BR-01 were left unwired, documented but
14
+ * dead, and no other production code called it either (verified: `grep -rn "hookRegistry\.attach"
15
+ * src --include=*.ts`, excluding tests, returned only this file's own now-corrected doc comment).
16
+ * `loader.ts` exports `attachLoadedPlugin()`, the real (not stub) extraction of that dead logic's
17
+ * attach half, widened to accept a `"glue"` source. Site Glue's content-lifecycle attachment point
18
+ * is `attachLoadedPlugin`'s first production caller; `loadPlugin()` itself still does not call it —
19
+ * a future SPEC-005 fix for its own activation path is expected to call the same function, per
20
+ * ADR-057 Decision 2.1, rather than re-inventing this wiring a second time.
21
+ *
22
+ * **CIC U-004 (Binding, no escalation marker — bounded blast radius via SPEC-001's revert):**
23
+ * `runBeforeSave()` must fully resolve (returning the merged patch) or throw before its caller
24
+ * (`post.ts`) constructs the final `PostRecord` passed to `deps.repo.save()`. There is exactly one
25
+ * `repo.save()` call per `createPost`/`updatePost` invocation, and it must never be reached if
26
+ * this function throws (BR-06 same-transaction requirement; BR-07/EC-10 fail-closed: no partial
27
+ * write, no change set on failure). This module's own responsibility ends at "resolve or throw
28
+ * before returning" — `post.ts` is responsible for not calling `repo.save()` on the throw path.
29
+ *
30
+ * Composition order is TB-01 (built-ins first by id ascending, then site plugins by id
31
+ * ascending) — the SAME order `PLUGINS_LIST` uses. Each plugin writes only its own
32
+ * `ext.{pluginId}` namespace (BR-04), so composition order does not create write conflicts, but
33
+ * the ordering is still fixed and deterministic (not incidental) because later filters observe
34
+ * earlier filters' already-merged `ext` values on the entry snapshot they receive.
35
+ *
36
+ * Architectural role:
37
+ * TDD-certified implementation (implementation outline C-010, CIC U-004). Signature and JSDoc are
38
+ * design-frozen; `runBeforeSave()` orders attached filters, gives each an isolated entry snapshot,
39
+ * validates each declared-field patch, and returns the merged per-plugin `ext` object fail-closed.
40
+ */
41
+ import type { JsonObject } from "@jini-ai/core/primitives";
42
+ import type { BeforeSaveFilter, ContentEntryDraft, HookPoints, PluginSdkBinding } from "./ports.js";
43
+ import { PluginHookFailedError } from "./errors.js";
44
+ /** Who attached a given filter — extended by ADR-057 Decision 3 with `"glue"`, ranked after
45
+ * `"site"` in {@link compareTb01}. Exported so `loader.ts`'s `attachLoadedPlugin()` and any other
46
+ * caller share this one source of truth for the vocabulary rather than re-declaring the union. */
47
+ export type AttachmentSource = "built-in" | "site" | "glue";
48
+ export { PluginHookFailedError };
49
+ /** One field this plugin declared in its manifest (BR-06's validation target — the merge step
50
+ * rejects a returned patch key/value that doesn't match a declared field). */
51
+ export interface HookRegistryFieldDecl {
52
+ readonly path: string;
53
+ readonly type: "string" | "integer" | "number" | "boolean";
54
+ }
55
+ /** Default recovery policy: tolerate two transient failures, quarantine on the third consecutive
56
+ * failure. Composition may inject a different positive integer per runtime instance. */
57
+ export declare const DEFAULT_PLUGIN_FAILURE_THRESHOLD = 3;
58
+ export interface PluginQuarantineEvent {
59
+ readonly pluginId: string;
60
+ readonly workspaceId: string;
61
+ readonly consecutiveFailures: number;
62
+ readonly reason: string;
63
+ }
64
+ export interface CreateHookRegistryOptions {
65
+ readonly failureThreshold?: number;
66
+ /** Persistence/action port supplied by composition. Absent keeps the registry's legacy
67
+ * fail-closed-only behavior (used by isolated consumers that have no activation repository). */
68
+ readonly onQuarantine?: (event: PluginQuarantineEvent) => Promise<void>;
69
+ }
70
+ export interface HookRegistry {
71
+ /** Registers one currently-enabled, successfully-loaded plugin's filter (BR-01 step 5). Safe to
72
+ * call again for the same `pluginId` — a second `attach` for an id already attached replaces
73
+ * the prior registration (re-enable after disable, or a loader retry). */
74
+ attach(required: {
75
+ pluginId: string;
76
+ source: AttachmentSource;
77
+ filter: BeforeSaveFilter;
78
+ declaredFields: readonly HookRegistryFieldDecl[];
79
+ }, optional?: Record<string, never>): void;
80
+ /** Removes a plugin's filter (disable, BR-05) — its `ext` data is untouched (INV-03); only the
81
+ * filter stops firing on subsequent saves. */
82
+ detach(required: {
83
+ pluginId: string;
84
+ }, optional?: Record<string, never>): void;
85
+ /** Implements `BeforeSaveHookPort` — the sole surface `post.ts` depends on. */
86
+ runBeforeSave(required: {
87
+ entry: Readonly<ContentEntryDraft>;
88
+ }, optional?: Record<string, never>): Promise<JsonObject>;
89
+ /** Admin preview (AW-7): runs ONE attached plugin's filter on a draft with the same snapshot and
90
+ * declared-field validation as a save, but merges, saves and counts nothing — a preview failure
91
+ * throws `PluginHookFailedError` without touching the quarantine counter or the attachment, so
92
+ * an editor trying drafts can never quarantine a plugin. Resolves `null` when `pluginId` is not
93
+ * attached (disabled, quarantined, or never loaded). */
94
+ previewBeforeSave(required: {
95
+ pluginId: string;
96
+ entry: Readonly<ContentEntryDraft>;
97
+ }, optional?: Record<string, never>): Promise<JsonObject | null>;
98
+ }
99
+ /**
100
+ * Creates a fresh, empty hook registry (no plugins attached). Each process has exactly one
101
+ * long-lived instance, constructed once at composition-root time and shared between `loader.ts`
102
+ * (attach/detach) and `post.ts` (via `BeforeSaveHookPort`, `runBeforeSave` only).
103
+ *
104
+ * @complexity `attach`/`detach` are O(1) (Map operations). `runBeforeSave` is
105
+ * O(attached-plugin-count · own-declared-field-count) for merge/validation bookkeeping, plus each
106
+ * plugin's own filter cost (unbounded, plugin-defined — no latency budget exists, ADR scalability
107
+ * axis, a disclosed gap).
108
+ * @overallScore 100/100
109
+ */
110
+ export declare function createHookRegistry<H extends HookPoints>(required: {
111
+ pluginSdkBinding: PluginSdkBinding<H>;
112
+ }, options?: CreateHookRegistryOptions): HookRegistry;
113
+ //# sourceMappingURL=hook-registry.d.ts.map
@@ -0,0 +1,190 @@
1
+ import { PluginHookFailedError } from "./errors.js";
2
+ // The class lives in `contracts/core` so `features/post` can recognize it without importing this
3
+ // feature (see that file's header); re-exported so this module's importers are unchanged.
4
+ export { PluginHookFailedError };
5
+ /** Default recovery policy: tolerate two transient failures, quarantine on the third consecutive
6
+ * failure. Composition may inject a different positive integer per runtime instance. */
7
+ export const DEFAULT_PLUGIN_FAILURE_THRESHOLD = 3;
8
+ /** TB-01's rank per source, ADR-057 Decision 3's additive third stage: built-ins (0), then site
9
+ * plugins (1), then glue modules (2) — id-ascending within each rank (`compareTb01` below). */
10
+ const SOURCE_RANK = { "built-in": 0, site: 1, glue: 2 };
11
+ /**
12
+ * TB-01 comparator: built-ins before site plugins before glue modules, id-ascending within each
13
+ * group. Shared with `discovery.ts`'s own ordering rule for the `built-in`/`site` ranks (PLUGINS_LIST
14
+ * uses the same order) so those two never diverge; the `glue` rank has no discovery-time analogue
15
+ * since glue modules are never listed by `discovery.ts` (ADR-057 Decision 6 — a separate tier).
16
+ */
17
+ function compareTb01(a, b) {
18
+ const rankDiff = SOURCE_RANK[a[1].source] - SOURCE_RANK[b[1].source];
19
+ if (rankDiff !== 0)
20
+ return rankDiff;
21
+ return a[0].localeCompare(b[0]);
22
+ }
23
+ /** The four JSON-primitive field types BR-06's declared-field vocabulary supports. */
24
+ function matchesDeclaredType(value, type) {
25
+ switch (type) {
26
+ case "integer":
27
+ return typeof value === "number" && Number.isInteger(value);
28
+ case "number":
29
+ return typeof value === "number";
30
+ case "string":
31
+ return typeof value === "string";
32
+ case "boolean":
33
+ return typeof value === "boolean";
34
+ default:
35
+ return false;
36
+ }
37
+ }
38
+ /** Last dot-segment of a declared `ext.{pluginId}.{field}` path — the field name a returned patch
39
+ * key is checked against. */
40
+ function fieldNameOf(declaredPath) {
41
+ const segments = declaredPath.split(".");
42
+ return segments[segments.length - 1] ?? declaredPath;
43
+ }
44
+ /** Calls one plugin's filter, re-shaping a thrown error into the module's own
45
+ * `PluginHookFailedError` vocabulary — the ONE place `runBeforeSave`'s per-plugin work touches the
46
+ * plugin's own code directly. */
47
+ async function callPluginFilter(pluginId, filter, snapshot, ctx, beforeSaveHook) {
48
+ try {
49
+ return await filter(snapshot, ctx);
50
+ }
51
+ catch (error) {
52
+ throw new PluginHookFailedError(pluginId, `plugin '${pluginId}' ${beforeSaveHook} filter failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
53
+ }
54
+ }
55
+ /** BR-07/EC-10: a filter's return value must be a plain object, never an array or a primitive. */
56
+ function assertPatchShape(pluginId, patch) {
57
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) {
58
+ throw new PluginHookFailedError(pluginId, `plugin '${pluginId}' returned a non-object ext patch from its beforeSave filter`);
59
+ }
60
+ }
61
+ /** BR-06: every key in a validated patch must match a field the plugin's own manifest declared,
62
+ * with a value matching that field's declared type — anything else is fail-closed, not dropped. */
63
+ function buildDeclaredPatch(pluginId, patch, declaredFields) {
64
+ const declaredByField = new Map(declaredFields.map((f) => [fieldNameOf(f.path), f]));
65
+ const pluginPatch = {};
66
+ for (const [field, value] of Object.entries(patch)) {
67
+ const decl = declaredByField.get(field);
68
+ if (!decl) {
69
+ throw new PluginHookFailedError(pluginId, `plugin '${pluginId}' returned undeclared ext field '${field}' (FIELD_PATH_INVALID)`);
70
+ }
71
+ if (!matchesDeclaredType(value, decl.type)) {
72
+ throw new PluginHookFailedError(pluginId, `plugin '${pluginId}' returned ext field '${field}' with a value not matching its declared type '${decl.type}' (FIELD_TYPE_MISMATCH)`);
73
+ }
74
+ pluginPatch[field] = value;
75
+ }
76
+ return pluginPatch;
77
+ }
78
+ /**
79
+ * One plugin's full contribution: builds its isolated entry snapshot (this plugin's own `ext`
80
+ * namespace overlaid with every earlier plugin's already-merged result, per TB-01's composition
81
+ * order), calls its filter, and validates the returned patch. Pulled out of `runBeforeSave`'s loop
82
+ * body because that loop's own job — ordering, failure bookkeeping, quarantine — is a different
83
+ * concern from what happens to any ONE plugin's filter call.
84
+ */
85
+ async function applyPluginFilter(pluginId, attachment, entry, mergedSoFar, beforeSaveHook) {
86
+ const snapshot = structuredClone({ ...entry, ext: { ...entry.ext, ...mergedSoFar } });
87
+ const ctx = { pluginId, workspaceId: entry.workspaceId };
88
+ const patch = await callPluginFilter(pluginId, attachment.filter, snapshot, ctx, beforeSaveHook);
89
+ assertPatchShape(pluginId, patch);
90
+ return buildDeclaredPatch(pluginId, patch, attachment.declaredFields);
91
+ }
92
+ /**
93
+ * Creates a fresh, empty hook registry (no plugins attached). Each process has exactly one
94
+ * long-lived instance, constructed once at composition-root time and shared between `loader.ts`
95
+ * (attach/detach) and `post.ts` (via `BeforeSaveHookPort`, `runBeforeSave` only).
96
+ *
97
+ * @complexity `attach`/`detach` are O(1) (Map operations). `runBeforeSave` is
98
+ * O(attached-plugin-count · own-declared-field-count) for merge/validation bookkeeping, plus each
99
+ * plugin's own filter cost (unbounded, plugin-defined — no latency budget exists, ADR scalability
100
+ * axis, a disclosed gap).
101
+ * @overallScore 100/100
102
+ */
103
+ export function createHookRegistry(required, options = {}) {
104
+ const beforeSaveHook = required.pluginSdkBinding.beforeSaveHook;
105
+ const failureThreshold = options.failureThreshold ?? DEFAULT_PLUGIN_FAILURE_THRESHOLD;
106
+ if (!Number.isInteger(failureThreshold) || failureThreshold < 1) {
107
+ throw new RangeError("plugin failure threshold must be a positive integer");
108
+ }
109
+ const attachments = new Map();
110
+ const consecutiveFailures = new Map();
111
+ function clearFailures(pluginId, workspaceId) {
112
+ if (workspaceId !== undefined) {
113
+ const workspaceFailures = consecutiveFailures.get(workspaceId);
114
+ workspaceFailures?.delete(pluginId);
115
+ if (workspaceFailures?.size === 0)
116
+ consecutiveFailures.delete(workspaceId);
117
+ return;
118
+ }
119
+ for (const [workspace, workspaceFailures] of consecutiveFailures) {
120
+ workspaceFailures.delete(pluginId);
121
+ if (workspaceFailures.size === 0)
122
+ consecutiveFailures.delete(workspace);
123
+ }
124
+ }
125
+ async function recordFailure(pluginId, workspaceId, failure) {
126
+ if (!options.onQuarantine)
127
+ return;
128
+ const workspaceFailures = consecutiveFailures.get(workspaceId) ?? new Map();
129
+ const next = (workspaceFailures.get(pluginId) ?? 0) + 1;
130
+ workspaceFailures.set(pluginId, next);
131
+ consecutiveFailures.set(workspaceId, workspaceFailures);
132
+ if (next < failureThreshold)
133
+ return;
134
+ // Recover the process first: the triggering save remains fail-closed, but all later saves see
135
+ // the attachment gone even while durable activation state is being recorded.
136
+ detach({ pluginId });
137
+ try {
138
+ await options.onQuarantine({
139
+ pluginId,
140
+ workspaceId,
141
+ consecutiveFailures: next,
142
+ reason: failure.message,
143
+ });
144
+ }
145
+ catch (error) {
146
+ throw new PluginHookFailedError(pluginId, `${failure.message}; automatic quarantine persistence failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
147
+ }
148
+ }
149
+ function attach({ pluginId, source, filter, declaredFields }, _optional = {}) {
150
+ clearFailures(pluginId);
151
+ attachments.set(pluginId, { source, filter, declaredFields });
152
+ }
153
+ function detach({ pluginId }, _optional = {}) {
154
+ attachments.delete(pluginId);
155
+ clearFailures(pluginId);
156
+ }
157
+ async function runBeforeSave({ entry }, _optional = {}) {
158
+ const ordered = [...attachments.entries()].sort(compareTb01);
159
+ const merged = {};
160
+ for (const [pluginId, attachment] of ordered) {
161
+ try {
162
+ merged[pluginId] = await applyPluginFilter(pluginId, attachment, entry, merged, beforeSaveHook);
163
+ clearFailures(pluginId, entry.workspaceId);
164
+ }
165
+ catch (error) {
166
+ const failure = error instanceof PluginHookFailedError
167
+ ? error
168
+ : new PluginHookFailedError(pluginId, `plugin '${pluginId}' beforeSave hook failed`, { cause: error });
169
+ await recordFailure(pluginId, entry.workspaceId, failure);
170
+ throw failure;
171
+ }
172
+ }
173
+ return merged;
174
+ }
175
+ async function previewBeforeSave({ pluginId, entry }, _optional = {}) {
176
+ const attachment = attachments.get(pluginId);
177
+ if (!attachment)
178
+ return null;
179
+ try {
180
+ return await applyPluginFilter(pluginId, attachment, entry, {}, beforeSaveHook);
181
+ }
182
+ catch (error) {
183
+ throw error instanceof PluginHookFailedError
184
+ ? error
185
+ : new PluginHookFailedError(pluginId, `plugin '${pluginId}' beforeSave hook failed`, { cause: error });
186
+ }
187
+ }
188
+ return { attach, detach, runBeforeSave, previewBeforeSave };
189
+ }
190
+ //# sourceMappingURL=hook-registry.js.map
@@ -0,0 +1,19 @@
1
+ /** Universal manifest, claims, activation and hook composition; never imports or evaluates a module. */
2
+ export * from './ports.js';
3
+ export * from './errors.js';
4
+ export * from './manifest.js';
5
+ export * from './discovery-types.js';
6
+ export * from './hook-registry.js';
7
+ export * from './attach-loaded-plugin.js';
8
+ export * from './plugin-claims.js';
9
+ export * from './claim-conflicts.js';
10
+ export * from './activation.js';
11
+ export * from './declarative-enable.js';
12
+ export * from './capability-sdk.js';
13
+ export * from './quarantine.js';
14
+ export * from './repo.memory.js';
15
+ export * from './uninstall.js';
16
+ export * from './source-policy.js';
17
+ export * from './contributions.js';
18
+ export * from './tool-contributions.js';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,19 @@
1
+ /** Universal manifest, claims, activation and hook composition; never imports or evaluates a module. */
2
+ export * from './ports.js';
3
+ export * from './errors.js';
4
+ export * from './manifest.js';
5
+ export * from './discovery-types.js';
6
+ export * from './hook-registry.js';
7
+ export * from './attach-loaded-plugin.js';
8
+ export * from './plugin-claims.js';
9
+ export * from './claim-conflicts.js';
10
+ export * from './activation.js';
11
+ export * from './declarative-enable.js';
12
+ export * from './capability-sdk.js';
13
+ export * from './quarantine.js';
14
+ export * from './repo.memory.js';
15
+ export * from './uninstall.js';
16
+ export * from './source-policy.js';
17
+ export * from './contributions.js';
18
+ export * from './tool-contributions.js';
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @file `PluginManifest` type + `validateManifest()` — static, collect-all manifest validation
3
+ * (SPEC-005 REQ-01, BR-02/BR-03; ADR-024 `tier`, 1.1.1 fix).
4
+ *
5
+ * Purpose:
6
+ * Pure, no-I/O validation of an already-parsed `tovu.plugin.json` object against the v1 required-
7
+ * field set, id/folder match, capability vocabulary, hook vocabulary, and field-declaration rules.
8
+ * Consumed by both `discovery.ts` (list-time, every discovery pass) and `loader.ts` (enable-time
9
+ * re-validation, BR-05) — one validator, two call sites, never diverging (mirrors SPEC-004's theme
10
+ * validator shape, per feature.spec.md's own Article IV note).
11
+ *
12
+ * Division of labor (a TDD design decision, not itself a spec requirement): BR-02 step (1),
13
+ * "package-level (size, disallowed files, server/index.mjs presence)", requires a directory
14
+ * listing this function's contract deliberately does NOT take as input (Implementation Outline
15
+ * C-006: `{ manifest: unknown, folderName: string, builtInIds: string[] }` — no file-list
16
+ * parameter). Package-level filesystem checks are therefore `discovery.ts`'s responsibility
17
+ * (REQ-02/03's discovery step, which does read the filesystem); this function owns BR-02 steps
18
+ * (2)-(6) only: manifest / identity / capabilities / hooks / fields. `discovery.ts` merges both
19
+ * error sets into one `PluginDiscoveryRecord.errors[]` array before listing/enabling a plugin.
20
+ *
21
+ * Architectural role:
22
+ * TDD-certified implementation (implementation outline C-005/C-006). Signature and JSDoc are
23
+ * design-frozen; `validateManifest()` collects every BR-02 steps (2)-(6) violation (identity,
24
+ * engine/tier, capabilities, hooks, fields) rather than stopping at the first, returning them in
25
+ * `errors[]` — it never throws. Verified against `__tests__/unit/manifest.unit.test.ts`.
26
+ */
27
+ import { type PluginIdentityExtension } from "@jini-ai/core/plugin-directory";
28
+ import type { HookPoints, ManifestHostPorts } from "./ports.js";
29
+ /** ADR-024 §1 trust-tier vocabulary (1.1.1 REQ-01 fix). Literal encoding reused verbatim from the
30
+ * existing, approved SPEC-032/ADR-023 precedent (`DataModuleDecl.pluginTier`). */
31
+ export type PluginTier = "tier-1" | "tier-2" | "tier-3";
32
+ /** REQ-04's exactly-three v1 capability vocabulary, as manifest-declared strings (validated
33
+ * against this set by `validateManifest`; `@tovu/sdk`'s `CONTENT_READ`/`CONTENT_EXTEND`/
34
+ * `HOOKS_ATTACH` constants are the same literal values, kept independent here so this module has
35
+ * no dependency on the SDK package per the Module Map). Sourced from `core/`'s
36
+ * `SharedExtensionCapability` — the sibling `site-glue` mechanism's own capability vocabulary
37
+ * declares this same three-member set as its first three members; both import the one shared
38
+ * declaration rather than each retyping the literals (2026-08-20 swarm-consensus synthesis,
39
+ * Result 1). */
40
+ export type PluginCapability = string;
41
+ /** REQ-06 field declaration — `ext.{pluginId}.{field}` (BR-06). `queryable` MUST be `false` in
42
+ * v1 (EC-04); a `true` value is a validation error (`QUERYABLE_UNSUPPORTED_V1`), not silently
43
+ * coerced. */
44
+ export interface PluginManifestFieldDecl {
45
+ readonly path: string;
46
+ readonly type: "string" | "integer" | "number" | "boolean";
47
+ readonly queryable: boolean;
48
+ /**
49
+ * Optional, human-readable, action-oriented description of what this field represents and how an
50
+ * agent should use it (2026-08-26 addition — `features/plugin-runtime/capability-tool-registrations.ts`
51
+ * is the sole consumer: it is folded into the indexed `search_tools` description for this plugin's
52
+ * capability-read tool when the plugin is enabled). Absent on every pre-existing manifest — this
53
+ * is additive, not a widened requirement, so no previously-valid manifest becomes invalid by
54
+ * omitting it; a plugin author who wants their capability to rank well against a real user query
55
+ * simply adds one.
56
+ */
57
+ readonly description?: string;
58
+ }
59
+ /** `tovu.plugin.json` — the ecosystem compatibility surface (state.spec.md §2, ADR-004). */
60
+ export interface PluginManifest {
61
+ /** Storage/activation key. Publisher identity lives in extensions[identityNamespace].id. */
62
+ readonly id: string;
63
+ readonly keywords?: readonly string[];
64
+ readonly extensions?: Readonly<Record<string, PluginIdentityExtension>>;
65
+ readonly name: string;
66
+ readonly version: string;
67
+ readonly sdkRange: string;
68
+ readonly engine: number;
69
+ readonly tier: PluginTier;
70
+ readonly capabilities: readonly string[];
71
+ readonly hooks: readonly string[];
72
+ readonly fields: readonly PluginManifestFieldDecl[];
73
+ readonly integrity: Readonly<Record<string, string>>;
74
+ /** Parsed-and-stored, UNUSED in v1 (forward-compat, no behavior — state.spec.md §2). */
75
+ readonly adminSurfaces?: readonly unknown[] | null;
76
+ /** Content types the plugin declares (AW-7 Tier 1, 2026-10-04) — no longer unused: validated by
77
+ * `declarative-content-types.ts`, claimed by key (`plugin-claims.ts`), created at enable. */
78
+ readonly contentTypes?: readonly unknown[] | null;
79
+ readonly provenance?: {
80
+ readonly sourceUrl?: string;
81
+ readonly signature?: string;
82
+ } | null;
83
+ readonly dependencies?: Readonly<Record<string, string>> | null;
84
+ /**
85
+ * What this plugin says it provides, by name (2026-10-04, conflict detection — see
86
+ * `plugin-claims.ts` and `ADS-memory/specs/005-plugin-system/conflicts.spec.md`). Optional and
87
+ * additive: a manifest without it claims only what its other fields already imply (its hooks and,
88
+ * when it declares `fields`, its generated capability tool). Each entry is a CLAIM: two enabled
89
+ * plugins, or a plugin and core, naming the same thing is refused at enable time and quarantined
90
+ * at boot rather than silently letting one overwrite the other. Declaring a surface the runtime
91
+ * does not mount yet (settings, widgets, routes — ADR-025/`adminSurfaces` are still unwired) is
92
+ * still binding for conflicts, so a plugin cannot squat a name today that a future mount would
93
+ * then have to arbitrate.
94
+ */
95
+ readonly contributes?: PluginContributions | null;
96
+ }
97
+ /** `tovu.plugin.json`'s `contributes` block — every list optional, every entry a plain name. */
98
+ export interface PluginContributions {
99
+ /** `"METHOD /path"` or `"/path"` (every method). Parameter names do not distinguish routes. */
100
+ readonly routes?: readonly string[];
101
+ /** Agent tool ids. The generated prefixes `plugin_capability_`/`agent_plugin_` are reserved. */
102
+ readonly tools?: readonly string[];
103
+ /** Data-module tables — must sit in this plugin's own `p_{id}__` namespace (ADR-023 §5). */
104
+ readonly tables?: readonly string[];
105
+ readonly settings?: readonly string[];
106
+ readonly widgets?: readonly string[];
107
+ /** Permission ids this plugin DEFINES (not ones it merely requires). */
108
+ readonly permissions?: readonly string[];
109
+ }
110
+ /** One validation-vocabulary entry (errors.spec.md §3). `file` names the offending packaged file
111
+ * when applicable; `null` for manifest-level errors with no single implicated file. This is the
112
+ * shared shape used verbatim by both `PLUGINS_LIST.plugins[].errors[]` and
113
+ * `PLUGIN_INVALID.details.errors[]` (errors.spec.md §4 — "one validator, two surfaces"). */
114
+ export interface PluginValidationError {
115
+ readonly code: string;
116
+ readonly file: string | null;
117
+ readonly message: string;
118
+ }
119
+ export interface ValidateManifestRequired<H extends HookPoints = HookPoints> extends ManifestHostPorts<H> {
120
+ /** An already-parsed `tovu.plugin.json` value (unparseable JSON is `discovery.ts`'s concern —
121
+ * this function receives a JS value, never a file path or raw bytes). */
122
+ readonly manifest: unknown;
123
+ /** The install folder name this manifest was read from (EC-01: `id` must equal this). */
124
+ readonly folderName: string;
125
+ /** Every currently-registered built-in plugin id (DUP-01: a site plugin id equal to a built-in
126
+ * id is `SHADOWS_BUILT_IN`, not silently shadowed). */
127
+ readonly builtInIds: readonly string[];
128
+ }
129
+ export type ValidateManifestOptional = Record<string, never>;
130
+ export interface ValidateManifestResult {
131
+ readonly warnings?: readonly string[];
132
+ /** Every applicable error, collected — NOT first-failure (BR-02). Empty when the manifest is
133
+ * statically valid (integrity/`sdkRange` are separate, load-pipeline-time checks, BR-01). */
134
+ readonly errors: readonly PluginValidationError[];
135
+ }
136
+ /** Shared id grammar for source paths and manifests. Identity admission (reserved ids, folder
137
+ * match and built-in shadowing) still belongs to full manifest validation. */
138
+ export declare function validatePluginIdFormat(required: {
139
+ id: string;
140
+ }, _optional?: Record<string, never>): readonly PluginValidationError[];
141
+ /** The owner id the claim system gives Tovu core (`plugin-claims.ts` re-exports it). Conflict
142
+ * detection never compares an owner with itself, so a plugin with this id would never conflict with
143
+ * core's reserved routes, tools or permissions — it is refused as an id instead. */
144
+ export declare const CORE_OWNER_ID = "core";
145
+ /** The `contributes` lists `validateContributes` accepts, in the order claims are derived. */
146
+ export declare const CONTRIBUTION_KEYS: readonly ["routes", "tools", "tables", "settings", "widgets", "permissions"];
147
+ /**
148
+ * Validates one already-parsed manifest against BR-02 steps (2)-(6), collecting every applicable
149
+ * error rather than stopping at the first (BR-02: "collect ALL statically-determinable errors").
150
+ * Pure — no I/O, no mutation of `manifest`.
151
+ *
152
+ * @throws Nothing — validation failures are reported via the returned `errors` array, never a
153
+ * thrown error (this function itself cannot fail; a malformed top-level shape, e.g. `manifest`
154
+ * being `null` or an array, is itself a `MANIFEST_MALFORMED` entry in the result, not a throw).
155
+ * @complexity O(fields.length + capabilities.length + hooks.length) — bounded by one manifest's
156
+ * own declared arrays, never by external/unbounded input.
157
+ */
158
+ export declare function validateManifest<H extends HookPoints>(required: ValidateManifestRequired<H>, _optional?: ValidateManifestOptional): ValidateManifestResult;
159
+ //# sourceMappingURL=manifest.d.ts.map