@xenosystem/primitives 0.0.0-stage → 0.2.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 (107) hide show
  1. package/README.md +29 -2
  2. package/dist/cjs/dirs/atomic.d.ts +9 -0
  3. package/dist/cjs/dirs/atomic.js +59 -0
  4. package/dist/cjs/dirs/check-cli.d.ts +2 -0
  5. package/dist/cjs/dirs/check-cli.js +50 -0
  6. package/dist/cjs/dirs/check.d.ts +49 -0
  7. package/dist/cjs/dirs/check.js +158 -0
  8. package/dist/cjs/dirs/cli.d.ts +2 -0
  9. package/dist/cjs/dirs/cli.js +72 -0
  10. package/dist/cjs/dirs/dirs.d.ts +57 -0
  11. package/dist/cjs/dirs/dirs.js +135 -0
  12. package/dist/cjs/dirs/doctor.d.ts +31 -0
  13. package/dist/cjs/dirs/doctor.js +80 -0
  14. package/dist/cjs/dirs/errors.d.ts +8 -0
  15. package/dist/cjs/dirs/errors.js +19 -0
  16. package/dist/cjs/dirs/host.d.ts +4 -0
  17. package/dist/cjs/dirs/host.js +26 -0
  18. package/dist/cjs/dirs/index.d.ts +13 -0
  19. package/dist/cjs/dirs/index.js +55 -0
  20. package/dist/cjs/dirs/inputs.d.ts +14 -0
  21. package/dist/cjs/dirs/inputs.js +14 -0
  22. package/dist/cjs/dirs/layout.d.ts +16 -0
  23. package/dist/cjs/dirs/layout.js +25 -0
  24. package/dist/cjs/dirs/lock.d.ts +38 -0
  25. package/dist/cjs/dirs/lock.js +128 -0
  26. package/dist/cjs/dirs/migrate.d.ts +134 -0
  27. package/dist/cjs/dirs/migrate.js +437 -0
  28. package/dist/cjs/dirs/procinfo.d.ts +10 -0
  29. package/dist/cjs/dirs/procinfo.js +67 -0
  30. package/dist/cjs/dirs/registry.d.ts +27 -0
  31. package/dist/cjs/dirs/registry.js +78 -0
  32. package/dist/cjs/dirs/roots.d.ts +23 -0
  33. package/dist/cjs/dirs/roots.js +114 -0
  34. package/dist/cjs/dirs/segments.d.ts +7 -0
  35. package/dist/cjs/dirs/segments.js +39 -0
  36. package/dist/cjs/generated/contract.d.ts +134 -0
  37. package/dist/cjs/generated/contract.js +233 -0
  38. package/dist/cjs/package.json +1 -0
  39. package/dist/cjs/secrets/envelope.d.ts +37 -0
  40. package/dist/cjs/secrets/envelope.js +90 -0
  41. package/dist/cjs/secrets/errors.d.ts +10 -0
  42. package/dist/cjs/secrets/errors.js +20 -0
  43. package/dist/cjs/secrets/index.d.ts +4 -0
  44. package/dist/cjs/secrets/index.js +17 -0
  45. package/dist/cjs/secrets/keystore.d.ts +37 -0
  46. package/dist/cjs/secrets/keystore.js +41 -0
  47. package/dist/cjs/secrets/os-stores.d.ts +17 -0
  48. package/dist/cjs/secrets/os-stores.js +195 -0
  49. package/dist/cjs/secrets/store.d.ts +32 -0
  50. package/dist/cjs/secrets/store.js +161 -0
  51. package/dist/cjs/secrets/testing.d.ts +5 -0
  52. package/dist/cjs/secrets/testing.js +20 -0
  53. package/dist/cjs/updates/index.d.ts +67 -0
  54. package/dist/cjs/updates/index.js +102 -0
  55. package/dist/esm/dirs/atomic.d.ts +9 -0
  56. package/dist/esm/dirs/atomic.js +56 -0
  57. package/dist/esm/dirs/check-cli.d.ts +2 -0
  58. package/dist/esm/dirs/check-cli.js +48 -0
  59. package/dist/esm/dirs/check.d.ts +49 -0
  60. package/dist/esm/dirs/check.js +152 -0
  61. package/dist/esm/dirs/cli.d.ts +2 -0
  62. package/dist/esm/dirs/cli.js +70 -0
  63. package/dist/esm/dirs/dirs.d.ts +57 -0
  64. package/dist/esm/dirs/dirs.js +129 -0
  65. package/dist/esm/dirs/doctor.d.ts +31 -0
  66. package/dist/esm/dirs/doctor.js +77 -0
  67. package/dist/esm/dirs/errors.d.ts +8 -0
  68. package/dist/esm/dirs/errors.js +14 -0
  69. package/dist/esm/dirs/host.d.ts +4 -0
  70. package/dist/esm/dirs/host.js +21 -0
  71. package/dist/esm/dirs/index.d.ts +13 -0
  72. package/dist/esm/dirs/index.js +13 -0
  73. package/dist/esm/dirs/inputs.d.ts +14 -0
  74. package/dist/esm/dirs/inputs.js +11 -0
  75. package/dist/esm/dirs/layout.d.ts +16 -0
  76. package/dist/esm/dirs/layout.js +21 -0
  77. package/dist/esm/dirs/lock.d.ts +38 -0
  78. package/dist/esm/dirs/lock.js +124 -0
  79. package/dist/esm/dirs/migrate.d.ts +134 -0
  80. package/dist/esm/dirs/migrate.js +428 -0
  81. package/dist/esm/dirs/procinfo.d.ts +10 -0
  82. package/dist/esm/dirs/procinfo.js +62 -0
  83. package/dist/esm/dirs/registry.d.ts +27 -0
  84. package/dist/esm/dirs/registry.js +71 -0
  85. package/dist/esm/dirs/roots.d.ts +23 -0
  86. package/dist/esm/dirs/roots.js +107 -0
  87. package/dist/esm/dirs/segments.d.ts +7 -0
  88. package/dist/esm/dirs/segments.js +35 -0
  89. package/dist/esm/generated/contract.d.ts +134 -0
  90. package/dist/esm/generated/contract.js +230 -0
  91. package/dist/esm/secrets/envelope.d.ts +37 -0
  92. package/dist/esm/secrets/envelope.js +81 -0
  93. package/dist/esm/secrets/errors.d.ts +10 -0
  94. package/dist/esm/secrets/errors.js +15 -0
  95. package/dist/esm/secrets/index.d.ts +4 -0
  96. package/dist/esm/secrets/index.js +4 -0
  97. package/dist/esm/secrets/keystore.d.ts +37 -0
  98. package/dist/esm/secrets/keystore.js +37 -0
  99. package/dist/esm/secrets/os-stores.d.ts +17 -0
  100. package/dist/esm/secrets/os-stores.js +189 -0
  101. package/dist/esm/secrets/store.d.ts +32 -0
  102. package/dist/esm/secrets/store.js +156 -0
  103. package/dist/esm/secrets/testing.d.ts +5 -0
  104. package/dist/esm/secrets/testing.js +12 -0
  105. package/dist/esm/updates/index.d.ts +67 -0
  106. package/dist/esm/updates/index.js +97 -0
  107. package/package.json +42 -4
