@xenosystem/primitives 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.
Files changed (103) hide show
  1. package/README.md +28 -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/esm/dirs/atomic.d.ts +9 -0
  54. package/dist/esm/dirs/atomic.js +56 -0
  55. package/dist/esm/dirs/check-cli.d.ts +2 -0
  56. package/dist/esm/dirs/check-cli.js +48 -0
  57. package/dist/esm/dirs/check.d.ts +49 -0
  58. package/dist/esm/dirs/check.js +152 -0
  59. package/dist/esm/dirs/cli.d.ts +2 -0
  60. package/dist/esm/dirs/cli.js +70 -0
  61. package/dist/esm/dirs/dirs.d.ts +57 -0
  62. package/dist/esm/dirs/dirs.js +129 -0
  63. package/dist/esm/dirs/doctor.d.ts +31 -0
  64. package/dist/esm/dirs/doctor.js +77 -0
  65. package/dist/esm/dirs/errors.d.ts +8 -0
  66. package/dist/esm/dirs/errors.js +14 -0
  67. package/dist/esm/dirs/host.d.ts +4 -0
  68. package/dist/esm/dirs/host.js +21 -0
  69. package/dist/esm/dirs/index.d.ts +13 -0
  70. package/dist/esm/dirs/index.js +13 -0
  71. package/dist/esm/dirs/inputs.d.ts +14 -0
  72. package/dist/esm/dirs/inputs.js +11 -0
  73. package/dist/esm/dirs/layout.d.ts +16 -0
  74. package/dist/esm/dirs/layout.js +21 -0
  75. package/dist/esm/dirs/lock.d.ts +38 -0
  76. package/dist/esm/dirs/lock.js +124 -0
  77. package/dist/esm/dirs/migrate.d.ts +134 -0
  78. package/dist/esm/dirs/migrate.js +428 -0
  79. package/dist/esm/dirs/procinfo.d.ts +10 -0
  80. package/dist/esm/dirs/procinfo.js +62 -0
  81. package/dist/esm/dirs/registry.d.ts +27 -0
  82. package/dist/esm/dirs/registry.js +71 -0
  83. package/dist/esm/dirs/roots.d.ts +23 -0
  84. package/dist/esm/dirs/roots.js +107 -0
  85. package/dist/esm/dirs/segments.d.ts +7 -0
  86. package/dist/esm/dirs/segments.js +35 -0
  87. package/dist/esm/generated/contract.d.ts +134 -0
  88. package/dist/esm/generated/contract.js +230 -0
  89. package/dist/esm/secrets/envelope.d.ts +37 -0
  90. package/dist/esm/secrets/envelope.js +81 -0
  91. package/dist/esm/secrets/errors.d.ts +10 -0
  92. package/dist/esm/secrets/errors.js +15 -0
  93. package/dist/esm/secrets/index.d.ts +4 -0
  94. package/dist/esm/secrets/index.js +4 -0
  95. package/dist/esm/secrets/keystore.d.ts +37 -0
  96. package/dist/esm/secrets/keystore.js +37 -0
  97. package/dist/esm/secrets/os-stores.d.ts +17 -0
  98. package/dist/esm/secrets/os-stores.js +189 -0
  99. package/dist/esm/secrets/store.d.ts +32 -0
  100. package/dist/esm/secrets/store.js +156 -0
  101. package/dist/esm/secrets/testing.d.ts +5 -0
  102. package/dist/esm/secrets/testing.js +12 -0
  103. package/package.json +38 -4
