@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
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @xenosystem/primitives
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
+ XENO back-end rung 1. Two families, one subpath each:
4
+
5
+ - `@xenosystem/primitives/dirs` – the XENO local home: where every kind of data lives, the area registry, `XENO_HOME`,
6
+ the layout version, atomic writes, locks, the copy-only migrator, `doctor`, and the static check.
7
+ - `@xenosystem/primitives/secrets` – envelope-encrypted credentials; the OS store holds one key per person per machine.
8
+ - `@xenosystem/primitives/secrets/testing` – an in-memory key store for tests only.
9
+ - `@xenosystem/primitives/updates` – an installed app updates only for an account allowed to: points electron-updater at the platform's gated feed (`/api/updates/<slug>/feed`) with the account's own fresh token. Signed out and no plan are states, not errors.
10
+
11
+ Authority: `XENO LOCAL HOME - SPEC.md` (LOCKED). Zero runtime dependencies. Proprietary (`UNLICENSED`).
12
+
13
+ ```ts
14
+ import { createDirs } from '@xenosystem/primitives/dirs';
15
+ import { createSecretStore, createOsKeyStore } from '@xenosystem/primitives/secrets';
16
+
17
+ const dirs = createDirs(); // the only place that reads the home directory
18
+ dirs.path('data', 'agents/environments', 'claude', 'profiles', 'default', 'profile.json');
19
+ dirs.path('cache', 'agents/environments', 'claude', '2.1.0', 'runtime.tgz');
20
+ await dirs.withLock('agents/environments', 'claude-2.1.0', async () => { /* exclusive */ });
21
+ await dirs.writeFile('data', 'agents/environments', ['claude', 'record.json'], json); // registry + layout checks, atomic
22
+
23
+ const secrets = createSecretStore({ dirs, keyStore: createOsKeyStore() });
24
+ if (!secrets.status().available) { /* show secrets.status().reason; do not save */ }
25
+ await secrets.set('identity', 'refresh-token', value);
26
+ ```
27
+
28
+ Rules: no `homedir()` and no hand-built XENO path in a product; run `npx xeno-dirs-check` in CI
29
+ (`--self-test` proves it can fail); `xeno-home doctor` lists unregistered entries; `xeno-home migrate` is a dry run
30
+ until `--confirm` and never deletes anything.
@@ -0,0 +1,9 @@
1
+ export interface AtomicWriteOptions {
2
+ /** POSIX mode for the new file (ignored on Windows). Default 0o644; secrets use 0o600. */
3
+ mode?: number;
4
+ }
5
+ /**
6
+ * Atomic replace (spec section 8): write a temporary file in the same directory, flush it to disk, rename it over the
7
+ * target, flush the directory. A reader sees the old bytes or the new bytes, never a prefix.
8
+ */
9
+ export declare function atomicWriteFile(target: string, data: string | Uint8Array, options?: AtomicWriteOptions): Promise<void>;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.atomicWriteFile = atomicWriteFile;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ const RETRYABLE = new Set(['EPERM', 'EBUSY', 'EACCES']);
8
+ async function renameWithRetry(from, to) {
9
+ // On Windows a rename onto a file another process has open (a virus scanner, an indexer) fails transiently.
10
+ for (let attempt = 0;; attempt++) {
11
+ try {
12
+ await node_fs_1.promises.rename(from, to);
13
+ return;
14
+ }
15
+ catch (e) {
16
+ const code = e.code ?? '';
17
+ if (process.platform !== 'win32' || !RETRYABLE.has(code) || attempt >= 15)
18
+ throw e;
19
+ await new Promise((r) => setTimeout(r, 20 + attempt * 10));
20
+ }
21
+ }
22
+ }
23
+ async function syncDirectory(dir) {
24
+ // Windows cannot open a directory for fsync from Node; NTFS journals the rename itself.
25
+ if (process.platform === 'win32')
26
+ return;
27
+ const h = await node_fs_1.promises.open(dir, 'r');
28
+ try {
29
+ await h.sync();
30
+ }
31
+ finally {
32
+ await h.close();
33
+ }
34
+ }
35
+ /**
36
+ * Atomic replace (spec section 8): write a temporary file in the same directory, flush it to disk, rename it over the
37
+ * target, flush the directory. A reader sees the old bytes or the new bytes, never a prefix.
38
+ */
39
+ async function atomicWriteFile(target, data, options = {}) {
40
+ const dir = (0, node_path_1.dirname)(target);
41
+ await node_fs_1.promises.mkdir(dir, { recursive: true });
42
+ const tmp = (0, node_path_1.join)(dir, `.${(0, node_path_1.basename)(target)}.${process.pid}.${(0, node_crypto_1.randomBytes)(6).toString('hex')}.tmp`);
43
+ let handle = null;
44
+ try {
45
+ handle = await node_fs_1.promises.open(tmp, 'wx', options.mode ?? 0o644);
46
+ await handle.writeFile(data);
47
+ await handle.sync();
48
+ await handle.close();
49
+ handle = null;
50
+ await renameWithRetry(tmp, target);
51
+ await syncDirectory(dir);
52
+ }
53
+ catch (e) {
54
+ if (handle !== null)
55
+ await handle.close().catch(() => undefined);
56
+ await node_fs_1.promises.rm(tmp, { force: true }).catch(() => undefined);
57
+ throw e;
58
+ }
59
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // xeno-dirs-check [dir] [--json] [--self-test]
5
+ // Exit 0: clean. 1: violations (or the self-test could not fail). 2: usage.
6
+ const node_path_1 = require("node:path");
7
+ const check_ts_1 = require("./check.js");
8
+ const args = process.argv.slice(2);
9
+ const flag = (n) => args.includes(n);
10
+ const positional = args.filter((a) => !a.startsWith('--'));
11
+ /** Proves the check can fail: every rule must fire on its own sample. Samples are assembled so this file stays clean. */
12
+ function selfTest() {
13
+ const h = 'home', d = 'dir';
14
+ const samples = {
15
+ 'homedir-call': ['ts', `const p = os.${h}${d}();`],
16
+ 'platform-dir-read': ['ts', `const a = process.env.APP${'DATA'};`],
17
+ 'legacy-home-name': ['ts', `const x = join(base, '.xeno-${'agent'}');`],
18
+ 'legacy-home-path': ['ts', `const x = '~/.${'xeno'}/config';`],
19
+ 'legacy-home-env': ['ts', `const x = process.env.XENO_AGENT_${'HOME'};`],
20
+ };
21
+ let bad = 0;
22
+ for (const id of new Set(check_ts_1.RULES.map((r) => r.id))) {
23
+ const [lang, text] = samples[id];
24
+ const hit = (0, check_ts_1.scanText)('sample', text, lang).some((v) => v.rule === id);
25
+ const clean = (0, check_ts_1.scanText)('sample', `// ${text}`, lang).length === 0;
26
+ const allowed = (0, check_ts_1.scanText)('sample', `${text} // xeno-dirs-allow: self-test of the allow marker`, lang).length === 0;
27
+ if (!hit || !clean || !allowed) {
28
+ console.error(`self-test FAILED for ${id}: fires=${hit} comment-ignored=${clean} allow-honoured=${allowed}`);
29
+ bad++;
30
+ }
31
+ }
32
+ console.log(bad === 0 ? `self-test ok: ${new Set(check_ts_1.RULES.map((r) => r.id)).size} rules fire, comments and allow markers are honoured` : 'self-test FAILED');
33
+ return bad === 0 ? 0 : 1;
34
+ }
35
+ if (flag('--self-test'))
36
+ process.exit(selfTest());
37
+ if (positional.length > 1) {
38
+ console.error('usage: xeno-dirs-check [dir] [--json] [--self-test]');
39
+ process.exit(2);
40
+ }
41
+ const root = (0, node_path_1.resolve)(positional[0] ?? '.');
42
+ const result = (0, check_ts_1.checkSource)(root);
43
+ if (flag('--json'))
44
+ console.log(JSON.stringify(result, null, 2));
45
+ else {
46
+ for (const v of result.violations)
47
+ console.log(`${v.file}:${v.line} ${v.rule} ${v.description}\n ${v.text}`);
48
+ console.log(result.ok ? `ok: ${result.filesScanned} files, no home-directory lookup or hard-coded XENO path outside the resolver` : `${result.violations.length} violation(s) in ${result.filesScanned} files`);
49
+ }
50
+ process.exit(result.ok ? 0 : 1);
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The reusable static check every product runs in CI (XENO LOCAL HOME - SPEC.md section 8, check 1): no home-directory
3
+ * lookup and no hard-coded XENO location outside the resolver. A violation is a defect, not a convenience.
4
+ *
5
+ * Rules (each with a stable id so an allow entry names exactly one):
6
+ * homedir-call a call that asks the OS for the home directory (homedir(), home_dir(), Path.home(), UserHomeDir())
7
+ * platform-dir-read reading HOME, USERPROFILE, APPDATA, LOCALAPPDATA or XDG_* from the environment to build a path
8
+ * legacy-home-name the legacy folders .xeno-agent, .xeno-anima, .xeno-code
9
+ * legacy-home-path ~/.xeno, %USERPROFILE%\.xeno, $HOME/.xeno and the %APPDATA%\XENO form (a per-project `.xeno/` is fine)
10
+ * legacy-home-env a XENO_*_HOME variable other than XENO_HOME (the thirteen legacy overrides)
11
+ * A line (or the line above it) carrying `xeno-dirs-allow: <reason>` is exempt; the reason is mandatory.
12
+ */
13
+ export interface Rule {
14
+ id: string;
15
+ description: string;
16
+ re: RegExp;
17
+ langs: readonly string[];
18
+ }
19
+ export declare const RULES: readonly Rule[];
20
+ export interface Violation {
21
+ file: string;
22
+ line: number;
23
+ rule: string;
24
+ description: string;
25
+ text: string;
26
+ }
27
+ export interface CheckConfig {
28
+ /** Files (relative, `/` separated, or `dir/**`) that are the resolver itself and may do what the rules forbid. */
29
+ resolverFiles?: string[];
30
+ exclude?: string[];
31
+ allow?: {
32
+ file: string;
33
+ rule: string;
34
+ reason: string;
35
+ }[];
36
+ }
37
+ export interface CheckResult {
38
+ ok: boolean;
39
+ filesScanned: number;
40
+ violations: Violation[];
41
+ config: string | null;
42
+ }
43
+ export declare const CONFIG_NAME = "xeno-dirs-check.json";
44
+ export declare function loadConfig(root: string): {
45
+ config: CheckConfig;
46
+ path: string | null;
47
+ };
48
+ export declare function scanText(file: string, text: string, lang: string): Violation[];
49
+ export declare function checkSource(root: string, override?: CheckConfig): CheckResult;
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CONFIG_NAME = exports.RULES = void 0;
4
+ exports.loadConfig = loadConfig;
5
+ exports.scanText = scanText;
6
+ exports.checkSource = checkSource;
7
+ const node_fs_1 = require("node:fs");
8
+ const node_path_1 = require("node:path");
9
+ const JS = ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts'];
10
+ exports.RULES = [
11
+ { id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\b(?:os\.)?homedir\s*\(|\.userInfo\s*\(\s*\)\s*\.homedir\b/, langs: JS },
12
+ { id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\b(?:dirs::|env::)?home_dir\s*\(|\bdirs::(?:config|data|data_local|cache|state)_dir\s*\(|\bProjectDirs::from\b/, langs: ['rs'] },
13
+ { id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\bPath\.home\s*\(|\bexpanduser\s*\(|\bplatformdirs\b|\buser_(?:config|data|cache|state)_dir\s*\(/, langs: ['py'] },
14
+ { id: 'homedir-call', description: 'asks the OS for the home directory; use the dirs resolver', re: /\bos\.User(?:Home|Config|Cache)Dir\s*\(/, langs: ['go'] },
15
+ { id: 'platform-dir-read', description: 'reads a platform directory variable; use the dirs resolver', re: /\b(?:process\.env|env)(?:\.|\s*\[\s*['"])(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z_]+)\b/, langs: JS },
16
+ { id: 'platform-dir-read', description: 'reads a platform directory variable; use the dirs resolver', re: /\bvar(?:_os)?\s*\(\s*"(?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z_]+)"/, langs: ['rs'] },
17
+ { id: 'platform-dir-read', description: 'reads a platform directory variable; use the dirs resolver', re: /\b(?:os\.environ(?:\.get\s*\(|\s*\[)|os\.getenv\s*\()\s*['"](?:HOME|USERPROFILE|APPDATA|LOCALAPPDATA|XDG_[A-Z_]+)['"]/, langs: ['py'] },
18
+ { id: 'legacy-home-name', description: 'names a legacy XENO home; use the dirs resolver', re: /(?<![\w-])\.xeno-(?:agent|anima|code)(?![\w-])/, langs: [...JS, 'rs', 'py', 'go'] },
19
+ { id: 'legacy-home-path', description: 'builds a path into the legacy home folder or the XENO app-data folder by hand', re: /(?:~|\$\{?HOME\}?|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE)[\\/]+\.xeno(?![\w-])|(?:%APPDATA%|%LOCALAPPDATA%|AppData[\\/]+(?:Roaming|Local))[\\/]+XENO\b/, langs: [...JS, 'rs', 'py', 'go'] },
20
+ { id: 'legacy-home-env', description: 'uses a legacy XENO_*_HOME variable; XENO_HOME is the only override', re: /\bXENO_(?!HOME\b)[A-Z0-9_]*_HOME\b/, langs: [...JS, 'rs', 'py', 'go'] },
21
+ ];
22
+ const DEFAULT_EXCLUDE_DIRS = new Set(['node_modules', 'dist', 'build', 'target', '.git', 'coverage', '.next', 'out', '.turbo', '.venv', '__pycache__', 'release', '.worktrees']);
23
+ const EXT_LANG = Object.fromEntries([...JS.map((e) => [e, e]), ['rs', 'rs'], ['py', 'py'], ['go', 'go']]);
24
+ const MAX_BYTES = 2_000_000;
25
+ function globToRe(g) {
26
+ // Placeholders first, so the expansions below are not themselves rewritten by the single-star rule.
27
+ const esc = g
28
+ .replace(/\*\*\//g, '@@DIR@@')
29
+ .replace(/\*\*/g, '@@ANY@@')
30
+ .replace(/\*/g, '@@SEG@@')
31
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
32
+ .replace(/@@DIR@@/g, '(?:.*/)?')
33
+ .replace(/@@ANY@@/g, '.*')
34
+ .replace(/@@SEG@@/g, '[^/]*');
35
+ return new RegExp(`^${esc}$`);
36
+ }
37
+ exports.CONFIG_NAME = 'xeno-dirs-check.json';
38
+ function loadConfig(root) {
39
+ const p = (0, node_path_1.join)(root, exports.CONFIG_NAME);
40
+ if (!(0, node_fs_1.existsSync)(p))
41
+ return { config: {}, path: null };
42
+ const c = JSON.parse((0, node_fs_1.readFileSync)(p, 'utf8'));
43
+ for (const a of c.allow ?? [])
44
+ if (!a.reason || a.reason.trim().length < 8)
45
+ throw new Error(`${exports.CONFIG_NAME}: allow entry for ${a.file} / ${a.rule} needs a real reason`);
46
+ return { config: c, path: p };
47
+ }
48
+ /** Strips comment text so documentation that names a path is not a violation. Keeps line numbering. */
49
+ function codeLines(text, lang) {
50
+ const out = [];
51
+ let block = false;
52
+ for (const raw of text.split(/\r?\n/)) {
53
+ let line = raw;
54
+ let comment = '';
55
+ if (lang === 'py') {
56
+ const i = line.indexOf('#');
57
+ if (i >= 0) {
58
+ comment = line.slice(i);
59
+ line = line.slice(0, i);
60
+ }
61
+ }
62
+ else {
63
+ if (block) {
64
+ const end = line.indexOf('*/');
65
+ if (end < 0) {
66
+ out.push({ code: '', comment: line });
67
+ continue;
68
+ }
69
+ comment = line.slice(0, end + 2);
70
+ line = line.slice(end + 2);
71
+ block = false;
72
+ }
73
+ const t = line.trimStart();
74
+ if (t.startsWith('//')) {
75
+ out.push({ code: '', comment: line });
76
+ continue;
77
+ }
78
+ const open = line.indexOf('/*');
79
+ if (open >= 0 && !/['"`].*\/\*.*['"`]/.test(line)) {
80
+ const close = line.indexOf('*/', open + 2);
81
+ if (close < 0) {
82
+ block = true;
83
+ comment += line.slice(open);
84
+ line = line.slice(0, open);
85
+ }
86
+ else {
87
+ comment += line.slice(open, close + 2);
88
+ line = line.slice(0, open) + line.slice(close + 2);
89
+ }
90
+ }
91
+ const trailing = line.search(/\s\/\/\s/);
92
+ if (trailing >= 0) {
93
+ comment += line.slice(trailing);
94
+ line = line.slice(0, trailing);
95
+ }
96
+ }
97
+ out.push({ code: line, comment });
98
+ }
99
+ return out;
100
+ }
101
+ const ALLOW = /xeno-dirs-allow:\s*(\S.*)$/;
102
+ function scanText(file, text, lang) {
103
+ const lines = codeLines(text, lang);
104
+ const found = [];
105
+ const rules = exports.RULES.filter((r) => r.langs.includes(lang));
106
+ lines.forEach((l, i) => {
107
+ const allowHere = ALLOW.exec(l.comment) ?? (i > 0 ? ALLOW.exec(lines[i - 1].comment) : null);
108
+ if (/xeno-dirs-allow:\s*$/.test(l.comment) || (allowHere !== null && allowHere[1].trim().length < 4)) {
109
+ found.push({ file, line: i + 1, rule: 'allow-without-reason', description: 'xeno-dirs-allow needs a reason', text: l.comment.trim().slice(0, 160) });
110
+ }
111
+ if (l.code.trim() === '')
112
+ return;
113
+ for (const r of rules) {
114
+ if (r.re.test(l.code) && allowHere === null) {
115
+ if (!found.some((f) => f.line === i + 1 && f.rule === r.id))
116
+ found.push({ file, line: i + 1, rule: r.id, description: r.description, text: l.code.trim().slice(0, 160) });
117
+ }
118
+ }
119
+ });
120
+ return found;
121
+ }
122
+ function checkSource(root, override) {
123
+ const { config: fileConfig, path } = loadConfig(root);
124
+ const config = { ...fileConfig, ...override };
125
+ const resolver = (config.resolverFiles ?? []).map(globToRe);
126
+ const exclude = (config.exclude ?? []).map(globToRe);
127
+ const allow = (config.allow ?? []).map((a) => ({ f: globToRe(a.file), rule: a.rule }));
128
+ const violations = [];
129
+ let scanned = 0;
130
+ const walk = (dir) => {
131
+ for (const name of (0, node_fs_1.readdirSync)(dir)) {
132
+ const abs = (0, node_path_1.join)(dir, name);
133
+ const st = (0, node_fs_1.lstatSync)(abs);
134
+ if (st.isSymbolicLink())
135
+ continue; // never follow a link out of the tree
136
+ const rel = (0, node_path_1.relative)(root, abs).split(node_path_1.sep).join('/');
137
+ if (st.isDirectory()) {
138
+ if (!DEFAULT_EXCLUDE_DIRS.has(name) && !exclude.some((e) => e.test(rel + '/')))
139
+ walk(abs);
140
+ continue;
141
+ }
142
+ const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : '';
143
+ const lang = EXT_LANG[ext];
144
+ if (lang === undefined || st.size > MAX_BYTES || name.endsWith('.min.js') || name.endsWith('.d.ts'))
145
+ continue;
146
+ if (exclude.some((e) => e.test(rel)) || resolver.some((e) => e.test(rel)))
147
+ continue;
148
+ scanned++;
149
+ for (const v of scanText(rel, (0, node_fs_1.readFileSync)(abs, 'utf8'), lang)) {
150
+ if (allow.some((a) => a.f.test(rel) && a.rule === v.rule))
151
+ continue;
152
+ violations.push(v);
153
+ }
154
+ }
155
+ };
156
+ walk(root);
157
+ return { ok: violations.length === 0, filesScanned: scanned, violations, config: path };
158
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // xeno-home print every resolved location (the engine behind `xeno home`)
5
+ // xeno-home doctor [--json] list entries no registry path allows (`xeno home doctor`; exit 1 if any)
6
+ // xeno-home migrate [--confirm] copy legacy homes into the layout (dry run unless --confirm; never deletes)
7
+ // xeno-home inputs show the owner-decided contract inputs
8
+ const inputs_ts_1 = require("./inputs.js");
9
+ const dirs_ts_1 = require("./dirs.js");
10
+ const doctor_ts_1 = require("./doctor.js");
11
+ const host_ts_1 = require("./host.js");
12
+ const migrate_ts_1 = require("./migrate.js");
13
+ const [cmd, ...rest] = process.argv.slice(2);
14
+ const json = rest.includes('--json');
15
+ const out = (v) => console.log(JSON.stringify(v, null, 2));
16
+ async function main() {
17
+ const dirs = (0, dirs_ts_1.createDirs)();
18
+ if (cmd === undefined || cmd === 'home') {
19
+ const d = dirs.describe();
20
+ if (json)
21
+ out(d);
22
+ else {
23
+ console.log(`platform: ${d.platform}${d.overridden ? ' (XENO_HOME override)' : ''}`);
24
+ for (const [k, v] of Object.entries(d.roots))
25
+ console.log(`${k.padEnd(8)}${v}`);
26
+ console.log(`layout: ${d.layout.state}${'layout' in d.layout ? ` (${d.layout.layout})` : ''}`);
27
+ for (const w of d.warnings)
28
+ console.log(`warning: ${w}`);
29
+ }
30
+ return 0;
31
+ }
32
+ if (cmd === 'doctor') {
33
+ const r = (0, doctor_ts_1.doctor)(dirs, { home: (0, host_ts_1.hostHome)() });
34
+ if (json)
35
+ out(r);
36
+ else {
37
+ for (const u of r.unregistered)
38
+ console.log(`UNREGISTERED ${u.kind}/${u.path} (${u.type}; ${u.reason})`);
39
+ for (const l of r.legacy.filter((x) => x.present))
40
+ console.log(`legacy home ${l.path} (run: xeno-home migrate)`);
41
+ console.log(r.ok ? 'ok: no unregistered entry in any XENO root' : `${r.unregistered.length} unregistered entr${r.unregistered.length === 1 ? 'y' : 'ies'}`);
42
+ }
43
+ return r.ok ? 0 : 1;
44
+ }
45
+ if (cmd === 'migrate') {
46
+ const plan = (0, migrate_ts_1.planMigration)({ dirs, home: (0, host_ts_1.hostHome)() });
47
+ const confirm = rest.includes('--confirm');
48
+ const result = await (0, migrate_ts_1.runMigration)(plan, { dirs, confirm });
49
+ if (json)
50
+ out({ plan: { id: plan.id, homes: plan.homes, entries: plan.entries.length }, result });
51
+ else {
52
+ console.log(`${confirm ? 'migrated' : 'DRY RUN (nothing written; pass --confirm)'} plan ${plan.id}`);
53
+ for (const h of plan.homes)
54
+ console.log(` ${h.name.padEnd(14)}${h.state}`);
55
+ for (const e of result.entries)
56
+ console.log(` ${e.status.padEnd(9)}${e.legacyHome}/${e.sourceRel} -> ${e.destRel}${e.reason ? ` (${e.reason})` : ''}`);
57
+ for (const r of result.refused)
58
+ console.log(` refused ${r.path} (${r.reason})`);
59
+ console.log(` unplaced: ${result.unplaced.count}${result.unplaced.truncated ? '+' : ''} (reported, never guessed)`);
60
+ if (confirm)
61
+ console.log(result.ok ? 'ok: every copy verified by hash; legacy homes left in place' : 'NOT ok: a product must not switch yet');
62
+ }
63
+ return confirm && !result.ok ? 1 : 0;
64
+ }
65
+ if (cmd === 'inputs') {
66
+ out((0, inputs_ts_1.contractInputs)());
67
+ return 0;
68
+ }
69
+ console.error('usage: xeno-home [home|doctor|migrate [--confirm]|inputs] [--json]');
70
+ return 2;
71
+ }
72
+ main().then((c) => process.exit(c), (e) => { console.error(`error: ${e.message}`); process.exit(1); });
@@ -0,0 +1,57 @@
1
+ import { type AtomicWriteOptions } from './atomic.ts';
2
+ import { type LayoutState } from './layout.ts';
3
+ import { type AcquireOptions, type LockHandle } from './lock.ts';
4
+ import { type Kind, type Platform, type ResolvedRoots } from './roots.ts';
5
+ export interface CreateDirsOptions {
6
+ platform?: Platform;
7
+ home?: string;
8
+ env?: Readonly<Record<string, string | undefined>>;
9
+ }
10
+ /**
11
+ * The resolver. Every XENO path comes from here; nothing else may build one. It refuses anything the registry does
12
+ * not list, and refuses to write when the layout on disk is newer than this build understands.
13
+ */
14
+ export declare class XenoDirs {
15
+ readonly platform: Platform;
16
+ readonly roots: Readonly<Record<Kind, string>>;
17
+ readonly warnings: readonly string[];
18
+ readonly overridden: boolean;
19
+ constructor(resolved: ResolvedRoots);
20
+ /** Root directory of a kind. */
21
+ root(kind: Kind): string;
22
+ /** Path relative to the kind root, `/`-separated, after registry validation. */
23
+ relative(kind: string, area: string, ...segments: string[]): string;
24
+ /** Absolute path for (kind, area, ...segments). Throws DirsError for anything unregistered or invalid. */
25
+ path(kind: Kind, area: string, ...segments: string[]): string;
26
+ /** `run/<area>/<name>.lock`. */
27
+ lockPath(area: string, name: string): string;
28
+ /** `data/layout.json`. */
29
+ layoutPath(): string;
30
+ /** `<kind>/<area>/area.json`, the optional per-area schema marker. */
31
+ areaMetaPath(kind: Kind, area: string): string;
32
+ /** Reads data/layout.json. Never throws for a missing file. */
33
+ readLayout(): LayoutState;
34
+ /** Throws unless this build may write: a newer or unreadable layout marker refuses (spec section 8). */
35
+ assertWritable(): LayoutState;
36
+ /** Creates data/layout.json at the supported version if absent; otherwise checks it. */
37
+ ensureLayout(): Promise<LayoutState>;
38
+ /** The only sanctioned way to write below the roots: registry check, layout check, atomic replace. */
39
+ writeFile(kind: Kind, area: string, segments: readonly string[], data: string | Uint8Array, options?: AtomicWriteOptions): Promise<string>;
40
+ /** Reads a registered file; returns null when absent. */
41
+ readFile(kind: Kind, area: string, segments: readonly string[]): Promise<Buffer | null>;
42
+ /** Acquires `run/<area>/<name>.lock` (spec section 8). */
43
+ acquireLock(area: string, name: string, options?: AcquireOptions): Promise<LockHandle>;
44
+ withLock<T>(area: string, name: string, fn: () => Promise<T>, options?: AcquireOptions): Promise<T>;
45
+ /** Every resolved location, for `xeno home`. */
46
+ describe(): {
47
+ platform: Platform;
48
+ overridden: boolean;
49
+ roots: Record<Kind, string>;
50
+ warnings: readonly string[];
51
+ layout: LayoutState;
52
+ };
53
+ }
54
+ /** Builds a resolver from the host (default) or from explicit inputs (tests, vectors, a fixture root). */
55
+ export declare function createDirs(options?: CreateDirsOptions): XenoDirs;
56
+ /** A resolver rooted entirely under one directory via XENO_HOME; the supported way to isolate tests and fixtures. */
57
+ export declare function createDirsAt(xenoHome: string, platform?: Platform): XenoDirs;
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.XenoDirs = void 0;
4
+ exports.createDirs = createDirs;
5
+ exports.createDirsAt = createDirsAt;
6
+ const node_fs_1 = require("node:fs");
7
+ const errors_ts_1 = require("./errors.js");
8
+ const atomic_ts_1 = require("./atomic.js");
9
+ const host_ts_1 = require("./host.js");
10
+ const layout_ts_1 = require("./layout.js");
11
+ const lock_ts_1 = require("./lock.js");
12
+ const registry_ts_1 = require("./registry.js");
13
+ const roots_ts_1 = require("./roots.js");
14
+ /**
15
+ * The resolver. Every XENO path comes from here; nothing else may build one. It refuses anything the registry does
16
+ * not list, and refuses to write when the layout on disk is newer than this build understands.
17
+ */
18
+ class XenoDirs {
19
+ platform;
20
+ roots;
21
+ warnings;
22
+ overridden;
23
+ constructor(resolved) {
24
+ this.platform = resolved.platform;
25
+ this.roots = resolved.roots;
26
+ this.warnings = resolved.warnings;
27
+ this.overridden = resolved.overridden;
28
+ }
29
+ /** Root directory of a kind. */
30
+ root(kind) {
31
+ return this.roots[kind];
32
+ }
33
+ /** Path relative to the kind root, `/`-separated, after registry validation. */
34
+ relative(kind, area, ...segments) {
35
+ return (0, registry_ts_1.registeredRelativePath)(kind, area, segments);
36
+ }
37
+ /** Absolute path for (kind, area, ...segments). Throws DirsError for anything unregistered or invalid. */
38
+ path(kind, area, ...segments) {
39
+ const rel = (0, registry_ts_1.registeredRelativePath)(kind, area, segments);
40
+ return (0, roots_ts_1.joinPath)(this.platform, this.roots[kind], ...rel.split('/'));
41
+ }
42
+ /** `run/<area>/<name>.lock`. */
43
+ lockPath(area, name) {
44
+ return (0, roots_ts_1.joinPath)(this.platform, this.roots.run, ...(0, registry_ts_1.lockRelativePath)(area, name).split('/'));
45
+ }
46
+ /** `data/layout.json`. */
47
+ layoutPath() {
48
+ return this.roots.data + roots_ts_1.SEP[this.platform] + 'layout.json';
49
+ }
50
+ /** `<kind>/<area>/area.json`, the optional per-area schema marker. */
51
+ areaMetaPath(kind, area) {
52
+ return this.path(kind, area, 'area.json');
53
+ }
54
+ /** Reads data/layout.json. Never throws for a missing file. */
55
+ readLayout() {
56
+ let text = null;
57
+ try {
58
+ text = (0, node_fs_1.readFileSync)(this.layoutPath(), 'utf8');
59
+ }
60
+ catch (e) {
61
+ if (e.code !== 'ENOENT')
62
+ return { state: 'invalid', reason: 'unreadable' };
63
+ }
64
+ return (0, layout_ts_1.parseLayout)(text);
65
+ }
66
+ /** Throws unless this build may write: a newer or unreadable layout marker refuses (spec section 8). */
67
+ assertWritable() {
68
+ const s = this.readLayout();
69
+ if (s.state === 'newer') {
70
+ throw new errors_ts_1.DirsError('layout-newer', `the XENO layout on disk is version ${s.layout}; this build understands up to ${layout_ts_1.SUPPORTED_LAYOUT}. Update the product before it writes.`, { found: s.layout, supported: layout_ts_1.SUPPORTED_LAYOUT });
71
+ }
72
+ if (s.state === 'invalid') {
73
+ throw new errors_ts_1.DirsError('layout-invalid', `data/layout.json is not readable (${s.reason}); refusing to write`, { reason: s.reason });
74
+ }
75
+ return s;
76
+ }
77
+ /** Creates data/layout.json at the supported version if absent; otherwise checks it. */
78
+ async ensureLayout() {
79
+ const s = this.assertWritable();
80
+ if (s.state === 'missing') {
81
+ await (0, atomic_ts_1.atomicWriteFile)(this.layoutPath(), JSON.stringify({ layout: layout_ts_1.SUPPORTED_LAYOUT }) + '\n');
82
+ return { state: 'ok', layout: layout_ts_1.SUPPORTED_LAYOUT };
83
+ }
84
+ return s;
85
+ }
86
+ /** The only sanctioned way to write below the roots: registry check, layout check, atomic replace. */
87
+ async writeFile(kind, area, segments, data, options = {}) {
88
+ const target = this.path(kind, area, ...segments);
89
+ await this.ensureLayout();
90
+ await (0, atomic_ts_1.atomicWriteFile)(target, data, kind === 'secrets' ? { mode: 0o600, ...options } : options);
91
+ return target;
92
+ }
93
+ /** Reads a registered file; returns null when absent. */
94
+ async readFile(kind, area, segments) {
95
+ try {
96
+ return await node_fs_1.promises.readFile(this.path(kind, area, ...segments));
97
+ }
98
+ catch (e) {
99
+ if (e.code === 'ENOENT')
100
+ return null;
101
+ throw e;
102
+ }
103
+ }
104
+ /** Acquires `run/<area>/<name>.lock` (spec section 8). */
105
+ acquireLock(area, name, options) {
106
+ return (0, lock_ts_1.acquireLockFile)(this.lockPath(area, name), options);
107
+ }
108
+ async withLock(area, name, fn, options) {
109
+ const lock = await this.acquireLock(area, name, options);
110
+ try {
111
+ return await fn();
112
+ }
113
+ finally {
114
+ await lock.release();
115
+ }
116
+ }
117
+ /** Every resolved location, for `xeno home`. */
118
+ describe() {
119
+ return { platform: this.platform, overridden: this.overridden, roots: { ...this.roots }, warnings: this.warnings, layout: this.readLayout() };
120
+ }
121
+ }
122
+ exports.XenoDirs = XenoDirs;
123
+ /** Builds a resolver from the host (default) or from explicit inputs (tests, vectors, a fixture root). */
124
+ function createDirs(options = {}) {
125
+ const input = {
126
+ platform: options.platform ?? (0, host_ts_1.hostPlatform)(),
127
+ home: options.home ?? (0, host_ts_1.hostHome)(),
128
+ env: options.env ?? (0, host_ts_1.hostEnv)(),
129
+ };
130
+ return new XenoDirs((0, roots_ts_1.resolveRoots)(input));
131
+ }
132
+ /** A resolver rooted entirely under one directory via XENO_HOME; the supported way to isolate tests and fixtures. */
133
+ function createDirsAt(xenoHome, platform = (0, host_ts_1.hostPlatform)()) {
134
+ return new XenoDirs((0, roots_ts_1.resolveRoots)({ platform, home: '', env: { XENO_HOME: xenoHome } }));
135
+ }