@sublang/spex 4.1.0 → 5.0.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 (98) hide show
  1. package/README.md +438 -54
  2. package/dist/cli.js +81 -31
  3. package/dist/commands/add.d.ts +12 -0
  4. package/dist/commands/add.js +138 -0
  5. package/dist/commands/auth-target.d.ts +11 -0
  6. package/dist/commands/auth-target.js +50 -0
  7. package/dist/commands/environment.d.ts +123 -0
  8. package/dist/commands/environment.js +411 -0
  9. package/dist/commands/export.d.ts +21 -0
  10. package/dist/commands/export.js +663 -0
  11. package/dist/commands/home.d.ts +56 -0
  12. package/dist/commands/home.js +215 -0
  13. package/dist/commands/install.d.ts +2 -0
  14. package/dist/commands/install.js +48 -0
  15. package/dist/commands/list.d.ts +2 -0
  16. package/dist/commands/list.js +87 -0
  17. package/dist/commands/login.d.ts +2 -0
  18. package/dist/commands/login.js +211 -0
  19. package/dist/commands/logout.d.ts +2 -0
  20. package/dist/commands/logout.js +74 -0
  21. package/dist/commands/publish.d.ts +2 -0
  22. package/dist/commands/publish.js +120 -0
  23. package/dist/commands/remove.d.ts +2 -0
  24. package/dist/commands/remove.js +34 -0
  25. package/dist/commands/run.d.ts +50 -0
  26. package/dist/commands/run.js +309 -0
  27. package/dist/commands/search.d.ts +2 -0
  28. package/dist/commands/search.js +34 -0
  29. package/dist/commands/settle.d.ts +124 -0
  30. package/dist/commands/settle.js +475 -0
  31. package/dist/commands/update.d.ts +2 -0
  32. package/dist/commands/update.js +37 -0
  33. package/dist/commands/whoami.d.ts +2 -0
  34. package/dist/commands/whoami.js +75 -0
  35. package/dist/lib/environment/agent-folders.d.ts +14 -0
  36. package/dist/lib/environment/agent-folders.js +11 -0
  37. package/dist/lib/environment/archive.d.ts +26 -0
  38. package/dist/lib/environment/archive.js +91 -0
  39. package/dist/lib/environment/builtins.d.ts +112 -0
  40. package/dist/lib/environment/builtins.js +539 -0
  41. package/dist/lib/environment/citations.d.ts +75 -0
  42. package/dist/lib/environment/citations.js +267 -0
  43. package/dist/lib/environment/exports.d.ts +190 -0
  44. package/dist/lib/environment/exports.js +1029 -0
  45. package/dist/lib/environment/format.d.ts +133 -0
  46. package/dist/lib/environment/format.js +651 -0
  47. package/dist/lib/environment/git-source.d.ts +41 -0
  48. package/dist/lib/environment/git-source.js +159 -0
  49. package/dist/lib/environment/index.d.ts +20 -0
  50. package/dist/lib/environment/index.js +27 -0
  51. package/dist/lib/environment/install.d.ts +140 -0
  52. package/dist/lib/environment/install.js +694 -0
  53. package/dist/lib/environment/layout.d.ts +15 -0
  54. package/dist/lib/environment/layout.js +50 -0
  55. package/dist/lib/environment/lock.d.ts +87 -0
  56. package/dist/lib/environment/lock.js +305 -0
  57. package/dist/lib/environment/marker.d.ts +15 -0
  58. package/dist/lib/environment/marker.js +31 -0
  59. package/dist/lib/environment/own-paths.d.ts +59 -0
  60. package/dist/lib/environment/own-paths.js +174 -0
  61. package/dist/lib/environment/placed-record.d.ts +32 -0
  62. package/dist/lib/environment/placed-record.js +72 -0
  63. package/dist/lib/environment/registries.d.ts +25 -0
  64. package/dist/lib/environment/registries.js +75 -0
  65. package/dist/lib/environment/registry.d.ts +173 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +108 -0
  68. package/dist/lib/environment/requests.js +403 -0
  69. package/dist/lib/environment/resolve.d.ts +70 -0
  70. package/dist/lib/environment/resolve.js +451 -0
  71. package/dist/lib/environment/semver.d.ts +30 -0
  72. package/dist/lib/environment/semver.js +130 -0
  73. package/dist/lib/environment/store.d.ts +23 -0
  74. package/dist/lib/environment/store.js +123 -0
  75. package/dist/lib/environment/tar.d.ts +27 -0
  76. package/dist/lib/environment/tar.js +219 -0
  77. package/dist/lib/files.d.ts +66 -0
  78. package/dist/lib/files.js +233 -0
  79. package/dist/lib/git-host.d.ts +579 -0
  80. package/dist/lib/git-host.js +1363 -0
  81. package/dist/lib/home-file.d.ts +124 -0
  82. package/dist/lib/home-file.js +288 -0
  83. package/dist/lib/instance.d.ts +63 -0
  84. package/dist/lib/instance.js +130 -0
  85. package/dist/lib/words.d.ts +32 -0
  86. package/dist/lib/words.js +27 -0
  87. package/dist/lint.js +8 -0
  88. package/dist/testing/index.d.ts +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/standin-registry.d.ts +94 -0
  91. package/dist/testing/standin-registry.js +449 -0
  92. package/package.json +37 -3
  93. package/dist/attached-cli.d.ts +0 -13
  94. package/dist/attached-cli.js +0 -247
  95. package/dist/attached-client.d.ts +0 -36
  96. package/dist/attached-client.js +0 -189
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
@@ -0,0 +1,451 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // Resolution and selection (environments-5, environments-6, DR-104).
4
+ // The graph holds the requested spec packages and everything they
5
+ // require at any depth; a solution gives each one version so that every
6
+ // requirement and `select` entry holds. A backtracking search assigns
7
+ // the requested names first, then the rest, each in name order, trying
8
+ // candidates newest first — so the first solution found is the highest
9
+ // by the record's comparison. Registry versions are picked from the
10
+ // version index alone; a version resource is read only for each version
11
+ // picked. Each registry package records the registry asked, or keeps
12
+ // the one the lock being replaced records where it resolves to the
13
+ // version and checksum recorded there (environments-5, DR-127): only the
14
+ // label is kept, never the solution. Within the solution, artifacts,
15
+ // languages, files and exports are selected in the record's four steps,
16
+ // the exports naming only what each release provides (environments-1),
17
+ // read from its manifest: a registry release's `meta.yaml` fetched as
18
+ // a raw file and checked against the digest its version resource lists.
19
+ import { existsSync, realpathSync } from "node:fs";
20
+ import { isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
21
+ import { ARTIFACT_KINDS, artifactLanguages, FormatError, inArtifact, parseManifestText, providedArtifacts, readRelease, ROOT_FILES, } from "./format.js";
22
+ import { sha256 } from "../files.js";
23
+ import { canonicalOrigin } from "../instance.js";
24
+ import { specExportName } from "./exports.js";
25
+ import { isRegistrySource, manifestRequires } from "./lock.js";
26
+ import { ownFolderIssue, ownPathIssue, ownPathMessage } from "./own-paths.js";
27
+ import { RegistryError, KNOWN_FORMAT } from "./registry.js";
28
+ import { isGitRequest, isInsidePath, isPathRequest, isRegistryRequest, requestsDigest } from "./requests.js";
29
+ import { compareVersions, isVersion, parseRequirement, satisfies } from "./semver.js";
30
+ export class ResolveError extends Error {
31
+ kind;
32
+ packageName;
33
+ detail;
34
+ constructor(kind, packageName, message, detail = {}) {
35
+ super(message);
36
+ this.kind = kind;
37
+ this.packageName = packageName;
38
+ this.detail = detail;
39
+ this.name = "ResolveError";
40
+ }
41
+ }
42
+ /** A `meta.yaml`'s issues as one cause. */
43
+ const issuesText = (error) => error.issues.map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)).join("; ");
44
+ /** Where the request file names spec packages in a conflict report. */
45
+ export const REQUESTS_FILE = "spex.yaml";
46
+ function describeSelection(selection) {
47
+ return `select ${selection.artifact}${selection.language ? ` in ${selection.language}` : ""}`;
48
+ }
49
+ function selectionHolds(selection, artifacts) {
50
+ return selection.every((entry) => {
51
+ const artifact = artifacts[entry.artifact];
52
+ return artifact !== undefined && (entry.language === undefined || artifact.languages.includes(entry.language));
53
+ });
54
+ }
55
+ /** A path your own group's clone refuses, in the library's words
56
+ * (environments-32), with its reason for a host to phrase. */
57
+ function confinedError(name, path, issue) {
58
+ return new ResolveError("path_confined", name, ownPathMessage(name, path, issue), { path, confined: issue });
59
+ }
60
+ /** A release read from a request's folder; one whose `meta.yaml` does not
61
+ * read is no package, named with where it was asked. */
62
+ async function readRequested(name, dir, where, detail) {
63
+ try {
64
+ return await readRelease(dir);
65
+ }
66
+ catch (error) {
67
+ if (!(error instanceof FormatError))
68
+ throw error;
69
+ throw new ResolveError("not_a_package", name, `${name}: ${where} is not a package: ${issuesText(error)}`, { ...detail, issues: issuesText(error) });
70
+ }
71
+ }
72
+ async function loadFixed(name, request, input) {
73
+ if (isPathRequest(request)) {
74
+ const root = input.pathRoot;
75
+ const path = request.path;
76
+ if (root === null)
77
+ throw new ResolveError("no_working_folder", name, `${name} is added from a folder, and this project has no folder on this computer`, { path });
78
+ const place = input.confined ? "your Personal records" : "the project folder";
79
+ if (!isInsidePath(path))
80
+ throw new ResolveError("path_outside", name, `${name}: ${path} is outside ${place}`, { path });
81
+ const dir = resolvePath(root, path);
82
+ const inside = relative(resolvePath(root), dir);
83
+ if (inside.startsWith("..") || inside.startsWith(sep))
84
+ throw new ResolveError("path_outside", name, `${name}: ${path} is outside ${place}`, { path });
85
+ if (input.confined) {
86
+ const issue = ownPathIssue(root, path);
87
+ if (issue)
88
+ throw confinedError(name, path, issue);
89
+ }
90
+ if (!existsSync(join(dir, "meta.yaml"))) {
91
+ const folderMissing = !existsSync(dir);
92
+ throw new ResolveError("path_missing", name, folderMissing ? `${name}: no folder at ${path}` : `${name}: ${path} has no meta.yaml`, { path, folderMissing });
93
+ }
94
+ // A link may not lead the path out of the folder either.
95
+ const real = relative(realpathSync(root), realpathSync(dir));
96
+ if (real.startsWith("..") || isAbsolute(real))
97
+ throw new ResolveError("path_outside", name, `${name}: ${path} leads out of ${place} through a link`, { path });
98
+ const release = await readRequested(name, dir, path, { path });
99
+ // Everything your own group's folder holds syncs with its clone.
100
+ if (input.confined) {
101
+ const issue = ownFolderIssue(root, request.path, release.files.map((file) => file.path));
102
+ if (issue)
103
+ throw confinedError(name, request.path, issue);
104
+ }
105
+ const found = `${release.manifest.org}/${release.manifest.name}`;
106
+ if (found !== name)
107
+ throw new ResolveError("name_mismatch", name, `${name}: the folder ${path} holds ${found}`, { path, found });
108
+ return { kind: "path", release, path };
109
+ }
110
+ if (isGitRequest(request)) {
111
+ const credential = input.gitCredential ? await input.gitCredential(request.git) : undefined;
112
+ const { commit, dir } = await input.git.fetch(request.git, request.rev, credential);
113
+ const releaseDir = request.path ? join(dir, ...request.path.split("/")) : dir;
114
+ const detail = { git: request.git, rev: request.rev, ...(request.path ? { path: request.path } : {}) };
115
+ const where = `${request.git} at ${request.rev}${request.path ? `, folder ${request.path}` : ""}`;
116
+ if (!existsSync(join(releaseDir, "meta.yaml")))
117
+ throw new ResolveError("path_missing", name, `${name}: ${where} holds no package`, detail);
118
+ const release = await readRequested(name, releaseDir, where, detail);
119
+ const found = `${release.manifest.org}/${release.manifest.name}`;
120
+ if (found !== name)
121
+ throw new ResolveError("name_mismatch", name, `${name}: ${where} holds ${found}`, { ...detail, found });
122
+ return { kind: "git", release, repo: request.git, commit, ...(request.path ? { subpath: request.path } : {}) };
123
+ }
124
+ return undefined;
125
+ }
126
+ function candidateOfFixed(fixed) {
127
+ const { manifest, files } = fixed.release;
128
+ const languages = artifactLanguages(manifest, files);
129
+ const artifacts = {};
130
+ for (const [id, artifact] of Object.entries(manifest.artifacts))
131
+ artifacts[id] = { kind: artifact.kind, languages: languages[id] ?? [] };
132
+ return { version: manifest.version, dependencies: { ...manifest.dependencies }, artifacts, fixed };
133
+ }
134
+ function usableEntry(entry) {
135
+ if (entry.format !== KNOWN_FORMAT || !isVersion(entry.version))
136
+ return false;
137
+ return Object.values(entry.dependencies).every((requirement) => {
138
+ try {
139
+ parseRequirement(requirement);
140
+ return true;
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ });
146
+ }
147
+ /** The registry a registry package keeps from the lock being replaced:
148
+ * the one that lock records for it where it records the same version
149
+ * and checksum (environments-5), as its instance's canonical origin
150
+ * (environments-3); none where it records another release, or a
151
+ * registry that names no origin. */
152
+ function keptRegistry(previous, name, version, checksum) {
153
+ const source = previous?.packages[name]?.source;
154
+ if (source === undefined || !isRegistrySource(source) || source.version !== version || source.checksum !== checksum)
155
+ return undefined;
156
+ try {
157
+ return canonicalOrigin(source.registry);
158
+ }
159
+ catch {
160
+ return undefined;
161
+ }
162
+ }
163
+ /** The kinds whose artifacts are placed under a skill name
164
+ * (environments-6). */
165
+ const PLACED_KINDS = ["skill", "playbook", "spec"];
166
+ /** What a registry release provides (environments-1): read from its
167
+ * `meta.yaml`, which its version resource does not restate, fetched as a
168
+ * raw file (environments-12) and taken only where its bytes carry the
169
+ * digest the resource lists for it. */
170
+ async function registryProvided(registry, name, version, files) {
171
+ const unreadable = (why) => new RegistryError("unreadable", name, `the registry's meta.yaml for ${name} ${version} is unreadable: ${why}`);
172
+ const listed = files.find((file) => file.path === "meta.yaml");
173
+ if (listed === undefined)
174
+ throw unreadable("the release lists none");
175
+ const bytes = Buffer.from(await registry.file(name, version, "meta.yaml"));
176
+ if (sha256(bytes) !== listed.sha256)
177
+ throw unreadable("its bytes do not match the digest the registry lists");
178
+ const { manifest, issues } = parseManifestText(bytes.toString("utf8"));
179
+ if (manifest === null)
180
+ throw unreadable(issues.map((issue) => issue.message).join("; "));
181
+ return providedArtifacts(manifest);
182
+ }
183
+ /** Resolve requests into a lock (environments-5, environments-6). */
184
+ export async function resolve(input) {
185
+ const { requests, registry } = input;
186
+ const requested = Object.keys(requests.packages).sort();
187
+ const fixed = new Map();
188
+ for (const name of requested) {
189
+ const loaded = await loadFixed(name, requests.packages[name], input);
190
+ if (loaded)
191
+ fixed.set(name, loaded);
192
+ }
193
+ const indexes = new Map();
194
+ // The packages the registry does not list to this reader — absent, or
195
+ // private to others — with its answer: a search finding no solution
196
+ // through one of them says the registry's answer, not a conflict, so a
197
+ // host can tell the reader to sign in (environments-12).
198
+ const unlisted = new Map();
199
+ async function indexOf(name) {
200
+ const cached = indexes.get(name);
201
+ if (cached)
202
+ return cached;
203
+ let entries;
204
+ try {
205
+ entries = (await registry.index(name)).versions;
206
+ }
207
+ catch (error) {
208
+ if (!(error instanceof RegistryError && error.kind === "not_found"))
209
+ throw error;
210
+ unlisted.set(name, error);
211
+ entries = [];
212
+ }
213
+ indexes.set(name, entries);
214
+ return entries;
215
+ }
216
+ const assigned = new Map();
217
+ const failures = [];
218
+ function requirementsOn(name) {
219
+ const out = [];
220
+ const request = requests.packages[name];
221
+ if (request && isRegistryRequest(request))
222
+ out.push({ by: REQUESTS_FILE, requirement: request.version });
223
+ for (const [by, candidate] of assigned) {
224
+ const requirement = candidate.dependencies[name];
225
+ if (requirement !== undefined)
226
+ out.push({ by, requirement });
227
+ }
228
+ return out;
229
+ }
230
+ function pickNext() {
231
+ for (const name of requested)
232
+ if (!assigned.has(name))
233
+ return name;
234
+ let next;
235
+ for (const candidate of assigned.values()) {
236
+ for (const dependency of Object.keys(candidate.dependencies)) {
237
+ if (!assigned.has(dependency) && (next === undefined || dependency < next))
238
+ next = dependency;
239
+ }
240
+ }
241
+ return next;
242
+ }
243
+ function fail(name, requirements) {
244
+ const request = requests.packages[name];
245
+ const extra = [];
246
+ if (request && isPathRequest(request))
247
+ extra.push({ by: REQUESTS_FILE, requirement: `path ${request.path} at ${fixed.get(name)?.release.manifest.version}` });
248
+ if (request && isGitRequest(request))
249
+ extra.push({ by: REQUESTS_FILE, requirement: `git ${request.git} at ${request.rev} (${fixed.get(name)?.release.manifest.version})` });
250
+ for (const selection of request?.select ?? [])
251
+ extra.push({ by: REQUESTS_FILE, requirement: describeSelection(selection) });
252
+ failures.push({ name, requirements: [...extra, ...requirements] });
253
+ }
254
+ async function candidates(name, requirements) {
255
+ const parsed = requirements.map((entry) => parseRequirement(entry.requirement));
256
+ const selection = requests.packages[name]?.select ?? [];
257
+ const own = fixed.get(name);
258
+ if (own) {
259
+ const candidate = candidateOfFixed(own);
260
+ return parsed.every((requirement) => satisfies(candidate.version, requirement)) && selectionHolds(selection, candidate.artifacts) ? [candidate] : [];
261
+ }
262
+ const entries = await indexOf(name);
263
+ return entries
264
+ .filter((entry) => {
265
+ if (!usableEntry(entry) || entry.suppressed)
266
+ return false;
267
+ if (entry.yanked && !parsed.some((requirement) => requirement.op === "exact" && compareVersions(requirement.version, entry.version) === 0))
268
+ return false;
269
+ if (!parsed.every((requirement) => satisfies(entry.version, requirement)))
270
+ return false;
271
+ return selectionHolds(selection, entry.artifacts);
272
+ })
273
+ .sort((a, b) => compareVersions(b.version, a.version))
274
+ .map((entry) => ({ version: entry.version, dependencies: { ...entry.dependencies }, artifacts: entry.artifacts, entry }));
275
+ }
276
+ const maxSteps = input.maxSteps ?? 20000;
277
+ let steps = 0;
278
+ async function solve() {
279
+ const name = pickNext();
280
+ if (name === undefined)
281
+ return true;
282
+ const requirements = requirementsOn(name);
283
+ const found = await candidates(name, requirements);
284
+ if (found.length === 0) {
285
+ fail(name, requirements);
286
+ return false;
287
+ }
288
+ for (const candidate of found) {
289
+ steps += 1;
290
+ if (steps > maxSteps)
291
+ throw new ResolveError("bound", name, `no versions found that fit every package within ${maxSteps} tries`);
292
+ const broken = Object.entries(candidate.dependencies)
293
+ .find(([dependency, requirement]) => assigned.has(dependency) && !satisfies(assigned.get(dependency).version, requirement));
294
+ if (broken) {
295
+ failures.push({ name: broken[0], requirements: [...requirementsOn(broken[0]), { by: name, requirement: broken[1] }] });
296
+ continue;
297
+ }
298
+ assigned.set(name, candidate);
299
+ if (await solve())
300
+ return true;
301
+ assigned.delete(name);
302
+ }
303
+ return false;
304
+ }
305
+ if (!(await solve())) {
306
+ const seen = new Set();
307
+ const conflicts = [];
308
+ for (const failure of failures) {
309
+ const key = `${failure.name}\u0000${failure.requirements.map((entry) => `${entry.by}:${entry.requirement}`).sort().join("\u0000")}`;
310
+ if (seen.has(key))
311
+ continue;
312
+ seen.add(key);
313
+ conflicts.push(failure);
314
+ }
315
+ const missing = conflicts.find((conflict) => unlisted.has(conflict.name));
316
+ if (missing)
317
+ throw unlisted.get(missing.name);
318
+ return { ok: false, conflicts };
319
+ }
320
+ // The solution stands: read each picked registry version's resource.
321
+ const names = [...assigned.keys()].sort();
322
+ const requiredBy = new Map();
323
+ for (const name of names)
324
+ requiredBy.set(name, []);
325
+ for (const [by, candidate] of assigned) {
326
+ for (const dependency of Object.keys(candidate.dependencies))
327
+ requiredBy.get(dependency)?.push(by);
328
+ }
329
+ const picked = [];
330
+ for (const name of names) {
331
+ const candidate = assigned.get(name);
332
+ if (candidate.fixed) {
333
+ const { release } = candidate.fixed;
334
+ const languages = artifactLanguages(release.manifest, release.files);
335
+ const artifacts = {};
336
+ for (const [id, artifact] of Object.entries(release.manifest.artifacts)) {
337
+ artifacts[id] = { kind: artifact.kind, ...(artifact.language !== undefined ? { language: artifact.language } : {}), languages: languages[id] ?? [], requires: artifact.requires };
338
+ }
339
+ const source = candidate.fixed.kind === "path"
340
+ ? { path: candidate.fixed.path, version: release.manifest.version, dependencies: { ...release.manifest.dependencies }, requires: manifestRequires(release.manifest) }
341
+ : { git: candidate.fixed.repo, commit: candidate.fixed.commit, ...(candidate.fixed.subpath ? { path: candidate.fixed.subpath } : {}) };
342
+ picked.push({ name, version: candidate.version, artifacts, files: release.files, source, lockFiles: candidate.fixed.kind === "git", provided: providedArtifacts(release.manifest) });
343
+ continue;
344
+ }
345
+ const resource = await registry.version(name, candidate.version);
346
+ if (!resource.files)
347
+ throw new RegistryError("not_found", name, `${name} ${candidate.version} lists no files: the registry withholds it`);
348
+ const artifacts = {};
349
+ for (const [id, artifact] of Object.entries(resource.artifacts)) {
350
+ if (!ARTIFACT_KINDS.includes(artifact.kind))
351
+ continue;
352
+ artifacts[id] = {
353
+ kind: artifact.kind,
354
+ ...(artifact.language !== undefined ? { language: artifact.language } : {}),
355
+ languages: artifact.languages.length > 0 ? artifact.languages : artifact.language ? [artifact.language] : [],
356
+ requires: Array.isArray(artifact.requires) ? artifact.requires : [],
357
+ };
358
+ }
359
+ const placed = Object.values(artifacts).some((artifact) => PLACED_KINDS.includes(artifact.kind));
360
+ picked.push({
361
+ name,
362
+ version: candidate.version,
363
+ artifacts,
364
+ files: resource.files,
365
+ source: { registry: keptRegistry(input.previous, name, candidate.version, resource.checksum) ?? registry.url, version: candidate.version, checksum: resource.checksum },
366
+ lockFiles: true,
367
+ provided: placed ? await registryProvided(registry, name, candidate.version, resource.files) : null,
368
+ });
369
+ }
370
+ // Selection, in the record's four steps.
371
+ const packages = {};
372
+ const exported = new Map();
373
+ for (const entry of picked) {
374
+ const request = requests.packages[entry.name];
375
+ const required = (requiredBy.get(entry.name) ?? []).length > 0;
376
+ // 1. Artifacts: the selected ones and what they require, or all.
377
+ let selected;
378
+ if (!request?.select || request.select.length === 0 || required) {
379
+ selected = Object.keys(entry.artifacts);
380
+ }
381
+ else {
382
+ const chosen = new Set();
383
+ const queue = request.select.map((selection) => selection.artifact);
384
+ while (queue.length > 0) {
385
+ const id = queue.shift();
386
+ if (chosen.has(id) || !entry.artifacts[id])
387
+ continue;
388
+ chosen.add(id);
389
+ queue.push(...entry.artifacts[id].requires);
390
+ }
391
+ selected = [...chosen];
392
+ }
393
+ selected.sort();
394
+ // 2. Languages.
395
+ const artifacts = {};
396
+ for (const id of selected) {
397
+ const artifact = entry.artifacts[id];
398
+ if (artifact.kind === "applet") {
399
+ artifacts[id] = { language: null, fallback: false };
400
+ continue;
401
+ }
402
+ const named = request?.select?.find((selection) => selection.artifact === id && selection.language !== undefined)?.language;
403
+ if (named !== undefined && artifact.languages.includes(named))
404
+ artifacts[id] = { language: named, fallback: false };
405
+ else if (requests.language !== undefined && artifact.languages.includes(requests.language))
406
+ artifacts[id] = { language: requests.language, fallback: false };
407
+ else {
408
+ const wanted = named ?? requests.language;
409
+ artifacts[id] = { language: artifact.language ?? null, fallback: wanted !== undefined && wanted !== artifact.language };
410
+ }
411
+ }
412
+ // 3. Files: the root files and each selected artifact's in its language.
413
+ const pkg = entry.name.split("/")[1];
414
+ const files = entry.lockFiles
415
+ ? entry.files
416
+ .filter((file) => ROOT_FILES.includes(file.path)
417
+ || selected.some((id) => inArtifact(file.path, entry.artifacts[id].kind, id, artifacts[id].language, pkg)))
418
+ .map((file) => ({ path: file.path, sha256: file.sha256, executable: file.executable }))
419
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
420
+ : [];
421
+ // 4. Exports: one skill per provided skill and playbook under its
422
+ // id, and per provided spec under `<org>-<pkg>` (DR-115), or alias;
423
+ // a selected artifact its release does not provide — a sibling's
424
+ // support, or of a kind `provides` leaves out — is installed with the
425
+ // rest and placed nowhere, so its name clashes with none.
426
+ const exports = {};
427
+ for (const id of selected) {
428
+ const kind = entry.artifacts[id].kind;
429
+ if (!PLACED_KINDS.includes(kind) || entry.provided?.has(id) !== true)
430
+ continue;
431
+ const name = request?.alias?.[id] ?? (kind === "spec" ? specExportName(entry.name) : id);
432
+ exports[name] = id;
433
+ const list = exported.get(name) ?? [];
434
+ list.push({ by: entry.name, kind, id });
435
+ exported.set(name, list);
436
+ }
437
+ packages[entry.name] = { source: entry.source, requiredBy: [...(requiredBy.get(entry.name) ?? [])].sort(), artifacts, files, exports };
438
+ }
439
+ const clashes = [];
440
+ for (const name of [...exported.keys()].sort()) {
441
+ const list = exported.get(name);
442
+ if (list.length < 2)
443
+ continue;
444
+ clashes.push({ name, requirements: list.map((item) => ({ by: item.by, requirement: `${item.kind} ${item.id}` })) });
445
+ }
446
+ if (clashes.length > 0)
447
+ return { ok: false, conflicts: clashes };
448
+ const digest = requestsDigest(input.requestsText ?? JSON.stringify(requests));
449
+ return { ok: true, lock: { format: 1, requests: digest, packages } };
450
+ }
451
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1,30 @@
1
+ export interface Version {
2
+ major: number;
3
+ minor: number;
4
+ patch: number;
5
+ /** Dot-separated prerelease identifiers; numeric ones as numbers. */
6
+ prerelease: (string | number)[];
7
+ build: string[];
8
+ raw: string;
9
+ }
10
+ export type RequirementOp = "exact" | "caret" | "tilde";
11
+ export interface Requirement {
12
+ op: RequirementOp;
13
+ version: Version;
14
+ raw: string;
15
+ }
16
+ /** The longest requirement string the registry accepts (Spex Space DR-013). */
17
+ export declare const MAX_REQUIREMENT_BYTES = 256;
18
+ export declare class VersionError extends Error {
19
+ constructor(message: string);
20
+ }
21
+ /** Parse a Semantic Versioning 2.0.0 version, or throw. */
22
+ export declare function parseVersion(text: string): Version;
23
+ export declare function isVersion(text: unknown): text is string;
24
+ /** Precedence: negative when a < b, zero when equal, build ignored. */
25
+ export declare function compareVersions(a: string | Version, b: string | Version): number;
26
+ /** Parse one of `1.2.3`, `^1.2.3` or `~1.2.3`, or throw. */
27
+ export declare function parseRequirement(text: string): Requirement;
28
+ export declare function isRequirement(text: unknown): text is string;
29
+ /** Whether a version satisfies a requirement (environments-4). */
30
+ export declare function satisfies(version: string | Version, requirement: string | Requirement): boolean;
@@ -0,0 +1,130 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ const NUMERIC = "0|[1-9]\\d*";
4
+ const PRERELEASE_ID = `(?:${NUMERIC}|\\d*[a-zA-Z-][0-9a-zA-Z-]*)`;
5
+ const VERSION_SOURCE = `(${NUMERIC})\\.(${NUMERIC})\\.(${NUMERIC})` +
6
+ `(?:-(${PRERELEASE_ID}(?:\\.${PRERELEASE_ID})*))?` +
7
+ `(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?`;
8
+ const VERSION_RE = new RegExp(`^${VERSION_SOURCE}$`);
9
+ const REQUIREMENT_RE = new RegExp(`^([\\^~]?)(${VERSION_SOURCE})$`);
10
+ /** The longest requirement string the registry accepts (Spex Space DR-013). */
11
+ export const MAX_REQUIREMENT_BYTES = 256;
12
+ export class VersionError extends Error {
13
+ constructor(message) {
14
+ super(message);
15
+ this.name = "VersionError";
16
+ }
17
+ }
18
+ function toNumber(text, raw) {
19
+ const value = Number(text);
20
+ if (!Number.isSafeInteger(value))
21
+ throw new VersionError(`version ${raw} has a component too large`);
22
+ return value;
23
+ }
24
+ /** Parse a Semantic Versioning 2.0.0 version, or throw. */
25
+ export function parseVersion(text) {
26
+ const match = typeof text === "string" ? VERSION_RE.exec(text) : null;
27
+ if (!match)
28
+ throw new VersionError(`"${String(text)}" is not a Semantic Versioning 2.0.0 version`);
29
+ return {
30
+ major: toNumber(match[1], text),
31
+ minor: toNumber(match[2], text),
32
+ patch: toNumber(match[3], text),
33
+ prerelease: match[4]
34
+ ? match[4].split(".").map((id) => (/^\d+$/.test(id) ? toNumber(id, text) : id))
35
+ : [],
36
+ build: match[5] ? match[5].split(".") : [],
37
+ raw: text,
38
+ };
39
+ }
40
+ export function isVersion(text) {
41
+ if (typeof text !== "string")
42
+ return false;
43
+ try {
44
+ parseVersion(text);
45
+ return true;
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ function asVersion(value) {
52
+ return typeof value === "string" ? parseVersion(value) : value;
53
+ }
54
+ function compareIds(a, b) {
55
+ if (typeof a === "number" && typeof b === "number")
56
+ return a - b;
57
+ if (typeof a === "number")
58
+ return -1;
59
+ if (typeof b === "number")
60
+ return 1;
61
+ return a < b ? -1 : a > b ? 1 : 0;
62
+ }
63
+ /** Precedence: negative when a < b, zero when equal, build ignored. */
64
+ export function compareVersions(a, b) {
65
+ const x = asVersion(a);
66
+ const y = asVersion(b);
67
+ if (x.major !== y.major)
68
+ return Math.sign(x.major - y.major);
69
+ if (x.minor !== y.minor)
70
+ return Math.sign(x.minor - y.minor);
71
+ if (x.patch !== y.patch)
72
+ return Math.sign(x.patch - y.patch);
73
+ if (x.prerelease.length === 0 || y.prerelease.length === 0) {
74
+ return Math.sign(y.prerelease.length - x.prerelease.length);
75
+ }
76
+ for (let i = 0; i < Math.min(x.prerelease.length, y.prerelease.length); i += 1) {
77
+ const order = compareIds(x.prerelease[i], y.prerelease[i]);
78
+ if (order !== 0)
79
+ return Math.sign(order);
80
+ }
81
+ return Math.sign(x.prerelease.length - y.prerelease.length);
82
+ }
83
+ /** Parse one of `1.2.3`, `^1.2.3` or `~1.2.3`, or throw. */
84
+ export function parseRequirement(text) {
85
+ if (typeof text !== "string")
86
+ throw new VersionError(`a version requirement must be a string`);
87
+ if (Buffer.byteLength(text, "utf8") > MAX_REQUIREMENT_BYTES || !/^[\x20-\x7e]*$/.test(text)) {
88
+ throw new VersionError(`"${text}" is not a version requirement`);
89
+ }
90
+ const match = REQUIREMENT_RE.exec(text);
91
+ if (!match)
92
+ throw new VersionError(`"${text}" is not a version requirement: use 1.2.3, ^1.2.3 or ~1.2.3`);
93
+ const op = match[1] === "^" ? "caret" : match[1] === "~" ? "tilde" : "exact";
94
+ return { op, version: parseVersion(match[2]), raw: text };
95
+ }
96
+ export function isRequirement(text) {
97
+ if (typeof text !== "string")
98
+ return false;
99
+ try {
100
+ parseRequirement(text);
101
+ return true;
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ function sameCore(a, b) {
108
+ return a.major === b.major && a.minor === b.minor && a.patch === b.patch;
109
+ }
110
+ function core(major, minor, patch) {
111
+ return { major, minor, patch, prerelease: [], build: [], raw: `${major}.${minor}.${patch}` };
112
+ }
113
+ /** Whether a version satisfies a requirement (environments-4). */
114
+ export function satisfies(version, requirement) {
115
+ const v = asVersion(version);
116
+ const req = typeof requirement === "string" ? parseRequirement(requirement) : requirement;
117
+ const base = req.version;
118
+ if (v.prerelease.length > 0 && !(base.prerelease.length > 0 && sameCore(v, base)))
119
+ return false;
120
+ if (req.op === "exact")
121
+ return compareVersions(v, base) === 0;
122
+ if (compareVersions(v, base) < 0)
123
+ return false;
124
+ const upper = req.op === "tilde" ? core(base.major, base.minor + 1, 0)
125
+ : base.major > 0 ? core(base.major + 1, 0, 0)
126
+ : base.minor > 0 ? core(0, base.minor + 1, 0)
127
+ : core(0, 0, base.patch + 1);
128
+ return compareVersions(v, upper) < 0;
129
+ }
130
+ //# sourceMappingURL=semver.js.map
@@ -0,0 +1,23 @@
1
+ import type { Lock } from "./lock.js";
2
+ export declare class DigestError extends Error {
3
+ readonly expected: string;
4
+ readonly actual: string;
5
+ readonly what: string;
6
+ constructor(expected: string, actual: string, what: string);
7
+ }
8
+ /** The key a store entry goes by: `<sha>` or `x/<sha>`. */
9
+ export declare function storeKey(sha256: string, executable: boolean): string;
10
+ /** Every store entry the given locks select. */
11
+ export declare function lockStoreKeys(locks: Iterable<Lock>): Set<string>;
12
+ export declare class ContentStore {
13
+ readonly root: string;
14
+ constructor(homeDir: string);
15
+ pathOf(sha256: string, executable: boolean): string;
16
+ has(sha256: string, executable: boolean): boolean;
17
+ /** Store bytes under their digest, verified first; written once. */
18
+ put(bytes: Uint8Array, sha256: string, executable: boolean, what?: string): string;
19
+ /** Every entry's key. */
20
+ keys(): string[];
21
+ /** Remove every entry no lock selects; returns the removed keys. */
22
+ gc(selected: Set<string>): string[];
23
+ }