@@ -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,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.doctor = doctor;
4
+ const node_fs_1 = require("node:fs");
5
+ const contract_ts_1 = require("../generated/contract.js");
6
+ const registry_ts_1 = require("./registry.js");
7
+ const roots_ts_1 = require("./roots.js");
8
+ const typeOf = (p) => {
9
+ const s = (0, node_fs_1.lstatSync)(p);
10
+ return s.isSymbolicLink() ? 'link' : s.isDirectory() ? 'directory' : s.isFile() ? 'file' : 'other';
11
+ };
12
+ const safeList = (p) => { try {
13
+ return (0, node_fs_1.readdirSync)(p);
14
+ }
15
+ catch {
16
+ return [];
17
+ } };
18
+ const sameOrInside = (parent, child, sep) => {
19
+ const norm = (x) => (sep === '\\' ? x.toLowerCase() : x);
20
+ return norm(child).startsWith(norm(parent) + sep);
21
+ };
22
+ /**
23
+ * `xeno home doctor`: lists every entry under each root that the registry does not allow (spec section 8, check 2).
24
+ * Registration is by area; what is inside an area belongs to its owner and is not inspected. A root that does not
25
+ * exist yet is fine. Reads only; never changes anything.
26
+ */
27
+ function doctor(dirs, options = {}) {
28
+ const sep = dirs.platform === 'windows' ? '\\' : '/';
29
+ const unregistered = [];
30
+ for (const kind of roots_ts_1.KINDS) {
31
+ const root = dirs.root(kind);
32
+ // Roots nested in another root (Linux secrets under data; the run fallback under state) are allowed there.
33
+ const nestedRoots = roots_ts_1.KINDS.filter((k) => k !== kind && sameOrInside(root, dirs.root(k), sep)).map((k) => dirs.root(k).slice(root.length + 1).split(sep)[0]);
34
+ const topAllowed = new Set(nestedRoots);
35
+ if (kind === 'data')
36
+ topAllowed.add('layout.json');
37
+ const areasOfKind = registry_ts_1.AREAS.filter((a) => kind === 'run' || a.uses.includes(kind));
38
+ for (const name of safeList(root)) {
39
+ const abs = root + sep + name;
40
+ if (topAllowed.has(name))
41
+ continue;
42
+ const top = areasOfKind.filter((a) => a.area.split('/')[0] === name);
43
+ if (top.length === 0) {
44
+ const elsewhere = registry_ts_1.AREAS.some((a) => a.area.split('/')[0] === name);
45
+ unregistered.push({ kind, path: name, type: typeOf(abs), reason: elsewhere ? `area ${name} is not registered for kind ${kind}` : 'not a registered area' });
46
+ continue;
47
+ }
48
+ // An area with a deeper name (agents/definitions, apps/<slug>) is checked one level down.
49
+ const deeper = top.filter((a) => a.area.includes('/'));
50
+ if (deeper.length === 0)
51
+ continue;
52
+ for (const child of safeList(abs)) {
53
+ const full = `${name}/${child}`;
54
+ const entry = (0, registry_ts_1.findArea)(full);
55
+ if (entry === null || !(kind === 'run' || entry.uses.includes(kind))) {
56
+ 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}` });
57
+ }
58
+ }
59
+ }
60
+ }
61
+ const home = options.home;
62
+ const legacy = home === undefined ? [] : contract_ts_1.INPUTS_JSON.legacyHomes.map((name) => {
63
+ const path = home + sep + name;
64
+ let present = false;
65
+ try {
66
+ present = (0, node_fs_1.lstatSync)(path).isDirectory() || (0, node_fs_1.lstatSync)(path).isSymbolicLink();
67
+ }
68
+ catch { /* absent */ }
69
+ return { name, path, present };
70
+ });
71
+ return {
72
+ ok: unregistered.length === 0,
73
+ platform: dirs.platform,
74
+ roots: { ...dirs.roots },
75
+ layout: dirs.readLayout(),
76
+ warnings: dirs.warnings,
77
+ unregistered: unregistered.sort((a, b) => { const x = a.kind + a.path, y = b.kind + b.path; return x < y ? -1 : x > y ? 1 : 0; }),
78
+ legacy,
79
+ };
80
+ }
@@ -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,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DirsError = void 0;
4
+ exports.isDirsError = isDirsError;
5
+ /** Every error this family throws. `code` is stable and is what callers branch on. */
6
+ class DirsError extends Error {
7
+ code;
8
+ detail;
9
+ constructor(code, message, detail = {}) {
10
+ super(message);
11
+ this.name = 'DirsError';
12
+ this.code = code;
13
+ this.detail = detail;
14
+ }
15
+ }
16
+ exports.DirsError = DirsError;
17
+ function isDirsError(e, code) {
18
+ return e instanceof DirsError && (code === undefined || e.code === code);
19
+ }
@@ -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,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hostPlatform = hostPlatform;
4
+ exports.hostHome = hostHome;
5
+ exports.hostEnv = hostEnv;
6
+ // The one place in the XENO ecosystem allowed to ask the OS for the person's home directory.
7
+ // (The static checker excludes exactly this file; see check.ts DEFAULT_RESOLVER_FILES.)
8
+ const node_os_1 = require("node:os");
9
+ function hostPlatform() {
10
+ switch (process.platform) {
11
+ case 'win32': return 'windows';
12
+ case 'darwin': return 'macos';
13
+ default: return 'linux';
14
+ }
15
+ }
16
+ function hostHome() {
17
+ try {
18
+ return (0, node_os_1.homedir)();
19
+ }
20
+ catch {
21
+ return '';
22
+ }
23
+ }
24
+ function hostEnv() {
25
+ return process.env;
26
+ }
@@ -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,55 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scanText = exports.loadConfig = exports.checkSource = exports.RULES = exports.CONFIG_NAME = exports.doctor = exports.verifyMigration = exports.runMigration = exports.readJournal = exports.planMigration = exports.planId = exports.journalPath = exports.BUILTIN_RULES = exports.contractInputs = exports.createDirsAt = exports.createDirs = exports.XenoDirs = exports.processStartTime = exports.isProcessAlive = exports.judgeLock = exports.acquireLockFile = exports.atomicWriteFile = exports.parseLayout = exports.SUPPORTED_LAYOUT = exports.lockRelativePath = exports.registeredRelativePath = exports.findArea = exports.LOCK_SUFFIX = exports.AREAS = exports.assertSegment = exports.segmentProblem = exports.resolveRoots = exports.normalizeBase = exports.joinPath = exports.isAbsolutePath = exports.SEP = exports.KINDS = exports.isDirsError = exports.DirsError = void 0;
4
+ var errors_ts_1 = require("./errors.js");
5
+ Object.defineProperty(exports, "DirsError", { enumerable: true, get: function () { return errors_ts_1.DirsError; } });
6
+ Object.defineProperty(exports, "isDirsError", { enumerable: true, get: function () { return errors_ts_1.isDirsError; } });
7
+ var roots_ts_1 = require("./roots.js");
8
+ Object.defineProperty(exports, "KINDS", { enumerable: true, get: function () { return roots_ts_1.KINDS; } });
9
+ Object.defineProperty(exports, "SEP", { enumerable: true, get: function () { return roots_ts_1.SEP; } });
10
+ Object.defineProperty(exports, "isAbsolutePath", { enumerable: true, get: function () { return roots_ts_1.isAbsolutePath; } });
11
+ Object.defineProperty(exports, "joinPath", { enumerable: true, get: function () { return roots_ts_1.joinPath; } });
12
+ Object.defineProperty(exports, "normalizeBase", { enumerable: true, get: function () { return roots_ts_1.normalizeBase; } });
13
+ Object.defineProperty(exports, "resolveRoots", { enumerable: true, get: function () { return roots_ts_1.resolveRoots; } });
14
+ var segments_ts_1 = require("./segments.js");
15
+ Object.defineProperty(exports, "segmentProblem", { enumerable: true, get: function () { return segments_ts_1.segmentProblem; } });
16
+ Object.defineProperty(exports, "assertSegment", { enumerable: true, get: function () { return segments_ts_1.assertSegment; } });
17
+ var registry_ts_1 = require("./registry.js");
18
+ Object.defineProperty(exports, "AREAS", { enumerable: true, get: function () { return registry_ts_1.AREAS; } });
19
+ Object.defineProperty(exports, "LOCK_SUFFIX", { enumerable: true, get: function () { return registry_ts_1.LOCK_SUFFIX; } });
20
+ Object.defineProperty(exports, "findArea", { enumerable: true, get: function () { return registry_ts_1.findArea; } });
21
+ Object.defineProperty(exports, "registeredRelativePath", { enumerable: true, get: function () { return registry_ts_1.registeredRelativePath; } });
22
+ Object.defineProperty(exports, "lockRelativePath", { enumerable: true, get: function () { return registry_ts_1.lockRelativePath; } });
23
+ var layout_ts_1 = require("./layout.js");
24
+ Object.defineProperty(exports, "SUPPORTED_LAYOUT", { enumerable: true, get: function () { return layout_ts_1.SUPPORTED_LAYOUT; } });
25
+ Object.defineProperty(exports, "parseLayout", { enumerable: true, get: function () { return layout_ts_1.parseLayout; } });
26
+ var atomic_ts_1 = require("./atomic.js");
27
+ Object.defineProperty(exports, "atomicWriteFile", { enumerable: true, get: function () { return atomic_ts_1.atomicWriteFile; } });
28
+ var lock_ts_1 = require("./lock.js");
29
+ Object.defineProperty(exports, "acquireLockFile", { enumerable: true, get: function () { return lock_ts_1.acquireLockFile; } });
30
+ Object.defineProperty(exports, "judgeLock", { enumerable: true, get: function () { return lock_ts_1.judgeLock; } });
31
+ var procinfo_ts_1 = require("./procinfo.js");
32
+ Object.defineProperty(exports, "isProcessAlive", { enumerable: true, get: function () { return procinfo_ts_1.isProcessAlive; } });
33
+ Object.defineProperty(exports, "processStartTime", { enumerable: true, get: function () { return procinfo_ts_1.processStartTime; } });
34
+ var dirs_ts_1 = require("./dirs.js");
35
+ Object.defineProperty(exports, "XenoDirs", { enumerable: true, get: function () { return dirs_ts_1.XenoDirs; } });
36
+ Object.defineProperty(exports, "createDirs", { enumerable: true, get: function () { return dirs_ts_1.createDirs; } });
37
+ Object.defineProperty(exports, "createDirsAt", { enumerable: true, get: function () { return dirs_ts_1.createDirsAt; } });
38
+ var inputs_ts_1 = require("./inputs.js");
39
+ Object.defineProperty(exports, "contractInputs", { enumerable: true, get: function () { return inputs_ts_1.contractInputs; } });
40
+ var migrate_ts_1 = require("./migrate.js");
41
+ Object.defineProperty(exports, "BUILTIN_RULES", { enumerable: true, get: function () { return migrate_ts_1.BUILTIN_RULES; } });
42
+ Object.defineProperty(exports, "journalPath", { enumerable: true, get: function () { return migrate_ts_1.journalPath; } });
43
+ Object.defineProperty(exports, "planId", { enumerable: true, get: function () { return migrate_ts_1.planId; } });
44
+ Object.defineProperty(exports, "planMigration", { enumerable: true, get: function () { return migrate_ts_1.planMigration; } });
45
+ Object.defineProperty(exports, "readJournal", { enumerable: true, get: function () { return migrate_ts_1.readJournal; } });
46
+ Object.defineProperty(exports, "runMigration", { enumerable: true, get: function () { return migrate_ts_1.runMigration; } });
47
+ Object.defineProperty(exports, "verifyMigration", { enumerable: true, get: function () { return migrate_ts_1.verifyMigration; } });
48
+ var doctor_ts_1 = require("./doctor.js");
49
+ Object.defineProperty(exports, "doctor", { enumerable: true, get: function () { return doctor_ts_1.doctor; } });
50
+ var check_ts_1 = require("./check.js");
51
+ Object.defineProperty(exports, "CONFIG_NAME", { enumerable: true, get: function () { return check_ts_1.CONFIG_NAME; } });
52
+ Object.defineProperty(exports, "RULES", { enumerable: true, get: function () { return check_ts_1.RULES; } });
53
+ Object.defineProperty(exports, "checkSource", { enumerable: true, get: function () { return check_ts_1.checkSource; } });
54
+ Object.defineProperty(exports, "loadConfig", { enumerable: true, get: function () { return check_ts_1.loadConfig; } });
55
+ Object.defineProperty(exports, "scanText", { enumerable: true, get: function () { return check_ts_1.scanText; } });
@@ -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,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.contractInputs = contractInputs;
4
+ const contract_ts_1 = require("../generated/contract.js");
5
+ /** Owner-decided inputs the layout depends on (spec section 11), exposed so tools can show them. */
6
+ function contractInputs() {
7
+ const i = contract_ts_1.INPUTS_JSON.inputs;
8
+ return {
9
+ layout: contract_ts_1.INPUTS_JSON.layout,
10
+ macosBundleId: i.macosBundleId,
11
+ legacyFallbackReleases: i.legacyFallbackReleases,
12
+ legacyHomes: contract_ts_1.INPUTS_JSON.legacyHomes,
13
+ };
14
+ }
@@ -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,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SUPPORTED_LAYOUT = void 0;
4
+ exports.parseLayout = parseLayout;
5
+ const contract_ts_1 = require("../generated/contract.js");
6
+ /** The layout version this build understands (data/layout.json, spec section 8). */
7
+ exports.SUPPORTED_LAYOUT = contract_ts_1.INPUTS_JSON.layout;
8
+ /** Pure parser for the contents of layout.json (null = the file does not exist). */
9
+ function parseLayout(text, supported = exports.SUPPORTED_LAYOUT) {
10
+ if (text === null)
11
+ return { state: 'missing' };
12
+ let v;
13
+ try {
14
+ v = JSON.parse(text);
15
+ }
16
+ catch {
17
+ return { state: 'invalid', reason: 'not valid JSON' };
18
+ }
19
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
20
+ return { state: 'invalid', reason: 'not an object' };
21
+ const n = v['layout'];
22
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1)
23
+ return { state: 'invalid', reason: 'layout is not a positive integer' };
24
+ return n > supported ? { state: 'newer', layout: n } : { state: 'ok', layout: n };
25
+ }
@@ -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,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.judgeLock = judgeLock;
4
+ exports.acquireLockFile = acquireLockFile;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_fs_1 = require("node:fs");
7
+ const node_os_1 = require("node:os");
8
+ const node_path_1 = require("node:path");
9
+ const errors_ts_1 = require("./errors.js");
10
+ const procinfo_ts_1 = require("./procinfo.js");
11
+ const defaultProbe = { isAlive: procinfo_ts_1.isProcessAlive, startTime: procinfo_ts_1.processStartTime, host: node_os_1.hostname };
12
+ /**
13
+ * Decides whether the holder of a lock is still running. A bare pid is never trusted: a live pid whose start time
14
+ * differs from the recorded one is a reused pid (stale); a live pid whose start time cannot be read on either side
15
+ * is treated as held, because guessing wrong would break mutual exclusion.
16
+ */
17
+ async function judgeLock(rec, probe = defaultProbe) {
18
+ if (rec.host.toLowerCase() !== probe.host().toLowerCase())
19
+ return 'foreign-host';
20
+ if (!probe.isAlive(rec.pid))
21
+ return 'stale';
22
+ const now = await probe.startTime(rec.pid);
23
+ if (now === null || rec.startTime === null)
24
+ return 'held';
25
+ return now === rec.startTime ? 'held' : 'stale';
26
+ }
27
+ function parseRecord(text) {
28
+ try {
29
+ const v = JSON.parse(text);
30
+ if (v && v.v === 1 && Number.isInteger(v.pid) && typeof v.token === 'string' && typeof v.host === 'string')
31
+ return v;
32
+ }
33
+ catch { /* fallthrough */ }
34
+ return null;
35
+ }
36
+ async function readRecord(path) {
37
+ try {
38
+ const text = await node_fs_1.promises.readFile(path, 'utf8');
39
+ return { rec: parseRecord(text), text };
40
+ }
41
+ catch (e) {
42
+ if (e.code === 'ENOENT')
43
+ return null;
44
+ throw e;
45
+ }
46
+ }
47
+ /** Creates the lock file atomically with its full content: write a temp file, then hard-link it into place. */
48
+ async function tryCreate(path, rec) {
49
+ const tmp = (0, node_path_1.join)((0, node_path_1.dirname)(path), `.${(0, node_path_1.basename)(path)}.${rec.token}.tmp`);
50
+ const h = await node_fs_1.promises.open(tmp, 'wx', 0o600);
51
+ try {
52
+ await h.writeFile(JSON.stringify(rec));
53
+ await h.sync();
54
+ }
55
+ finally {
56
+ await h.close();
57
+ }
58
+ try {
59
+ await node_fs_1.promises.link(tmp, path);
60
+ return true;
61
+ }
62
+ catch (e) {
63
+ if (e.code === 'EEXIST')
64
+ return false;
65
+ throw e;
66
+ }
67
+ finally {
68
+ await node_fs_1.promises.rm(tmp, { force: true }).catch(() => undefined);
69
+ }
70
+ }
71
+ /** Removes a lock judged stale, but only if the file still holds the record that was judged. */
72
+ async function breakStale(path, judged) {
73
+ const moved = `${path}.stale.${(0, node_crypto_1.randomBytes)(4).toString('hex')}`;
74
+ try {
75
+ await node_fs_1.promises.rename(path, moved);
76
+ }
77
+ catch (e) {
78
+ if (e.code === 'ENOENT')
79
+ return;
80
+ throw e;
81
+ }
82
+ const taken = await readRecord(moved);
83
+ if (taken?.rec?.token !== judged.token) {
84
+ // We moved a lock another process had just created. Put it back; if that fails the next release() no-ops safely.
85
+ await node_fs_1.promises.link(moved, path).catch(() => undefined);
86
+ }
87
+ await node_fs_1.promises.rm(moved, { force: true }).catch(() => undefined);
88
+ }
89
+ /** Acquires a lock file at an absolute path produced by `XenoDirs.lockPath`. */
90
+ async function acquireLockFile(path, options = {}) {
91
+ const probe = { ...defaultProbe, ...options.probe };
92
+ await node_fs_1.promises.mkdir((0, node_path_1.dirname)(path), { recursive: true });
93
+ const deadline = Date.now() + (options.timeoutMs ?? 0);
94
+ const startTime = options.probe?.startTime ? await options.probe.startTime(process.pid) : await (0, procinfo_ts_1.ownProcessStartTime)();
95
+ for (;;) {
96
+ const rec = {
97
+ v: 1, pid: process.pid, startTime, host: probe.host(), token: (0, node_crypto_1.randomBytes)(12).toString('hex'),
98
+ owner: options.owner ?? '', createdAt: new Date().toISOString(),
99
+ };
100
+ if (await tryCreate(path, rec)) {
101
+ return {
102
+ path, record: rec,
103
+ async release() {
104
+ const cur = await readRecord(path);
105
+ if (cur?.rec?.token !== rec.token)
106
+ return false;
107
+ await node_fs_1.promises.rm(path, { force: true });
108
+ return true;
109
+ },
110
+ };
111
+ }
112
+ const cur = await readRecord(path);
113
+ if (cur === null)
114
+ continue; // vanished between our attempt and our read: try again
115
+ if (cur.rec === null) {
116
+ throw new errors_ts_1.DirsError('lock-corrupt', 'a lock file exists but cannot be read; it is not removed automatically', { path });
117
+ }
118
+ const verdict = await judgeLock(cur.rec, probe);
119
+ if (verdict === 'stale') {
120
+ await breakStale(path, cur.rec);
121
+ continue;
122
+ }
123
+ if (Date.now() >= deadline) {
124
+ throw new errors_ts_1.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 });
125
+ }
126
+ await new Promise((r) => setTimeout(r, 50));
127
+ }
128
+ }
@@ -0,0 +1,134 @@
1
+ import type { XenoDirs } from './dirs.ts';
2
+ import type { Kind } from './roots.ts';
3
+ /**
4
+ * The copy-only migrator (XENO LOCAL HOME - SPEC.md section 10). It copies known legacy files to their registered
5
+ * locations, records source, destination and SHA-256 in a journal under state/platform/migrations/, verifies every
6
+ * copy by hash, refuses a destination that already holds different bytes and refuses links and junctions, converts
7
+ * plaintext credentials into encrypted secrets through a caller-supplied sink, leaves every legacy home in place, and
8
+ * reports whatever it found but could not place. It never deletes or moves anything, and it never guesses.
9
+ */
10
+ export type MigrationRule = {
11
+ id: string;
12
+ legacyHome: string;
13
+ match: string;
14
+ action: 'copy';
15
+ target: {
16
+ kind: Kind;
17
+ area: string;
18
+ segments: string[];
19
+ };
20
+ } | {
21
+ id: string;
22
+ legacyHome: string;
23
+ match: string;
24
+ action: 'secret';
25
+ target: {
26
+ area: string;
27
+ name: string;
28
+ };
29
+ };
30
+ /** Rules the contract itself knows (only those the ecosystem documents state explicitly). Owners add their own. */
31
+ export declare const BUILTIN_RULES: readonly MigrationRule[];
32
+ export interface PlanEntry {
33
+ rule: string;
34
+ action: 'copy' | 'secret';
35
+ legacyHome: string;
36
+ sourceRel: string;
37
+ source: string;
38
+ bytes: number;
39
+ /** Absolute destination for a copy; null for a secret. */
40
+ dest: string | null;
41
+ /** Destination relative to its kind root, `/` separated (copy) or `area/name` (secret). */
42
+ destRel: string;
43
+ destKind: Kind | 'secret';
44
+ secret?: {
45
+ area: string;
46
+ name: string;
47
+ };
48
+ }
49
+ export interface Refusal {
50
+ path: string;
51
+ reason: string;
52
+ }
53
+ export interface MigrationPlan {
54
+ id: string;
55
+ homes: {
56
+ name: string;
57
+ path: string;
58
+ state: 'present' | 'absent' | 'refused-link';
59
+ }[];
60
+ entries: PlanEntry[];
61
+ refused: Refusal[];
62
+ unplaced: {
63
+ count: number;
64
+ sample: string[];
65
+ truncated: boolean;
66
+ };
67
+ }
68
+ /** Deterministic id: the same plan (rules, sources, destinations) always has the same journal. */
69
+ export declare function planId(entries: readonly {
70
+ rule: string;
71
+ sourceRel: string;
72
+ destRel: string;
73
+ legacyHome: string;
74
+ }[]): string;
75
+ export interface PlanOptions {
76
+ dirs: XenoDirs;
77
+ /** The person's home directory, where the legacy homes live. */
78
+ home: string;
79
+ rules?: readonly MigrationRule[];
80
+ legacyHomes?: readonly string[];
81
+ }
82
+ export declare function planMigration(options: PlanOptions): MigrationPlan;
83
+ export type EntryStatus = 'copied' | 'already' | 'secret' | 'conflict' | 'refused' | 'failed';
84
+ export interface EntryResult {
85
+ rule: string;
86
+ legacyHome: string;
87
+ sourceRel: string;
88
+ dest: string | null;
89
+ destRel: string;
90
+ status: EntryStatus;
91
+ bytes: number;
92
+ /** SHA-256 of the file's bytes. Never recorded for a secret. */
93
+ sha256?: string;
94
+ reason?: string;
95
+ }
96
+ export interface SecretSink {
97
+ set(area: string, name: string, value: Uint8Array): Promise<void>;
98
+ get(area: string, name: string): Promise<Uint8Array | null>;
99
+ }
100
+ export interface RunOptions {
101
+ dirs: XenoDirs;
102
+ /** Nothing is written unless this is true (dry run by default). */
103
+ confirm?: boolean;
104
+ /** Required to migrate `secret` entries; without it they are reported, not migrated. */
105
+ secrets?: SecretSink;
106
+ /** Write XENO-MIGRATED.txt into each legacy home (default true). */
107
+ writeNote?: boolean;
108
+ }
109
+ export interface MigrationResult {
110
+ id: string;
111
+ confirmed: boolean;
112
+ /** True only when every planned entry is copied/already/secret-verified and nothing was refused. A product may switch only on true. */
113
+ ok: boolean;
114
+ entries: EntryResult[];
115
+ refused: Refusal[];
116
+ unplaced: MigrationPlan['unplaced'];
117
+ journal: string | null;
118
+ /** Plaintext credential files that still sit in a legacy home; deleting them is a person's confirmed step. */
119
+ plaintextRemains: string[];
120
+ }
121
+ export declare function journalPath(dirs: XenoDirs, id: string): string;
122
+ export declare function readJournal(path: string): Promise<Record<string, unknown>[]>;
123
+ export declare function runMigration(plan: MigrationPlan, options: RunOptions): Promise<MigrationResult>;
124
+ export interface VerifyResult {
125
+ id: string;
126
+ complete: boolean;
127
+ checked: number;
128
+ problems: string[];
129
+ }
130
+ /**
131
+ * Re-checks a finished migration against its journal: every copied destination still exists and still hashes to the
132
+ * recorded SHA-256. A product switches to the new location only when `complete` is true.
133
+ */
134
+ export declare function verifyMigration(dirs: XenoDirs, id: string): Promise<VerifyResult>;