@@ -0,0 +1,129 @@
1
+ import { promises as fsp, readFileSync } from 'node:fs';
2
+ import { DirsError } from "./errors.js";
3
+ import { atomicWriteFile } from "./atomic.js";
4
+ import { hostEnv, hostHome, hostPlatform } from "./host.js";
5
+ import { parseLayout, SUPPORTED_LAYOUT } from "./layout.js";
6
+ import { acquireLockFile } from "./lock.js";
7
+ import { lockRelativePath, registeredRelativePath } from "./registry.js";
8
+ import { joinPath, resolveRoots, SEP } from "./roots.js";
9
+ /**
10
+ * The resolver. Every XENO path comes from here; nothing else may build one. It refuses anything the registry does
11
+ * not list, and refuses to write when the layout on disk is newer than this build understands.
12
+ */
13
+ export class XenoDirs {
14
+ platform;
15
+ roots;
16
+ warnings;
17
+ overridden;
18
+ constructor(resolved) {
19
+ this.platform = resolved.platform;
20
+ this.roots = resolved.roots;
21
+ this.warnings = resolved.warnings;
22
+ this.overridden = resolved.overridden;
23
+ }
24
+ /** Root directory of a kind. */
25
+ root(kind) {
26
+ return this.roots[kind];
27
+ }
28
+ /** Path relative to the kind root, `/`-separated, after registry validation. */
29
+ relative(kind, area, ...segments) {
30
+ return registeredRelativePath(kind, area, segments);
31
+ }
32
+ /** Absolute path for (kind, area, ...segments). Throws DirsError for anything unregistered or invalid. */
33
+ path(kind, area, ...segments) {
34
+ const rel = registeredRelativePath(kind, area, segments);
35
+ return joinPath(this.platform, this.roots[kind], ...rel.split('/'));
36
+ }
37
+ /** `run/<area>/<name>.lock`. */
38
+ lockPath(area, name) {
39
+ return joinPath(this.platform, this.roots.run, ...lockRelativePath(area, name).split('/'));
40
+ }
41
+ /** `data/layout.json`. */
42
+ layoutPath() {
43
+ return this.roots.data + SEP[this.platform] + 'layout.json';
44
+ }
45
+ /** `<kind>/<area>/area.json`, the optional per-area schema marker. */
46
+ areaMetaPath(kind, area) {
47
+ return this.path(kind, area, 'area.json');
48
+ }
49
+ /** Reads data/layout.json. Never throws for a missing file. */
50
+ readLayout() {
51
+ let text = null;
52
+ try {
53
+ text = readFileSync(this.layoutPath(), 'utf8');
54
+ }
55
+ catch (e) {
56
+ if (e.code !== 'ENOENT')
57
+ return { state: 'invalid', reason: 'unreadable' };
58
+ }
59
+ return parseLayout(text);
60
+ }
61
+ /** Throws unless this build may write: a newer or unreadable layout marker refuses (spec section 8). */
62
+ assertWritable() {
63
+ const s = this.readLayout();
64
+ if (s.state === 'newer') {
65
+ throw new DirsError('layout-newer', `the XENO layout on disk is version ${s.layout}; this build understands up to ${SUPPORTED_LAYOUT}. Update the product before it writes.`, { found: s.layout, supported: SUPPORTED_LAYOUT });
66
+ }
67
+ if (s.state === 'invalid') {
68
+ throw new DirsError('layout-invalid', `data/layout.json is not readable (${s.reason}); refusing to write`, { reason: s.reason });
69
+ }
70
+ return s;
71
+ }
72
+ /** Creates data/layout.json at the supported version if absent; otherwise checks it. */
73
+ async ensureLayout() {
74
+ const s = this.assertWritable();
75
+ if (s.state === 'missing') {
76
+ await atomicWriteFile(this.layoutPath(), JSON.stringify({ layout: SUPPORTED_LAYOUT }) + '\n');
77
+ return { state: 'ok', layout: SUPPORTED_LAYOUT };
78
+ }
79
+ return s;
80
+ }
81
+ /** The only sanctioned way to write below the roots: registry check, layout check, atomic replace. */
82
+ async writeFile(kind, area, segments, data, options = {}) {
83
+ const target = this.path(kind, area, ...segments);
84
+ await this.ensureLayout();
85
+ await atomicWriteFile(target, data, kind === 'secrets' ? { mode: 0o600, ...options } : options);
86
+ return target;
87
+ }
88
+ /** Reads a registered file; returns null when absent. */
89
+ async readFile(kind, area, segments) {
90
+ try {
91
+ return await fsp.readFile(this.path(kind, area, ...segments));
92
+ }
93
+ catch (e) {
94
+ if (e.code === 'ENOENT')
95
+ return null;
96
+ throw e;
97
+ }
98
+ }
99
+ /** Acquires `run/<area>/<name>.lock` (spec section 8). */
100
+ acquireLock(area, name, options) {
101
+ return acquireLockFile(this.lockPath(area, name), options);
102
+ }
103
+ async withLock(area, name, fn, options) {
104
+ const lock = await this.acquireLock(area, name, options);
105
+ try {
106
+ return await fn();
107
+ }
108
+ finally {
109
+ await lock.release();
110
+ }
111
+ }
112
+ /** Every resolved location, for `xeno home`. */
113
+ describe() {
114
+ return { platform: this.platform, overridden: this.overridden, roots: { ...this.roots }, warnings: this.warnings, layout: this.readLayout() };
115
+ }
116
+ }
117
+ /** Builds a resolver from the host (default) or from explicit inputs (tests, vectors, a fixture root). */
118
+ export function createDirs(options = {}) {
119
+ const input = {
120
+ platform: options.platform ?? hostPlatform(),
121
+ home: options.home ?? hostHome(),
122
+ env: options.env ?? hostEnv(),
123
+ };
124
+ return new XenoDirs(resolveRoots(input));
125
+ }
126
+ /** A resolver rooted entirely under one directory via XENO_HOME; the supported way to isolate tests and fixtures. */
127
+ export function createDirsAt(xenoHome, platform = hostPlatform()) {
128
+ return new XenoDirs(resolveRoots({ platform, home: '', env: { XENO_HOME: xenoHome } }));
129
+ }
@@ -0,0 +1,31 @@
1
+ import type { XenoDirs } from './dirs.ts';
2
+ import type { LayoutState } from './layout.ts';
3
+ import { type Kind } from './roots.ts';
4
+ export interface Unregistered {
5
+ kind: Kind;
6
+ /** Path relative to the kind root, `/` separated. */
7
+ path: string;
8
+ type: 'file' | 'directory' | 'link' | 'other';
9
+ reason: string;
10
+ }
11
+ export interface DoctorReport {
12
+ ok: boolean;
13
+ platform: string;
14
+ roots: Record<Kind, string>;
15
+ layout: LayoutState;
16
+ warnings: readonly string[];
17
+ unregistered: Unregistered[];
18
+ legacy: {
19
+ name: string;
20
+ path: string;
21
+ present: boolean;
22
+ }[];
23
+ }
24
+ /**
25
+ * `xeno home doctor`: lists every entry under each root that the registry does not allow (spec section 8, check 2).
26
+ * Registration is by area; what is inside an area belongs to its owner and is not inspected. A root that does not
27
+ * exist yet is fine. Reads only; never changes anything.
28
+ */
29
+ export declare function doctor(dirs: XenoDirs, options?: {
30
+ home?: string;
31
+ }): DoctorReport;
@@ -0,0 +1,77 @@
1
+ import { lstatSync, readdirSync } from 'node:fs';
2
+ import { INPUTS_JSON } from "../generated/contract.js";
3
+ import { AREAS, findArea } from "./registry.js";
4
+ import { KINDS } from "./roots.js";
5
+ const typeOf = (p) => {
6
+ const s = lstatSync(p);
7
+ return s.isSymbolicLink() ? 'link' : s.isDirectory() ? 'directory' : s.isFile() ? 'file' : 'other';
8
+ };
9
+ const safeList = (p) => { try {
10
+ return readdirSync(p);
11
+ }
12
+ catch {
13
+ return [];
14
+ } };
15
+ const sameOrInside = (parent, child, sep) => {
16
+ const norm = (x) => (sep === '\\' ? x.toLowerCase() : x);
17
+ return norm(child).startsWith(norm(parent) + sep);
18
+ };
19
+ /**
20
+ * `xeno home doctor`: lists every entry under each root that the registry does not allow (spec section 8, check 2).
21
+ * Registration is by area; what is inside an area belongs to its owner and is not inspected. A root that does not
22
+ * exist yet is fine. Reads only; never changes anything.
23
+ */
24
+ export function doctor(dirs, options = {}) {
25
+ const sep = dirs.platform === 'windows' ? '\\' : '/';
26
+ const unregistered = [];
27
+ for (const kind of KINDS) {
28
+ const root = dirs.root(kind);
29
+ // Roots nested in another root (Linux secrets under data; the run fallback under state) are allowed there.
30
+ const nestedRoots = KINDS.filter((k) => k !== kind && sameOrInside(root, dirs.root(k), sep)).map((k) => dirs.root(k).slice(root.length + 1).split(sep)[0]);
31
+ const topAllowed = new Set(nestedRoots);
32
+ if (kind === 'data')
33
+ topAllowed.add('layout.json');
34
+ const areasOfKind = AREAS.filter((a) => kind === 'run' || a.uses.includes(kind));
35
+ for (const name of safeList(root)) {
36
+ const abs = root + sep + name;
37
+ if (topAllowed.has(name))
38
+ continue;
39
+ const top = areasOfKind.filter((a) => a.area.split('/')[0] === name);
40
+ if (top.length === 0) {
41
+ const elsewhere = AREAS.some((a) => a.area.split('/')[0] === name);
42
+ unregistered.push({ kind, path: name, type: typeOf(abs), reason: elsewhere ? `area ${name} is not registered for kind ${kind}` : 'not a registered area' });
43
+ continue;
44
+ }
45
+ // An area with a deeper name (agents/definitions, apps/<slug>) is checked one level down.
46
+ const deeper = top.filter((a) => a.area.includes('/'));
47
+ if (deeper.length === 0)
48
+ continue;
49
+ for (const child of safeList(abs)) {
50
+ const full = `${name}/${child}`;
51
+ const entry = findArea(full);
52
+ if (entry === null || !(kind === 'run' || entry.uses.includes(kind))) {
53
+ unregistered.push({ kind, path: full, type: typeOf(abs + sep + child), reason: entry === null ? 'not a registered area' : `area ${full} is not registered for kind ${kind}` });
54
+ }
55
+ }
56
+ }
57
+ }
58
+ const home = options.home;
59
+ const legacy = home === undefined ? [] : INPUTS_JSON.legacyHomes.map((name) => {
60
+ const path = home + sep + name;
61
+ let present = false;
62
+ try {
63
+ present = lstatSync(path).isDirectory() || lstatSync(path).isSymbolicLink();
64
+ }
65
+ catch { /* absent */ }
66
+ return { name, path, present };
67
+ });
68
+ return {
69
+ ok: unregistered.length === 0,
70
+ platform: dirs.platform,
71
+ roots: { ...dirs.roots },
72
+ layout: dirs.readLayout(),
73
+ warnings: dirs.warnings,
74
+ unregistered: unregistered.sort((a, b) => { const x = a.kind + a.path, y = b.kind + b.path; return x < y ? -1 : x > y ? 1 : 0; }),
75
+ legacy,
76
+ };
77
+ }
@@ -0,0 +1,8 @@
1
+ export type DirsErrorCode = 'home-unresolvable' | 'unregistered-area' | 'kind-not-used' | 'locks-only' | 'invalid-segment' | 'layout-newer' | 'layout-invalid' | 'lock-held' | 'lock-corrupt' | 'lock-timeout' | 'migration-refused' | 'invalid-argument';
2
+ /** Every error this family throws. `code` is stable and is what callers branch on. */
3
+ export declare class DirsError extends Error {
4
+ readonly code: DirsErrorCode;
5
+ readonly detail: Record<string, string | number | boolean | null>;
6
+ constructor(code: DirsErrorCode, message: string, detail?: Record<string, string | number | boolean | null>);
7
+ }
8
+ export declare function isDirsError(e: unknown, code?: DirsErrorCode): e is DirsError;
@@ -0,0 +1,14 @@
1
+ /** Every error this family throws. `code` is stable and is what callers branch on. */
2
+ export class DirsError extends Error {
3
+ code;
4
+ detail;
5
+ constructor(code, message, detail = {}) {
6
+ super(message);
7
+ this.name = 'DirsError';
8
+ this.code = code;
9
+ this.detail = detail;
10
+ }
11
+ }
12
+ export function isDirsError(e, code) {
13
+ return e instanceof DirsError && (code === undefined || e.code === code);
14
+ }
@@ -0,0 +1,4 @@
1
+ import type { Platform } from './roots.ts';
2
+ export declare function hostPlatform(): Platform;
3
+ export declare function hostHome(): string;
4
+ export declare function hostEnv(): Readonly<Record<string, string | undefined>>;
@@ -0,0 +1,21 @@
1
+ // The one place in the XENO ecosystem allowed to ask the OS for the person's home directory.
2
+ // (The static checker excludes exactly this file; see check.ts DEFAULT_RESOLVER_FILES.)
3
+ import { homedir } from 'node:os';
4
+ export function hostPlatform() {
5
+ switch (process.platform) {
6
+ case 'win32': return 'windows';
7
+ case 'darwin': return 'macos';
8
+ default: return 'linux';
9
+ }
10
+ }
11
+ export function hostHome() {
12
+ try {
13
+ return homedir();
14
+ }
15
+ catch {
16
+ return '';
17
+ }
18
+ }
19
+ export function hostEnv() {
20
+ return process.env;
21
+ }
@@ -0,0 +1,13 @@
1
+ export { DirsError, isDirsError, type DirsErrorCode } from './errors.ts';
2
+ export { KINDS, SEP, isAbsolutePath, joinPath, normalizeBase, resolveRoots, type Kind, type Platform, type ResolveInput, type ResolvedRoots } from './roots.ts';
3
+ export { segmentProblem, assertSegment } from './segments.ts';
4
+ export { AREAS, LOCK_SUFFIX, findArea, registeredRelativePath, lockRelativePath, type AreaEntry } from './registry.ts';
5
+ export { SUPPORTED_LAYOUT, parseLayout, type LayoutState } from './layout.ts';
6
+ export { atomicWriteFile, type AtomicWriteOptions } from './atomic.ts';
7
+ export { acquireLockFile, judgeLock, type AcquireOptions, type LockHandle, type LockRecord, type LockVerdict, type Probe } from './lock.ts';
8
+ export { isProcessAlive, processStartTime } from './procinfo.ts';
9
+ export { XenoDirs, createDirs, createDirsAt, type CreateDirsOptions } from './dirs.ts';
10
+ export { contractInputs } from './inputs.ts';
11
+ export { BUILTIN_RULES, journalPath, planId, planMigration, readJournal, runMigration, verifyMigration, type EntryResult, type EntryStatus, type MigrationPlan, type MigrationResult, type MigrationRule, type PlanEntry, type PlanOptions, type Refusal, type RunOptions, type SecretSink, type VerifyResult, } from './migrate.ts';
12
+ export { doctor, type DoctorReport, type Unregistered } from './doctor.ts';
13
+ export { CONFIG_NAME, RULES, checkSource, loadConfig, scanText, type CheckConfig, type CheckResult, type Rule, type Violation } from './check.ts';
@@ -0,0 +1,13 @@
1
+ export { DirsError, isDirsError } from "./errors.js";
2
+ export { KINDS, SEP, isAbsolutePath, joinPath, normalizeBase, resolveRoots } from "./roots.js";
3
+ export { segmentProblem, assertSegment } from "./segments.js";
4
+ export { AREAS, LOCK_SUFFIX, findArea, registeredRelativePath, lockRelativePath } from "./registry.js";
5
+ export { SUPPORTED_LAYOUT, parseLayout } from "./layout.js";
6
+ export { atomicWriteFile } from "./atomic.js";
7
+ export { acquireLockFile, judgeLock } from "./lock.js";
8
+ export { isProcessAlive, processStartTime } from "./procinfo.js";
9
+ export { XenoDirs, createDirs, createDirsAt } from "./dirs.js";
10
+ export { contractInputs } from "./inputs.js";
11
+ export { BUILTIN_RULES, journalPath, planId, planMigration, readJournal, runMigration, verifyMigration, } from "./migrate.js";
12
+ export { doctor } from "./doctor.js";
13
+ export { CONFIG_NAME, RULES, checkSource, loadConfig, scanText } from "./check.js";
@@ -0,0 +1,14 @@
1
+ export interface ContractInput<T> {
2
+ value: T;
3
+ status: 'locked' | 'open';
4
+ decided: string;
5
+ source: string;
6
+ }
7
+ /** Owner-decided inputs the layout depends on (spec section 11), exposed so tools can show them. */
8
+ export declare function contractInputs(): {
9
+ layout: number;
10
+ macosBundleId: ContractInput<string>;
11
+ /** Releases after a product adopts the layout during which it still reads the legacy location. */
12
+ legacyFallbackReleases: ContractInput<number>;
13
+ legacyHomes: readonly string[];
14
+ };
@@ -0,0 +1,11 @@
1
+ import { INPUTS_JSON } from "../generated/contract.js";
2
+ /** Owner-decided inputs the layout depends on (spec section 11), exposed so tools can show them. */
3
+ export function contractInputs() {
4
+ const i = INPUTS_JSON.inputs;
5
+ return {
6
+ layout: INPUTS_JSON.layout,
7
+ macosBundleId: i.macosBundleId,
8
+ legacyFallbackReleases: i.legacyFallbackReleases,
9
+ legacyHomes: INPUTS_JSON.legacyHomes,
10
+ };
11
+ }
@@ -0,0 +1,16 @@
1
+ /** The layout version this build understands (data/layout.json, spec section 8). */
2
+ export declare const SUPPORTED_LAYOUT: number;
3
+ export type LayoutState = {
4
+ state: 'missing';
5
+ } | {
6
+ state: 'ok';
7
+ layout: number;
8
+ } | {
9
+ state: 'newer';
10
+ layout: number;
11
+ } | {
12
+ state: 'invalid';
13
+ reason: string;
14
+ };
15
+ /** Pure parser for the contents of layout.json (null = the file does not exist). */
16
+ export declare function parseLayout(text: string | null, supported?: number): LayoutState;
@@ -0,0 +1,21 @@
1
+ import { INPUTS_JSON } from "../generated/contract.js";
2
+ /** The layout version this build understands (data/layout.json, spec section 8). */
3
+ export const SUPPORTED_LAYOUT = INPUTS_JSON.layout;
4
+ /** Pure parser for the contents of layout.json (null = the file does not exist). */
5
+ export function parseLayout(text, supported = SUPPORTED_LAYOUT) {
6
+ if (text === null)
7
+ return { state: 'missing' };
8
+ let v;
9
+ try {
10
+ v = JSON.parse(text);
11
+ }
12
+ catch {
13
+ return { state: 'invalid', reason: 'not valid JSON' };
14
+ }
15
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
16
+ return { state: 'invalid', reason: 'not an object' };
17
+ const n = v['layout'];
18
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1)
19
+ return { state: 'invalid', reason: 'layout is not a positive integer' };
20
+ return n > supported ? { state: 'newer', layout: n } : { state: 'ok', layout: n };
21
+ }
@@ -0,0 +1,38 @@
1
+ /** What a lock file records. `startTime` is what makes the pid an identity (see procinfo). */
2
+ export interface LockRecord {
3
+ v: 1;
4
+ pid: number;
5
+ startTime: string | null;
6
+ host: string;
7
+ token: string;
8
+ owner: string;
9
+ createdAt: string;
10
+ }
11
+ export interface LockHandle {
12
+ readonly path: string;
13
+ readonly record: LockRecord;
14
+ /** Removes the lock only if it is still ours. Returns false when it was not (already gone or taken over). */
15
+ release(): Promise<boolean>;
16
+ }
17
+ export interface AcquireOptions {
18
+ /** Free text recorded in the lock, shown to the next contender. Never put a secret here. */
19
+ owner?: string;
20
+ /** Poll for up to this long when the lock is held. Default 0 (fail at once). */
21
+ timeoutMs?: number;
22
+ /** Injection points for tests. */
23
+ probe?: Partial<Probe>;
24
+ }
25
+ export interface Probe {
26
+ isAlive(pid: number): boolean;
27
+ startTime(pid: number): Promise<string | null>;
28
+ host(): string;
29
+ }
30
+ export type LockVerdict = 'held' | 'stale' | 'foreign-host';
31
+ /**
32
+ * Decides whether the holder of a lock is still running. A bare pid is never trusted: a live pid whose start time
33
+ * differs from the recorded one is a reused pid (stale); a live pid whose start time cannot be read on either side
34
+ * is treated as held, because guessing wrong would break mutual exclusion.
35
+ */
36
+ export declare function judgeLock(rec: LockRecord, probe?: Probe): Promise<LockVerdict>;
37
+ /** Acquires a lock file at an absolute path produced by `XenoDirs.lockPath`. */
38
+ export declare function acquireLockFile(path: string, options?: AcquireOptions): Promise<LockHandle>;
@@ -0,0 +1,124 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { promises as fsp } from 'node:fs';
3
+ import { hostname } from 'node:os';
4
+ import { dirname, basename, join } from 'node:path';
5
+ import { DirsError } from "./errors.js";
6
+ import { isProcessAlive, ownProcessStartTime, processStartTime } from "./procinfo.js";
7
+ const defaultProbe = { isAlive: isProcessAlive, startTime: processStartTime, host: hostname };
8
+ /**
9
+ * Decides whether the holder of a lock is still running. A bare pid is never trusted: a live pid whose start time
10
+ * differs from the recorded one is a reused pid (stale); a live pid whose start time cannot be read on either side
11
+ * is treated as held, because guessing wrong would break mutual exclusion.
12
+ */
13
+ export async function judgeLock(rec, probe = defaultProbe) {
14
+ if (rec.host.toLowerCase() !== probe.host().toLowerCase())
15
+ return 'foreign-host';
16
+ if (!probe.isAlive(rec.pid))
17
+ return 'stale';
18
+ const now = await probe.startTime(rec.pid);
19
+ if (now === null || rec.startTime === null)
20
+ return 'held';
21
+ return now === rec.startTime ? 'held' : 'stale';
22
+ }
23
+ function parseRecord(text) {
24
+ try {
25
+ const v = JSON.parse(text);
26
+ if (v && v.v === 1 && Number.isInteger(v.pid) && typeof v.token === 'string' && typeof v.host === 'string')
27
+ return v;
28
+ }
29
+ catch { /* fallthrough */ }
30
+ return null;
31
+ }
32
+ async function readRecord(path) {
33
+ try {
34
+ const text = await fsp.readFile(path, 'utf8');
35
+ return { rec: parseRecord(text), text };
36
+ }
37
+ catch (e) {
38
+ if (e.code === 'ENOENT')
39
+ return null;
40
+ throw e;
41
+ }
42
+ }
43
+ /** Creates the lock file atomically with its full content: write a temp file, then hard-link it into place. */
44
+ async function tryCreate(path, rec) {
45
+ const tmp = join(dirname(path), `.${basename(path)}.${rec.token}.tmp`);
46
+ const h = await fsp.open(tmp, 'wx', 0o600);
47
+ try {
48
+ await h.writeFile(JSON.stringify(rec));
49
+ await h.sync();
50
+ }
51
+ finally {
52
+ await h.close();
53
+ }
54
+ try {
55
+ await fsp.link(tmp, path);
56
+ return true;
57
+ }
58
+ catch (e) {
59
+ if (e.code === 'EEXIST')
60
+ return false;
61
+ throw e;
62
+ }
63
+ finally {
64
+ await fsp.rm(tmp, { force: true }).catch(() => undefined);
65
+ }
66
+ }
67
+ /** Removes a lock judged stale, but only if the file still holds the record that was judged. */
68
+ async function breakStale(path, judged) {
69
+ const moved = `${path}.stale.${randomBytes(4).toString('hex')}`;
70
+ try {
71
+ await fsp.rename(path, moved);
72
+ }
73
+ catch (e) {
74
+ if (e.code === 'ENOENT')
75
+ return;
76
+ throw e;
77
+ }
78
+ const taken = await readRecord(moved);
79
+ if (taken?.rec?.token !== judged.token) {
80
+ // We moved a lock another process had just created. Put it back; if that fails the next release() no-ops safely.
81
+ await fsp.link(moved, path).catch(() => undefined);
82
+ }
83
+ await fsp.rm(moved, { force: true }).catch(() => undefined);
84
+ }
85
+ /** Acquires a lock file at an absolute path produced by `XenoDirs.lockPath`. */
86
+ export async function acquireLockFile(path, options = {}) {
87
+ const probe = { ...defaultProbe, ...options.probe };
88
+ await fsp.mkdir(dirname(path), { recursive: true });
89
+ const deadline = Date.now() + (options.timeoutMs ?? 0);
90
+ const startTime = options.probe?.startTime ? await options.probe.startTime(process.pid) : await ownProcessStartTime();
91
+ for (;;) {
92
+ const rec = {
93
+ v: 1, pid: process.pid, startTime, host: probe.host(), token: randomBytes(12).toString('hex'),
94
+ owner: options.owner ?? '', createdAt: new Date().toISOString(),
95
+ };
96
+ if (await tryCreate(path, rec)) {
97
+ return {
98
+ path, record: rec,
99
+ async release() {
100
+ const cur = await readRecord(path);
101
+ if (cur?.rec?.token !== rec.token)
102
+ return false;
103
+ await fsp.rm(path, { force: true });
104
+ return true;
105
+ },
106
+ };
107
+ }
108
+ const cur = await readRecord(path);
109
+ if (cur === null)
110
+ continue; // vanished between our attempt and our read: try again
111
+ if (cur.rec === null) {
112
+ throw new DirsError('lock-corrupt', 'a lock file exists but cannot be read; it is not removed automatically', { path });
113
+ }
114
+ const verdict = await judgeLock(cur.rec, probe);
115
+ if (verdict === 'stale') {
116
+ await breakStale(path, cur.rec);
117
+ continue;
118
+ }
119
+ if (Date.now() >= deadline) {
120
+ throw new DirsError(options.timeoutMs ? 'lock-timeout' : 'lock-held', verdict === 'foreign-host' ? 'the lock is held by another machine; it is not judged' : 'the lock is held by a running process', { path, pid: cur.rec.pid, owner: cur.rec.owner, since: cur.rec.createdAt });
121
+ }
122
+ await new Promise((r) => setTimeout(r, 50));
123
+ }
124
+ }