mapsource-node 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # Mapsource Node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Mapsource Node provides a terminal dashboard for Mapsource infrastructure and
4
+ an enrollment client for compatible Linux read-engine hosts.
5
+
6
+ ```sh
7
+ npm install --global mapsource-node@next
8
+ mapsource-node
9
+ ```
10
+
11
+ Use Node.js 24.14 or newer on Debian or Ubuntu on x86-64 or ARM64. OpenTUI runs
12
+ under the included Bun runtime. On a system that enforces dependency Node
13
+ engine constraints, pass `--engine-strict=false` when installing this release.
14
+
15
+ Use `mapsource-node --json` for a read-only telemetry snapshot. The Services
16
+ tab shows recent queue depth and latency when the local controller measures
17
+ them. The operator can run `mapsource-node services` on a configured enrollment
18
+ authority to see the available service profiles.
19
+
20
+ ```sh
21
+ mapsource-node invite --node new-node --services search,routing --out ./sync-key
22
+ mapsource-node setup --key-file ./sync-key
23
+ mapsource-node status
24
+ ```
25
+
26
+ Run the first command on the authority and the others on the new host. Keep
27
+ the key file private and remove it after the node claims the invitation.
28
+ Run `mapsource-node resume` after an interruption. A registered Cloudflare
29
+ peer endpoint establishes node identity and transport. Serving traffic
30
+ requires a separate fleet admission. Use `disable` or `retire` to preview
31
+ the services affected by either operation.
32
+
33
+ Use `mapsource-node --help` for the CLI and [RELEASING.md](RELEASING.md) for
34
+ publishing.
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { createRequire } from "node:module";
4
+ import { readFile } from "node:fs/promises";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const require = createRequire(import.meta.url);
8
+ const pkg = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
9
+ const [command, ...args] = process.argv.slice(2);
10
+
11
+ try {
12
+ if (command === "--version" && !args.length) console.log(`mapsource-node ${pkg.version}`);
13
+ else if (command === "--json" && !args.length) {
14
+ const { readTelemetry } = await import("../src/telemetry.ts");
15
+ console.log(JSON.stringify(await readTelemetry(), null, 2));
16
+ } else if (command === undefined || command === "--self-test") {
17
+ if (command === undefined && await (await import("../src/commands.mjs")).firstRun()) process.exit(0);
18
+ const candidates = { x64: "@oven/bun-linux-x64-baseline", arm64: "@oven/bun-linux-aarch64" };
19
+ const platform = candidates[process.arch];
20
+ if (process.platform !== "linux" || !platform) throw new Error("The terminal interface requires Linux x64 or ARM64.");
21
+ const executable = require.resolve(`${platform}/bin/bun`);
22
+ const entrypoint = fileURLToPath(new URL("../src/index.ts", import.meta.url));
23
+ const child = spawn(executable, ["--no-env-file", entrypoint, ...process.argv.slice(2)], {
24
+ stdio: "inherit",
25
+ env: { ...process.env, OPENTUI_LIBC: "glibc", MAPSOURCE_NODE_BUILD: pkg.version },
26
+ });
27
+ const signalChild = () => child.kill("SIGTERM");
28
+ process.once("SIGTERM", signalChild);
29
+ try {
30
+ process.exitCode = await new Promise((resolve, reject) => {
31
+ child.once("error", reject);
32
+ child.once("exit", (code, signal) => resolve(code ?? (signal === "SIGINT" ? 130 : 1)));
33
+ });
34
+ } finally {
35
+ process.removeListener("SIGTERM", signalChild);
36
+ }
37
+ } else {
38
+ const { main } = await import("../src/commands.mjs");
39
+ await main(command, args);
40
+ }
41
+ } catch (error) {
42
+ process.stderr.write(`mapsource-node: ${error.message}\n`);
43
+ process.exitCode = 1;
44
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "mapsource-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Mapsource node operations and enrollment",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
7
+ "repository": { "type": "git", "url": "git+https://github.com/robit-man/mapsource-node.git" },
8
+ "homepage": "https://mapsource.io",
9
+ "bin": { "mapsource-node": "bin/mapsource-node.mjs" },
10
+ "files": ["bin/", "src/", "protocol/"],
11
+ "engines": { "node": ">=24.14.0" },
12
+ "os": ["linux"],
13
+ "cpu": ["x64", "arm64"],
14
+ "packageManager": "npm@11.9.0",
15
+ "scripts": {
16
+ "check": "npm run typecheck && npm test && npm run test:tui",
17
+ "typecheck": "tsc --noEmit && node scripts/check-source.mjs",
18
+ "test": "node --test test/*.test.mjs",
19
+ "test:tui": "node bin/mapsource-node.mjs --self-test",
20
+ "release": "node scripts/release.mjs"
21
+ },
22
+ "dependencies": {
23
+ "@opentui/core": "0.9.9"
24
+ },
25
+ "optionalDependencies": {
26
+ "@oven/bun-linux-aarch64": "1.4.5",
27
+ "@oven/bun-linux-x64-baseline": "1.4.5"
28
+ },
29
+ "devDependencies": {
30
+ "@types/bun": "1.3.14",
31
+ "typescript": "6.0.3"
32
+ },
33
+ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" }
34
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "schema": "mapsource-mirror-runtime.v1",
3
+ "nodeVersion": "24.14.0",
4
+ "pnpmVersion": "10.27.0",
5
+ "cloudflaredVersion": "2026.10.0",
6
+ "cloudflaredSha256": {
7
+ "arm64": "e6422b9d4f72d3194bc5a38676f13667c06666523217b842a877d72a80b5ac08",
8
+ "x64": "d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db"
9
+ },
10
+ "nodeSha256": {
11
+ "arm64": "e7adfca03d9173276114a6f2219df1a7d25e1bfd6bbd771d3f839118a2053094",
12
+ "x64": "41cd79bb7877c81605a9e68ec4c91547774f46a40c67a17e34d7179ef11729df"
13
+ },
14
+ "images": {
15
+ "overpass": {
16
+ "arm64": "wiktorn/overpass-api:v0.7.62.11@sha256:1f54ea54d04011af6a7e0b8166bc147c152081ee1a5c88d64fb4b8a38794f83c",
17
+ "x64": "wiktorn/overpass-api:v0.7.62.11@sha256:5f643f2aa500333f19458fe8be14457215d6e0b9f891ca5c5ed452b1f8882c47"
18
+ },
19
+ "tiles": {
20
+ "arm64": "maptiler/tileserver-gl:v5.6.0@sha256:2bee34c072c07d694f6fac75e17d2feb6227eaab007177179e9740822ab89cc6",
21
+ "x64": "maptiler/tileserver-gl:v5.6.0@sha256:f5f954587478ca6be606f834fba1880b5ddd9c958132ded79a573bc1790a8bf0"
22
+ },
23
+ "routing": {
24
+ "arm64": "ghcr.io/valhalla/valhalla-scripted@sha256:7dc78be25a7f8718b2fefe8b6d735812bc71c3c88628bfbcfb0e24620cec0244",
25
+ "x64": "ghcr.io/valhalla/valhalla-scripted@sha256:be108b27664e43eaf3388c719dc9806e5ff1cbe753be32c799d86812dc28432f"
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,531 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import {
4
+ lstat,
5
+ mkdir,
6
+ mkdtemp,
7
+ open,
8
+ opendir,
9
+ readFile,
10
+ readlink,
11
+ readdir,
12
+ realpath,
13
+ rename,
14
+ rm,
15
+ stat,
16
+ statfs,
17
+ utimes,
18
+ writeFile,
19
+ } from "node:fs/promises";
20
+ import { tmpdir, userInfo } from "node:os";
21
+ import path from "node:path";
22
+ import { fileURLToPath } from "node:url";
23
+
24
+ export const REPO_ROOT = fileURLToPath(new URL("../", import.meta.url));
25
+ export const PROJECT_TEMP_PREFIXES = ["mapsource-"];
26
+ export const DEFAULT_FREE_SPACE_FLOOR_BYTES = 10 * 1024 ** 3;
27
+
28
+ const DAY = 86_400_000;
29
+ // The directory descriptor protects callbacks from other processes' scanners;
30
+ // this set also protects same-process cleanup, including injected reference
31
+ // inventories, without relying on a callback's cwd, argv or ordinary files.
32
+ const activeTempDirectories = new Set();
33
+
34
+ /**
35
+ * Retained diagnostics are deliberately separate from runtime databases.
36
+ * Anything worth preserving longer belongs in docs/ or another reviewed,
37
+ * durable store rather than having these ceilings raised indefinitely.
38
+ */
39
+ export const RETAINED_ARTIFACT_POLICIES = Object.freeze({
40
+ diagnostics: Object.freeze({
41
+ id: "diagnostics",
42
+ root: path.join(REPO_ROOT, ".local", "diagnostics"),
43
+ maxFileBytes: 16 * 1024 ** 2,
44
+ maxBytes: 256 * 1024 ** 2,
45
+ maxCount: 80,
46
+ maxAgeMs: 14 * DAY,
47
+ freeSpaceFloorBytes: DEFAULT_FREE_SPACE_FLOOR_BYTES,
48
+ }),
49
+ qualification: Object.freeze({
50
+ id: "qualification",
51
+ root: path.join(REPO_ROOT, ".aiwg", "testing"),
52
+ maxFileBytes: 32 * 1024 ** 2,
53
+ maxBytes: 512 * 1024 ** 2,
54
+ maxCount: 120,
55
+ maxAgeMs: 90 * DAY,
56
+ freeSpaceFloorBytes: DEFAULT_FREE_SPACE_FLOOR_BYTES,
57
+ }),
58
+ });
59
+
60
+ function errorCode(error) {
61
+ return error && typeof error === "object" && "code" in error ? error.code : undefined;
62
+ }
63
+
64
+ function currentUid() {
65
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
66
+ }
67
+
68
+ function within(root, target) {
69
+ const relative = path.relative(path.resolve(root), path.resolve(target));
70
+ return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
71
+ }
72
+
73
+ /** Resolve two directories through a single visible Linux mount. Separate bind
74
+ * mounts can report the same device while rename(2) still rejects crossing
75
+ * their mount IDs. Only aliases of the same backing paths are considered. */
76
+ export function publicationAliases(mountInfo, source, destinationParent) {
77
+ const decode = value => value.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
78
+ const mounts = mountInfo.trim().split("\n").map(line => {
79
+ const [id, , device, root, target] = line.split(" ");
80
+ return { id, device, root: decode(root), target: decode(target) };
81
+ });
82
+ const contains = (root, target) => root === target || within(root, target);
83
+ const mountAt = filename => mounts.reduce((selected, mount) =>
84
+ contains(mount.target, filename) && (!selected || mount.target.length >= selected.target.length) ? mount : selected, undefined);
85
+ const from = mountAt(source), to = mountAt(destinationParent);
86
+ if (!from || !to || from.device !== to.device) throw new Error("Release publication requires the same filesystem");
87
+ if (from.id === to.id) return [source, destinationParent];
88
+ const sourcePath = path.join(from.root, path.relative(from.target, source));
89
+ const parentPath = path.join(to.root, path.relative(to.target, destinationParent));
90
+ for (const mount of mounts) {
91
+ if (mount.device !== from.device || !contains(mount.root, sourcePath) || !contains(mount.root, parentPath)) continue;
92
+ const sourceAlias = path.join(mount.target, path.relative(mount.root, sourcePath));
93
+ const parentAlias = path.join(mount.target, path.relative(mount.root, parentPath));
94
+ if (mountAt(sourceAlias)?.id === mount.id && mountAt(parentAlias)?.id === mount.id) return [sourceAlias, parentAlias];
95
+ }
96
+ throw new Error("Release publication requires a visible common mount for its staging and destination directories");
97
+ }
98
+
99
+ export async function atomicPublicationPaths(source, destination) {
100
+ if (process.platform !== "linux") return [source, destination];
101
+ const parent = path.dirname(destination);
102
+ const [from, to, mounts] = await Promise.all([realpath(source), realpath(parent), readFile("/proc/self/mountinfo", "utf8")]);
103
+ if (from !== source || to !== parent) throw new Error("Release publication paths must not traverse symlinks");
104
+ const [sourceAlias, parentAlias] = publicationAliases(mounts, source, parent);
105
+ for (const [original, alias] of [[source, sourceAlias], [parent, parentAlias]]) {
106
+ if (alias === original) continue;
107
+ const [identity, resolved, canonical] = await Promise.all([lstat(original), lstat(alias), realpath(alias)]);
108
+ if (canonical !== alias || identity.dev !== resolved.dev || identity.ino !== resolved.ino) {
109
+ throw new Error("Release publication mount alias no longer identifies the original directory");
110
+ }
111
+ }
112
+ return [sourceAlias, path.join(parentAlias, path.basename(destination))];
113
+ }
114
+
115
+ function directChild(root, target) {
116
+ return path.dirname(path.resolve(target)) === path.resolve(root);
117
+ }
118
+
119
+ function allocatedBytes(info) {
120
+ return Number.isFinite(info.blocks) ? Number(info.blocks) * 512 : Number(info.size);
121
+ }
122
+
123
+ async function nearestExistingDirectory(target) {
124
+ let current = path.resolve(target);
125
+ while (true) {
126
+ try {
127
+ const info = await stat(current);
128
+ return info.isDirectory() ? current : path.dirname(current);
129
+ } catch (error) {
130
+ if (errorCode(error) !== "ENOENT") throw error;
131
+ const parent = path.dirname(current);
132
+ if (parent === current) throw error;
133
+ current = parent;
134
+ }
135
+ }
136
+ }
137
+
138
+ export async function freeSpacePreflight({ target, projectedBytes, floorBytes = DEFAULT_FREE_SPACE_FLOOR_BYTES }) {
139
+ if (!Number.isSafeInteger(projectedBytes) || projectedBytes < 0) throw new Error("projectedBytes must be a non-negative safe integer");
140
+ if (!Number.isSafeInteger(floorBytes) || floorBytes < 0) throw new Error("floorBytes must be a non-negative safe integer");
141
+ const directory = await nearestExistingDirectory(target);
142
+ const filesystem = await statfs(directory);
143
+ const availableBytes = Number(filesystem.bavail) * Number(filesystem.bsize);
144
+ const accepted = availableBytes - projectedBytes >= floorBytes;
145
+ const result = { target: path.resolve(target), filesystem: directory, availableBytes, projectedBytes, floorBytes, accepted };
146
+ if (!accepted) {
147
+ const error = new Error(`insufficient free space for ${result.target}: ${availableBytes} available, ${projectedBytes} projected, ${floorBytes} safety floor`);
148
+ error.storage = result;
149
+ throw error;
150
+ }
151
+ return result;
152
+ }
153
+
154
+ async function inspectTree(target, expectedUid, expectedDevice) {
155
+ const result = {
156
+ bytes: 0,
157
+ allocatedBytes: 0,
158
+ entries: 0,
159
+ oldestMtimeMs: Number.POSITIVE_INFINITY,
160
+ newestMtimeMs: 0,
161
+ ownershipValid: true,
162
+ mountBoundaryValid: true,
163
+ };
164
+
165
+ async function visit(current) {
166
+ const info = await lstat(current);
167
+ result.entries += 1;
168
+ result.bytes += Number(info.size);
169
+ result.allocatedBytes += allocatedBytes(info);
170
+ result.oldestMtimeMs = Math.min(result.oldestMtimeMs, info.mtimeMs);
171
+ result.newestMtimeMs = Math.max(result.newestMtimeMs, info.mtimeMs);
172
+ if (expectedUid !== undefined && info.uid !== expectedUid) result.ownershipValid = false;
173
+ if (info.dev !== expectedDevice) result.mountBoundaryValid = false;
174
+ if (!info.isDirectory() || info.isSymbolicLink()) return;
175
+ const directory = await opendir(current);
176
+ for await (const entry of directory) await visit(path.join(current, entry.name));
177
+ }
178
+
179
+ await visit(target);
180
+ if (!Number.isFinite(result.oldestMtimeMs)) result.oldestMtimeMs = 0;
181
+ return result;
182
+ }
183
+
184
+ export async function inspectManagedTree(target) {
185
+ const resolved = path.resolve(target);
186
+ try {
187
+ const info = await lstat(resolved);
188
+ const details = await inspectTree(resolved, currentUid(), info.dev);
189
+ return { path: resolved, exists: true, ...details };
190
+ } catch (error) {
191
+ if (errorCode(error) === "ENOENT") {
192
+ return { path: resolved, exists: false, bytes: 0, allocatedBytes: 0, entries: 0, oldestMtimeMs: 0, newestMtimeMs: 0, ownershipValid: true, mountBoundaryValid: true };
193
+ }
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ async function processReferenceTexts(procRoot = "/proc") {
199
+ const texts = [];
200
+ let entries;
201
+ try { entries = await readdir(procRoot, { withFileTypes: true }); } catch { return texts; }
202
+ for (const entry of entries) {
203
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name) || Number(entry.name) === process.pid) continue;
204
+ const base = path.join(procRoot, entry.name);
205
+ try { texts.push((await readFile(path.join(base, "cmdline"))).toString("utf8")); } catch { /* process exited */ }
206
+ try { texts.push(await readlink(path.join(base, "cwd"))); } catch { /* restricted or exited */ }
207
+ try {
208
+ const descriptors = await readdir(path.join(base, "fd"));
209
+ for (const descriptor of descriptors) {
210
+ try { texts.push((await readlink(path.join(base, "fd", descriptor))).replace(/ \(deleted\)$/, "")); } catch { /* descriptor closed */ }
211
+ }
212
+ } catch { /* restricted or exited */ }
213
+ try {
214
+ const maps = await readFile(path.join(base, "maps"), "utf8");
215
+ texts.push(maps);
216
+ } catch { /* kernel thread, restricted, or exited */ }
217
+ }
218
+ return texts;
219
+ }
220
+
221
+ function referenced(target, references) {
222
+ const resolved = path.resolve(target);
223
+ return references.some((reference) => reference === resolved
224
+ || reference.startsWith(`${resolved}${path.sep}`)
225
+ || reference.includes(resolved));
226
+ }
227
+
228
+ function producerFor(name) {
229
+ const producers = [
230
+ ["mapsource-fonts-", "services/gateway/src/fonts.test.ts"],
231
+ ["mapsource-places-", "services/gateway/src/place-index.test.ts"],
232
+ ["mapsource-facilitator-", "services/facilitator/src/config.test.ts"],
233
+ ["mapsource-render-", "services/gateway/src/browser.ts (Chromium profile)"],
234
+ ["mapsource-geoip-test-", "services/gateway/src/geoip-download.test.ts"],
235
+ ["mapsource-account-usage-test-", "scripts/account-coordinator.test.ts"],
236
+ ["mapsource-cutover-test-", "services/gateway/src/overpass-readiness.test.ts"],
237
+ ["mapsource-workflows-", "services/gateway/src/reference-workflows.test.ts"],
238
+ ["mapsource-distribution-test-", "packages/contracts/src/distribution-planner.test.ts"],
239
+ ["mapsource-vps-seed-", "scripts/deploy-vps.mjs"],
240
+ ["mapsource-distribution-seed-", "scripts/deploy-vps.mjs"],
241
+ ];
242
+ return producers.find(([prefix]) => name.startsWith(prefix))?.[1] ?? "operator/diagnostic command (not emitted by a tracked writer)";
243
+ }
244
+
245
+ /**
246
+ * Inspect or remove only direct children of the selected temp root whose names
247
+ * begin with the Mapsource prefix. No glob is expanded and symlinks are never
248
+ * followed. A target is rejected if ownership, age, mount, or liveness cannot
249
+ * be proven safe.
250
+ */
251
+ export async function scavengeProjectTemp({
252
+ root = tmpdir(),
253
+ prefixes = PROJECT_TEMP_PREFIXES,
254
+ minimumAgeMs = 6 * 60 * 60_000,
255
+ dryRun = true,
256
+ now = Date.now(),
257
+ activeReferences,
258
+ } = {}) {
259
+ if (!Array.isArray(prefixes) || prefixes.length === 0
260
+ || prefixes.some((prefix) => !PROJECT_TEMP_PREFIXES.includes(prefix))) {
261
+ throw new Error(`temporary cleanup prefixes must be selected from: ${PROJECT_TEMP_PREFIXES.join(", ")}`);
262
+ }
263
+ const resolvedRoot = await realpath(path.resolve(root));
264
+ const rootInfo = await stat(resolvedRoot);
265
+ if (!rootInfo.isDirectory()) throw new Error(`temporary root is not a directory: ${resolvedRoot}`);
266
+ const uid = currentUid();
267
+ const references = activeReferences ?? await processReferenceTexts();
268
+ const entries = await readdir(resolvedRoot, { withFileTypes: true });
269
+ const candidates = entries
270
+ .filter((entry) => prefixes.some((prefix) => entry.name.startsWith(prefix)))
271
+ .map((entry) => path.join(resolvedRoot, entry.name))
272
+ .sort();
273
+ const report = {
274
+ schema: "mapsource-artifact-scavenge.v1",
275
+ checkedAt: new Date(now).toISOString(),
276
+ root: resolvedRoot,
277
+ dryRun,
278
+ minimumAgeMs,
279
+ prefixes,
280
+ current: { count: 0, bytes: 0, allocatedBytes: 0, oldestMtime: null, newestMtime: null },
281
+ removed: { count: 0, bytes: 0, allocatedBytes: 0, paths: [] },
282
+ eligible: [],
283
+ rejectedCleanupTargets: [],
284
+ artifacts: [],
285
+ };
286
+
287
+ for (const target of candidates) {
288
+ const name = path.basename(target);
289
+ const rejection = [];
290
+ if (!directChild(resolvedRoot, target) || !prefixes.some((prefix) => name.startsWith(prefix))) rejection.push("invalid-target");
291
+ let details;
292
+ try {
293
+ details = await inspectTree(target, uid, rootInfo.dev);
294
+ } catch (error) {
295
+ rejection.push(`inspection-failed:${errorCode(error) ?? "unknown"}`);
296
+ details = { bytes: 0, allocatedBytes: 0, entries: 0, oldestMtimeMs: 0, newestMtimeMs: now, ownershipValid: false, mountBoundaryValid: false };
297
+ }
298
+ if (!details.ownershipValid) rejection.push("ownership-mismatch");
299
+ if (!details.mountBoundaryValid) rejection.push("mount-boundary");
300
+ if (now - details.newestMtimeMs < minimumAgeMs) rejection.push("too-young");
301
+ if (referenced(target, references) || referenced(target, [...activeTempDirectories])) rejection.push("active-process-reference");
302
+ const artifact = {
303
+ path: target,
304
+ owner: userInfo().username,
305
+ ownerUid: uid,
306
+ producer: producerFor(name),
307
+ bytes: details.bytes,
308
+ allocatedBytes: details.allocatedBytes,
309
+ entries: details.entries,
310
+ oldestMtime: details.oldestMtimeMs ? new Date(details.oldestMtimeMs).toISOString() : null,
311
+ newestMtime: details.newestMtimeMs ? new Date(details.newestMtimeMs).toISOString() : null,
312
+ rejection,
313
+ };
314
+ report.artifacts.push(artifact);
315
+ report.current.count += 1;
316
+ report.current.bytes += details.bytes;
317
+ report.current.allocatedBytes += details.allocatedBytes;
318
+ if (!report.current.oldestMtime || artifact.oldestMtime < report.current.oldestMtime) report.current.oldestMtime = artifact.oldestMtime;
319
+ if (!report.current.newestMtime || artifact.newestMtime > report.current.newestMtime) report.current.newestMtime = artifact.newestMtime;
320
+ if (rejection.length) {
321
+ report.rejectedCleanupTargets.push({ path: target, reasons: rejection });
322
+ continue;
323
+ }
324
+ report.eligible.push(target);
325
+ if (dryRun) continue;
326
+ await rm(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
327
+ report.removed.count += 1;
328
+ report.removed.bytes += details.bytes;
329
+ report.removed.allocatedBytes += details.allocatedBytes;
330
+ report.removed.paths.push(target);
331
+ }
332
+ return report;
333
+ }
334
+
335
+ export async function withProjectTempDirectory(prefix, action, {
336
+ root = tmpdir(),
337
+ projectedBytes = 0,
338
+ freeSpaceFloorBytes = DEFAULT_FREE_SPACE_FLOOR_BYTES,
339
+ } = {}) {
340
+ if (!PROJECT_TEMP_PREFIXES.some((known) => prefix.startsWith(known)) || /[\\/]/.test(prefix)) {
341
+ throw new Error(`temporary prefix is not Mapsource-owned: ${prefix}`);
342
+ }
343
+ await freeSpacePreflight({ target: root, projectedBytes, floorBytes: freeSpaceFloorBytes });
344
+ const directory = await mkdtemp(path.join(path.resolve(root), prefix));
345
+ let lease, canonical;
346
+ try {
347
+ lease = await open(directory, "r");
348
+ canonical = await realpath(directory);
349
+ activeTempDirectories.add(canonical);
350
+ return await action(directory);
351
+ } finally {
352
+ activeTempDirectories.delete(canonical);
353
+ try { await lease?.close(); }
354
+ finally { await rm(directory, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); }
355
+ }
356
+ }
357
+
358
+ async function processAlive(pid) {
359
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
360
+ try { process.kill(pid, 0); return true; } catch (error) { return errorCode(error) === "EPERM"; }
361
+ }
362
+
363
+ export async function withProjectLock(name, action, { root = path.join(REPO_ROOT, ".local", "locks"), staleAfterMs = 60_000 } = {}) {
364
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) throw new Error(`invalid lock name: ${name}`);
365
+ const resolvedRoot = path.resolve(root);
366
+ await mkdir(resolvedRoot, { recursive: true, mode: 0o700 });
367
+ const lock = path.join(resolvedRoot, `mapsource-${name}.lock`);
368
+ const claim = async () => {
369
+ try {
370
+ await mkdir(lock, { mode: 0o700 });
371
+ await writeFile(path.join(lock, "owner.json"), `${JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() })}\n`, { flag: "wx", mode: 0o600 });
372
+ return;
373
+ } catch (error) {
374
+ if (errorCode(error) !== "EEXIST") throw error;
375
+ }
376
+ let owner;
377
+ let info;
378
+ try { owner = JSON.parse(await readFile(path.join(lock, "owner.json"), "utf8")); } catch { owner = {}; }
379
+ try { info = await lstat(lock); } catch (error) { if (errorCode(error) === "ENOENT") return claim(); throw error; }
380
+ if (info.uid !== currentUid()) throw new Error(`lock is not owned by this user: ${lock}`);
381
+ if (await processAlive(Number(owner.pid))) throw new Error(`overlapping ${name} run is active as pid ${owner.pid}`);
382
+ if (Date.now() - info.mtimeMs < staleAfterMs) throw new Error(`inactive ${name} lock is younger than the stale threshold: ${lock}`);
383
+ await rm(lock, { recursive: true, force: true });
384
+ return claim();
385
+ };
386
+ await claim();
387
+ try {
388
+ return await action();
389
+ } finally {
390
+ await rm(lock, { recursive: true, force: true });
391
+ }
392
+ }
393
+
394
+ async function listRetainedFiles(policy) {
395
+ const root = path.resolve(policy.root);
396
+ let rootInfo;
397
+ try { rootInfo = await stat(root); } catch (error) { if (errorCode(error) === "ENOENT") return []; throw error; }
398
+ const uid = currentUid();
399
+ const files = [];
400
+ async function visit(directory) {
401
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
402
+ const target = path.join(directory, entry.name);
403
+ const info = await lstat(target);
404
+ if (info.uid !== uid || info.dev !== rootInfo.dev || info.isSymbolicLink()) {
405
+ files.push({ path: target, rejected: "ownership-mount-or-symlink", bytes: 0, allocatedBytes: 0, mtimeMs: info.mtimeMs });
406
+ } else if (info.isDirectory()) await visit(target);
407
+ else if (info.isFile()) files.push({ path: target, bytes: Number(info.size), allocatedBytes: allocatedBytes(info), mtimeMs: info.mtimeMs });
408
+ }
409
+ }
410
+ await visit(root);
411
+ return files;
412
+ }
413
+
414
+ export async function retainedArtifactStatus(policy, now = Date.now()) {
415
+ const files = await listRetainedFiles(policy);
416
+ const accepted = files.filter((file) => !file.rejected);
417
+ return {
418
+ id: policy.id,
419
+ root: path.resolve(policy.root),
420
+ limits: {
421
+ maxFileBytes: policy.maxFileBytes,
422
+ maxBytes: policy.maxBytes,
423
+ maxCount: policy.maxCount,
424
+ maxAgeMs: policy.maxAgeMs,
425
+ freeSpaceFloorBytes: policy.freeSpaceFloorBytes,
426
+ },
427
+ current: {
428
+ count: accepted.length,
429
+ bytes: accepted.reduce((total, file) => total + file.bytes, 0),
430
+ allocatedBytes: accepted.reduce((total, file) => total + file.allocatedBytes, 0),
431
+ oldestArtifact: accepted.length ? new Date(Math.min(...accepted.map((file) => file.mtimeMs))).toISOString() : null,
432
+ },
433
+ rejectedCleanupTargets: files.filter((file) => file.rejected).map((file) => ({ path: file.path, reason: file.rejected })),
434
+ expiredCount: accepted.filter((file) => now - file.mtimeMs > policy.maxAgeMs).length,
435
+ };
436
+ }
437
+
438
+ export async function enforceRetainedArtifactPolicy(policy, { dryRun = true, protect = [], now = Date.now() } = {}) {
439
+ const files = await listRetainedFiles(policy);
440
+ const rejectedCleanupTargets = files.filter((file) => file.rejected).map((file) => ({ path: file.path, reason: file.rejected }));
441
+ const candidates = files.filter((file) => !file.rejected).sort((left, right) => left.mtimeMs - right.mtimeMs || left.path.localeCompare(right.path));
442
+ const protectedPaths = new Set(protect.map((target) => path.resolve(target)));
443
+ const sizeOf = file => policy.allocated ? file.allocatedBytes : file.bytes;
444
+ let count = candidates.length;
445
+ let bytes = candidates.reduce((total, file) => total + sizeOf(file), 0);
446
+ const selected = [];
447
+ for (const file of candidates) {
448
+ const expired = now - file.mtimeMs > policy.maxAgeMs;
449
+ const oversized = sizeOf(file) > policy.maxFileBytes;
450
+ const overAggregate = count > policy.maxCount || bytes > policy.maxBytes;
451
+ if ((!expired && !oversized && !overAggregate) || protectedPaths.has(path.resolve(file.path))) continue;
452
+ selected.push(file);
453
+ count -= 1;
454
+ bytes -= sizeOf(file);
455
+ }
456
+ if (count > policy.maxCount || bytes > policy.maxBytes) {
457
+ throw new Error(`retention limits cannot be met without deleting a protected artifact in ${policy.root}`);
458
+ }
459
+ if (!dryRun) for (const file of selected) await rm(file.path, { force: true });
460
+ return {
461
+ id: policy.id,
462
+ root: path.resolve(policy.root),
463
+ dryRun,
464
+ removed: { count: dryRun ? 0 : selected.length, bytes: dryRun ? 0 : selected.reduce((total, file) => total + file.bytes, 0), paths: dryRun ? [] : selected.map((file) => file.path) },
465
+ eligible: selected.map((file) => file.path),
466
+ rejectedCleanupTargets,
467
+ remaining: { count, bytes },
468
+ };
469
+ }
470
+
471
+ export async function writeRetainedArtifact(policy, relativeTarget, data) {
472
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
473
+ return writeRetained(policy, relativeTarget, buffer.byteLength, handle => handle.writeFile(buffer));
474
+ }
475
+
476
+ export async function writeRetainedArtifactFromFile(policy, relativeTarget, source) {
477
+ const info = await lstat(source);
478
+ if (!info.isFile() || info.uid !== currentUid()) throw new Error("Retained artifact source must be a regular file owned by this user");
479
+ return writeRetained(policy, relativeTarget, info.size, async handle => {
480
+ const input = createReadStream(source);
481
+ let written = 0;
482
+ for await (const data of input) {
483
+ if (written + data.length > info.size) throw new Error("Retained artifact grew during copy");
484
+ await handle.writeFile(data);
485
+ written += data.length;
486
+ }
487
+ if (written !== info.size) throw new Error("Retained artifact shrank during copy");
488
+ });
489
+ }
490
+
491
+ async function writeRetained(policy, relativeTarget, bytes, write) {
492
+ const target = path.resolve(policy.root, relativeTarget);
493
+ if (!within(policy.root, target)) throw new Error(`artifact target escapes ${policy.root}: ${relativeTarget}`);
494
+ if (!policy.diskBounded && bytes > policy.maxFileBytes) throw new Error(`artifact exceeds ${policy.maxFileBytes} byte per-file limit: ${target}`);
495
+ await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
496
+ const rootInfo = await stat(policy.root);
497
+ const parentInfo = await stat(path.dirname(target));
498
+ const canonicalRoot = await realpath(policy.root);
499
+ const canonicalParent = await realpath(path.dirname(target));
500
+ if (canonicalParent !== canonicalRoot && !within(canonicalRoot, canonicalParent)) {
501
+ throw new Error(`artifact target has a parent outside the managed root: ${target}`);
502
+ }
503
+ if (rootInfo.uid !== currentUid() || parentInfo.uid !== currentUid() || rootInfo.dev !== parentInfo.dev) {
504
+ throw new Error(`artifact target failed ownership or mount validation: ${target}`);
505
+ }
506
+ return withProjectLock(`artifacts-${policy.id}`, async () => {
507
+ const storage = await freeSpacePreflight({ target, projectedBytes: bytes, floorBytes: policy.freeSpaceFloorBytes });
508
+ const available = storage.availableBytes - storage.floorBytes;
509
+ const retained = policy.diskBounded ? (await retainedArtifactStatus(policy)).current.allocatedBytes : 0;
510
+ // The live filesystem budget applies to checkpoint bytes. Count and age
511
+ // still bound history, independent of how large one snapshot becomes.
512
+ const limits = policy.diskBounded ? { ...policy, maxFileBytes: retained + available, maxBytes: retained + available, allocated: true } : policy;
513
+ const temporary = path.join(path.dirname(target), `.mapsource-write-${process.pid}-${randomUUID()}.tmp`);
514
+ try {
515
+ const handle = await open(temporary, "wx", 0o600);
516
+ try { await write(handle); await handle.sync(); } finally { await handle.close(); }
517
+ if (policy.diskBounded) await freeSpacePreflight({ target, projectedBytes: 0, floorBytes: policy.freeSpaceFloorBytes });
518
+ await rename(temporary, target);
519
+ const retention = await enforceRetainedArtifactPolicy(limits, { dryRun: false, protect: [target] });
520
+ return { target, bytes, storage, retention };
521
+ } finally {
522
+ await rm(temporary, { force: true });
523
+ }
524
+ });
525
+ }
526
+
527
+ /** Test helper: make an artifact old without shelling out. */
528
+ export async function ageArtifact(target, ageMs) {
529
+ const at = new Date(Date.now() - ageMs);
530
+ await utimes(target, at, at);
531
+ }