@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,407 @@
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 * as semver from "semver";
28
+ /**
29
+ * Validates one already-parsed manifest against BR-02 steps (2)-(6), collecting every applicable
30
+ * error rather than stopping at the first (BR-02: "collect ALL statically-determinable errors").
31
+ * Pure — no I/O, no mutation of `manifest`.
32
+ *
33
+ * @throws Nothing — validation failures are reported via the returned `errors` array, never a
34
+ * thrown error (this function itself cannot fail; a malformed top-level shape, e.g. `manifest`
35
+ * being `null` or an array, is itself a `MANIFEST_MALFORMED` entry in the result, not a throw).
36
+ * @complexity O(fields.length + capabilities.length + hooks.length) — bounded by one manifest's
37
+ * own declared arrays, never by external/unbounded input.
38
+ */
39
+ /** REQ-01's required top-level manifest keys — every one of these must be present. */
40
+ const REQUIRED_KEYS = [
41
+ "id",
42
+ "name",
43
+ "version",
44
+ "sdkRange",
45
+ "engine",
46
+ "tier",
47
+ "capabilities",
48
+ "hooks",
49
+ "fields",
50
+ "integrity",
51
+ ];
52
+ /** REQ-01's "parsed-and-stored but unused in v1" forward-compat keys — allowed, never validated. */
53
+ const OPTIONAL_KEYS = ["adminSurfaces", "contentTypes", "provenance", "dependencies", "contributes"];
54
+ const ALLOWED_KEYS = new Set([...REQUIRED_KEYS, ...OPTIONAL_KEYS]);
55
+ const VALID_TIERS = new Set(["tier-1", "tier-2", "tier-3"]);
56
+ const VALID_FIELD_TYPES = new Set(["string", "integer", "number", "boolean"]);
57
+ /** The one plugin-contract version this runtime understands in v1 (REQ-01). A manifest declaring
58
+ * any other value is `ENGINE_UNSUPPORTED` — there is no older version to be backward-compatible
59
+ * with yet, so "not exactly 1" and "newer than supported" coincide in practice. */
60
+ const SUPPORTED_ENGINE_VERSION = 1;
61
+ const ID_PATTERN = /^[a-z0-9-]+$/;
62
+ const MAX_ID_LENGTH = 50;
63
+ function malformed(message) {
64
+ return { code: "MANIFEST_MALFORMED", file: null, message };
65
+ }
66
+ /** Unknown-key and missing-required-key checks (BR-02 step 1's manifest-shape half). */
67
+ function validateKeys(raw) {
68
+ const errors = [];
69
+ for (const key of Object.keys(raw)) {
70
+ if (!ALLOWED_KEYS.has(key)) {
71
+ errors.push(malformed(`unknown manifest key '${key}'`));
72
+ }
73
+ }
74
+ for (const key of REQUIRED_KEYS) {
75
+ if (raw[key] === undefined) {
76
+ errors.push(malformed(`missing required manifest field '${key}'`));
77
+ }
78
+ }
79
+ return errors;
80
+ }
81
+ /** id shape only: pattern + length (BR-02 step 2 half of id validation). */
82
+ function validateIdFormat(id) {
83
+ if (!ID_PATTERN.test(id) || id.length < 1 || id.length > MAX_ID_LENGTH) {
84
+ return [malformed(`id '${id}' must match ${ID_PATTERN} and be 1-${MAX_ID_LENGTH} characters`)];
85
+ }
86
+ return [];
87
+ }
88
+ /** The owner id the claim system gives Tovu core (`plugin-claims.ts` re-exports it). Conflict
89
+ * detection never compares an owner with itself, so a plugin with this id would never conflict with
90
+ * core's reserved routes, tools or permissions — it is refused as an id instead. */
91
+ export const CORE_OWNER_ID = "core";
92
+ /** id identity: reserved id + folder match + built-in shadowing (BR-02 step 3, DUP-01). */
93
+ function validateIdIdentity(id, folderName, builtInIds, coreOwnerName) {
94
+ const errors = [];
95
+ if (id === CORE_OWNER_ID) {
96
+ errors.push({ code: "ID_RESERVED", file: null, message: `id '${id}' is reserved for ${coreOwnerName}` });
97
+ }
98
+ if (id !== folderName) {
99
+ errors.push({
100
+ code: "ID_FOLDER_MISMATCH",
101
+ file: null,
102
+ message: `manifest id '${id}' does not match its install folder name '${folderName}'`,
103
+ });
104
+ }
105
+ if (builtInIds.some((builtInId) => builtInId.toLowerCase() === id.toLowerCase())) {
106
+ errors.push({
107
+ code: "SHADOWS_BUILT_IN",
108
+ file: null,
109
+ message: `id '${id}' shadows an existing built-in plugin id`,
110
+ });
111
+ }
112
+ return errors;
113
+ }
114
+ /** id: presence/type gate, then format + folder match + built-in shadowing (BR-02 step 2/3). */
115
+ function validateId(raw, folderName, builtInIds, coreOwnerName) {
116
+ const id = typeof raw.id === "string" ? raw.id : undefined;
117
+ if (raw.id !== undefined && id === undefined) {
118
+ return { errors: [malformed("'id' must be a string")], id };
119
+ }
120
+ if (id === undefined) {
121
+ return { errors: [], id };
122
+ }
123
+ return { errors: [...validateIdFormat(id), ...validateIdIdentity(id, folderName, builtInIds, coreOwnerName)], id };
124
+ }
125
+ /** The one hash format `loader.ts` computes and compares (`sha256-` + 64 lowercase hex). */
126
+ const INTEGRITY_HASH_PATTERN = /^sha256-[0-9a-f]{64}$/;
127
+ /**
128
+ * `value` is a strict SemVer string written in canonical form. `semver.valid()` alone is not enough:
129
+ * it also accepts `v1.0.0` or padded text, and the canonical string it returns drops build metadata,
130
+ * so comparing against it would refuse a valid `1.0.0+build.42`. The build suffix is re-appended.
131
+ *
132
+ * @complexity O(n) for n characters.
133
+ */
134
+ function isExactSemver(value) {
135
+ const parsed = semver.parse(value);
136
+ if (parsed === null)
137
+ return false;
138
+ const build = parsed.build.length > 0 ? `+${parsed.build.join(".")}` : "";
139
+ return `${parsed.version}${build}` === value;
140
+ }
141
+ /**
142
+ * name, version and integrity shapes (REQ-01: `name`, `version` (semver), `integrity` (SHA-256 per
143
+ * packaged file)). Presence is `validateKeys`' job; a present-but-wrong value is caught here so it
144
+ * fails at discovery rather than later: a non-semver version cannot take part in latest-by-semver
145
+ * selection (AC-09), and a malformed hash can never match, so it would only surface at load time
146
+ * as a misleading INTEGRITY_FAILED (F3193).
147
+ */
148
+ function validateIdentityFields(raw) {
149
+ const errors = [];
150
+ if (raw.name !== undefined && (typeof raw.name !== "string" || raw.name.trim() === "")) {
151
+ errors.push(malformed("'name' must be a non-empty string"));
152
+ }
153
+ if (raw.version !== undefined && (typeof raw.version !== "string" || !isExactSemver(raw.version))) {
154
+ errors.push(malformed(`version '${String(raw.version)}' must be a semver version (e.g. 1.0.0)`));
155
+ }
156
+ if (raw.integrity === undefined)
157
+ return errors;
158
+ if (typeof raw.integrity !== "object" || raw.integrity === null || Array.isArray(raw.integrity)) {
159
+ errors.push(malformed("'integrity' must be an object mapping packaged file paths to sha256 hashes"));
160
+ return errors;
161
+ }
162
+ for (const [file, hash] of Object.entries(raw.integrity)) {
163
+ if (file === "" || typeof hash !== "string" || !INTEGRITY_HASH_PATTERN.test(hash)) {
164
+ errors.push(malformed(`integrity entry '${file}' must be 'sha256-' followed by 64 lowercase hex characters`));
165
+ }
166
+ }
167
+ return errors;
168
+ }
169
+ /** engine (BR-02 step 2). */
170
+ function validateEngine(raw) {
171
+ if (raw.engine === undefined) {
172
+ return [];
173
+ }
174
+ if (typeof raw.engine !== "number" || !Number.isInteger(raw.engine) || raw.engine < 1) {
175
+ return [malformed("'engine' must be a positive integer")];
176
+ }
177
+ if (raw.engine !== SUPPORTED_ENGINE_VERSION) {
178
+ return [
179
+ {
180
+ code: "ENGINE_UNSUPPORTED",
181
+ file: null,
182
+ message: `engine ${raw.engine} is not supported by this runtime (supports ${SUPPORTED_ENGINE_VERSION})`,
183
+ },
184
+ ];
185
+ }
186
+ return [];
187
+ }
188
+ /** tier (BR-02 step 2, ADR-024 §1 / 1.1.1 fix). */
189
+ function validateTier(raw) {
190
+ if (raw.tier === undefined) {
191
+ return [];
192
+ }
193
+ if (typeof raw.tier !== "string" || !VALID_TIERS.has(raw.tier)) {
194
+ return [malformed(`tier '${String(raw.tier)}' must be one of tier-1 | tier-2 | tier-3`)];
195
+ }
196
+ return [];
197
+ }
198
+ /** capabilities (BR-02 step 4, REQ-04). */
199
+ function validateCapabilities(raw, vocabulary) {
200
+ const errors = [];
201
+ const capabilities = Array.isArray(raw.capabilities) ? raw.capabilities : [];
202
+ if (raw.capabilities !== undefined && !Array.isArray(raw.capabilities)) {
203
+ errors.push(malformed("'capabilities' must be an array"));
204
+ }
205
+ for (const capability of capabilities) {
206
+ if (typeof capability !== "string" || !vocabulary.includes(capability)) {
207
+ errors.push({
208
+ code: "CAPABILITY_UNKNOWN",
209
+ file: null,
210
+ message: `capability '${String(capability)}' is outside the v1 vocabulary`,
211
+ });
212
+ }
213
+ }
214
+ return errors;
215
+ }
216
+ /** hooks (BR-02 step 5, REQ-05, INV-06 anti-hook-soup). */
217
+ function validateHooks(raw, hooksVocabulary) {
218
+ const errors = [];
219
+ const hooks = Array.isArray(raw.hooks) ? raw.hooks : [];
220
+ if (raw.hooks !== undefined && !Array.isArray(raw.hooks)) {
221
+ errors.push(malformed("'hooks' must be an array"));
222
+ }
223
+ for (const hook of hooks) {
224
+ if (typeof hook !== "string" || !hooksVocabulary.includes(hook)) {
225
+ errors.push({ code: "HOOK_UNKNOWN", file: null, message: `hook point '${String(hook)}' is not declared by core` });
226
+ }
227
+ }
228
+ return errors;
229
+ }
230
+ /** Path namespacing half of one `fields[]` entry (BR-02 step 6 part 1). */
231
+ function validateFieldPath(decl, expectedPrefix) {
232
+ if (typeof decl.path === "string" && decl.path.startsWith(expectedPrefix) && decl.path.length > expectedPrefix.length) {
233
+ return undefined;
234
+ }
235
+ return {
236
+ code: "FIELD_PATH_INVALID",
237
+ file: null,
238
+ message: `field path '${String(decl.path)}' must be namespaced to this plugin's own id ('${expectedPrefix}*')`,
239
+ };
240
+ }
241
+ /** Declared type half of one `fields[]` entry (BR-02 step 6 part 2). */
242
+ function validateFieldType(decl) {
243
+ if (typeof decl.type === "string" && VALID_FIELD_TYPES.has(decl.type))
244
+ return undefined;
245
+ return malformed(`field '${String(decl.path)}' has an unrecognized type '${String(decl.type)}'`);
246
+ }
247
+ /**
248
+ * `queryable` half of one `fields[]` entry (BR-02 step 6 part 3, EC-04).
249
+ *
250
+ * BUG FIX (this pass — found auditing this exact function for the complexity refactor, not
251
+ * introduced by it): the prior check was `decl.queryable === true`, which only ever rejects the
252
+ * literal boolean `true`. `PluginManifestFieldDecl.queryable` is a REQUIRED `boolean` field, but
253
+ * nothing enforced that shape — a manifest declaring `queryable: "true"` (a string), `queryable: 1`,
254
+ * or omitting `queryable` entirely all produced ZERO errors, silently accepted as if `queryable:
255
+ * false` had been declared. `queryable` currently has no downstream reader anywhere in this
256
+ * codebase (verified: `grep -rn '\.queryable\b'` finds only this file), so today's blast radius is
257
+ * a validator that doesn't validate rather than a live exploit — but the very first consumer that
258
+ * does `if (field.queryable)` on a manifest this function already certified as error-free would
259
+ * treat a JS-truthy non-boolean (`"true"`, `1`, `"false"` — also truthy!) as enabled, quietly
260
+ * defeating the "unsupported in v1" restriction this code exists to enforce. Fixed by requiring the
261
+ * boolean type itself first, matching how {@link validateFieldType} already validates shape before
262
+ * value for its own field. Regression: `manifest.unit.test.ts` ("a non-boolean queryable value...").
263
+ */
264
+ function validateFieldQueryable(decl) {
265
+ if (typeof decl.queryable !== "boolean") {
266
+ return malformed(`field '${String(decl.path)}' has an invalid 'queryable' value '${String(decl.queryable)}' — must be a boolean`);
267
+ }
268
+ if (decl.queryable === true) {
269
+ return {
270
+ code: "QUERYABLE_UNSUPPORTED_V1",
271
+ file: null,
272
+ message: `field '${String(decl.path)}' declares queryable:true, unsupported in v1 (OQ-04)`,
273
+ };
274
+ }
275
+ return undefined;
276
+ }
277
+ /** Optional `description` half of one `fields[]` entry (2026-08-26 addition, see
278
+ * `PluginManifestFieldDecl.description`'s own doc) — absent is always fine (most fields, and every
279
+ * pre-existing manifest, declare none); present-but-not-a-non-empty-string is rejected so a typo'd
280
+ * `description: ""` cannot silently ship an empty, useless search_tools description instead of a
281
+ * validation error a plugin author can act on. */
282
+ function validateFieldDescription(decl) {
283
+ if (decl.description === undefined)
284
+ return undefined;
285
+ if (typeof decl.description === "string" && decl.description.trim().length > 0)
286
+ return undefined;
287
+ return {
288
+ code: "FIELD_DESCRIPTION_INVALID",
289
+ file: null,
290
+ message: `field '${String(decl.path)}' declares a 'description' that must be a non-empty string when present`,
291
+ };
292
+ }
293
+ /** One `fields[]` entry (BR-02 step 6, REQ-06): path namespacing, declared type, `queryable`,
294
+ * optional `description` — each half delegated to its own validator (see each one's own doc), this
295
+ * function only shape-gates the entry itself and collects whichever of the four report an error. */
296
+ function validateField(field, expectedPrefix) {
297
+ if (typeof field !== "object" || field === null) {
298
+ return [malformed("each 'fields' entry must be an object")];
299
+ }
300
+ const decl = field;
301
+ return [validateFieldPath(decl, expectedPrefix), validateFieldType(decl), validateFieldQueryable(decl), validateFieldDescription(decl)].filter((error) => error !== undefined);
302
+ }
303
+ /** fields (BR-02 step 6, REQ-06) — `expectedPrefix` is constant across the array (it depends only
304
+ * on the manifest's own `id`, not on the field being checked), so it's computed once here rather
305
+ * than per-iteration. */
306
+ function validateFields(raw, id) {
307
+ const errors = [];
308
+ const fields = Array.isArray(raw.fields) ? raw.fields : [];
309
+ if (raw.fields !== undefined && !Array.isArray(raw.fields)) {
310
+ errors.push(malformed("'fields' must be an array"));
311
+ }
312
+ const expectedPrefix = `ext.${id ?? ""}.`;
313
+ for (const field of fields) {
314
+ errors.push(...validateField(field, expectedPrefix));
315
+ }
316
+ return errors;
317
+ }
318
+ /** The `contributes` lists `validateContributes` accepts, in the order claims are derived. */
319
+ export const CONTRIBUTION_KEYS = ["routes", "tools", "tables", "settings", "widgets", "permissions"];
320
+ const CONTRIBUTION_KEY_SET = new Set(CONTRIBUTION_KEYS);
321
+ /** Tool-id prefixes the runtime generates itself (`capability-tool-registrations.ts`,
322
+ * `agent-plugins/tool-registrations.ts`) — a plugin declaring one could impersonate another
323
+ * plugin's generated tool, so they are refused here, before conflict detection ever runs. */
324
+ const RESERVED_TOOL_PREFIXES = ["plugin_capability_", "agent_plugin_"];
325
+ const ROUTE_PATTERN = /^(?:(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|ANY|\*) )?\/\S*$/i;
326
+ function contributesInvalid(message) {
327
+ return { code: "CONTRIBUTES_INVALID", file: null, message };
328
+ }
329
+ /** Kind-specific shape checks, one per `contributes` list that has more than the shared rule —
330
+ * each returns the problem in words, or `undefined`. */
331
+ const CONTRIBUTION_CHECKS = {
332
+ routes: (entry) => (ROUTE_PATTERN.test(entry) ? undefined : "must be '/path' or 'METHOD /path'"),
333
+ tools: (entry) => RESERVED_TOOL_PREFIXES.some((prefix) => entry.startsWith(prefix)) ? "uses a prefix reserved for generated tools" : undefined,
334
+ tables: (entry, id) => {
335
+ const prefix = `p_${(id ?? "").replace(/-/g, "_")}__`;
336
+ return entry.startsWith(prefix) && entry.length > prefix.length ? undefined : `must be namespaced to this plugin ('${prefix}*')`;
337
+ },
338
+ };
339
+ /** One entry: the shared no-pattern rule, then its kind's own check. Plugins never claim a `*`
340
+ * prefix — reserving a whole namespace is core's privilege (see `claim-conflicts.ts` rule 6); a
341
+ * plugin doing it would squat every future name in it. */
342
+ function validateContribution(key, entry, id) {
343
+ // A route's leading `* ` is its METHOD ("every method"), not a name pattern.
344
+ const name = key === "routes" ? entry.replace(/^\* /, "") : entry;
345
+ const problem = name.includes("*") ? "must name one thing, not a '*' pattern" : CONTRIBUTION_CHECKS[key]?.(entry, id);
346
+ return problem === undefined ? undefined : contributesInvalid(`contributes.${key} entry '${entry}' ${problem}`);
347
+ }
348
+ /** `contributes` (2026-10-04): an object of known string lists — see `PluginManifest.contributes`. */
349
+ function validateContributes(raw, id) {
350
+ if (raw.contributes === undefined || raw.contributes === null)
351
+ return [];
352
+ if (typeof raw.contributes !== "object" || Array.isArray(raw.contributes)) {
353
+ return [contributesInvalid("'contributes' must be an object of string lists")];
354
+ }
355
+ const errors = [];
356
+ for (const [key, list] of Object.entries(raw.contributes)) {
357
+ if (!CONTRIBUTION_KEY_SET.has(key)) {
358
+ errors.push(contributesInvalid(`unknown contributes key '${key}' (expected one of ${CONTRIBUTION_KEYS.join(", ")})`));
359
+ continue;
360
+ }
361
+ if (!Array.isArray(list) || list.some((entry) => typeof entry !== "string" || entry.trim() === "")) {
362
+ errors.push(contributesInvalid(`contributes.${key} must be a list of non-empty strings`));
363
+ continue;
364
+ }
365
+ for (const entry of list) {
366
+ const error = validateContribution(key, entry, id);
367
+ if (error)
368
+ errors.push(error);
369
+ }
370
+ }
371
+ return errors;
372
+ }
373
+ /**
374
+ * Validates one already-parsed manifest against BR-02 steps (2)-(6), collecting every applicable
375
+ * error rather than stopping at the first (BR-02: "collect ALL statically-determinable errors").
376
+ * Pure — no I/O, no mutation of `manifest`.
377
+ *
378
+ * @throws Nothing — validation failures are reported via the returned `errors` array, never a
379
+ * thrown error (this function itself cannot fail; a malformed top-level shape, e.g. `manifest`
380
+ * being `null` or an array, is itself a `MANIFEST_MALFORMED` entry in the result, not a throw).
381
+ * @complexity O(fields.length + capabilities.length + hooks.length) — bounded by one manifest's
382
+ * own declared arrays, never by external/unbounded input.
383
+ */
384
+ export function validateManifest(required, _optional = {}) {
385
+ const { manifest, folderName, builtInIds } = required;
386
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
387
+ return { errors: [malformed("tovu.plugin.json must be a JSON object")] };
388
+ }
389
+ // Treat the input as a read-only bag of unknown values — never assigned back into.
390
+ const raw = manifest;
391
+ const { errors: idErrors, id } = validateId(raw, folderName, builtInIds, required.coreOwnerName);
392
+ const errors = [
393
+ ...validateKeys(raw),
394
+ ...idErrors,
395
+ ...validateIdentityFields(raw),
396
+ ...validateEngine(raw),
397
+ ...validateTier(raw),
398
+ ...validateCapabilities(raw, required.capabilityVocabulary),
399
+ ...validateHooks(raw, required.pluginSdkBinding.hookIds),
400
+ ...validateFields(raw, id),
401
+ ...validateContributes(raw, id),
402
+ // AW-7 Tier 1: `contentTypes` grammar and the tier-1 "no code surface" rule.
403
+ ...required.declarativeContentTypes.validateManifest({ manifest: raw }).errors,
404
+ ];
405
+ return { errors };
406
+ }
407
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,25 @@
1
+ import type { BuiltInPluginSource, PluginDiscoveryRecord } from "../discovery-types.js";
2
+ import type { ManifestHostPorts, PluginTierPolicy } from "../ports.js";
3
+ export type { BuiltInPluginSource, PluginDiscoveryRecord } from "../discovery-types.js";
4
+ export interface DiscoverPluginsRequired extends ManifestHostPorts {
5
+ readonly builtIns: readonly BuiltInPluginSource[];
6
+ readonly installDir?: string;
7
+ readonly tierPolicy: PluginTierPolicy;
8
+ }
9
+ export type DiscoverPluginsOptional = Record<string, never>;
10
+ /**
11
+ * The absolute entry-file path for a discovered SITE plugin (REQ-02's fixed `server/index.mjs`
12
+ * package layout, ADR-004) — the exact path `loadPlugin()`'s `entryPath` param expects, and the
13
+ * same join `discoverOneSiteCandidate()` below already performs internally for its manifest read.
14
+ * Exported so a composition root resolving a dynamic site-sourced load target (`plugin-runtime.ts`)
15
+ * does not re-derive this convention independently and risk it drifting from discovery's own.
16
+ *
17
+ * @complexity O(1) — pure path join, no I/O.
18
+ */
19
+ export declare function siteEntryPath({ installDir, id, version }: {
20
+ installDir: string;
21
+ id: string;
22
+ version: string;
23
+ }, _optional?: Record<string, never>): string;
24
+ export declare function discoverPlugins(required: DiscoverPluginsRequired, _optional?: DiscoverPluginsOptional): Promise<readonly PluginDiscoveryRecord[]>;
25
+ //# sourceMappingURL=discovery.d.ts.map
@@ -0,0 +1,217 @@
1
+ /** Site tier admission belongs to tierPolicy.siteErrors; static validation uses host-supplied
2
+ * catalogs and declaration grammar. */
3
+ /**
4
+ * @file `discoverPlugins()` — enumerate built-in + site plugins with status (SPEC-005 REQ-02/03,
5
+ * EC-08/EC-09, TB-01, DUP-01).
6
+ *
7
+ * Purpose:
8
+ * Read-only enumeration. Scans the install-dir's `plugins/<id>/<version>/` tree (REQ-02) plus the
9
+ * compiled-in built-in registry, performs BR-02 step (1)'s package-level checks (size, disallowed
10
+ * files, `server/index.mjs` presence — see `manifest.ts`'s header for why those checks live here
11
+ * rather than in `validateManifest()`), delegates manifest/identity/capability/hook/field checks to
12
+ * `validateManifest()`, and returns one `PluginDiscoveryRecord` per discovered id with every
13
+ * applicable error recorded — never throws for an individual plugin's own validation failure
14
+ * (errors are data, not control flow; REQ-10/`PLUGINS_LIST` lists every discovered plugin, valid or
15
+ * not).
16
+ *
17
+ * Never `import()`s plugin code — that is `loader.ts`'s job, gated by integrity/`sdkRange` first
18
+ * (BR-01, CIC U-001). Discovery only reads bytes to hash/measure/list them.
19
+ *
20
+ * Architectural role:
21
+ * TDD-certified implementation (implementation outline C-007). Signature and JSDoc are
22
+ * design-frozen; `discoverPlugins()` validates built-ins, selects the latest installed site
23
+ * version per id, records candidate-local errors without aborting discovery, marks duplicate ids,
24
+ * and returns deterministic TB-01 ordering.
25
+ */
26
+ import { readdir, readFile } from "node:fs/promises";
27
+ import path from "node:path";
28
+ import * as semver from "semver";
29
+ import { validateManifest } from "../manifest.js";
30
+ /**
31
+ * Enumerates every built-in and (when `installDir` is present) site-installed plugin, in TB-01
32
+ * order (built-ins first by id ascending, then site plugins by id ascending). When two installed
33
+ * versions of one site plugin id exist, only the latest-by-semver is included in the result (the
34
+ * other stays dormant on disk, EC-08/AC-09) — the loader (not discovery) is what actually imports
35
+ * the winning version later.
36
+ *
37
+ * @throws Never for an individual plugin's own validation/package failure — that plugin's record
38
+ * simply carries a non-empty `errors[]` and a non-`valid` `status`. May reject for a genuine
39
+ * infrastructure failure (e.g. `installDir` exists but is unreadable due to a permissions error)
40
+ * that is not itself one specific plugin's fault.
41
+ * @complexity O(n) over installed-plugin count, bounded I/O per candidate (one directory listing
42
+ * + manifest read + per-file size stat).
43
+ */
44
+ const VALID_TIERS = new Set(["tier-1", "tier-2", "tier-3"]);
45
+ /** Last-resort display tier when a malformed manifest has no validated tier. Every discovery
46
+ * record needs a renderable tier (REQ-18/AC-26); this fallback does not grant executable admission. */
47
+ const FALLBACK_TIER = "tier-3";
48
+ /** Safely reads a JSON value's string property, or `undefined` when absent/wrong-typed. */
49
+ function readStringField(value, key) {
50
+ if (typeof value !== "object" || value === null)
51
+ return undefined;
52
+ const raw = value[key];
53
+ return typeof raw === "string" ? raw : undefined;
54
+ }
55
+ function readTierField(value) {
56
+ const raw = readStringField(value, "tier");
57
+ return raw !== undefined && VALID_TIERS.has(raw) ? raw : FALLBACK_TIER;
58
+ }
59
+ /** Parses one `tovu.plugin.json` file's bytes; unparseable JSON becomes `null` — `validateManifest`
60
+ * already reports a `MANIFEST_MALFORMED` entry for any non-object value (its own top-level guard),
61
+ * so a parse failure and a wrong-shape object are handled through the exact same code path. */
62
+ function parseManifestJson(raw) {
63
+ try {
64
+ return JSON.parse(raw);
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ function toDiscoveryRecord(params) {
71
+ const isValid = params.errors.length === 0;
72
+ return {
73
+ id: params.id,
74
+ name: params.name,
75
+ version: params.version,
76
+ source: params.source,
77
+ tier: readTierField(params.manifestValue),
78
+ status: isValid ? "valid" : "invalid",
79
+ errors: params.errors,
80
+ // Safe only because `isValid` means `validateManifest()` already reported zero errors against
81
+ // this exact value — an invalid candidate's `manifestValue` is never cast (see the field's own
82
+ // doc on `PluginDiscoveryRecord`).
83
+ manifest: isValid ? params.manifestValue : undefined,
84
+ };
85
+ }
86
+ /**
87
+ * The absolute entry-file path for a discovered SITE plugin (REQ-02's fixed `server/index.mjs`
88
+ * package layout, ADR-004) — the exact path `loadPlugin()`'s `entryPath` param expects, and the
89
+ * same join `discoverOneSiteCandidate()` below already performs internally for its manifest read.
90
+ * Exported so a composition root resolving a dynamic site-sourced load target (`plugin-runtime.ts`)
91
+ * does not re-derive this convention independently and risk it drifting from discovery's own.
92
+ *
93
+ * @complexity O(1) — pure path join, no I/O.
94
+ */
95
+ export function siteEntryPath({ installDir, id, version }, _optional = {}) {
96
+ return path.join(installDir, id, version, "server", "index.mjs");
97
+ }
98
+ /** One directory entry directly under `installDir` — a candidate plugin "id slot" that may contain
99
+ * one or more version subdirectories (REQ-02's `plugins/<id>/<version>/` layout). */
100
+ async function listInstalledPluginIdFolders(installDir) {
101
+ try {
102
+ const entries = await readdir(installDir, { withFileTypes: true });
103
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
104
+ }
105
+ catch (error) {
106
+ if (error?.code === "ENOENT")
107
+ return [];
108
+ throw error;
109
+ }
110
+ }
111
+ /** Picks the latest-by-semver version subdirectory under one id folder (AC-09/EC-08) — the other
112
+ * installed versions stay dormant on disk, never surfaced as a second row. Non-semver directory
113
+ * names sort last (defensive; every certified fixture uses valid semver directory names). */
114
+ async function pickLatestVersionFolder(idFolderPath) {
115
+ const entries = await readdir(idFolderPath, { withFileTypes: true });
116
+ const versionNames = entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
117
+ if (versionNames.length === 0)
118
+ return null;
119
+ const sorted = [...versionNames].sort((a, b) => {
120
+ const aValid = semver.valid(a);
121
+ const bValid = semver.valid(b);
122
+ if (aValid && bValid)
123
+ return semver.rcompare(aValid, bValid);
124
+ if (aValid)
125
+ return -1;
126
+ if (bValid)
127
+ return 1;
128
+ return b.localeCompare(a);
129
+ });
130
+ return sorted[0] ?? null;
131
+ }
132
+ /**
133
+ * The installer refuses a sideloaded tier-2 package (`install.ts`'s `checkTierAndCode`): a package
134
+ * cannot grant itself the verified-publisher tier, and a tier-2 worker is not a security sandbox
135
+ * (it can still import `node:fs`). A package placed straight into `installDir` skips the installer,
136
+ * so discovery applies the same rule — enable and boot load only `valid` records, so neither ever
137
+ * runs one.
138
+ *
139
+ * @complexity O(1).
140
+ */
141
+ async function discoverOneSiteCandidate(installDir, idFolderName, builtInIds, host) {
142
+ const idFolderPath = path.join(installDir, idFolderName);
143
+ const versionFolderName = await pickLatestVersionFolder(idFolderPath);
144
+ if (versionFolderName === null)
145
+ return null;
146
+ const manifestPath = path.join(idFolderPath, versionFolderName, "tovu.plugin.json");
147
+ let manifestValue = null;
148
+ let missing = false;
149
+ try {
150
+ manifestValue = parseManifestJson(await readFile(manifestPath, "utf8"));
151
+ }
152
+ catch (error) {
153
+ if (error?.code === "ENOENT") {
154
+ missing = true;
155
+ }
156
+ else {
157
+ throw error;
158
+ }
159
+ }
160
+ const errors = missing
161
+ ? [{ code: "MANIFEST_MISSING", file: "tovu.plugin.json", message: "tovu.plugin.json was not found" }]
162
+ : [...validateManifest({ ...host, manifest: manifestValue, folderName: idFolderName, builtInIds }).errors, ...host.tierPolicy.siteErrors({ manifestValue })];
163
+ const id = readStringField(manifestValue, "id") ?? idFolderName;
164
+ const name = readStringField(manifestValue, "name") ?? idFolderName;
165
+ return toDiscoveryRecord({ id, name, version: versionFolderName, source: "site", manifestValue, errors });
166
+ }
167
+ /** DUP-01 (`ID_DUPLICATE` half — `SHADOWS_BUILT_IN` is already handled per-record inside
168
+ * `validateManifest`, which only ever sees one candidate at a time): a case-insensitive id
169
+ * collision between two SITE plugins can only be detected once every candidate is known, so this
170
+ * runs as a whole-set post-pass over the already-built site records. */
171
+ function markCaseInsensitiveDuplicates(records) {
172
+ const countByLowerId = new Map();
173
+ for (const record of records) {
174
+ const key = record.id.toLowerCase();
175
+ countByLowerId.set(key, (countByLowerId.get(key) ?? 0) + 1);
176
+ }
177
+ return records.map((record) => {
178
+ const isDuplicate = (countByLowerId.get(record.id.toLowerCase()) ?? 0) > 1;
179
+ if (!isDuplicate)
180
+ return record;
181
+ const errors = [
182
+ ...record.errors,
183
+ { code: "ID_DUPLICATE", file: null, message: `id '${record.id}' collides case-insensitively with another installed site plugin` },
184
+ ];
185
+ return { ...record, errors, status: "invalid" };
186
+ });
187
+ }
188
+ /** TB-01: built-ins first (id ascending), then site plugins (id ascending) — the same ordering
189
+ * `hook-registry.ts`'s composition uses, so `PLUGINS_LIST` and hook-composition order never
190
+ * diverge. */
191
+ function orderTb01(records) {
192
+ const rank = (source) => (source === "built-in" ? 0 : 1);
193
+ return [...records].sort((a, b) => rank(a.source) - rank(b.source) || a.id.localeCompare(b.id));
194
+ }
195
+ export async function discoverPlugins(required, _optional = {}) {
196
+ const { builtIns, installDir } = required;
197
+ const builtInIds = builtIns.map((b) => b.manifest.id);
198
+ const builtInRecords = builtIns.map((builtIn) => {
199
+ const errors = validateManifest({ ...required, manifest: builtIn.manifest, folderName: builtIn.manifest.id, builtInIds: [] }).errors;
200
+ return toDiscoveryRecord({
201
+ id: builtIn.manifest.id,
202
+ name: builtIn.manifest.name,
203
+ version: builtIn.manifest.version,
204
+ source: "built-in",
205
+ manifestValue: builtIn.manifest,
206
+ errors,
207
+ });
208
+ });
209
+ let siteRecords = [];
210
+ if (installDir !== undefined) {
211
+ const idFolders = await listInstalledPluginIdFolders(installDir);
212
+ const candidates = await Promise.all(idFolders.map((idFolderName) => discoverOneSiteCandidate(installDir, idFolderName, builtInIds, required)));
213
+ siteRecords = markCaseInsensitiveDuplicates(candidates.filter((r) => r !== null));
214
+ }
215
+ return orderTb01([...builtInRecords, ...siteRecords]);
216
+ }
217
+ //# sourceMappingURL=discovery.js.map
@@ -0,0 +1,7 @@
1
+ /** Node file effects and ordered loading. Executable import and archive parsing are required host ports. */
2
+ export * from './discovery.js';
3
+ export * from './loader.js';
4
+ export * from './package-files.js';
5
+ export * from './install.js';
6
+ export * from './module-snapshot.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,7 @@
1
+ /** Node file effects and ordered loading. Executable import and archive parsing are required host ports. */
2
+ export * from './discovery.js';
3
+ export * from './loader.js';
4
+ export * from './package-files.js';
5
+ export * from './install.js';
6
+ export * from './module-snapshot.js';
7
+ //# sourceMappingURL=index.js.map