@sublang/spex 4.2.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 (100) hide show
  1. package/README.md +433 -89
  2. package/dist/cli.js +80 -42
  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 -249
  95. package/dist/attached-client.d.ts +0 -53
  96. package/dist/attached-client.js +0 -237
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
  99. package/dist/package-init.d.ts +0 -21
  100. package/dist/package-init.js +0 -442
@@ -0,0 +1,124 @@
1
+ import { type ExportReport, type InstallReport, type Lock, type Requests, type Resolution, type SpecPlacement } from "../lib/environment/index.js";
2
+ import type { AuthScope } from "../lib/git-host.js";
3
+ import { type Environment } from "./environment.js";
4
+ import { Refusal } from "./run.js";
5
+ /** `install`: resolve only where the lock is missing or stale;
6
+ * `resolve`: resolve again from `spex.yaml` whatever the lock holds,
7
+ * rewriting a lock that does not read. */
8
+ export type SettleMode = "install" | "resolve";
9
+ export interface Settled {
10
+ /** The lock as it stood before; null where none stood or it did not
11
+ * read. */
12
+ before: Lock | null;
13
+ /** Why the lock standing before was stale; null where it was not. */
14
+ staleBefore: string[] | null;
15
+ /** The lock installed. */
16
+ lock: Lock;
17
+ /** Whether a resolution ran, and whether it wrote the lock. */
18
+ resolved: boolean;
19
+ lockWritten: boolean;
20
+ install: InstallReport;
21
+ exported: ExportReport;
22
+ }
23
+ /** Why a lock no longer stands against the files at the root, or null. */
24
+ export declare function staleReasons(root: string, lock: Lock, requestsText: string | null): string[] | null;
25
+ /** A Git locator as a reader reads it: a local path or file URL as
26
+ * given; a network remote unnamed, since the command line reads no
27
+ * Space's Git origin and so never tells a Space's repository from
28
+ * another's, and never names the Git host behind a Space. */
29
+ export declare function gitShown(repo: string): string;
30
+ /** A Git repository as a source's words name it: `Git <repository>`
31
+ * for one of this computer, `a Git remote` for a network one. */
32
+ export declare function gitLabel(repo: string): string;
33
+ /** Every Git locator the environment's files name, longest first, with
34
+ * the spec packages fetched from it. */
35
+ export type GitLocators = [repo: string, names: string[]][];
36
+ export declare function gitLocators(requests: Requests | null, lock: Lock | null): GitLocators;
37
+ /** A text with every network Git locator of the environment unnamed. */
38
+ export declare function unnamedText(text: string, locators: GitLocators): string;
39
+ /** A failure of a settle as one phrase ending in what to do (cli-13). */
40
+ export declare function refusalOf(env: Environment, error: unknown, context: {
41
+ origin: string;
42
+ scope: AuthScope;
43
+ }, locators?: GitLocators): Promise<Refusal>;
44
+ /** Settle the environment; null where it holds neither file. */
45
+ export declare function settle(env: Environment, mode: SettleMode): Promise<Settled | null>;
46
+ /** A spec package's version as its lock records it, or as its folder's
47
+ * manifest states it. */
48
+ export declare function versionOf(root: string, name: string, resolution: Resolution): string;
49
+ /** Where a package comes from, as a project's Packages tab says it
50
+ * (cli-6): the registry, a folder, a Git repository at its commit with
51
+ * no network remote named, or built in for the app's own. */
52
+ export declare function sourceLabel(name: string, resolution: Resolution): string;
53
+ /** The project-level agent folders of the table, each once, with
54
+ * whether a playbook's skill goes there (environments-16). */
55
+ export declare function projectFolders(): {
56
+ folder: string;
57
+ playbooks: boolean;
58
+ }[];
59
+ /** The skills Spex's last export left in an agent folder of the root,
60
+ * as that folder's manifest names them. */
61
+ export declare function exportedIn(root: string, folder: string): string[];
62
+ /** Whether a package's files stand as the lock records them
63
+ * (environments-14): `installed`; `not installed`; or `files missing`
64
+ * where the install placed it, or its folder is not at its path. */
65
+ export type PackageState = "installed" | "not installed" | "files missing";
66
+ export declare function packageState(root: string, lock: Lock, name: string, installed: Set<string>, recorded: Set<string>): PackageState;
67
+ /** The state of every package of a lock, read from the files. */
68
+ export declare function packageStates(root: string, lock: Lock): Map<string, PackageState>;
69
+ /** Where one exported skill of a package stands, read from the files:
70
+ * the agent folders holding it as Spex's export, those a folder of the
71
+ * reader's keeps it out of, and why it is placed nowhere (environments-8). */
72
+ export interface SkillPlace {
73
+ skill: string;
74
+ placed: string[];
75
+ yours: string[];
76
+ why: string | null;
77
+ }
78
+ export declare function skillPlaces(root: string, lock: Lock, name: string, state: PackageState): SkillPlace[];
79
+ /** One skill's place as a line's cell: its folders, with those yours
80
+ * keeps it out of, or `not placed` with why. */
81
+ export declare function placeText(place: SkillPlace): string;
82
+ /** Rows aligned in columns, two spaces apart, under a two-space indent;
83
+ * a column no row fills is left out. */
84
+ export declare function table(rows: string[][]): string[];
85
+ /** The lines of a package's skills under its line: each skill with where
86
+ * it stands for the agents (cli-2, cli-4). */
87
+ export declare function skillLines(root: string, lock: Lock, name: string, state: PackageState): string[];
88
+ /** A provided spec's place as a line, in a project's Packages tab's
89
+ * words (cli-6, environments-41), an edited copy naming the newer
90
+ * release's version where one waits; an edited copy its package no
91
+ * longer places, the project's own now, reads as edited too (DR-172). */
92
+ export declare function specText(placement: SpecPlacement): string;
93
+ /** The lines beneath a package of its provided spec (cli-2, cli-4,
94
+ * cli-6): where it stands, then one line per package its links wait
95
+ * for, with the command adding it. */
96
+ export declare function specLines(placements: readonly SpecPlacement[], name: string, indent?: string): string[];
97
+ /** Each change from one lock to the next: a package gained, updated from
98
+ * one version to another, switched to another source at one version, or
99
+ * removed. */
100
+ export interface LockChange {
101
+ name: string;
102
+ from: string | null;
103
+ to: string | null;
104
+ /** The source after, where the source changed. */
105
+ source?: string;
106
+ }
107
+ export declare function lockChanges(root: string, before: Lock | null, after: Lock): LockChange[];
108
+ /** A change as a reader reads it: added, with the packages it came for
109
+ * where `spex.yaml` does not add it itself; updated, with both versions
110
+ * and its new source; removed. */
111
+ export declare function changeLine(change: LockChange, lock?: Lock, added?: ReadonlySet<string>): string;
112
+ /** The lines naming each package gained, updated or removed, with where
113
+ * each one's spec and skills went — a removed package's edited copy left
114
+ * as the project's own (cli-2, cli-3, environments-41). */
115
+ export declare function gainedLines(root: string, settled: Settled, added: ReadonlySet<string>): string[];
116
+ /** The line naming the app's built-in spec package an install left to
117
+ * the app, no seed and no registry serving it: marked built in, for
118
+ * the Spex app to install (cli-4). */
119
+ export declare function leftToAppLine(name: string, version: string): string;
120
+ /** The lines naming each spec package an install left to the app. */
121
+ export declare function leftToAppLines(root: string, settled: Settled): string[];
122
+ /** The lines naming each folder package whose folder is not at its path
123
+ * here (environments-7). */
124
+ export declare function missingPathLines(settled: Settled): string[];
@@ -0,0 +1,475 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // The settle of an environment from the command line (cli-2 to cli-5,
4
+ // environments-5, environments-7, environments-8): read `spex.yaml` and
5
+ // `spex.lock` at the root; resolve where asked, or where the lock is
6
+ // missing or stale; write the lock under the version read; install under
7
+ // `<root>/.spex/` with no engine (cli-14), the app's built-in spec
8
+ // package that no seed and no registry serves left to the app; export
9
+ // into the root with the library's agent table. It follows the order
10
+ // and the version checks of the app's settle, without its state,
11
+ // announcements or catalog: every write is a versioned write, refused
12
+ // where its file changed meanwhile (DR-111). What it prints speaks a
13
+ // project's Packages tab's words (DR-172): added, installed, updated,
14
+ // removed, the registry by its name, skills for agents, and beneath a
15
+ // package providing a spec where that spec stands in `specs/` with the
16
+ // packages its links wait for (cli-6, environments-41, DR-174).
17
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
18
+ import { isAbsolute, join, posix } from "node:path";
19
+ import { AGENT_FOLDERS, BUILTIN_PACKAGE_NAME, EXPORTS_MANIFEST, exportEnvironment, GitSourceError, install, InstallError, installedPackages, isGitRequest, isGitSource, isPathSource, isRegistrySource, lockStaleness, packageRoot, installedDir, parseManifestText, providedArtifacts, recordedPackages, RegistryError, resolve, ResolveError, resolutionVersion, serializeLock, writeLock, } from "../lib/environment/index.js";
20
+ import { fileVersion, sha256, VersionConflictError } from "../lib/files.js";
21
+ import { shown } from "./environment.js";
22
+ import { Refusal } from "./run.js";
23
+ /** A path source's manifest where its path resolves under the root; null
24
+ * where the folder holds none (environments-7). */
25
+ function pathManifest(root, path) {
26
+ const file = join(root, ...path.split("/"), "meta.yaml");
27
+ if (!existsSync(file))
28
+ return null;
29
+ const { manifest, issues } = parseManifestText(readFileSync(file, "utf8"));
30
+ if (!manifest)
31
+ throw new Error(issues.map((issue) => issue.message).join("; "));
32
+ return manifest;
33
+ }
34
+ /** Why a lock no longer stands against the files at the root, or null. */
35
+ export function staleReasons(root, lock, requestsText) {
36
+ const staleness = lockStaleness(lock, requestsText, (path) => pathManifest(root, path));
37
+ return staleness.stale ? staleness.reasons : null;
38
+ }
39
+ // -- Git locators as a reader is shown them (environments-29, DR-120) ---------
40
+ /** Whether a Git locator is a folder of this computer: a path, or a
41
+ * file URL. */
42
+ function localGit(repo) {
43
+ return isAbsolute(repo) || /^file:/i.test(repo)
44
+ || (!/^[a-z][a-z0-9+.-]*:\/\//i.test(repo) && !/^[^/\\]+:/.test(repo));
45
+ }
46
+ /** A Git locator as a reader reads it: a local path or file URL as
47
+ * given; a network remote unnamed, since the command line reads no
48
+ * Space's Git origin and so never tells a Space's repository from
49
+ * another's, and never names the Git host behind a Space. */
50
+ export function gitShown(repo) {
51
+ return localGit(repo) ? repo : "a Git remote";
52
+ }
53
+ /** A Git repository as a source's words name it: `Git <repository>`
54
+ * for one of this computer, `a Git remote` for a network one. */
55
+ export function gitLabel(repo) {
56
+ return localGit(repo) ? `Git ${repo}` : gitShown(repo);
57
+ }
58
+ export function gitLocators(requests, lock) {
59
+ const out = new Map();
60
+ const add = (repo, name) => { out.set(repo, (out.get(repo) ?? new Set()).add(name)); };
61
+ for (const [name, request] of Object.entries(requests?.packages ?? {}))
62
+ if (isGitRequest(request))
63
+ add(request.git, name);
64
+ for (const [name, resolution] of Object.entries(lock?.packages ?? {}))
65
+ if (isGitSource(resolution.source))
66
+ add(resolution.source.git, name);
67
+ return [...out.entries()].map(([repo, names]) => [repo, [...names].sort()]).sort(([a], [b]) => b.length - a.length);
68
+ }
69
+ /** A text with every network Git locator of the environment unnamed. */
70
+ export function unnamedText(text, locators) {
71
+ return locators.reduce((out, [repo]) => (localGit(repo) ? out : out.split(repo).join(gitShown(repo))), text);
72
+ }
73
+ /** A Git fetch's failure as a reader reads it: Git's own words for a
74
+ * local repository; for a network remote, what it answered and no raw
75
+ * output, which may name the host behind a Space. */
76
+ function gitFailure(error, locators) {
77
+ if (localGit(error.repo))
78
+ return error.message;
79
+ const status = /returned error: (\d{3})|RPC failed; HTTP (\d{3})|HTTP (\d{3})/i.exec(error.run?.stderr ?? "");
80
+ const answer = status ? ` (HTTP ${status[1] ?? status[2] ?? status[3]})` : "";
81
+ const names = locators.find(([repo]) => repo === error.repo)?.[1] ?? [];
82
+ return `${names.length > 0 ? `${names.join(", ")}: ` : ""}${gitShown(error.repo)} answered with an error${answer} — check that Git on this computer can read it, then retry`;
83
+ }
84
+ /** What the library's install says before its cause where it kept the
85
+ * last files. */
86
+ const KEPT = "installing failed; the last files stay: ";
87
+ /** A resolution's refusal of a package's source in the CLI's words, each
88
+ * ending in what to do (cli-13): a folder missing, holding no
89
+ * `meta.yaml` or another package, leading out of the project folder, or
90
+ * no package; a Git repository holding none; no versions found in time. */
91
+ function resolvePhrase(error) {
92
+ const pkg = error.packageName ?? "a package";
93
+ const { path, git, rev, folderMissing, found, issues } = error.detail;
94
+ const where = git !== undefined ? `${gitShown(git)} at ${rev}${path ? `, folder ${path}` : ""}` : path;
95
+ const fix = git !== undefined ? "fix its git, rev or path in spex.yaml" : "fix its path in spex.yaml";
96
+ switch (error.kind) {
97
+ case "path_missing":
98
+ if (git !== undefined)
99
+ return `${pkg}: ${where} holds no package — ${fix}`;
100
+ return folderMissing
101
+ ? `${pkg}: no folder at ${path} — ${fix}, or spex remove ${pkg}`
102
+ : `${pkg}: ${path} has no meta.yaml, so it is no package — ${fix}, or spex remove ${pkg}`;
103
+ case "path_outside":
104
+ return `${pkg}: ${path} leads out of this project folder — ${fix} to a folder inside it, or spex remove ${pkg}`;
105
+ case "name_mismatch":
106
+ return `${pkg}: ${where} holds ${found} — fix the name in spex.yaml, or in its meta.yaml`;
107
+ case "not_a_package":
108
+ return `${pkg}: ${where} is not a package: ${issues} — fix its meta.yaml, then retry`;
109
+ case "bound":
110
+ return "no versions found that fit every package in time — loosen a version in spex.yaml, then spex update";
111
+ default:
112
+ return null;
113
+ }
114
+ }
115
+ /** A failure of a settle as one phrase ending in what to do (cli-13). */
116
+ export async function refusalOf(env, error, context, locators = []) {
117
+ if (error instanceof Refusal)
118
+ return error;
119
+ if (error instanceof GitSourceError)
120
+ return new Refusal(gitFailure(error, locators));
121
+ if (error instanceof InstallError && error.cause instanceof GitSourceError)
122
+ return new Refusal(gitFailure(error.cause, locators));
123
+ const registryError = error instanceof RegistryError ? error : error instanceof InstallError && error.cause instanceof RegistryError ? error.cause : null;
124
+ if (registryError !== null)
125
+ return new Refusal(unnamedText((await env.registryRefusal(registryError, context)).message, locators));
126
+ if (error instanceof VersionConflictError)
127
+ return new Refusal(`${shown(env.root, error.file)} changed meanwhile — retry`);
128
+ const phrase = error instanceof ResolveError ? resolvePhrase(error) : null;
129
+ if (phrase !== null)
130
+ return new Refusal(unnamedText(phrase, locators));
131
+ const message = error instanceof Error ? error.message : String(error);
132
+ if (error instanceof InstallError && message.startsWith(KEPT))
133
+ return new Refusal(unnamedText(`installing stopped, the last files stay: ${message.slice(KEPT.length)} — retry`, locators));
134
+ if (error instanceof InstallError && / no registry has it as spex\.lock records it/.test(message)) {
135
+ return new Refusal(unnamedText(`${message} — spex update picks a version the registry has`, locators));
136
+ }
137
+ // Anything else still ends in what to do.
138
+ return new Refusal(unnamedText(/ — /.test(message) ? message : `${message} — retry`, locators));
139
+ }
140
+ /** Settle the environment; null where it holds neither file. */
141
+ export async function settle(env, mode) {
142
+ const read = env.readRequests();
143
+ const locked = mode === "resolve" ? env.readLockForUpdate() : env.readLock();
144
+ if (read === null && locked === null)
145
+ return null;
146
+ const { root, requestsFile, lockFile } = env;
147
+ // The environment's registry: the one its `spex.yaml` names, else its
148
+ // Space's in a file naming none (environments-2, environments-38).
149
+ const target = env.registryOf(read?.requests ?? null);
150
+ const context = { origin: target.origin, scope: target.scope };
151
+ const instance = target.origin;
152
+ const registry = env.registryAt(instance, target.scope);
153
+ const locators = gitLocators(read?.requests ?? null, locked?.lock ?? null);
154
+ let lock = locked?.lock ?? null;
155
+ let lockVersion = locked?.version ?? null;
156
+ const staleBefore = lock !== null && read !== null ? staleReasons(root, lock, read.text) : null;
157
+ const needsResolve = mode === "resolve" || lock === null || staleBefore !== null;
158
+ let lockWritten = false;
159
+ if (needsResolve) {
160
+ if (read === null)
161
+ throw new Refusal(`no spex.yaml in ${root} — spex add <org>/<pkg>`);
162
+ let result;
163
+ try {
164
+ result = await resolve({
165
+ requests: read.requests, requestsText: read.text, registry, pathRoot: root, git: env.git,
166
+ // A package resolving to the release its lock records keeps the
167
+ // registry recorded there (environments-5).
168
+ ...(locked?.lock ? { previous: locked.lock } : {}),
169
+ });
170
+ }
171
+ catch (error) {
172
+ throw await refusalOf(env, error, context, locators);
173
+ }
174
+ if (!result.ok) {
175
+ const conflicts = result.conflicts.map((conflict) => `${conflict.name} (${conflict.requirements.map((entry) => `${entry.by}: ${entry.requirement}`).join(", ")})`);
176
+ throw new Refusal(unnamedText(`no version fits every package: ${conflicts.join(", ")} — change or remove one`, locators));
177
+ }
178
+ // The lock is written only while `spex.yaml` stands as resolved and
179
+ // the lock as read, both checked at the instant of the write; a lock
180
+ // already holding these bytes is left as it is.
181
+ try {
182
+ if (fileVersion(requestsFile) !== read.version)
183
+ throw new VersionConflictError(requestsFile);
184
+ if (serializeLock(result.lock) !== locked?.text) {
185
+ lockVersion = sha256(await writeLock(lockFile, result.lock, lockVersion));
186
+ lockWritten = true;
187
+ }
188
+ }
189
+ catch (error) {
190
+ throw await refusalOf(env, error, context);
191
+ }
192
+ lock = result.lock;
193
+ }
194
+ if (lock === null)
195
+ throw new Refusal(`no spex.lock in ${root} — spex install`);
196
+ let report;
197
+ try {
198
+ report = await install({
199
+ root,
200
+ lock,
201
+ lockVersion,
202
+ store: env.store,
203
+ cache: env.cache,
204
+ registry,
205
+ registries: (source) => env.installRegistries(instance, source, target.scope),
206
+ // The built-in spec package from this computer's seed, by its
207
+ // files' digests; where no seed and no registry serves it, left
208
+ // out as not installed for the app's next use to install, the rest
209
+ // installed (environments-7).
210
+ seed: env.seed(),
211
+ builtinUnserved: "leave",
212
+ git: env.git,
213
+ pathRoot: root,
214
+ requestsText: read?.text ?? null,
215
+ });
216
+ }
217
+ catch (error) {
218
+ throw await refusalOf(env, error, context, locators);
219
+ }
220
+ // A stale lock installs and exports nothing (environments-7).
221
+ if (report.stale)
222
+ throw new Refusal(unnamedText(`${report.stale.join("; ")} while spex ran — retry`, locators));
223
+ // Exports derive from the installed tree and its lock: written only
224
+ // while both still stand as this install left them, and cover the
225
+ // spec packages installed alone (environments-8).
226
+ let exported;
227
+ try {
228
+ if (fileVersion(lockFile) !== lockVersion)
229
+ throw new VersionConflictError(lockFile);
230
+ const installed = installedPackages(root, lock);
231
+ const left = new Set(report.left ?? []);
232
+ if (!Object.entries(lock.packages).every(([name, resolution]) => isPathSource(resolution.source) || left.has(name) || installed.has(name))) {
233
+ throw new VersionConflictError(installedDir(root));
234
+ }
235
+ const exportedLock = left.size === 0 ? lock : { ...lock, packages: Object.fromEntries(Object.entries(lock.packages).filter(([name]) => !left.has(name))) };
236
+ exported = await exportEnvironment({ root, lock: exportedLock, workingFolder: root, pathRoot: root, userHome: null, agents: [] });
237
+ }
238
+ catch (error) {
239
+ throw await refusalOf(env, error, context);
240
+ }
241
+ return { before: locked?.lock ?? null, staleBefore, lock, resolved: needsResolve, lockWritten, install: report, exported };
242
+ }
243
+ // -- what a reader is told ----------------------------------------------------
244
+ /** A spec package's version as its lock records it, or as its folder's
245
+ * manifest states it. */
246
+ export function versionOf(root, name, resolution) {
247
+ return resolutionVersion(resolution) ?? manifestVersion(root, name, resolution) ?? "?";
248
+ }
249
+ function manifestVersion(root, name, resolution) {
250
+ const dir = packageRoot(name, resolution, installedDir(root), root);
251
+ if (dir === null)
252
+ return null;
253
+ try {
254
+ return pathManifest(dir, ".")?.version ?? null;
255
+ }
256
+ catch {
257
+ return null;
258
+ }
259
+ }
260
+ /** Where a package comes from, as a project's Packages tab says it
261
+ * (cli-6): the registry, a folder, a Git repository at its commit with
262
+ * no network remote named, or built in for the app's own. */
263
+ export function sourceLabel(name, resolution) {
264
+ const source = resolution.source;
265
+ if (isRegistrySource(source))
266
+ return name === BUILTIN_PACKAGE_NAME ? "built in" : "from the registry";
267
+ if (isGitSource(source))
268
+ return `from ${gitLabel(source.git)} at ${source.commit.slice(0, 12)}${source.path ? `, folder ${source.path}` : ""}`;
269
+ return `from folder ${source.path}`;
270
+ }
271
+ /** The project-level agent folders of the table, each once, with
272
+ * whether a playbook's skill goes there (environments-16). */
273
+ export function projectFolders() {
274
+ const out = new Map();
275
+ for (const entry of Object.values(AGENT_FOLDERS))
276
+ out.set(entry.project, (out.get(entry.project) ?? false) || entry.playbooks);
277
+ return [...out.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([folder, playbooks]) => ({ folder, playbooks }));
278
+ }
279
+ /** The skills Spex's last export left in an agent folder of the root,
280
+ * as that folder's manifest names them. */
281
+ export function exportedIn(root, folder) {
282
+ try {
283
+ const value = JSON.parse(readFileSync(join(root, ...folder.split("/"), EXPORTS_MANIFEST), "utf8"));
284
+ return Array.isArray(value.skills) ? value.skills.filter((item) => typeof item === "string") : [];
285
+ }
286
+ catch {
287
+ return [];
288
+ }
289
+ }
290
+ export function packageState(root, lock, name, installed, recorded) {
291
+ const resolution = lock.packages[name];
292
+ if (isPathSource(resolution.source))
293
+ return existsSync(join(root, ...resolution.source.path.split("/"), "meta.yaml")) ? "installed" : "files missing";
294
+ if (installed.has(name))
295
+ return "installed";
296
+ return recorded.has(name) ? "files missing" : "not installed";
297
+ }
298
+ /** The state of every package of a lock, read from the files. */
299
+ export function packageStates(root, lock) {
300
+ const installed = installedPackages(root, lock);
301
+ const recorded = recordedPackages(root, lock);
302
+ return new Map(Object.keys(lock.packages).map((name) => [name, packageState(root, lock, name, installed, recorded)]));
303
+ }
304
+ function standing(path) {
305
+ try {
306
+ lstatSync(path);
307
+ return true;
308
+ }
309
+ catch {
310
+ return false;
311
+ }
312
+ }
313
+ export function skillPlaces(root, lock, name, state) {
314
+ const resolution = lock.packages[name];
315
+ if (Object.keys(resolution.exports).length === 0)
316
+ return [];
317
+ const dir = packageRoot(name, resolution, installedDir(root), root);
318
+ let manifest = null;
319
+ try {
320
+ manifest = dir === null ? null : pathManifest(dir, ".");
321
+ }
322
+ catch {
323
+ manifest = null;
324
+ }
325
+ // A skill for the agents of what the release provides alone, and
326
+ // never a provided spec's: the command line's root is a project's,
327
+ // where a spec stands in `specs/packages/` or nowhere (environments-6,
328
+ // environments-8); a release not here is read as its lock names it,
329
+ // its spec by the file the lock selects, or a folder's by its id
330
+ // `<pkg>` (environments-1).
331
+ const provided = manifest === null ? null : providedArtifacts(manifest);
332
+ const pkg = name.slice(name.indexOf("/") + 1);
333
+ const lockedSpec = (id) => (isPathSource(resolution.source)
334
+ ? id === pkg
335
+ : resolution.files.some((file) => file.path.startsWith("specs/") && file.path.endsWith(`/${id}.md`)));
336
+ const skills = Object.keys(resolution.exports).sort().filter((skill) => {
337
+ const id = resolution.exports[skill];
338
+ if (manifest === null || provided === null)
339
+ return !lockedSpec(id);
340
+ return provided.has(id) && manifest.artifacts[id]?.kind !== "spec";
341
+ });
342
+ const folders = projectFolders().map((entry) => ({ ...entry, skills: new Set(exportedIn(root, entry.folder)) }));
343
+ return skills.map((skill) => {
344
+ const playbook = manifest?.artifacts[resolution.exports[skill]]?.kind === "playbook";
345
+ const placed = [];
346
+ const yours = [];
347
+ for (const folder of folders) {
348
+ if (playbook && !folder.playbooks)
349
+ continue;
350
+ if (folder.skills.has(skill))
351
+ placed.push(folder.folder);
352
+ else if (standing(join(root, ...folder.folder.split("/"), skill)))
353
+ yours.push(folder.folder);
354
+ }
355
+ let why = null;
356
+ if (placed.length === 0) {
357
+ why = yours.length > 0 ? `yours is in ${yours.join(", ")}`
358
+ : state === "files missing" ? "files missing"
359
+ : state === "not installed" ? (name === BUILTIN_PACKAGE_NAME ? "the Spex app installs it" : "not installed")
360
+ : "spex install places it";
361
+ }
362
+ return { skill, placed, yours, why };
363
+ });
364
+ }
365
+ /** One skill's place as a line's cell: its folders, with those yours
366
+ * keeps it out of, or `not placed` with why. */
367
+ export function placeText(place) {
368
+ if (place.placed.length === 0)
369
+ return `not placed: ${place.why ?? "spex install places it"}`;
370
+ return `${place.placed.join(", ")}${place.yours.length > 0 ? `, not ${place.yours.join(", ")} (yours is there)` : ""}`;
371
+ }
372
+ /** Rows aligned in columns, two spaces apart, under a two-space indent;
373
+ * a column no row fills is left out. */
374
+ export function table(rows) {
375
+ const widths = rows.reduce((out, row) => row.map((cell, at) => Math.max(out[at] ?? 0, cell.length)), []);
376
+ const kept = widths.map((width, at) => (width > 0 ? at : -1)).filter((at) => at >= 0);
377
+ const last = kept.at(-1);
378
+ return rows.map((row) => ` ${kept.map((at) => (at === last ? row[at] ?? "" : (row[at] ?? "").padEnd(widths[at]))).join(" ")}`.trimEnd());
379
+ }
380
+ /** The lines of a package's skills under its line: each skill with where
381
+ * it stands for the agents (cli-2, cli-4). */
382
+ export function skillLines(root, lock, name, state) {
383
+ return table(skillPlaces(root, lock, name, state).map((place) => [place.skill, placeText(place)]));
384
+ }
385
+ /** A provided spec's place as a line, in a project's Packages tab's
386
+ * words (cli-6, environments-41), an edited copy naming the newer
387
+ * release's version where one waits; an edited copy its package no
388
+ * longer places, the project's own now, reads as edited too (DR-172). */
389
+ export function specText(placement) {
390
+ switch (placement.state) {
391
+ case "placed": return `spec in ${placement.path}`;
392
+ case "edited": return `spec edited in specs/ — left as yours${placement.waitingVersion ? `, ${placement.waitingVersion} waiting` : ""}`;
393
+ case "blocked": return `spec not placed — specs/ holds ${posix.basename(placement.path)} already`;
394
+ case "no-specs": return "spec needs specs/ — spex scaffold";
395
+ }
396
+ }
397
+ /** The lines beneath a package of its provided spec (cli-2, cli-4,
398
+ * cli-6): where it stands, then one line per package its links wait
399
+ * for, with the command adding it. */
400
+ export function specLines(placements, name, indent = " ") {
401
+ return placements.filter((placement) => placement.name === name).flatMap((placement) => [
402
+ `${indent}${specText(placement)}`,
403
+ ...placement.waiting.map((wait) => `${indent}${wait.count === 1 ? "1 link waits" : `${wait.count} links wait`} for ${wait.name} — spex add ${wait.name}`),
404
+ ]);
405
+ }
406
+ export function lockChanges(root, before, after) {
407
+ const out = [];
408
+ const names = new Set([...Object.keys(before?.packages ?? {}), ...Object.keys(after.packages)]);
409
+ for (const name of [...names].sort()) {
410
+ const was = before?.packages[name];
411
+ const now = after.packages[name];
412
+ const from = was ? versionOf(root, name, was) : null;
413
+ const to = now ? versionOf(root, name, now) : null;
414
+ const moved = was !== undefined && now !== undefined && sourceKind(was) !== sourceKind(now);
415
+ if (from !== to || moved)
416
+ out.push({ name, from, to, ...(moved ? { source: sourceLabel(name, now) } : {}) });
417
+ }
418
+ return out;
419
+ }
420
+ /** A resolution's source with no version: where its files come from. */
421
+ function sourceKind(resolution) {
422
+ const source = resolution.source;
423
+ if (isRegistrySource(source))
424
+ return `registry ${source.registry}`;
425
+ if (isGitSource(source))
426
+ return `git ${source.git} ${source.commit} ${source.path ?? ""}`;
427
+ return `path ${source.path}`;
428
+ }
429
+ /** A change as a reader reads it: added, with the packages it came for
430
+ * where `spex.yaml` does not add it itself; updated, with both versions
431
+ * and its new source; removed. */
432
+ export function changeLine(change, lock, added) {
433
+ if (change.from === null) {
434
+ const requiredBy = lock?.packages[change.name]?.requiredBy ?? [];
435
+ const forOthers = added !== undefined && !added.has(change.name) && requiredBy.length > 0 ? ` for ${requiredBy.join(", ")}` : "";
436
+ return `Added ${change.name} ${change.to}${forOthers}`;
437
+ }
438
+ if (change.to === null)
439
+ return `Removed ${change.name} ${change.from}`;
440
+ const version = change.from === change.to ? change.to : `${change.from} → ${change.to}`;
441
+ return `Updated ${change.name} ${version}${change.source ? `, now ${change.source}` : ""}`;
442
+ }
443
+ /** The lines naming each package gained, updated or removed, with where
444
+ * each one's spec and skills went — a removed package's edited copy left
445
+ * as the project's own (cli-2, cli-3, environments-41). */
446
+ export function gainedLines(root, settled, added) {
447
+ const lines = [];
448
+ const states = packageStates(root, settled.lock);
449
+ for (const change of lockChanges(root, settled.before, settled.lock)) {
450
+ lines.push(changeLine(change, settled.lock, added), ...specLines(settled.exported.specs, change.name));
451
+ if (change.to === null)
452
+ continue;
453
+ lines.push(...skillLines(root, settled.lock, change.name, states.get(change.name)));
454
+ }
455
+ return lines;
456
+ }
457
+ /** The line naming the app's built-in spec package an install left to
458
+ * the app, no seed and no registry serving it: marked built in, for
459
+ * the Spex app to install (cli-4). */
460
+ export function leftToAppLine(name, version) {
461
+ return `${name} ${version} built in — the Spex app installs it when it opens this project`;
462
+ }
463
+ /** The lines naming each spec package an install left to the app. */
464
+ export function leftToAppLines(root, settled) {
465
+ return (settled.install.left ?? []).map((name) => leftToAppLine(name, versionOf(root, name, settled.lock.packages[name])));
466
+ }
467
+ /** The lines naming each folder package whose folder is not at its path
468
+ * here (environments-7). */
469
+ export function missingPathLines(settled) {
470
+ return settled.install.missingPaths.map((name) => {
471
+ const source = settled.lock.packages[name]?.source;
472
+ return `Files missing for ${name}: no folder at ${source && isPathSource(source) ? source.path : "its path"}`;
473
+ });
474
+ }
475
+ //# sourceMappingURL=settle.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from "./run.js";
2
+ export declare const update: Command;
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // `spex update` (cli-5, environments-5): pick again the newest versions
4
+ // `spex.yaml` allows, install and place the skills and specs, and print
5
+ // each package whose version changed, with both versions and where its
6
+ // spec stands — an edited copy left as the reader's, the newer release
7
+ // waiting — or that everything is up to date. A `spex.lock` that does
8
+ // not read is written anew.
9
+ import { Environment } from "./environment.js";
10
+ import { changeLine, leftToAppLines, lockChanges, missingPathLines, settle, specLines } from "./settle.js";
11
+ import { parsed, Refusal } from "./run.js";
12
+ export const update = async (args) => {
13
+ parsed("update", args, {}, { min: 0, max: 0 });
14
+ const env = new Environment();
15
+ const read = env.readRequests();
16
+ if (read === null)
17
+ throw new Refusal(`no spex.yaml in ${env.root} — spex add <org>/<pkg>`);
18
+ const settled = await settle(env, "resolve");
19
+ if (settled === null)
20
+ return;
21
+ // Each version changed, both named; a source changed at one version is
22
+ // no change of version (cli-5).
23
+ const added = new Set(Object.keys(read.requests.packages));
24
+ const lines = lockChanges(env.root, settled.before, settled.lock)
25
+ .filter((change) => change.from !== change.to)
26
+ .flatMap((change) => [
27
+ changeLine({ name: change.name, from: change.from, to: change.to }, settled.lock, added),
28
+ ...specLines(settled.exported.specs, change.name),
29
+ ]);
30
+ if (settled.before === null && settled.lockWritten)
31
+ lines.unshift("Wrote spex.lock");
32
+ else if (lines.length === 0)
33
+ lines.push("Up to date");
34
+ lines.push(...missingPathLines(settled), ...leftToAppLines(env.root, settled));
35
+ console.log(lines.join("\n"));
36
+ };
37
+ //# sourceMappingURL=update.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from "./run.js";
2
+ export declare const whoami: Command;