@jini-ai/plugins 0.4.0 → 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.
@@ -25,6 +25,7 @@
25
25
  * `errors[]` — it never throws. Verified against `__tests__/unit/manifest.unit.test.ts`.
26
26
  */
27
27
  import * as semver from "semver";
28
+ import { readPluginIdentity, validatePluginIdentity } from "@jini-ai/core/plugin-directory";
28
29
  /**
29
30
  * Validates one already-parsed manifest against BR-02 steps (2)-(6), collecting every applicable
30
31
  * error rather than stopping at the first (BR-02: "collect ALL statically-determinable errors").
@@ -50,7 +51,7 @@ const REQUIRED_KEYS = [
50
51
  "integrity",
51
52
  ];
52
53
  /** 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 OPTIONAL_KEYS = ["adminSurfaces", "contentTypes", "provenance", "dependencies", "contributes", "keywords", "extensions"];
54
55
  const ALLOWED_KEYS = new Set([...REQUIRED_KEYS, ...OPTIONAL_KEYS]);
55
56
  const VALID_TIERS = new Set(["tier-1", "tier-2", "tier-3"]);
56
57
  const VALID_FIELD_TYPES = new Set(["string", "integer", "number", "boolean"]);
@@ -85,6 +86,11 @@ function validateIdFormat(id) {
85
86
  }
86
87
  return [];
87
88
  }
89
+ /** Shared id grammar for source paths and manifests. Identity admission (reserved ids, folder
90
+ * match and built-in shadowing) still belongs to full manifest validation. */
91
+ export function validatePluginIdFormat(required, _optional = {}) {
92
+ return validateIdFormat(required.id);
93
+ }
88
94
  /** The owner id the claim system gives Tovu core (`plugin-claims.ts` re-exports it). Conflict
89
95
  * detection never compares an owner with itself, so a plugin with this id would never conflict with
90
96
  * core's reserved routes, tools or permissions — it is refused as an id instead. */
