@sublang/spex 4.2.0 → 6.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 +438 -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 +12 -0
  6. package/dist/commands/auth-target.js +52 -0
  7. package/dist/commands/environment.d.ts +117 -0
  8. package/dist/commands/environment.js +399 -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 +312 -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 +71 -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 +39 -0
  38. package/dist/lib/environment/archive.js +122 -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 +23 -0
  64. package/dist/lib/environment/registries.js +48 -0
  65. package/dist/lib/environment/registry.d.ts +172 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +109 -0
  68. package/dist/lib/environment/requests.js +401 -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,123 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // The content-addressed store under the home (environments-7, DR-104):
4
+ // each distinct file once, named by its SHA-256, written once after its
5
+ // digest is verified, read-only; an executable copy apart under `x/`
6
+ // because hard links share one mode. A file stays while a lock in a
7
+ // spex repository on this device selects it.
8
+ import { randomUUID } from "node:crypto";
9
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { sha256Hex } from "./format.js";
12
+ export class DigestError extends Error {
13
+ expected;
14
+ actual;
15
+ what;
16
+ constructor(expected, actual, what) {
17
+ super(`${what}: SHA-256 ${actual} does not match the expected ${expected}`);
18
+ this.expected = expected;
19
+ this.actual = actual;
20
+ this.what = what;
21
+ this.name = "DigestError";
22
+ }
23
+ }
24
+ /** The key a store entry goes by: `<sha>` or `x/<sha>`. */
25
+ export function storeKey(sha256, executable) {
26
+ return executable ? `x/${sha256}` : sha256;
27
+ }
28
+ /** Every store entry the given locks select. */
29
+ export function lockStoreKeys(locks) {
30
+ const keys = new Set();
31
+ for (const lock of locks) {
32
+ for (const resolution of Object.values(lock.packages)) {
33
+ for (const file of resolution.files)
34
+ keys.add(storeKey(file.sha256, file.executable));
35
+ }
36
+ }
37
+ return keys;
38
+ }
39
+ const SHA_RE = /^[0-9a-f]{64}$/;
40
+ export class ContentStore {
41
+ root;
42
+ constructor(homeDir) {
43
+ this.root = join(homeDir, "store");
44
+ }
45
+ pathOf(sha256, executable) {
46
+ if (!SHA_RE.test(sha256))
47
+ throw new Error(`"${sha256}" is not a SHA-256 digest`);
48
+ return executable ? join(this.root, "x", sha256) : join(this.root, sha256);
49
+ }
50
+ has(sha256, executable) {
51
+ return existsSync(this.pathOf(sha256, executable));
52
+ }
53
+ /** Store bytes under their digest, verified first; written once. */
54
+ put(bytes, sha256, executable, what = "file") {
55
+ const target = this.pathOf(sha256, executable);
56
+ const actual = sha256Hex(bytes);
57
+ if (actual !== sha256)
58
+ throw new DigestError(sha256, actual, what);
59
+ if (existsSync(target))
60
+ return target;
61
+ const dir = executable ? join(this.root, "x") : this.root;
62
+ mkdirSync(dir, { recursive: true });
63
+ const temporary = join(this.root, `.tmp-${randomUUID()}`);
64
+ const fd = openSync(temporary, "wx", 0o600);
65
+ try {
66
+ let offset = 0;
67
+ while (offset < bytes.length)
68
+ offset += writeSync(fd, bytes, offset, bytes.length - offset);
69
+ fsyncSync(fd);
70
+ }
71
+ finally {
72
+ closeSync(fd);
73
+ }
74
+ chmodSync(temporary, executable ? 0o555 : 0o444);
75
+ if (existsSync(target))
76
+ rmSync(temporary, { force: true });
77
+ else
78
+ renameSync(temporary, target);
79
+ return target;
80
+ }
81
+ /** Every entry's key. */
82
+ keys() {
83
+ const out = [];
84
+ if (!existsSync(this.root))
85
+ return out;
86
+ for (const name of readdirSync(this.root))
87
+ if (SHA_RE.test(name))
88
+ out.push(name);
89
+ const x = join(this.root, "x");
90
+ if (existsSync(x))
91
+ for (const name of readdirSync(x))
92
+ if (SHA_RE.test(name))
93
+ out.push(`x/${name}`);
94
+ return out;
95
+ }
96
+ /** Remove every entry no lock selects; returns the removed keys. */
97
+ gc(selected) {
98
+ const removed = [];
99
+ for (const key of this.keys()) {
100
+ if (selected.has(key))
101
+ continue;
102
+ rmSync(join(this.root, ...key.split("/")), { force: true });
103
+ removed.push(key);
104
+ }
105
+ // A temporary file an interrupted put left behind, once it is old
106
+ // enough not to be a put still running.
107
+ if (existsSync(this.root)) {
108
+ const before = Date.now() - 60 * 60 * 1000;
109
+ for (const name of readdirSync(this.root)) {
110
+ if (!name.startsWith(".tmp-"))
111
+ continue;
112
+ const file = join(this.root, name);
113
+ try {
114
+ if (statSync(file).mtimeMs < before)
115
+ rmSync(file, { force: true });
116
+ }
117
+ catch { /* gone */ }
118
+ }
119
+ }
120
+ return removed;
121
+ }
122
+ }
123
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1,27 @@
1
+ export type TarEntryType = "file" | "directory" | "symlink" | "hardlink" | "other";
2
+ export interface TarEntry {
3
+ path: string;
4
+ type: TarEntryType;
5
+ /** Permission bits, as the header states them. */
6
+ mode: number;
7
+ /** A file's bytes; empty for every other type. */
8
+ data: Uint8Array;
9
+ /** A link's target. */
10
+ linkname?: string;
11
+ }
12
+ export interface TarInput {
13
+ path: string;
14
+ type: "file" | "directory";
15
+ mode?: number;
16
+ data?: Uint8Array;
17
+ }
18
+ /** Pack entries into an uncompressed tar, deterministically. */
19
+ export declare function writeTar(entries: TarInput[]): Uint8Array;
20
+ export declare class TarError extends Error {
21
+ constructor(message: string);
22
+ }
23
+ /** Read every entry of an uncompressed tar, PAX and GNU long names
24
+ * applied; a global PAX header is skipped. */
25
+ export declare function readTar(tar: Uint8Array): TarEntry[];
26
+ export declare function gzip(data: Uint8Array): Uint8Array;
27
+ export declare function gunzip(data: Uint8Array): Uint8Array;
@@ -0,0 +1,219 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // A minimal ustar codec for release archives (DR-104, Spex Space DR-016):
4
+ // the registry's archive is a gzipped tarball rooted at `<pkg>/`, and a
5
+ // Git source's tree comes out of `git archive` as a tar. Writing is
6
+ // deterministic — zero times and owners, entries in the given order —
7
+ // so one release always packs to the same bytes. Reading keeps every
8
+ // entry's type, so a link or special file is seen and refused, never
9
+ // followed.
10
+ import { gunzipSync, gzipSync } from "node:zlib";
11
+ const BLOCK = 512;
12
+ const encoder = new TextEncoder();
13
+ const decoder = new TextDecoder("utf-8");
14
+ function writeString(header, offset, length, value) {
15
+ const bytes = encoder.encode(value);
16
+ header.set(bytes.subarray(0, length), offset);
17
+ }
18
+ function writeOctal(header, offset, length, value) {
19
+ // length - 1 digits, then NUL.
20
+ const digits = value.toString(8).padStart(length - 1, "0");
21
+ writeString(header, offset, length - 1, digits);
22
+ header[offset + length - 1] = 0;
23
+ }
24
+ function checksum(header) {
25
+ let sum = 0;
26
+ for (let i = 0; i < BLOCK; i += 1)
27
+ sum += i >= 148 && i < 156 ? 0x20 : header[i];
28
+ return sum;
29
+ }
30
+ function headerBlock(name, prefix, mode, size, type) {
31
+ const header = new Uint8Array(BLOCK);
32
+ writeString(header, 0, 100, name);
33
+ writeOctal(header, 100, 8, mode & 0o7777);
34
+ writeOctal(header, 108, 8, 0);
35
+ writeOctal(header, 116, 8, 0);
36
+ writeOctal(header, 124, 12, size);
37
+ writeOctal(header, 136, 12, 0);
38
+ header[156] = type.charCodeAt(0);
39
+ writeString(header, 257, 6, "ustar");
40
+ header[262] = 0;
41
+ writeString(header, 263, 2, "00");
42
+ writeString(header, 345, 155, prefix);
43
+ const sum = checksum(header);
44
+ writeString(header, 148, 6, sum.toString(8).padStart(6, "0"));
45
+ header[154] = 0;
46
+ header[155] = 0x20;
47
+ return header;
48
+ }
49
+ /** Split a path into ustar's name and prefix, or undefined when it
50
+ * fits neither, and a PAX record must carry it. */
51
+ function splitUstar(path) {
52
+ const bytes = encoder.encode(path).length;
53
+ if (bytes <= 100)
54
+ return { name: path, prefix: "" };
55
+ for (let i = path.lastIndexOf("/"); i > 0; i = path.lastIndexOf("/", i - 1)) {
56
+ const prefix = path.slice(0, i);
57
+ const name = path.slice(i + 1);
58
+ if (encoder.encode(prefix).length <= 155 && encoder.encode(name).length <= 100 && name.length > 0) {
59
+ return { name, prefix };
60
+ }
61
+ }
62
+ return undefined;
63
+ }
64
+ function paxRecord(key, value) {
65
+ const body = ` ${key}=${value}\n`;
66
+ const bodyLength = encoder.encode(body).length;
67
+ // The length counts its own digits.
68
+ let length = bodyLength + 1;
69
+ while (String(length).length + bodyLength !== length)
70
+ length = String(length).length + bodyLength;
71
+ return encoder.encode(`${length}${body}`);
72
+ }
73
+ function padded(data) {
74
+ const rest = data.length % BLOCK;
75
+ return rest === 0 ? [data] : [data, new Uint8Array(BLOCK - rest)];
76
+ }
77
+ /** Pack entries into an uncompressed tar, deterministically. */
78
+ export function writeTar(entries) {
79
+ const chunks = [];
80
+ for (const entry of entries) {
81
+ const path = entry.type === "directory" && !entry.path.endsWith("/") ? `${entry.path}/` : entry.path;
82
+ const data = entry.type === "file" ? (entry.data ?? new Uint8Array()) : new Uint8Array();
83
+ const mode = entry.mode ?? (entry.type === "directory" ? 0o755 : 0o644);
84
+ let split = splitUstar(path);
85
+ if (!split) {
86
+ const record = paxRecord("path", path);
87
+ chunks.push(headerBlock("PaxHeader", "", 0o644, record.length, "x"), ...padded(record));
88
+ split = { name: path.slice(0, 100), prefix: "" };
89
+ }
90
+ chunks.push(headerBlock(split.name, split.prefix, mode, data.length, entry.type === "directory" ? "5" : "0"));
91
+ if (data.length > 0)
92
+ chunks.push(...padded(data));
93
+ }
94
+ chunks.push(new Uint8Array(BLOCK * 2));
95
+ return concat(chunks);
96
+ }
97
+ function concat(chunks) {
98
+ const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
99
+ const out = new Uint8Array(total);
100
+ let offset = 0;
101
+ for (const chunk of chunks) {
102
+ out.set(chunk, offset);
103
+ offset += chunk.length;
104
+ }
105
+ return out;
106
+ }
107
+ function readString(block, offset, length) {
108
+ const slice = block.subarray(offset, offset + length);
109
+ const end = slice.indexOf(0);
110
+ return decoder.decode(end === -1 ? slice : slice.subarray(0, end));
111
+ }
112
+ function readOctal(block, offset, length) {
113
+ const slice = block.subarray(offset, offset + length);
114
+ if (slice[0] & 0x80) {
115
+ // Base-256: GNU's encoding for large values.
116
+ let value = 0;
117
+ for (let i = 1; i < slice.length; i += 1)
118
+ value = value * 256 + slice[i];
119
+ return value;
120
+ }
121
+ const text = readString(block, offset, length).trim();
122
+ if (text === "")
123
+ return 0;
124
+ if (!/^[0-7]+$/.test(text))
125
+ throw new TarError(`malformed octal field "${text}"`);
126
+ return parseInt(text, 8);
127
+ }
128
+ function parsePax(data) {
129
+ const records = {};
130
+ let offset = 0;
131
+ while (offset < data.length) {
132
+ const space = data.indexOf(0x20, offset);
133
+ if (space === -1)
134
+ break;
135
+ const length = Number(decoder.decode(data.subarray(offset, space)));
136
+ if (!Number.isInteger(length) || length <= 0)
137
+ throw new TarError("malformed PAX record");
138
+ const record = decoder.decode(data.subarray(space + 1, offset + length - 1));
139
+ const equals = record.indexOf("=");
140
+ if (equals > 0)
141
+ records[record.slice(0, equals)] = record.slice(equals + 1);
142
+ offset += length;
143
+ }
144
+ return records;
145
+ }
146
+ export class TarError extends Error {
147
+ constructor(message) {
148
+ super(`tar: ${message}`);
149
+ this.name = "TarError";
150
+ }
151
+ }
152
+ /** Read every entry of an uncompressed tar, PAX and GNU long names
153
+ * applied; a global PAX header is skipped. */
154
+ export function readTar(tar) {
155
+ const entries = [];
156
+ let offset = 0;
157
+ let pending = {};
158
+ let longName;
159
+ let longLink;
160
+ while (offset + BLOCK <= tar.length) {
161
+ const block = tar.subarray(offset, offset + BLOCK);
162
+ if (block.every((byte) => byte === 0))
163
+ break;
164
+ const stored = readOctal(block, 148, 8);
165
+ if (stored !== checksum(block))
166
+ throw new TarError(`bad header checksum at ${offset}`);
167
+ const size = readOctal(block, 124, 12);
168
+ const typeflag = String.fromCharCode(block[156]);
169
+ const dataStart = offset + BLOCK;
170
+ if (dataStart + size > tar.length)
171
+ throw new TarError("truncated entry");
172
+ const data = tar.slice(dataStart, dataStart + size);
173
+ offset = dataStart + Math.ceil(size / BLOCK) * BLOCK;
174
+ if (typeflag === "x") {
175
+ pending = { ...pending, ...parsePax(data) };
176
+ continue;
177
+ }
178
+ if (typeflag === "g")
179
+ continue;
180
+ if (typeflag === "L") {
181
+ longName = readString(data, 0, data.length);
182
+ continue;
183
+ }
184
+ if (typeflag === "K") {
185
+ longLink = readString(data, 0, data.length);
186
+ continue;
187
+ }
188
+ const name = readString(block, 0, 100);
189
+ const magic = readString(block, 257, 6);
190
+ const prefix = magic.startsWith("ustar") ? readString(block, 345, 155) : "";
191
+ let path = pending.path ?? longName ?? (prefix ? `${prefix}/${name}` : name);
192
+ const linkname = pending.linkpath ?? longLink ?? readString(block, 157, 100);
193
+ pending = {};
194
+ longName = undefined;
195
+ longLink = undefined;
196
+ const type = typeflag === "0" || typeflag === "\0" || typeflag === "7" ? "file"
197
+ : typeflag === "5" ? "directory"
198
+ : typeflag === "2" ? "symlink"
199
+ : typeflag === "1" ? "hardlink"
200
+ : "other";
201
+ if (type === "directory" && path.endsWith("/"))
202
+ path = path.slice(0, -1);
203
+ entries.push({
204
+ path,
205
+ type,
206
+ mode: readOctal(block, 100, 8),
207
+ data: type === "file" ? data : new Uint8Array(),
208
+ ...(type === "symlink" || type === "hardlink" ? { linkname } : {}),
209
+ });
210
+ }
211
+ return entries;
212
+ }
213
+ export function gzip(data) {
214
+ return new Uint8Array(gzipSync(data, { level: 9 }));
215
+ }
216
+ export function gunzip(data) {
217
+ return new Uint8Array(gunzipSync(data));
218
+ }
219
+ //# sourceMappingURL=tar.js.map
@@ -0,0 +1,66 @@
1
+ import { type Stats } from "node:fs";
2
+ /** A canonical lowercase UUID. */
3
+ export declare const UUID: RegExp;
4
+ /** A list a language punctuates its own way (core-service-111). */
5
+ export declare const listed: (names: readonly string[]) => string;
6
+ export declare class StorageFormatError extends Error {
7
+ readonly file: string;
8
+ readonly reason: string;
9
+ constructor(file: string, reason: string);
10
+ }
11
+ /** Spex's private-storage policy over facts inspected by fs-safe. Windows
12
+ * administrators and SYSTEM are privileged principals, as root is on POSIX. */
13
+ export declare function hasPrivatePermissions(file: string, stat: Pick<Stats, "mode" | "uid">): boolean;
14
+ /** Create a Windows state root privately from its first appearance. Existing
15
+ * roots are verified, never silently repaired or admitted by synthetic mode bits. */
16
+ export declare function prepareWindowsStorageDirectory(directory: string): Promise<void>;
17
+ /** Synchronous callers use the library's same private creator. */
18
+ export declare function makePrivateDirectory(directory: string): void;
19
+ /** A directory reader never follows a linked root. Missing roots are
20
+ * empty; a present non-directory is a storage diagnostic. */
21
+ export declare function assertPlainDirectory(file: string): void;
22
+ export declare const isObject: (value: unknown) => value is Record<string, unknown>;
23
+ export declare const isText: (value: unknown) => value is string;
24
+ export declare const isTimestamp: (value: unknown) => value is number;
25
+ export declare const isUuid: (value: unknown) => value is string;
26
+ /** A normalized absolute path on this device. */
27
+ export declare const isLocalPath: (value: unknown) => value is string;
28
+ /** A recorded path keeps its source device's syntax; it never authorizes
29
+ * execution. */
30
+ export declare const isRecordedPath: (value: unknown) => value is string;
31
+ export declare function need(condition: unknown, file: string, reason: string): asserts condition;
32
+ /** A closed object: the required fields present, nothing undeclared. */
33
+ export declare function closed(value: unknown, required: string[], optional: string[], file: string): asserts value is Record<string, unknown>;
34
+ /** A reader refuses a layout version it does not know (storage-1): one
35
+ * format, or any of a list a reader reads. */
36
+ export declare function knownFormat(value: Record<string, unknown>, file: string, format?: number | readonly number[]): void;
37
+ export declare function readJsonFile(file: string): unknown;
38
+ /** Atomic same-directory replacement, synced before and after the rename. */
39
+ export declare function writeApplicationBytes(file: string, bytes: Buffer | string): void;
40
+ export declare function writeApplicationFile(file: string, value: unknown): void;
41
+ export declare const sha256: (bytes: Buffer | string) => string;
42
+ /** A file's version: the SHA-256 of its exact bytes, or null where no
43
+ * file stands. */
44
+ export type FileVersion = string | null;
45
+ /** A versioned write found its file changed since it was read: the
46
+ * caller reads again and retries (DR-111). */
47
+ export declare class VersionConflictError extends Error {
48
+ readonly file: string;
49
+ constructor(file: string);
50
+ }
51
+ /** A file's bytes with their version; null bytes where it is absent. */
52
+ export declare function readVersioned(file: string): {
53
+ bytes: Buffer | null;
54
+ version: FileVersion;
55
+ };
56
+ export declare const fileVersion: (file: string) => FileVersion;
57
+ /** Atomic same-directory replacement under a version: the file is
58
+ * checked at the instant before the rename and the write refused as a
59
+ * conflict where it no longer stands at `expected`. It is published
60
+ * with `mode` exactly, the umask applying to none of it. No folder is made:
61
+ * a write whose folder is gone is refused the same way. The temporary
62
+ * file never outlives a refusal or a failure. */
63
+ export declare function writeVersionedBytes(file: string, bytes: Buffer | string, expected: FileVersion, mode?: number): void;
64
+ /** Whether a path of a clone may leave the device: not one of the
65
+ * catalog's ignored families (storage-1, storage-17). */
66
+ export declare const portable: (file: string) => boolean;
@@ -0,0 +1,233 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // The primitives every Spex-owned file shares (storage-14): closed
4
+ // encodings checked field by field, atomic same-directory replacement —
5
+ // plain, or under the version the writer read (DR-111) — the one
6
+ // storage fault a reader reports, and which of a clone's paths may leave
7
+ // the device. Their words are the host's (words.ts).
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import { closeSync, fchmodSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
+ import { readOwnerAndDacl } from "@openclaw/fs-safe/permissions";
11
+ import { createDirectorySync, createFileSync, assertNoSymlinkParentsSync } from "@openclaw/fs-safe/advanced";
12
+ import { dirname, isAbsolute, parse, posix, resolve, win32 } from "node:path";
13
+ import { words } from "./words.js";
14
+ /** A canonical lowercase UUID. */
15
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
16
+ /** A list a language punctuates its own way (core-service-111). */
17
+ export const listed = (names) => names.join(words().listSeparator());
18
+ export class StorageFormatError extends Error {
19
+ file;
20
+ reason;
21
+ constructor(file, reason) {
22
+ super(words().storageFault(file, reason));
23
+ this.file = file;
24
+ this.reason = reason;
25
+ this.name = "StorageFormatError";
26
+ }
27
+ }
28
+ /** Spex's private-storage policy over facts inspected by fs-safe. Windows
29
+ * administrators and SYSTEM are privileged principals, as root is on POSIX. */
30
+ export function hasPrivatePermissions(file, stat) {
31
+ if (process.platform !== "win32")
32
+ return (stat.mode & 0o077) === 0 &&
33
+ (typeof process.getuid !== "function" || stat.uid === process.getuid());
34
+ const facts = readOwnerAndDacl(file);
35
+ if (facts.status !== "supported" || !facts.complete || !facts.isLocal || !facts.daclPresent || facts.unsupportedAceTypes.length)
36
+ return false;
37
+ const trusted = new Set([facts.currentUserSid, "s-1-5-18", "s-1-5-32-544"]);
38
+ return trusted.has(facts.ownerSid) && facts.aces.every(ace => ace.aceType === "deny" || ace.mask === 0 || trusted.has(ace.sid));
39
+ }
40
+ /** Create a Windows state root privately from its first appearance. Existing
41
+ * roots are verified, never silently repaired or admitted by synthetic mode bits. */
42
+ export async function prepareWindowsStorageDirectory(directory) {
43
+ if (process.platform === "win32")
44
+ makePrivateDirectory(directory);
45
+ }
46
+ /** Synchronous callers use the library's same private creator. */
47
+ export function makePrivateDirectory(directory) {
48
+ if (process.platform !== "win32") {
49
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
50
+ return;
51
+ }
52
+ assertNoSymlinkParentsSync({ rootDir: parse(directory).root, targetPath: directory, requireDirectories: true });
53
+ const info = lstatSync(directory, { throwIfNoEntry: false });
54
+ if (!info) {
55
+ const parent = dirname(directory);
56
+ if (!lstatSync(parent, { throwIfNoEntry: false }))
57
+ makePrivateDirectory(parent);
58
+ try {
59
+ createDirectorySync(directory, { private: true });
60
+ }
61
+ catch (error) {
62
+ if (!["EEXIST", "already-exists"].includes(error.code ?? ""))
63
+ throw error;
64
+ }
65
+ }
66
+ const current = lstatSync(directory);
67
+ if (current.isSymbolicLink() || !current.isDirectory() || !hasPrivatePermissions(directory, current)) {
68
+ throw new StorageFormatError(directory, "private storage permissions cannot be verified");
69
+ }
70
+ }
71
+ function assertPrivateWindowsEntry(file) {
72
+ if (process.platform !== "win32")
73
+ return;
74
+ const info = lstatSync(file);
75
+ if (info.isSymbolicLink() || !hasPrivatePermissions(file, info)) {
76
+ throw new StorageFormatError(file, "private storage permissions cannot be verified");
77
+ }
78
+ }
79
+ /** A directory reader never follows a linked root. Missing roots are
80
+ * empty; a present non-directory is a storage diagnostic. */
81
+ export function assertPlainDirectory(file) {
82
+ const info = lstatSync(file, { throwIfNoEntry: false });
83
+ if (info && (info.isSymbolicLink() || !info.isDirectory())) {
84
+ throw new StorageFormatError(file, "unsafe destination parent");
85
+ }
86
+ }
87
+ export const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
88
+ export const isText = (value) => typeof value === "string" && value.length > 0;
89
+ export const isTimestamp = (value) => Number.isSafeInteger(value) && value >= 0;
90
+ export const isUuid = (value) => typeof value === "string" && UUID.test(value);
91
+ /** A normalized absolute path on this device. */
92
+ export const isLocalPath = (value) => isText(value) && !value.includes("\0") && isAbsolute(value) && resolve(value) === value;
93
+ /** A recorded path keeps its source device's syntax; it never authorizes
94
+ * execution. */
95
+ export const isRecordedPath = (value) => isText(value) && !value.includes("\0") && (posix.isAbsolute(value) && posix.resolve(value) === value ||
96
+ (/^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\")) && win32.isAbsolute(value) && win32.resolve(value) === value);
97
+ export function need(condition, file, reason) {
98
+ if (!condition)
99
+ throw new StorageFormatError(file, reason);
100
+ }
101
+ /** A closed object: the required fields present, nothing undeclared. */
102
+ export function closed(value, required, optional, file) {
103
+ need(isObject(value), file, words().expectedObject());
104
+ need(required.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required.includes(key) || optional.includes(key)), file, words().expectedFields(listed(required), optional.length ? words().optionalFields(listed(optional)) : ""));
105
+ }
106
+ /** A reader refuses a layout version it does not know (storage-1): one
107
+ * format, or any of a list a reader reads. */
108
+ export function knownFormat(value, file, format = 1) {
109
+ const formats = typeof format === "number" ? [format] : format;
110
+ need(formats.includes(value.format), file, words().unsupportedFormat(String(value.format)));
111
+ }
112
+ export function readJsonFile(file) {
113
+ try {
114
+ return JSON.parse(readFileSync(file, "utf8"));
115
+ }
116
+ catch (error) {
117
+ throw new StorageFormatError(file, error.message);
118
+ }
119
+ }
120
+ /** Atomic same-directory replacement, synced before and after the rename. */
121
+ export function writeApplicationBytes(file, bytes) {
122
+ assertPrivateWindowsEntry(dirname(file));
123
+ const temporary = `${file}.${randomUUID()}.tmp`;
124
+ const owned = process.platform === "win32" ? createFileSync(temporary, { private: true }) : undefined;
125
+ const fd = owned?.fd ?? openSync(temporary, "wx", 0o600);
126
+ try {
127
+ writeFileSync(fd, bytes);
128
+ fsyncSync(fd);
129
+ }
130
+ finally {
131
+ if (owned)
132
+ owned.close();
133
+ else
134
+ closeSync(fd);
135
+ }
136
+ assertPrivateWindowsEntry(temporary);
137
+ renameSync(temporary, file);
138
+ // Directory handles are not supported by Windows; the file is still synced.
139
+ if (process.platform !== "win32") {
140
+ const dir = openSync(dirname(file), "r");
141
+ try {
142
+ fsyncSync(dir);
143
+ }
144
+ finally {
145
+ closeSync(dir);
146
+ }
147
+ }
148
+ }
149
+ export function writeApplicationFile(file, value) { writeApplicationBytes(file, JSON.stringify(value)); }
150
+ export const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
151
+ /** A versioned write found its file changed since it was read: the
152
+ * caller reads again and retries (DR-111). */
153
+ export class VersionConflictError extends Error {
154
+ file;
155
+ constructor(file) {
156
+ super(words().changedMeanwhile(file));
157
+ this.file = file;
158
+ this.name = "VersionConflictError";
159
+ }
160
+ }
161
+ /** A file's bytes with their version; null bytes where it is absent. */
162
+ export function readVersioned(file) {
163
+ let bytes;
164
+ try {
165
+ bytes = readFileSync(file);
166
+ }
167
+ catch (error) {
168
+ if (error.code === "ENOENT")
169
+ return { bytes: null, version: null };
170
+ throw error;
171
+ }
172
+ return { bytes, version: sha256(bytes) };
173
+ }
174
+ export const fileVersion = (file) => readVersioned(file).version;
175
+ /** Atomic same-directory replacement under a version: the file is
176
+ * checked at the instant before the rename and the write refused as a
177
+ * conflict where it no longer stands at `expected`. It is published
178
+ * with `mode` exactly, the umask applying to none of it. No folder is made:
179
+ * a write whose folder is gone is refused the same way. The temporary
180
+ * file never outlives a refusal or a failure. */
181
+ export function writeVersionedBytes(file, bytes, expected, mode = 0o600) {
182
+ if (mode === 0o600)
183
+ assertPrivateWindowsEntry(dirname(file));
184
+ const temporary = `${file}.${randomUUID()}.tmp`;
185
+ let fd;
186
+ let owned;
187
+ try {
188
+ if (process.platform === "win32" && mode === 0o600)
189
+ owned = createFileSync(temporary, { private: true });
190
+ fd = owned?.fd ?? openSync(temporary, "wx", mode);
191
+ }
192
+ catch (error) {
193
+ if (error.code === "ENOENT")
194
+ throw new VersionConflictError(file);
195
+ throw error;
196
+ }
197
+ try {
198
+ try {
199
+ writeFileSync(fd, bytes);
200
+ fchmodSync(fd, mode);
201
+ fsyncSync(fd);
202
+ }
203
+ finally {
204
+ if (owned)
205
+ owned.close();
206
+ else
207
+ closeSync(fd);
208
+ }
209
+ if (mode === 0o600)
210
+ assertPrivateWindowsEntry(temporary);
211
+ if (fileVersion(file) !== expected)
212
+ throw new VersionConflictError(file);
213
+ renameSync(temporary, file);
214
+ }
215
+ catch (error) {
216
+ rmSync(temporary, { force: true });
217
+ throw error;
218
+ }
219
+ if (process.platform !== "win32") {
220
+ const dir = openSync(dirname(file), "r");
221
+ try {
222
+ fsyncSync(dir);
223
+ }
224
+ finally {
225
+ closeSync(dir);
226
+ }
227
+ }
228
+ }
229
+ /** Whether a path of a clone may leave the device: not one of the
230
+ * catalog's ignored families (storage-1, storage-17). */
231
+ export const portable = (file) => !/^(\.spex\/|packages\/|skills\/|local\/|\.spex-uploads\/|\.spex-apply\.json$|\.lock)/.test(file) &&
232
+ !/\.(hints|spex)\.json$|(?<!^spex)\.lock(?:\.|\/|$)|\.tmp$|\.bak(?:\.|$)|\.backup(?:\.|$)/.test(file);
233
+ //# sourceMappingURL=files.js.map