@@ -391,6 +397,7 @@ export function validateManifest(required, _optional = {}) {
391
397
  const { errors: idErrors, id } = validateId(raw, folderName, builtInIds, required.coreOwnerName);
392
398
  const errors = [
393
399
  ...validateKeys(raw),
400
+ ...validatePluginIdentity({ manifest: raw, namespace: required.identityNamespace ?? "tovu" }).errors.map(message => ({ code: "PLUGIN_IDENTITY_INVALID", file: null, message })),
394
401
  ...idErrors,
395
402
  ...validateIdentityFields(raw),
396
403
  ...validateEngine(raw),
@@ -402,6 +409,9 @@ export function validateManifest(required, _optional = {}) {
402
409
  // AW-7 Tier 1: `contentTypes` grammar and the tier-1 "no code surface" rule.
403
410
  ...required.declarativeContentTypes.validateManifest({ manifest: raw }).errors,
404
411
  ];
405
- return { errors };
412
+ const warnings = errors.length === 0
413
+ ? readPluginIdentity({ manifest: raw, name: id, namespace: required.identityNamespace ?? "tovu" }).warnings
414
+ : [];
415
+ return { errors, warnings };
406
416
  }
407
417
  //# sourceMappingURL=manifest.js.map
@@ -6,7 +6,14 @@ export interface DiscoverPluginsRequired extends ManifestHostPorts {
6
6
  readonly installDir?: string;
7
7
  readonly tierPolicy: PluginTierPolicy;
8
8
  }
9
- export type DiscoverPluginsOptional = Record<string, never>;
9
+ /** Activation/boot may pin an enabled revision while newer packages remain installed for review.
10
+ * Admin discovery defaults to the latest version; a missing pinned version never falls forward. */
11
+ export interface DiscoverPluginsOptional {
12
+ readonly versions?: ReadonlyMap<string, string>;
13
+ }
14
+ export declare class PluginDiscoveryVersionError extends Error {
15
+ constructor(message: string);
16
+ }
10
17
  /**
11
18
  * The absolute entry-file path for a discovered SITE plugin (REQ-02's fixed `server/index.mjs`
12
19
  * package layout, ADR-004) — the exact path `loadPlugin()`'s `entryPath` param expects, and the
@@ -21,5 +28,5 @@ export declare function siteEntryPath({ installDir, id, version }: {
21
28
  id: string;
22
29
  version: string;
23
30
  }, _optional?: Record<string, never>): string;
24
- export declare function discoverPlugins(required: DiscoverPluginsRequired, _optional?: DiscoverPluginsOptional): Promise<readonly PluginDiscoveryRecord[]>;
31
+ export declare function discoverPlugins(required: DiscoverPluginsRequired, optional?: DiscoverPluginsOptional): Promise<readonly PluginDiscoveryRecord[]>;
25
32
  //# sourceMappingURL=discovery.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { readPluginIdentity } from "@jini-ai/core/plugin-directory";
1
2
  /** Site tier admission belongs to tierPolicy.siteErrors; static validation uses host-supplied
2
3
  * catalogs and declaration grammar. */
3
4
  /**
@@ -27,6 +28,9 @@ import { readdir, readFile } from "node:fs/promises";
27
28
  import path from "node:path";
28
29
  import * as semver from "semver";
29
30
  import { validateManifest } from "../manifest.js";
31
+ export class PluginDiscoveryVersionError extends Error {
32
+ constructor(message) { super(message); this.name = 'PluginDiscoveryVersionError'; }
33
+ }
30
34
  /**
31
35
  * Enumerates every built-in and (when `installDir` is present) site-installed plugin, in TB-01
32
36
  * order (built-ins first by id ascending, then site plugins by id ascending). When two installed
@@ -100,7 +104,9 @@ export function siteEntryPath({ installDir, id, version }, _optional = {}) {
100
104
  async function listInstalledPluginIdFolders(installDir) {
101
105
  try {
102
106
  const entries = await readdir(installDir, { withFileTypes: true });
103
- return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
107
+ // Hidden working/staging areas (notably .drafts) are never install candidates. Valid manifest
108
+ // ids cannot start with a dot, so no valid installed package loses discovery reachability.
109
+ return entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.')).map((entry) => entry.name);
104
110
  }
105
111
  catch (error) {
106
112
  if (error?.code === "ENOENT")
@@ -138,9 +144,13 @@ async function pickLatestVersionFolder(idFolderPath) {
138
144
  *
139
145
  * @complexity O(1).
140
146
  */
141
- async function discoverOneSiteCandidate(installDir, idFolderName, builtInIds, host) {
147
+ async function discoverOneSiteCandidate(installDir, idFolderName, builtInIds, host, options = {}) {
142
148
  const idFolderPath = path.join(installDir, idFolderName);
143
- const versionFolderName = await pickLatestVersionFolder(idFolderPath);
149
+ const requestedVersion = options.versions?.get(idFolderName);
150
+ if (requestedVersion !== undefined && (!semver.valid(requestedVersion) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(requestedVersion))) {
151
+ throw new PluginDiscoveryVersionError('The requested plugin activation version is not a safe semantic version.');
152
+ }
153
+ const versionFolderName = requestedVersion ?? await pickLatestVersionFolder(idFolderPath);
144
154
  if (versionFolderName === null)
145
155
  return null;
146
156
  const manifestPath = path.join(idFolderPath, versionFolderName, "tovu.plugin.json");
@@ -192,7 +202,7 @@ function orderTb01(records) {
192
202
  const rank = (source) => (source === "built-in" ? 0 : 1);
193
203
  return [...records].sort((a, b) => rank(a.source) - rank(b.source) || a.id.localeCompare(b.id));
194
204
  }
195
- export async function discoverPlugins(required, _optional = {}) {
205
+ export async function discoverPlugins(required, optional = {}) {
196
206
  const { builtIns, installDir } = required;
197
207
  const builtInIds = builtIns.map((b) => b.manifest.id);
198
208
  const builtInRecords = builtIns.map((builtIn) => {
@@ -209,9 +219,23 @@ export async function discoverPlugins(required, _optional = {}) {
209
219
  let siteRecords = [];
210
220
  if (installDir !== undefined) {
211
221
  const idFolders = await listInstalledPluginIdFolders(installDir);
212
- const candidates = await Promise.all(idFolders.map((idFolderName) => discoverOneSiteCandidate(installDir, idFolderName, builtInIds, required)));
222
+ const candidates = await Promise.all(idFolders.map((idFolderName) => discoverOneSiteCandidate(installDir, idFolderName, builtInIds, required, optional)));
213
223
  siteRecords = markCaseInsensitiveDuplicates(candidates.filter((r) => r !== null));
214
224
  }
215
- return orderTb01([...builtInRecords, ...siteRecords]);
225
+ const records = orderTb01([...builtInRecords, ...siteRecords]);
226
+ const qualifiedIds = new Set();
227
+ // TB-01 places built-ins first: the incumbent keeps its id; only later claims are invalid.
228
+ // Disabled valid installs still own ids.
229
+ return records.map(record => {
230
+ if (record.status !== "valid" || !record.manifest)
231
+ return record;
232
+ const identity = readPluginIdentity({ manifest: record.manifest, name: record.id, namespace: required.identityNamespace ?? "tovu" });
233
+ if (!qualifiedIds.has(identity.id)) {
234
+ qualifiedIds.add(identity.id);
235
+ return { ...record, warnings: identity.warnings };
236
+ }
237
+ return { ...record, status: "invalid", manifest: undefined, warnings: identity.warnings,
238
+ errors: [...record.errors, { code: "PLUGIN_ID_DUPLICATE", file: null, message: `duplicate publisher-qualified plugin id '${identity.id}'` }], };
239
+ });
216
240
  }
217
241
  //# sourceMappingURL=discovery.js.map
@@ -4,4 +4,5 @@ export * from './loader.js';
4
4
  export * from './package-files.js';
5
5
  export * from './install.js';
6
6
  export * from './module-snapshot.js';
7
+ export * from './source-drafts.js';
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -4,4 +4,5 @@ export * from './loader.js';
4
4
  export * from './package-files.js';
5
5
  export * from './install.js';
6
6
  export * from './module-snapshot.js';
7
+ export * from './source-drafts.js';
7
8
  //# sourceMappingURL=index.js.map
@@ -7,6 +7,10 @@ export declare class PluginInstallError extends Error {
7
7
  constructor(code: string, message: string);
8
8
  }
9
9
  export interface PluginInstallPreview {
10
+ readonly warnings?: readonly string[];
11
+ readonly publisherId?: string;
12
+ readonly provides?: readonly string[];
13
+ readonly keywords?: readonly string[];
10
14
  id: string;
11
15
  name: string;
12
16
  version: string;
@@ -33,10 +37,20 @@ export type PluginInstallInput = ({
33
37
  replace?: boolean;
34
38
  };
35
39
  export interface PluginInstallDeps extends ManifestHostPorts {
40
+ /** Internal authoring path only: append immutable versions while retaining rollback bytes.
41
+ * Same-version replacement still refuses enabled plugins. Ordinary installs keep their policy. */
42
+ readonly versionAppend?: boolean;
43
+ readonly warn?: (message: string) => void;
36
44
  readonly archiveReader: ArchiveReaderPort;
37
45
  readonly tierPolicy: PluginTierPolicy;
38
46
  installDir: string;
39
47
  builtInIds: readonly string[];
48
+ /** Built-in publisher reservations, independent of their local storage ids. Hosts supplying
49
+ * only builtInIds must wrap publication in their cross-family identity-admission transaction;
50
+ * publisher identities cannot be inferred from a local name or extension namespace. */
51
+ readonly builtInManifests?: readonly PluginManifest[];
52
+ /** Installed-neighbour reads only; extraction and publication retain their native effects. */
53
+ readonly identityFilesystem?: Pick<typeof import('node:fs/promises'), 'lstat' | 'readdir' | 'readFile'>;
40
54
  repo: Pick<PluginActivationRepoPort, "listAll">;
41
55
  /** Names the staged manifest would take that core or an enabled plugin already holds. Install is
42
56
  * site-wide but activation is per workspace: the admin root answers for the workspace it serves
@@ -46,26 +60,57 @@ export interface PluginInstallDeps extends ManifestHostPorts {
46
60
  }, optional?: Record<string, never>) => Promise<readonly PluginConflict[]>;
47
61
  }
48
62
  export interface PluginInstallerPort {
49
- preview(required: PluginInstallInput, optional?: Record<string, never>): Promise<PluginInstallPreview>;
63
+ preview(required: PluginInstallInput, optional?: PluginInstallOptions): Promise<PluginInstallPreview>;
50
64
  install(required: PluginInstallInput & {
51
65
  expectedDigest: string;
52
- }, optional?: Record<string, never>): Promise<PluginInstallPreview>;
66
+ }, optional?: PluginInstallOptions): Promise<PluginInstallPreview>;
67
+ }
68
+ /** Not a model input: the source authoring service opts into immutable version publication. */
69
+ export interface PluginInstallOptions {
70
+ readonly versionAppend?: boolean;
71
+ }
72
+ export interface PluginSnapshotLimits {
73
+ readonly maxEntries?: number;
74
+ readonly maxFileBytes?: number;
75
+ readonly maxTotalBytes?: number;
76
+ }
77
+ /** Retained bytes plus the entry count, including empty directories, for authoring preflight. */
78
+ export interface PluginPackageSnapshot extends Map<string, Buffer> {
79
+ readonly entryCount: number;
53
80
  }
54
81
  /** Activation callbacks share this guard; the activation service compensates a rejected enable. */
55
82
  export declare function assertPluginInstallIdle(required: {
56
83
  installDir: string;
57
84
  }, _optional?: Record<string, never>): Promise<void>;
85
+ /** Retire obsolete immutable source releases after a successful controlled reload.
86
+ * All workspace active pointers survive, plus the newest three versions for rollback.
87
+ * Uses the installer's publication lock so pruning cannot overlap a package install.
88
+ * @returns Retired version names; dotfiles are unrelated metadata and remain untouched.
89
+ * @throws PluginInstallError for unsafe paths, invalid version slots or an active install.
90
+ * @complexity O(V log V + A) for V installed versions and A activation rows, then one removal per retired version.
91
+ */
92
+ export declare function pruneSitePluginVersions(required: {
93
+ id: string;
94
+ installDir: string;
95
+ repo: Pick<PluginActivationRepoPort, 'listAll'>;
96
+ }, _optional?: Record<string, never>): Promise<readonly string[]>;
58
97
  /** Loader uses the same bounded, link-free byte snapshot, then verifies the retained bytes. */
59
98
  export declare function snapshotSitePluginPackage(required: {
60
99
  sourceDir: string;
61
- }, _optional?: Record<string, never>): Promise<Map<string, Buffer>>;
100
+ }, optional?: PluginSnapshotLimits): Promise<PluginPackageSnapshot>;
101
+ /** The installer's consent digest, also used to bind site-authored provenance to exact bytes.
102
+ * @returns A SHA-256 digest covering the manifest and every retained file.
103
+ */
104
+ export declare function digestSitePluginSnapshot(required: {
105
+ files: ReadonlyMap<string, Buffer>;
106
+ }, _optional?: {}): string;
62
107
  export declare function computePluginIntegrity(required: {
63
108
  sourceDir: string;
64
109
  }, _optional?: Record<string, never>): Promise<Record<string, string>>;
65
110
  export declare function previewSitePluginInstall(required: PluginInstallInput & {
66
111
  deps: PluginInstallDeps;
67
112
  }, _optional?: Record<string, never>): Promise<PluginInstallPreview>;
68
- /** Directory lock is also cross-process: CLI and admin cannot replace the same site concurrently. */
113
+ /** Publication and retention use the same installer-owned cross-process lock. */
69
114
  export declare function installSitePlugin(required: PluginInstallInput & {
70
115
  expectedDigest: string;
71
116
  deps: PluginInstallDeps;
@@ -1,3 +1,4 @@
1
+ import { readPluginIdentity, assertPluginIdentityAvailable } from "@jini-ai/core/plugin-directory";
1
2
  /** Local-install environment consent is host-owned; archiveReader owns zip-slip/decompression
2
3
  * checks and tierPolicy.checkInstall owns publisher admission. */
3
4
  /** Site plugin folder installer governed by plugin-install-plan.md, M1a.
@@ -5,11 +6,11 @@
5
6
  * Staging is a sibling of discovery's root, on the same filesystem, so partial copies never list.
6
7
  */
7
8
  import { constants } from "node:fs";
8
- import { lstat, realpath, readdir, open, mkdir, mkdtemp, writeFile, rename, rm } from "node:fs/promises";
9
+ import { lstat, realpath, readdir, readFile, open, mkdir, mkdtemp, writeFile, rename, rm } from "node:fs/promises";
9
10
  import path from "node:path";
10
11
  import { createHash } from "node:crypto";
11
12
  import * as semver from "semver";
12
- import { validateManifest } from "../manifest.js";
13
+ import { validateManifest, validatePluginIdFormat } from "../manifest.js";
13
14
  export class PluginInstallError extends Error {
14
15
  code;
15
16
  constructor(code, message) {
@@ -42,7 +43,14 @@ export async function assertPluginInstallIdle(required, _optional = {}) {
42
43
  fail("PLUGIN_INSTALL_BUSY", "Another install is in progress.");
43
44
  }
44
45
  /** Retain the inspected bytes, rather than copying a mutable source after consent verification. */
45
- async function snapshot(sourceDir) {
46
+ async function snapshot(sourceDir, limits = {}) {
47
+ for (const limit of Object.values(limits)) {
48
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1))
49
+ fail('PLUGIN_SNAPSHOT_LIMIT_INVALID', 'Snapshot limits must be positive safe integers.');
50
+ }
51
+ const maxEntries = Math.min(limits.maxEntries ?? MAX_ENTRIES, MAX_ENTRIES);
52
+ const maxFileBytes = Math.min(limits.maxFileBytes ?? MAX_FILE_BYTES, MAX_FILE_BYTES);
53
+ const maxTotalBytes = Math.min(limits.maxTotalBytes ?? MAX_TOTAL_BYTES, MAX_TOTAL_BYTES);
46
54
  const files = new Map();
47
55
  let entries = 0;
48
56
  let total = 0;
@@ -51,7 +59,7 @@ async function snapshot(sourceDir) {
51
59
  if (!stat.isDirectory() || stat.isSymbolicLink())
52
60
  fail("PLUGIN_PACKAGE_UNSAFE", "Package directories must not be symbolic links.");
53
61
  for (const name of (await readdir(dir)).sort()) {
54
- if (++entries > MAX_ENTRIES)
62
+ if (++entries > maxEntries)
55
63
  fail("PLUGIN_PACKAGE_TOO_LARGE", "Package has too many entries.");
56
64
  const target = path.join(dir, name);
57
65
  const relative = prefix + name;
@@ -64,7 +72,7 @@ async function snapshot(sourceDir) {
64
72
  }
65
73
  if (!info.isFile() || info.nlink !== 1)
66
74
  fail("PLUGIN_PACKAGE_UNSAFE", "Only regular files without hard links are allowed.");
67
- if (info.size > MAX_FILE_BYTES || total + info.size > MAX_TOTAL_BYTES)
75
+ if (info.size > maxFileBytes || total + info.size > maxTotalBytes)
68
76
  fail("PLUGIN_PACKAGE_TOO_LARGE", "Package exceeds the file or total size limit.");
69
77
  const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
70
78
  try {
@@ -80,7 +88,7 @@ async function snapshot(sourceDir) {
80
88
  break;
81
89
  length += read.bytesRead;
82
90
  }
83
- if (length > MAX_FILE_BYTES || total + length > MAX_TOTAL_BYTES)
91
+ if (length > maxFileBytes || total + length > maxTotalBytes)
84
92
  fail("PLUGIN_PACKAGE_TOO_LARGE", "Package grew past its size limit.");
85
93
  if (length > info.size || (await handle.stat()).size !== length)
86
94
  fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
@@ -93,7 +101,7 @@ async function snapshot(sourceDir) {
93
101
  }
94
102
  }
95
103
  await walk(sourceDir, "");
96
- return files;
104
+ return Object.assign(files, { entryCount: entries });
97
105
  }
98
106
  /** Files a manifest-only package may carry: documentation, data and images — nothing a browser or
99
107
  * Node would execute. An allowlist, so a new script-like extension is refused by default (SVG is
@@ -135,7 +143,8 @@ function validatePackage(files, deps) {
135
143
  // The manifest's own messages, so a refused declaration says what is wrong with it.
136
144
  if (result.errors.length)
137
145
  fail("PLUGIN_MANIFEST_INVALID", result.errors.map((error) => error.message).join("; "));
138
- if (!candidate || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id) || typeof candidate.version !== "string" || !semver.valid(candidate.version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(candidate.version))
146
+ // validateManifest owns the id grammar; only the version needs extra path-safety checks.
147
+ if (!candidate || typeof candidate.version !== "string" || !semver.valid(candidate.version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(candidate.version))
139
148
  fail("PLUGIN_MANIFEST_INVALID", "Package manifest, id or version is invalid.");
140
149
  checkTierAndCode(candidate, files, deps.tierPolicy);
141
150
  if (typeof candidate.name !== "string" || !candidate.name.trim() || typeof candidate.sdkRange !== "string" || !semver.validRange(candidate.sdkRange))
@@ -152,37 +161,144 @@ function validatePackage(files, deps) {
152
161
  }
153
162
  async function checkDestination(manifest, input, deps) {
154
163
  const root = path.resolve(deps.installDir);
155
- const entries = await readdir(root).catch((e) => { if (e.code === "ENOENT")
164
+ const scan = deps.identityFilesystem ?? { lstat, readdir, readFile };
165
+ const entries = await scan.readdir(root).catch((e) => { if (e.code === "ENOENT")
156
166
  return []; throw e; });
167
+ const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace ?? "tovu" });
168
+ const candidate = { ...identity, family: "site-runtime", localId: manifest.id };
169
+ const builtIns = (deps.builtInManifests ?? []).map(builtIn => ({
170
+ ...readPluginIdentity({ manifest: builtIn, name: builtIn.id, namespace: deps.identityNamespace ?? "tovu" }),
171
+ family: "site-runtime", localId: builtIn.id, version: builtIn.version, enabled: false,
172
+ }));
173
+ try {
174
+ assertPluginIdentityAvailable({ candidate, installed: builtIns });
175
+ }
176
+ catch {
177
+ fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
178
+ }
179
+ const warnUnavailableSlot = (localId, error) => {
180
+ if (!['ENOENT', 'EACCES'].includes(error.code ?? ''))
181
+ throw error;
182
+ // A disappearing/unreadable neighbour is isolated; link refusals and other I/O faults remain fatal.
183
+ (deps.warn ?? console.warn)(`Plugin '${localId}': installed slot is unavailable; omitted from identity admission.`);
184
+ };
185
+ for (const localId of entries) {
186
+ const slot = path.join(root, localId);
187
+ let versions;
188
+ try {
189
+ const info = await scan.lstat(slot);
190
+ if (info.isSymbolicLink())
191
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
192
+ if (!info.isDirectory())
193
+ continue;
194
+ versions = await scan.readdir(slot);
195
+ }
196
+ catch (error) {
197
+ warnUnavailableSlot(localId, error);
198
+ continue;
199
+ }
200
+ for (const version of versions) {
201
+ if (!semver.valid(version))
202
+ continue;
203
+ const versionDir = path.join(slot, version);
204
+ try {
205
+ const versionInfo = await scan.lstat(versionDir);
206
+ if (versionInfo.isSymbolicLink())
207
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin version must not be a link.");
208
+ if (!versionInfo.isDirectory())
209
+ continue;
210
+ }
211
+ catch (error) {
212
+ warnUnavailableSlot(localId, error);
213
+ continue;
214
+ }
215
+ const manifestPath = path.join(versionDir, MANIFEST);
216
+ let installed;
217
+ try {
218
+ const manifestInfo = await scan.lstat(manifestPath);
219
+ if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink())
220
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin manifests must not be links.");
221
+ const installedManifest = JSON.parse(await scan.readFile(manifestPath, "utf8"));
222
+ installed = readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace ?? "tovu" });
223
+ }
224
+ catch (error) {
225
+ if (error instanceof PluginInstallError)
226
+ throw error;
227
+ // Preserve link refusals while isolating one broken unrelated manifest.
228
+ (deps.warn ?? console.warn)(`Plugin '${localId}': installed identity manifest is unreadable or invalid; omitted from identity admission.`);
229
+ continue;
230
+ }
231
+ try {
232
+ assertPluginIdentityAvailable({ candidate,
233
+ installed: [{ ...installed, family: "site-runtime", localId, version, enabled: false }] });
234
+ }
235
+ catch {
236
+ fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
237
+ }
238
+ }
239
+ }
157
240
  if (entries.some((name) => name.toLowerCase() === manifest.id.toLowerCase() && name !== manifest.id))
158
241
  fail("PLUGIN_ID_CONFLICT", "A plugin id differs only by letter case.");
159
242
  if (await exists(path.join(path.dirname(root), path.basename(root) + "-trash", manifest.id)))
160
243
  fail("PLUGIN_IN_TRASH", "Restore or delete this plugin in Trash first.");
161
- if ((await deps.repo.listAll()).some((row) => row.pluginId.toLowerCase() === manifest.id.toLowerCase() && row.enabled))
162
- fail("PLUGIN_ENABLED", "Turn the plugin off in every workspace first.");
163
244
  const slot = path.join(root, manifest.id);
245
+ const versionExists = await exists(path.join(slot, manifest.version));
246
+ if ((!deps.versionAppend || versionExists) && (await deps.repo.listAll()).some((row) => row.pluginId.toLowerCase() === manifest.id.toLowerCase() && row.enabled))
247
+ fail("PLUGIN_ENABLED", "Turn the plugin off in every workspace first.");
164
248
  if (!(await exists(slot)))
165
249
  return undefined;
166
250
  const stat = await lstat(slot);
167
251
  if (!stat.isDirectory() || stat.isSymbolicLink())
168
252
  fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
169
- const versions = await readdir(slot);
253
+ const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
170
254
  if (versions.some((version) => !semver.valid(version)))
171
255
  fail("PLUGIN_ID_CONFLICT", "Existing plugin has an unrecognized version folder.");
172
256
  const latest = versions.sort(semver.rcompare)[0];
173
257
  if (latest && semver.lt(manifest.version, latest))
174
258
  fail("PLUGIN_DOWNGRADE", "Installing an older version is not allowed.");
175
- if (versions.some((version) => semver.eq(version, manifest.version)) && !input.replace)
176
- fail("PLUGIN_VERSION_EXISTS", "This version exists. Choose replace explicitly.");
259
+ if (versions.some((version) => semver.eq(version, manifest.version)) && (deps.versionAppend || !input.replace))
260
+ fail("PLUGIN_VERSION_EXISTS", deps.versionAppend ? "Version append requires a new version; installed bytes are immutable." : "This version exists. Choose replace explicitly.");
177
261
  return latest;
178
262
  }
263
+ /** Retire obsolete immutable source releases after a successful controlled reload.
264
+ * All workspace active pointers survive, plus the newest three versions for rollback.
265
+ * Uses the installer's publication lock so pruning cannot overlap a package install.
266
+ * @returns Retired version names; dotfiles are unrelated metadata and remain untouched.
267
+ * @throws PluginInstallError for unsafe paths, invalid version slots or an active install.
268
+ * @complexity O(V log V + A) for V installed versions and A activation rows, then one removal per retired version.
269
+ */
270
+ export async function pruneSitePluginVersions(required, _optional = {}) {
271
+ if (validatePluginIdFormat({ id: required.id }).length)
272
+ fail('PLUGIN_PACKAGE_UNSAFE', 'Invalid plugin id.');
273
+ const root = path.resolve(required.installDir);
274
+ const slot = path.join(root, required.id);
275
+ for (const target of [root, slot]) {
276
+ const info = await lstat(target);
277
+ if (!info.isDirectory() || info.isSymbolicLink())
278
+ fail('PLUGIN_PACKAGE_UNSAFE', 'Installed plugin directory must not be a link.');
279
+ }
280
+ return withPluginInstallLock({ root, run: async () => {
281
+ const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
282
+ if (versions.some(version => !semver.valid(version)))
283
+ fail('PLUGIN_ID_CONFLICT', 'Existing plugin has an unrecognized version folder.');
284
+ const retained = new Set(versions.sort(semver.rcompare).slice(0, 3));
285
+ for (const row of await required.repo.listAll())
286
+ if (row.pluginId === required.id && row.enabled)
287
+ retained.add(row.version);
288
+ const retired = versions.filter(version => !retained.has(version));
289
+ for (const version of retired)
290
+ await rm(path.join(slot, version), { recursive: true, force: true });
291
+ return retired;
292
+ } });
293
+ }
179
294
  async function inspect(input, deps) {
180
295
  const files = input.archive !== undefined ? new Map([...await deps.archiveReader({ archive: input.archive })].map(([key, bytes]) => [key, Buffer.from(bytes)])) : await inspectFolder(input.sourceDir, deps);
181
296
  const manifest = validatePackage(files, deps);
182
297
  const upgradeFrom = await checkDestination(manifest, input, deps);
183
298
  // Include manifest bytes: changed capabilities/name/version must invalidate human consent too.
184
- const digest = hash(Buffer.from(JSON.stringify([...files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
185
- const preview = { id: manifest.id, name: manifest.name, version: manifest.version, tier: manifest.tier, capabilities: manifest.capabilities, hooks: manifest.hooks, hasCode: manifest.tier !== "tier-1", contentTypes: deps.declarativeContentTypes.parse({ value: manifest.contentTypes }).decls.map((decl) => decl.key), conflicts: await deps.conflicts({ manifest }), digest, ...(upgradeFrom ? { upgradeFrom } : {}) };
299
+ const digest = digestSitePluginSnapshot({ files });
300
+ const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace ?? "tovu" });
301
+ const preview = { warnings: identity.warnings, publisherId: identity.id, provides: identity.provides, keywords: identity.keywords, id: manifest.id, name: manifest.name, version: manifest.version, tier: manifest.tier, capabilities: manifest.capabilities, hooks: manifest.hooks, hasCode: manifest.tier !== "tier-1", contentTypes: deps.declarativeContentTypes.parse({ value: manifest.contentTypes }).decls.map((decl) => decl.key), conflicts: await deps.conflicts({ manifest }), digest, ...(upgradeFrom ? { upgradeFrom } : {}) };
186
302
  return { files, manifest, preview };
187
303
  }
188
304
  async function inspectFolder(source, deps) {
@@ -208,8 +324,14 @@ async function inspectFolder(source, deps) {
208
324
  return snapshot(sourceDir);
209
325
  }
210
326
  /** Loader uses the same bounded, link-free byte snapshot, then verifies the retained bytes. */
211
- export async function snapshotSitePluginPackage(required, _optional = {}) {
212
- return snapshot(required.sourceDir);
327
+ export async function snapshotSitePluginPackage(required, optional = {}) {
328
+ return snapshot(required.sourceDir, optional);
329
+ }
330
+ /** The installer's consent digest, also used to bind site-authored provenance to exact bytes.
331
+ * @returns A SHA-256 digest covering the manifest and every retained file.
332
+ */
333
+ export function digestSitePluginSnapshot(required, _optional = {}) {
334
+ return hash(Buffer.from(JSON.stringify([...required.files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
213
335
  }
214
336
  export async function computePluginIntegrity(required, _optional = {}) {
215
337
  return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => key !== MANIFEST).map(([key, bytes]) => [key, hash(bytes)]));
@@ -218,6 +340,25 @@ export async function previewSitePluginInstall(required, _optional = {}) {
218
340
  return (await inspect(required, required.deps)).preview;
219
341
  }
220
342
  /** Directory lock is also cross-process: CLI and admin cannot replace the same site concurrently. */
343
+ async function withPluginInstallLock(required, _optional = {}) {
344
+ const lock = required.root + '-install-lock';
345
+ await mkdir(path.dirname(required.root), { recursive: true });
346
+ try {
347
+ await mkdir(lock);
348
+ }
349
+ catch (error) {
350
+ if (error.code === 'EEXIST')
351
+ fail('PLUGIN_INSTALL_BUSY', 'Another install is in progress.');
352
+ throw error;
353
+ }
354
+ try {
355
+ return await required.run();
356
+ }
357
+ finally {
358
+ await rm(lock, { recursive: true, force: true });
359
+ }
360
+ }
361
+ /** Publication and retention use the same installer-owned cross-process lock. */
221
362
  export async function installSitePlugin(required, _optional = {}) {
222
363
  const optional = required.deps;
223
364
  const root = path.resolve(optional.installDir);
@@ -231,71 +372,60 @@ export async function installSitePlugin(required, _optional = {}) {
231
372
  fail("PLUGIN_PACKAGE_UNSAFE", "Install, staging and Trash roots must be real directories.");
232
373
  }
233
374
  }
234
- const lock = root + "-install-lock";
235
- await mkdir(path.dirname(root), { recursive: true });
236
- try {
237
- await mkdir(lock);
238
- }
239
- catch (e) {
240
- if (e.code === "EEXIST")
241
- fail("PLUGIN_INSTALL_BUSY", "Another install is in progress.");
242
- throw e;
243
- }
244
- let staging;
245
- try {
246
- await mkdir(root + "-staging", { recursive: true });
247
- staging = await mkdtemp(path.join(root + "-staging", "install-"));
248
- const stagedSlot = path.join(staging, "new");
249
- const versionDir = path.join(stagedSlot, manifest.version);
250
- for (const [key, bytes] of files) {
251
- const target = path.join(versionDir, key);
252
- await mkdir(path.dirname(target), { recursive: true });
253
- await writeFile(target, bytes, { flag: "wx" });
254
- }
255
- await checkDestination(manifest, required, optional);
256
- await mkdir(root, { recursive: true });
257
- const live = path.join(root, manifest.id);
258
- if (!(await exists(live))) {
259
- await rename(stagedSlot, live);
260
- }
261
- else {
262
- const liveVersion = path.join(live, manifest.version);
263
- const backup = path.join(staging, "old");
264
- const replaced = await exists(liveVersion);
265
- if (replaced)
266
- await rename(liveVersion, backup);
375
+ return withPluginInstallLock({ root, run: async () => {
376
+ let staging;
267
377
  try {
268
- await rename(versionDir, liveVersion);
269
- }
270
- catch (error) {
271
- if (replaced) {
378
+ await mkdir(root + "-staging", { recursive: true });
379
+ staging = await mkdtemp(path.join(root + "-staging", "install-"));
380
+ const stagedSlot = path.join(staging, "new");
381
+ const versionDir = path.join(stagedSlot, manifest.version);
382
+ for (const [key, bytes] of files) {
383
+ const target = path.join(versionDir, key);
384
+ await mkdir(path.dirname(target), { recursive: true });
385
+ await writeFile(target, bytes, { flag: "wx" });
386
+ }
387
+ await checkDestination(manifest, required, optional);
388
+ await mkdir(root, { recursive: true });
389
+ const live = path.join(root, manifest.id);
390
+ if (!(await exists(live))) {
391
+ await rename(stagedSlot, live);
392
+ }
393
+ else {
394
+ const liveVersion = path.join(live, manifest.version);
395
+ const backup = path.join(staging, "old");
396
+ const replaced = await exists(liveVersion);
397
+ if (replaced)
398
+ await rename(liveVersion, backup);
272
399
  try {
273
- await rename(backup, liveVersion);
400
+ await rename(versionDir, liveVersion);
401
+ }
402
+ catch (error) {
403
+ if (replaced) {
404
+ try {
405
+ await rename(backup, liveVersion);
406
+ }
407
+ catch {
408
+ // Never let cleanup erase the sole remaining copy when rollback itself fails.
409
+ staging = undefined;
410
+ fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`);
411
+ }
412
+ }
413
+ throw error;
274
414
  }
275
- catch {
276
- // Never let cleanup erase the sole remaining copy when rollback itself fails.
277
- staging = undefined;
278
- fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`);
415
+ // Publish first, retire old versions second: discovery always sees a complete upgrade.
416
+ if (!optional.versionAppend) {
417
+ for (const version of await readdir(live)) {
418
+ if (version !== manifest.version)
419
+ await rm(path.join(live, version), { recursive: true, force: true });
420
+ }
279
421
  }
280
422
  }
281
- throw error;
423
+ return preview;
282
424
  }
283
- // Publish first, retire old versions second: discovery always sees a complete upgrade.
284
- for (const version of await readdir(live)) {
285
- if (version !== manifest.version)
286
- await rm(path.join(live, version), { recursive: true, force: true });
425
+ finally {
426
+ if (staging)
427
+ await rm(staging, { recursive: true, force: true });
287
428
  }
288
- }
289
- return preview;
290
- }
291
- finally {
292
- try {
293
- if (staging)
294
- await rm(staging, { recursive: true, force: true });
295
- }
296
- finally {
297
- await rm(lock, { recursive: true, force: true });
298
- }
299
- }
429
+ } });
300
430
  }
301
431
  //# sourceMappingURL=install.js.map