@xenosystem/primitives 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,12 @@ XENO back-end rung 1. Two families, one subpath each:
10
10
 
11
11
  Authority: `XENO LOCAL HOME - SPEC.md` (LOCKED). Zero runtime dependencies. Proprietary (`UNLICENSED`).
12
12
 
13
+ **Where it lives (0.3.0, owner 2026-10-25):** `~/.xeno/{config,data,secrets,state,cache,run}` on every OS — on Windows
14
+ `C:\Users\<name>\.xeno`. `XENO_HOME=<absolute path>` moves the whole folder. Platform folders (`APPDATA`,
15
+ `LOCALAPPDATA`, `XDG_*`, `TMPDIR`) no longer place anything; 0.1.x–0.2.x used them, and `xeno-home migrate` copies what
16
+ those versions wrote into `~/.xeno` (config, data, secrets and state; cache and run are reported, not copied; links are
17
+ never followed). `resolvePlatformNativeRoots` names the old locations for a product's own migration.
18
+
13
19
  ```ts
14
20
  import { createDirs } from '@xenosystem/primitives/dirs';
15
21
  import { createSecretStore, createOsKeyStore } from '@xenosystem/primitives/secrets';
@@ -6,7 +6,9 @@
6
6
  * homedir-call a call that asks the OS for the home directory (homedir(), home_dir(), Path.home(), UserHomeDir())
7
7
  * platform-dir-read reading HOME, USERPROFILE, APPDATA, LOCALAPPDATA or XDG_* from the environment to build a path
8
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)
9
+ * legacy-home-path ~/.xeno, %USERPROFILE%\.xeno, $HOME/.xeno and the 0.2.x %APPDATA%\XENO form, built by hand. Since
10
+ * 2026-10-25 ~/.xeno IS the XENO home, so only the resolver builds a path into it (a per-project
11
+ * `.xeno/` is fine)
10
12
  * legacy-home-env a XENO_*_HOME variable other than XENO_HOME (the thirteen legacy overrides)
11
13
  * A line (or the line above it) carrying `xeno-dirs-allow: <reason>` is exempt; the reason is mandatory.
12
14
  */
@@ -16,7 +16,7 @@ exports.RULES = [
16
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
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
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'] },
19
+ { id: 'legacy-home-path', description: 'builds a path into the XENO home or the 0.2.x app-data folder by hand; only the dirs resolver builds it', re: /(?:~|\$\{?HOME\}?|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE)[\\/]+\.xeno(?![\w-])|(?:%APPDATA%|%LOCALAPPDATA%|AppData[\\/]+(?:Roaming|Local))[\\/]+XENO\b/, langs: [...JS, 'rs', 'py', 'go'] },
20
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
21
  ];
22
22
  const DEFAULT_EXCLUDE_DIRS = new Set(['node_modules', 'dist', 'build', 'target', '.git', 'coverage', '.next', 'out', '.turbo', '.venv', '__pycache__', 'release', '.worktrees']);
@@ -3,12 +3,13 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  // xeno-home print every resolved location (the engine behind `xeno home`)
5
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)
6
+ // xeno-home migrate [--confirm] copy legacy homes and the 0.2.x platform folders into the layout (dry run unless --confirm; never deletes)
7
7
  // xeno-home inputs show the owner-decided contract inputs
8
8
  const inputs_ts_1 = require("./inputs.js");
9
9
  const dirs_ts_1 = require("./dirs.js");
10
10
  const doctor_ts_1 = require("./doctor.js");
11
11
  const host_ts_1 = require("./host.js");
12
+ const roots_ts_1 = require("./roots.js");
12
13
  const migrate_ts_1 = require("./migrate.js");
13
14
  const [cmd, ...rest] = process.argv.slice(2);
14
15
  const json = rest.includes('--json');
@@ -43,7 +44,15 @@ async function main() {
43
44
  return r.ok ? 0 : 1;
44
45
  }
45
46
  if (cmd === 'migrate') {
46
- const plan = (0, migrate_ts_1.planMigration)({ dirs, home: (0, host_ts_1.hostHome)() });
47
+ // 0.1.x-0.2.x placed kinds in the platform folders; they are relocated into ~/.xeno with the legacy homes.
48
+ let previousRoots;
49
+ try {
50
+ previousRoots = (0, roots_ts_1.resolvePlatformNativeRoots)({ platform: dirs.platform, home: (0, host_ts_1.hostHome)(), env: (0, host_ts_1.hostEnv)() }).roots;
51
+ }
52
+ catch {
53
+ previousRoots = undefined;
54
+ }
55
+ const plan = (0, migrate_ts_1.planMigration)({ dirs, home: (0, host_ts_1.hostHome)(), ...(previousRoots ? { previousRoots } : {}) });
47
56
  const confirm = rest.includes('--confirm');
48
57
  const result = await (0, migrate_ts_1.runMigration)(plan, { dirs, confirm });
49
58
  if (json)
@@ -1,5 +1,5 @@
1
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';
2
+ export { KINDS, SEP, isAbsolutePath, joinPath, normalizeBase, resolvePlatformNativeRoots, resolveRoots, type Kind, type Platform, type ResolveInput, type ResolvedRoots } from './roots.ts';
3
3
  export { segmentProblem, assertSegment } from './segments.ts';
4
4
  export { AREAS, LOCK_SUFFIX, findArea, registeredRelativePath, lockRelativePath, type AreaEntry } from './registry.ts';
5
5
  export { SUPPORTED_LAYOUT, parseLayout, type LayoutState } from './layout.ts';
@@ -8,6 +8,6 @@ export { acquireLockFile, judgeLock, type AcquireOptions, type LockHandle, type
8
8
  export { isProcessAlive, processStartTime } from './procinfo.ts';
9
9
  export { XenoDirs, createDirs, createDirsAt, type CreateDirsOptions } from './dirs.ts';
10
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';
11
+ export { BUILTIN_RULES, RELOCATED_KINDS, RELOCATE_RULE_ID, 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
12
  export { doctor, type DoctorReport, type Unregistered } from './doctor.ts';
13
13
  export { CONFIG_NAME, RULES, checkSource, loadConfig, scanText, type CheckConfig, type CheckResult, type Rule, type Violation } from './check.ts';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
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;
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.RELOCATE_RULE_ID = exports.RELOCATED_KINDS = 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.resolvePlatformNativeRoots = exports.normalizeBase = exports.joinPath = exports.isAbsolutePath = exports.SEP = exports.KINDS = exports.isDirsError = exports.DirsError = void 0;
4
4
  var errors_ts_1 = require("./errors.js");
5
5
  Object.defineProperty(exports, "DirsError", { enumerable: true, get: function () { return errors_ts_1.DirsError; } });
6
6
  Object.defineProperty(exports, "isDirsError", { enumerable: true, get: function () { return errors_ts_1.isDirsError; } });
@@ -10,6 +10,7 @@ Object.defineProperty(exports, "SEP", { enumerable: true, get: function () { ret
10
10
  Object.defineProperty(exports, "isAbsolutePath", { enumerable: true, get: function () { return roots_ts_1.isAbsolutePath; } });
11
11
  Object.defineProperty(exports, "joinPath", { enumerable: true, get: function () { return roots_ts_1.joinPath; } });
12
12
  Object.defineProperty(exports, "normalizeBase", { enumerable: true, get: function () { return roots_ts_1.normalizeBase; } });
13
+ Object.defineProperty(exports, "resolvePlatformNativeRoots", { enumerable: true, get: function () { return roots_ts_1.resolvePlatformNativeRoots; } });
13
14
  Object.defineProperty(exports, "resolveRoots", { enumerable: true, get: function () { return roots_ts_1.resolveRoots; } });
14
15
  var segments_ts_1 = require("./segments.js");
15
16
  Object.defineProperty(exports, "segmentProblem", { enumerable: true, get: function () { return segments_ts_1.segmentProblem; } });
@@ -39,6 +40,8 @@ var inputs_ts_1 = require("./inputs.js");
39
40
  Object.defineProperty(exports, "contractInputs", { enumerable: true, get: function () { return inputs_ts_1.contractInputs; } });
40
41
  var migrate_ts_1 = require("./migrate.js");
41
42
  Object.defineProperty(exports, "BUILTIN_RULES", { enumerable: true, get: function () { return migrate_ts_1.BUILTIN_RULES; } });
43
+ Object.defineProperty(exports, "RELOCATED_KINDS", { enumerable: true, get: function () { return migrate_ts_1.RELOCATED_KINDS; } });
44
+ Object.defineProperty(exports, "RELOCATE_RULE_ID", { enumerable: true, get: function () { return migrate_ts_1.RELOCATE_RULE_ID; } });
42
45
  Object.defineProperty(exports, "journalPath", { enumerable: true, get: function () { return migrate_ts_1.journalPath; } });
43
46
  Object.defineProperty(exports, "planId", { enumerable: true, get: function () { return migrate_ts_1.planId; } });
44
47
  Object.defineProperty(exports, "planMigration", { enumerable: true, get: function () { return migrate_ts_1.planMigration; } });
@@ -86,18 +86,40 @@ async function breakStale(path, judged) {
86
86
  }
87
87
  await node_fs_1.promises.rm(moved, { force: true }).catch(() => undefined);
88
88
  }
89
+ /**
90
+ * Windows reports a lock file that its holder is deleting ("delete pending") as access denied or busy, not as
91
+ * "exists", for a link onto it and for a read of it. That is contention, not a failure. Bounded, so a real permission
92
+ * problem still surfaces as its own error rather than as "held".
93
+ */
94
+ const TRANSIENT_WINDOWS_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
95
+ const TRANSIENT_RETRIES = 20;
96
+ const isTransientContention = (e) => process.platform === 'win32' && TRANSIENT_WINDOWS_CODES.has(e?.code ?? '');
89
97
  /** Acquires a lock file at an absolute path produced by `XenoDirs.lockPath`. */
90
98
  async function acquireLockFile(path, options = {}) {
91
99
  const probe = { ...defaultProbe, ...options.probe };
92
100
  await node_fs_1.promises.mkdir((0, node_path_1.dirname)(path), { recursive: true });
93
101
  const deadline = Date.now() + (options.timeoutMs ?? 0);
94
102
  const startTime = options.probe?.startTime ? await options.probe.startTime(process.pid) : await (0, procinfo_ts_1.ownProcessStartTime)();
103
+ let transient = 0;
95
104
  for (;;) {
96
105
  const rec = {
97
106
  v: 1, pid: process.pid, startTime, host: probe.host(), token: (0, node_crypto_1.randomBytes)(12).toString('hex'),
98
107
  owner: options.owner ?? '', createdAt: new Date().toISOString(),
99
108
  };
100
- if (await tryCreate(path, rec)) {
109
+ let created;
110
+ let cur;
111
+ try {
112
+ created = await tryCreate(path, rec);
113
+ cur = created ? null : await readRecord(path);
114
+ }
115
+ catch (e) {
116
+ if (!isTransientContention(e) || (++transient > TRANSIENT_RETRIES && Date.now() >= deadline))
117
+ throw e;
118
+ await new Promise((r) => setTimeout(r, 10));
119
+ continue;
120
+ }
121
+ transient = 0;
122
+ if (created) {
101
123
  return {
102
124
  path, record: rec,
103
125
  async release() {
@@ -109,7 +131,6 @@ async function acquireLockFile(path, options = {}) {
109
131
  },
110
132
  };
111
133
  }
112
- const cur = await readRecord(path);
113
134
  if (cur === null)
114
135
  continue; // vanished between our attempt and our read: try again
115
136
  if (cur.rec === null) {
@@ -1,5 +1,5 @@
1
1
  import type { XenoDirs } from './dirs.ts';
2
- import type { Kind } from './roots.ts';
2
+ import { type Kind } from './roots.ts';
3
3
  /**
4
4
  * The copy-only migrator (XENO LOCAL HOME - SPEC.md section 10). It copies known legacy files to their registered
5
5
  * locations, records source, destination and SHA-256 in a journal under state/platform/migrations/, verifies every
@@ -52,10 +52,14 @@ export interface Refusal {
52
52
  }
53
53
  export interface MigrationPlan {
54
54
  id: string;
55
+ /**
56
+ * `not-relocated`: a previous kind root that is deliberately not copied (cache is re-creatable, run is ephemeral);
57
+ * reported so a person can see it, never silently dropped.
58
+ */
55
59
  homes: {
56
60
  name: string;
57
61
  path: string;
58
- state: 'present' | 'absent' | 'refused-link';
62
+ state: 'present' | 'absent' | 'refused-link' | 'not-relocated';
59
63
  }[];
60
64
  entries: PlanEntry[];
61
65
  refused: Refusal[];
@@ -78,7 +82,17 @@ export interface PlanOptions {
78
82
  home: string;
79
83
  rules?: readonly MigrationRule[];
80
84
  legacyHomes?: readonly string[];
85
+ /**
86
+ * Where 0.1.x-0.2.x placed each kind (`resolvePlatformNativeRoots`). When given, config, data, secrets and state are
87
+ * relocated one to one into this layout's roots; cache and run are reported, not copied. Links and junctions are
88
+ * never followed, and the previous roots are left in place.
89
+ */
90
+ previousRoots?: Readonly<Record<Kind, string>>;
81
91
  }
92
+ /** Kinds a relocation copies. Cache is re-creatable and run is ephemeral, so copying them only costs disk. */
93
+ export declare const RELOCATED_KINDS: readonly Kind[];
94
+ /** The rule id every relocation entry carries. */
95
+ export declare const RELOCATE_RULE_ID = "relocate-layout-1";
82
96
  export declare function planMigration(options: PlanOptions): MigrationPlan;
83
97
  export type EntryStatus = 'copied' | 'already' | 'secret' | 'conflict' | 'refused' | 'failed';
84
98
  export interface EntryResult {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BUILTIN_RULES = void 0;
3
+ exports.RELOCATE_RULE_ID = exports.RELOCATED_KINDS = exports.BUILTIN_RULES = void 0;
4
4
  exports.planId = planId;
5
5
  exports.planMigration = planMigration;
6
6
  exports.journalPath = journalPath;
@@ -14,6 +14,7 @@ const contract_ts_1 = require("../generated/contract.js");
14
14
  const atomic_ts_1 = require("./atomic.js");
15
15
  const errors_ts_1 = require("./errors.js");
16
16
  const segments_ts_1 = require("./segments.js");
17
+ const roots_ts_1 = require("./roots.js");
17
18
  /** Rules the contract itself knows (only those the ecosystem documents state explicitly). Owners add their own. */
18
19
  exports.BUILTIN_RULES = contract_ts_1.LEGACY_MAP_JSON.rules;
19
20
  const SAMPLE = 200;
@@ -42,6 +43,12 @@ function planId(entries) {
42
43
  const lines = entries.map((e) => `${e.rule}\t${e.legacyHome}\t${e.sourceRel}\t${e.destRel}`).sort().join('\n');
43
44
  return 'm-' + (0, node_crypto_1.createHash)('sha256').update(lines).digest('hex').slice(0, 12);
44
45
  }
46
+ /** Kinds a relocation copies. Cache is re-creatable and run is ephemeral, so copying them only costs disk. */
47
+ exports.RELOCATED_KINDS = ['config', 'data', 'secrets', 'state'];
48
+ /** The rule id every relocation entry carries. */
49
+ exports.RELOCATE_RULE_ID = 'relocate-layout-1';
50
+ /** The note the migrator writes into each source it copied from; it is never itself migrated. */
51
+ const NOTE_NAME = 'XENO-MIGRATED.txt';
45
52
  function planMigration(options) {
46
53
  const rules = [...exports.BUILTIN_RULES, ...(options.rules ?? [])];
47
54
  const seen = new Set();
@@ -57,6 +64,10 @@ function planMigration(options) {
57
64
  const unplaced = { count: 0, sample: [], truncated: false };
58
65
  let visited = 0;
59
66
  const sep = options.dirs.platform === 'windows' ? '\\' : '/';
67
+ // The current layout may sit INSIDE a legacy home (the default is <home>/.xeno/<kind>, and .xeno is also a legacy
68
+ // home), so its own roots are skipped rather than migrated into themselves.
69
+ const key = (q) => (options.dirs.platform === 'windows' ? q.toLowerCase() : q);
70
+ const ownRoots = new Set(roots_ts_1.KINDS.map((k) => key(options.dirs.root(k))));
60
71
  for (const name of names) {
61
72
  const path = options.home + sep + name;
62
73
  let st;
@@ -93,6 +104,8 @@ function planMigration(options) {
93
104
  return;
94
105
  }
95
106
  const abs = dir + sep + entry;
107
+ if (ownRoots.has(key(abs)) || (rel === '' && entry === NOTE_NAME))
108
+ continue;
96
109
  const r = rel ? `${rel}/${entry}` : entry;
97
110
  const s = (0, node_fs_1.lstatSync)(abs);
98
111
  const hits = mine.map((rule) => ({ rule, m: matchRule(rule, r) })).filter((h) => h.m !== null);
@@ -141,6 +154,76 @@ function planMigration(options) {
141
154
  };
142
155
  walk(path, '');
143
156
  }
157
+ if (options.previousRoots) {
158
+ for (const kind of roots_ts_1.KINDS) {
159
+ const from = options.previousRoots[kind];
160
+ const name = `layout-1:${kind}`;
161
+ if (key(from) === key(options.dirs.root(kind)))
162
+ continue; // the same place; nothing to relocate
163
+ let st;
164
+ try {
165
+ st = (0, node_fs_1.lstatSync)(from);
166
+ }
167
+ catch {
168
+ homes.push({ name, path: from, state: 'absent' });
169
+ continue;
170
+ }
171
+ if (st.isSymbolicLink()) {
172
+ homes.push({ name, path: from, state: 'refused-link' });
173
+ refused.push({ path: from, reason: 'the previous kind root is a link or junction' });
174
+ continue;
175
+ }
176
+ if (!st.isDirectory()) {
177
+ homes.push({ name, path: from, state: 'absent' });
178
+ continue;
179
+ }
180
+ if (!exports.RELOCATED_KINDS.includes(kind)) {
181
+ homes.push({ name, path: from, state: 'not-relocated' });
182
+ continue;
183
+ }
184
+ homes.push({ name, path: from, state: 'present' });
185
+ const relocate = (dir, rel) => {
186
+ let list;
187
+ try {
188
+ list = (0, node_fs_1.readdirSync)(dir);
189
+ }
190
+ catch {
191
+ refused.push({ path: dir, reason: 'unreadable directory' });
192
+ return;
193
+ }
194
+ for (const entry of list) {
195
+ if (++visited > WALK_CAP) {
196
+ unplaced.truncated = true;
197
+ return;
198
+ }
199
+ if (rel === '' && entry === NOTE_NAME)
200
+ continue;
201
+ const abs = dir + sep + entry;
202
+ const r = rel ? `${rel}/${entry}` : entry;
203
+ const s = (0, node_fs_1.lstatSync)(abs);
204
+ // Never followed: a junction (Spawn's session pool) points at data that is relocated on its own, and its
205
+ // owner re-creates the link in the new layout.
206
+ if (s.isSymbolicLink()) {
207
+ refused.push({ path: abs, reason: 'a link or junction is never followed; its owner re-creates it' });
208
+ continue;
209
+ }
210
+ if (s.isDirectory()) {
211
+ relocate(abs, r);
212
+ continue;
213
+ }
214
+ if (!s.isFile()) {
215
+ unplaced.count++;
216
+ if (unplaced.sample.length < SAMPLE)
217
+ unplaced.sample.push(`${name}/${r}`);
218
+ continue;
219
+ }
220
+ const dest = options.dirs.root(kind) + sep + r.split('/').join(sep);
221
+ entries.push({ rule: exports.RELOCATE_RULE_ID, action: 'copy', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest, destRel: r, destKind: kind });
222
+ }
223
+ };
224
+ relocate(from, '');
225
+ }
226
+ }
144
227
  // Two sources must never map to one destination.
145
228
  const byDest = new Map();
146
229
  for (const e of entries)
@@ -382,7 +465,7 @@ async function runMigration(plan, options) {
382
465
  '',
383
466
  ].join('\n');
384
467
  try {
385
- await (0, atomic_ts_1.atomicWriteFile)(h.path + sep + 'XENO-MIGRATED.txt', note);
468
+ await (0, atomic_ts_1.atomicWriteFile)(h.path + sep + NOTE_NAME, note);
386
469
  }
387
470
  catch { /* a read-only legacy home is not a failure of the migration */ }
388
471
  }
@@ -20,4 +20,17 @@ export declare function isAbsolutePath(platform: Platform, p: string): boolean;
20
20
  /** Normalises separators and drops trailing ones, so `base + sep + name` is always well formed. */
21
21
  export declare function normalizeBase(platform: Platform, p: string): string;
22
22
  export declare function joinPath(platform: Platform, base: string, ...parts: string[]): string;
23
+ /**
24
+ * Where every kind lives: `<home>/.xeno/<kind>` on every OS, or `<XENO_HOME>/<kind>` when XENO_HOME is absolute.
25
+ *
26
+ * Owner decision, 2026-10-25 ("ok then lets have it done right"): one folder in the person's home that they and their
27
+ * agents can find, the way `~/.claude` and `~/.codex` are found, with the spec's structure inside it. Platform folders
28
+ * (APPDATA, LOCALAPPDATA, XDG_*, TMPDIR) no longer place anything. `resolvePlatformNativeRoots` keeps the previous
29
+ * placement so the migrator can find what 0.1.x-0.2.x wrote there.
30
+ */
23
31
  export declare function resolveRoots(input: ResolveInput): ResolvedRoots;
32
+ /**
33
+ * The platform-native placement of 0.1.x-0.2.x (XENO LOCAL HOME - SPEC.md section 4 before its 2026-10-25
34
+ * amendment). Not the default: the migrator reads it to find data those versions wrote.
35
+ */
36
+ export declare function resolvePlatformNativeRoots(input: ResolveInput): ResolvedRoots;
@@ -5,6 +5,7 @@ exports.isAbsolutePath = isAbsolutePath;
5
5
  exports.normalizeBase = normalizeBase;
6
6
  exports.joinPath = joinPath;
7
7
  exports.resolveRoots = resolveRoots;
8
+ exports.resolvePlatformNativeRoots = resolvePlatformNativeRoots;
8
9
  const contract_ts_1 = require("../generated/contract.js");
9
10
  const errors_ts_1 = require("./errors.js");
10
11
  exports.KINDS = ['config', 'data', 'secrets', 'state', 'cache', 'run'];
@@ -39,7 +40,41 @@ function getEnv(platform, env, name) {
39
40
  return env[k];
40
41
  return undefined;
41
42
  }
43
+ /**
44
+ * Where every kind lives: `<home>/.xeno/<kind>` on every OS, or `<XENO_HOME>/<kind>` when XENO_HOME is absolute.
45
+ *
46
+ * Owner decision, 2026-10-25 ("ok then lets have it done right"): one folder in the person's home that they and their
47
+ * agents can find, the way `~/.claude` and `~/.codex` are found, with the spec's structure inside it. Platform folders
48
+ * (APPDATA, LOCALAPPDATA, XDG_*, TMPDIR) no longer place anything. `resolvePlatformNativeRoots` keeps the previous
49
+ * placement so the migrator can find what 0.1.x-0.2.x wrote there.
50
+ */
42
51
  function resolveRoots(input) {
52
+ const { platform, home, env } = input;
53
+ const sep = exports.SEP[platform];
54
+ const override = getEnv(platform, env, 'XENO_HOME');
55
+ const warnings = [];
56
+ let base;
57
+ if (override !== undefined && override !== '') {
58
+ if (isAbsolutePath(platform, override))
59
+ base = normalizeBase(platform, override);
60
+ else
61
+ warnings.push('xeno-home-relative-ignored');
62
+ }
63
+ const overridden = base !== undefined;
64
+ if (base === undefined) {
65
+ if (!home || !isAbsolutePath(platform, home)) {
66
+ throw new errors_ts_1.DirsError('home-unresolvable', 'the home directory is unknown or relative, and no XENO_HOME override is set');
67
+ }
68
+ base = normalizeBase(platform, home) + sep + contract_ts_1.INPUTS_JSON.inputs.defaultHomeDir.value;
69
+ }
70
+ const roots = Object.fromEntries(exports.KINDS.map((k) => [k, base + sep + k]));
71
+ return { platform, roots, warnings, overridden };
72
+ }
73
+ /**
74
+ * The platform-native placement of 0.1.x-0.2.x (XENO LOCAL HOME - SPEC.md section 4 before its 2026-10-25
75
+ * amendment). Not the default: the migrator reads it to find data those versions wrote.
76
+ */
77
+ function resolvePlatformNativeRoots(input) {
43
78
  const { platform, home, env } = input;
44
79
  const warnings = [];
45
80
  const get = (n) => getEnv(platform, env, n);
@@ -109,6 +109,13 @@ export declare const INPUTS_JSON: {
109
109
  source: string;
110
110
  note: string;
111
111
  };
112
+ defaultHomeDir: {
113
+ value: string;
114
+ status: string;
115
+ decided: string;
116
+ source: string;
117
+ note: string;
118
+ };
112
119
  };
113
120
  legacyHomes: string[];
114
121
  windowsVendorDir: string;
@@ -198,6 +198,13 @@ exports.INPUTS_JSON = {
198
198
  "decided": "2026-10-11",
199
199
  "source": "XENO LOCAL HOME - SPEC.md section 11.2",
200
200
  "note": "Releases after a product adopts the layout during which it still reads the legacy location. The legacy copy is never deleted automatically."
201
+ },
202
+ "defaultHomeDir": {
203
+ "value": ".xeno",
204
+ "status": "locked",
205
+ "decided": "2026-10-25",
206
+ "source": "XENO LOCAL HOME - SPEC.md section 4 (amended 2026-10-25)",
207
+ "note": "The default XENO home is <user home>/<value> on every OS, with config/data/secrets/state/cache/run inside. XENO_HOME overrides it. Platform folders (APPDATA, LOCALAPPDATA, XDG_*, TMPDIR) no longer place anything."
201
208
  }
202
209
  },
203
210
  "legacyHomes": [
@@ -6,7 +6,9 @@
6
6
  * homedir-call a call that asks the OS for the home directory (homedir(), home_dir(), Path.home(), UserHomeDir())
7
7
  * platform-dir-read reading HOME, USERPROFILE, APPDATA, LOCALAPPDATA or XDG_* from the environment to build a path
8
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)
9
+ * legacy-home-path ~/.xeno, %USERPROFILE%\.xeno, $HOME/.xeno and the 0.2.x %APPDATA%\XENO form, built by hand. Since
10
+ * 2026-10-25 ~/.xeno IS the XENO home, so only the resolver builds a path into it (a per-project
11
+ * `.xeno/` is fine)
10
12
  * legacy-home-env a XENO_*_HOME variable other than XENO_HOME (the thirteen legacy overrides)
11
13
  * A line (or the line above it) carrying `xeno-dirs-allow: <reason>` is exempt; the reason is mandatory.
12
14
  */
@@ -10,7 +10,7 @@ export const RULES = [
10
10
  { 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'] },
11
11
  { 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'] },
12
12
  { 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'] },
13
- { 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'] },
13
+ { id: 'legacy-home-path', description: 'builds a path into the XENO home or the 0.2.x app-data folder by hand; only the dirs resolver builds it', re: /(?:~|\$\{?HOME\}?|%USERPROFILE%|%HOMEPATH%|\$env:USERPROFILE)[\\/]+\.xeno(?![\w-])|(?:%APPDATA%|%LOCALAPPDATA%|AppData[\\/]+(?:Roaming|Local))[\\/]+XENO\b/, langs: [...JS, 'rs', 'py', 'go'] },
14
14
  { 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'] },
15
15
  ];
16
16
  const DEFAULT_EXCLUDE_DIRS = new Set(['node_modules', 'dist', 'build', 'target', '.git', 'coverage', '.next', 'out', '.turbo', '.venv', '__pycache__', 'release', '.worktrees']);
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  // xeno-home print every resolved location (the engine behind `xeno home`)
3
3
  // xeno-home doctor [--json] list entries no registry path allows (`xeno home doctor`; exit 1 if any)
4
- // xeno-home migrate [--confirm] copy legacy homes into the layout (dry run unless --confirm; never deletes)
4
+ // xeno-home migrate [--confirm] copy legacy homes and the 0.2.x platform folders into the layout (dry run unless --confirm; never deletes)
5
5
  // xeno-home inputs show the owner-decided contract inputs
6
6
  import { contractInputs } from "./inputs.js";
7
7
  import { createDirs } from "./dirs.js";
8
8
  import { doctor } from "./doctor.js";
9
- import { hostHome } from "./host.js";
9
+ import { hostEnv, hostHome } from "./host.js";
10
+ import { resolvePlatformNativeRoots } from "./roots.js";
10
11
  import { planMigration, runMigration } from "./migrate.js";
11
12
  const [cmd, ...rest] = process.argv.slice(2);
12
13
  const json = rest.includes('--json');
@@ -41,7 +42,15 @@ async function main() {
41
42
  return r.ok ? 0 : 1;
42
43
  }
43
44
  if (cmd === 'migrate') {
44
- const plan = planMigration({ dirs, home: hostHome() });
45
+ // 0.1.x-0.2.x placed kinds in the platform folders; they are relocated into ~/.xeno with the legacy homes.
46
+ let previousRoots;
47
+ try {
48
+ previousRoots = resolvePlatformNativeRoots({ platform: dirs.platform, home: hostHome(), env: hostEnv() }).roots;
49
+ }
50
+ catch {
51
+ previousRoots = undefined;
52
+ }
53
+ const plan = planMigration({ dirs, home: hostHome(), ...(previousRoots ? { previousRoots } : {}) });
45
54
  const confirm = rest.includes('--confirm');
46
55
  const result = await runMigration(plan, { dirs, confirm });
47
56
  if (json)
@@ -1,5 +1,5 @@
1
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';
2
+ export { KINDS, SEP, isAbsolutePath, joinPath, normalizeBase, resolvePlatformNativeRoots, resolveRoots, type Kind, type Platform, type ResolveInput, type ResolvedRoots } from './roots.ts';
3
3
  export { segmentProblem, assertSegment } from './segments.ts';
4
4
  export { AREAS, LOCK_SUFFIX, findArea, registeredRelativePath, lockRelativePath, type AreaEntry } from './registry.ts';
5
5
  export { SUPPORTED_LAYOUT, parseLayout, type LayoutState } from './layout.ts';
@@ -8,6 +8,6 @@ export { acquireLockFile, judgeLock, type AcquireOptions, type LockHandle, type
8
8
  export { isProcessAlive, processStartTime } from './procinfo.ts';
9
9
  export { XenoDirs, createDirs, createDirsAt, type CreateDirsOptions } from './dirs.ts';
10
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';
11
+ export { BUILTIN_RULES, RELOCATED_KINDS, RELOCATE_RULE_ID, 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
12
  export { doctor, type DoctorReport, type Unregistered } from './doctor.ts';
13
13
  export { CONFIG_NAME, RULES, checkSource, loadConfig, scanText, type CheckConfig, type CheckResult, type Rule, type Violation } from './check.ts';
@@ -1,5 +1,5 @@
1
1
  export { DirsError, isDirsError } from "./errors.js";
2
- export { KINDS, SEP, isAbsolutePath, joinPath, normalizeBase, resolveRoots } from "./roots.js";
2
+ export { KINDS, SEP, isAbsolutePath, joinPath, normalizeBase, resolvePlatformNativeRoots, resolveRoots } from "./roots.js";
3
3
  export { segmentProblem, assertSegment } from "./segments.js";
4
4
  export { AREAS, LOCK_SUFFIX, findArea, registeredRelativePath, lockRelativePath } from "./registry.js";
5
5
  export { SUPPORTED_LAYOUT, parseLayout } from "./layout.js";
@@ -8,6 +8,6 @@ export { acquireLockFile, judgeLock } from "./lock.js";
8
8
  export { isProcessAlive, processStartTime } from "./procinfo.js";
9
9
  export { XenoDirs, createDirs, createDirsAt } from "./dirs.js";
10
10
  export { contractInputs } from "./inputs.js";
11
- export { BUILTIN_RULES, journalPath, planId, planMigration, readJournal, runMigration, verifyMigration, } from "./migrate.js";
11
+ export { BUILTIN_RULES, RELOCATED_KINDS, RELOCATE_RULE_ID, journalPath, planId, planMigration, readJournal, runMigration, verifyMigration, } from "./migrate.js";
12
12
  export { doctor } from "./doctor.js";
13
13
  export { CONFIG_NAME, RULES, checkSource, loadConfig, scanText } from "./check.js";
@@ -82,18 +82,40 @@ async function breakStale(path, judged) {
82
82
  }
83
83
  await fsp.rm(moved, { force: true }).catch(() => undefined);
84
84
  }
85
+ /**
86
+ * Windows reports a lock file that its holder is deleting ("delete pending") as access denied or busy, not as
87
+ * "exists", for a link onto it and for a read of it. That is contention, not a failure. Bounded, so a real permission
88
+ * problem still surfaces as its own error rather than as "held".
89
+ */
90
+ const TRANSIENT_WINDOWS_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
91
+ const TRANSIENT_RETRIES = 20;
92
+ const isTransientContention = (e) => process.platform === 'win32' && TRANSIENT_WINDOWS_CODES.has(e?.code ?? '');
85
93
  /** Acquires a lock file at an absolute path produced by `XenoDirs.lockPath`. */
86
94
  export async function acquireLockFile(path, options = {}) {
87
95
  const probe = { ...defaultProbe, ...options.probe };
88
96
  await fsp.mkdir(dirname(path), { recursive: true });
89
97
  const deadline = Date.now() + (options.timeoutMs ?? 0);
90
98
  const startTime = options.probe?.startTime ? await options.probe.startTime(process.pid) : await ownProcessStartTime();
99
+ let transient = 0;
91
100
  for (;;) {
92
101
  const rec = {
93
102
  v: 1, pid: process.pid, startTime, host: probe.host(), token: randomBytes(12).toString('hex'),
94
103
  owner: options.owner ?? '', createdAt: new Date().toISOString(),
95
104
  };
96
- if (await tryCreate(path, rec)) {
105
+ let created;
106
+ let cur;
107
+ try {
108
+ created = await tryCreate(path, rec);
109
+ cur = created ? null : await readRecord(path);
110
+ }
111
+ catch (e) {
112
+ if (!isTransientContention(e) || (++transient > TRANSIENT_RETRIES && Date.now() >= deadline))
113
+ throw e;
114
+ await new Promise((r) => setTimeout(r, 10));
115
+ continue;
116
+ }
117
+ transient = 0;
118
+ if (created) {
97
119
  return {
98
120
  path, record: rec,
99
121
  async release() {
@@ -105,7 +127,6 @@ export async function acquireLockFile(path, options = {}) {
105
127
  },
106
128
  };
107
129
  }
108
- const cur = await readRecord(path);
109
130
  if (cur === null)
110
131
  continue; // vanished between our attempt and our read: try again
111
132
  if (cur.rec === null) {
@@ -1,5 +1,5 @@
1
1
  import type { XenoDirs } from './dirs.ts';
2
- import type { Kind } from './roots.ts';
2
+ import { type Kind } from './roots.ts';
3
3
  /**
4
4
  * The copy-only migrator (XENO LOCAL HOME - SPEC.md section 10). It copies known legacy files to their registered
5
5
  * locations, records source, destination and SHA-256 in a journal under state/platform/migrations/, verifies every
@@ -52,10 +52,14 @@ export interface Refusal {
52
52
  }
53
53
  export interface MigrationPlan {
54
54
  id: string;
55
+ /**
56
+ * `not-relocated`: a previous kind root that is deliberately not copied (cache is re-creatable, run is ephemeral);
57
+ * reported so a person can see it, never silently dropped.
58
+ */
55
59
  homes: {
56
60
  name: string;
57
61
  path: string;
58
- state: 'present' | 'absent' | 'refused-link';
62
+ state: 'present' | 'absent' | 'refused-link' | 'not-relocated';
59
63
  }[];
60
64
  entries: PlanEntry[];
61
65
  refused: Refusal[];
@@ -78,7 +82,17 @@ export interface PlanOptions {
78
82
  home: string;
79
83
  rules?: readonly MigrationRule[];
80
84
  legacyHomes?: readonly string[];
85
+ /**
86
+ * Where 0.1.x-0.2.x placed each kind (`resolvePlatformNativeRoots`). When given, config, data, secrets and state are
87
+ * relocated one to one into this layout's roots; cache and run are reported, not copied. Links and junctions are
88
+ * never followed, and the previous roots are left in place.
89
+ */
90
+ previousRoots?: Readonly<Record<Kind, string>>;
81
91
  }
92
+ /** Kinds a relocation copies. Cache is re-creatable and run is ephemeral, so copying them only costs disk. */
93
+ export declare const RELOCATED_KINDS: readonly Kind[];
94
+ /** The rule id every relocation entry carries. */
95
+ export declare const RELOCATE_RULE_ID = "relocate-layout-1";
82
96
  export declare function planMigration(options: PlanOptions): MigrationPlan;
83
97
  export type EntryStatus = 'copied' | 'already' | 'secret' | 'conflict' | 'refused' | 'failed';
84
98
  export interface EntryResult {
@@ -5,6 +5,7 @@ import { INPUTS_JSON, LEGACY_MAP_JSON } from "../generated/contract.js";
5
5
  import { atomicWriteFile } from "./atomic.js";
6
6
  import { DirsError } from "./errors.js";
7
7
  import { assertSegment } from "./segments.js";
8
+ import { KINDS as KIND_LIST } from "./roots.js";
8
9
  /** Rules the contract itself knows (only those the ecosystem documents state explicitly). Owners add their own. */
9
10
  export const BUILTIN_RULES = LEGACY_MAP_JSON.rules;
10
11
  const SAMPLE = 200;
@@ -33,6 +34,12 @@ export function planId(entries) {
33
34
  const lines = entries.map((e) => `${e.rule}\t${e.legacyHome}\t${e.sourceRel}\t${e.destRel}`).sort().join('\n');
34
35
  return 'm-' + createHash('sha256').update(lines).digest('hex').slice(0, 12);
35
36
  }
37
+ /** Kinds a relocation copies. Cache is re-creatable and run is ephemeral, so copying them only costs disk. */
38
+ export const RELOCATED_KINDS = ['config', 'data', 'secrets', 'state'];
39
+ /** The rule id every relocation entry carries. */
40
+ export const RELOCATE_RULE_ID = 'relocate-layout-1';
41
+ /** The note the migrator writes into each source it copied from; it is never itself migrated. */
42
+ const NOTE_NAME = 'XENO-MIGRATED.txt';
36
43
  export function planMigration(options) {
37
44
  const rules = [...BUILTIN_RULES, ...(options.rules ?? [])];
38
45
  const seen = new Set();
@@ -48,6 +55,10 @@ export function planMigration(options) {
48
55
  const unplaced = { count: 0, sample: [], truncated: false };
49
56
  let visited = 0;
50
57
  const sep = options.dirs.platform === 'windows' ? '\\' : '/';
58
+ // The current layout may sit INSIDE a legacy home (the default is <home>/.xeno/<kind>, and .xeno is also a legacy
59
+ // home), so its own roots are skipped rather than migrated into themselves.
60
+ const key = (q) => (options.dirs.platform === 'windows' ? q.toLowerCase() : q);
61
+ const ownRoots = new Set(KIND_LIST.map((k) => key(options.dirs.root(k))));
51
62
  for (const name of names) {
52
63
  const path = options.home + sep + name;
53
64
  let st;
@@ -84,6 +95,8 @@ export function planMigration(options) {
84
95
  return;
85
96
  }
86
97
  const abs = dir + sep + entry;
98
+ if (ownRoots.has(key(abs)) || (rel === '' && entry === NOTE_NAME))
99
+ continue;
87
100
  const r = rel ? `${rel}/${entry}` : entry;
88
101
  const s = lstatSync(abs);
89
102
  const hits = mine.map((rule) => ({ rule, m: matchRule(rule, r) })).filter((h) => h.m !== null);
@@ -132,6 +145,76 @@ export function planMigration(options) {
132
145
  };
133
146
  walk(path, '');
134
147
  }
148
+ if (options.previousRoots) {
149
+ for (const kind of KIND_LIST) {
150
+ const from = options.previousRoots[kind];
151
+ const name = `layout-1:${kind}`;
152
+ if (key(from) === key(options.dirs.root(kind)))
153
+ continue; // the same place; nothing to relocate
154
+ let st;
155
+ try {
156
+ st = lstatSync(from);
157
+ }
158
+ catch {
159
+ homes.push({ name, path: from, state: 'absent' });
160
+ continue;
161
+ }
162
+ if (st.isSymbolicLink()) {
163
+ homes.push({ name, path: from, state: 'refused-link' });
164
+ refused.push({ path: from, reason: 'the previous kind root is a link or junction' });
165
+ continue;
166
+ }
167
+ if (!st.isDirectory()) {
168
+ homes.push({ name, path: from, state: 'absent' });
169
+ continue;
170
+ }
171
+ if (!RELOCATED_KINDS.includes(kind)) {
172
+ homes.push({ name, path: from, state: 'not-relocated' });
173
+ continue;
174
+ }
175
+ homes.push({ name, path: from, state: 'present' });
176
+ const relocate = (dir, rel) => {
177
+ let list;
178
+ try {
179
+ list = readdirSync(dir);
180
+ }
181
+ catch {
182
+ refused.push({ path: dir, reason: 'unreadable directory' });
183
+ return;
184
+ }
185
+ for (const entry of list) {
186
+ if (++visited > WALK_CAP) {
187
+ unplaced.truncated = true;
188
+ return;
189
+ }
190
+ if (rel === '' && entry === NOTE_NAME)
191
+ continue;
192
+ const abs = dir + sep + entry;
193
+ const r = rel ? `${rel}/${entry}` : entry;
194
+ const s = lstatSync(abs);
195
+ // Never followed: a junction (Spawn's session pool) points at data that is relocated on its own, and its
196
+ // owner re-creates the link in the new layout.
197
+ if (s.isSymbolicLink()) {
198
+ refused.push({ path: abs, reason: 'a link or junction is never followed; its owner re-creates it' });
199
+ continue;
200
+ }
201
+ if (s.isDirectory()) {
202
+ relocate(abs, r);
203
+ continue;
204
+ }
205
+ if (!s.isFile()) {
206
+ unplaced.count++;
207
+ if (unplaced.sample.length < SAMPLE)
208
+ unplaced.sample.push(`${name}/${r}`);
209
+ continue;
210
+ }
211
+ const dest = options.dirs.root(kind) + sep + r.split('/').join(sep);
212
+ entries.push({ rule: RELOCATE_RULE_ID, action: 'copy', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest, destRel: r, destKind: kind });
213
+ }
214
+ };
215
+ relocate(from, '');
216
+ }
217
+ }
135
218
  // Two sources must never map to one destination.
136
219
  const byDest = new Map();
137
220
  for (const e of entries)
@@ -373,7 +456,7 @@ export async function runMigration(plan, options) {
373
456
  '',
374
457
  ].join('\n');
375
458
  try {
376
- await atomicWriteFile(h.path + sep + 'XENO-MIGRATED.txt', note);
459
+ await atomicWriteFile(h.path + sep + NOTE_NAME, note);
377
460
  }
378
461
  catch { /* a read-only legacy home is not a failure of the migration */ }
379
462
  }
@@ -20,4 +20,17 @@ export declare function isAbsolutePath(platform: Platform, p: string): boolean;
20
20
  /** Normalises separators and drops trailing ones, so `base + sep + name` is always well formed. */
21
21
  export declare function normalizeBase(platform: Platform, p: string): string;
22
22
  export declare function joinPath(platform: Platform, base: string, ...parts: string[]): string;
23
+ /**
24
+ * Where every kind lives: `<home>/.xeno/<kind>` on every OS, or `<XENO_HOME>/<kind>` when XENO_HOME is absolute.
25
+ *
26
+ * Owner decision, 2026-10-25 ("ok then lets have it done right"): one folder in the person's home that they and their
27
+ * agents can find, the way `~/.claude` and `~/.codex` are found, with the spec's structure inside it. Platform folders
28
+ * (APPDATA, LOCALAPPDATA, XDG_*, TMPDIR) no longer place anything. `resolvePlatformNativeRoots` keeps the previous
29
+ * placement so the migrator can find what 0.1.x-0.2.x wrote there.
30
+ */
23
31
  export declare function resolveRoots(input: ResolveInput): ResolvedRoots;
32
+ /**
33
+ * The platform-native placement of 0.1.x-0.2.x (XENO LOCAL HOME - SPEC.md section 4 before its 2026-10-25
34
+ * amendment). Not the default: the migrator reads it to find data those versions wrote.
35
+ */
36
+ export declare function resolvePlatformNativeRoots(input: ResolveInput): ResolvedRoots;
@@ -32,7 +32,41 @@ function getEnv(platform, env, name) {
32
32
  return env[k];
33
33
  return undefined;
34
34
  }
35
+ /**
36
+ * Where every kind lives: `<home>/.xeno/<kind>` on every OS, or `<XENO_HOME>/<kind>` when XENO_HOME is absolute.
37
+ *
38
+ * Owner decision, 2026-10-25 ("ok then lets have it done right"): one folder in the person's home that they and their
39
+ * agents can find, the way `~/.claude` and `~/.codex` are found, with the spec's structure inside it. Platform folders
40
+ * (APPDATA, LOCALAPPDATA, XDG_*, TMPDIR) no longer place anything. `resolvePlatformNativeRoots` keeps the previous
41
+ * placement so the migrator can find what 0.1.x-0.2.x wrote there.
42
+ */
35
43
  export function resolveRoots(input) {
44
+ const { platform, home, env } = input;
45
+ const sep = SEP[platform];
46
+ const override = getEnv(platform, env, 'XENO_HOME');
47
+ const warnings = [];
48
+ let base;
49
+ if (override !== undefined && override !== '') {
50
+ if (isAbsolutePath(platform, override))
51
+ base = normalizeBase(platform, override);
52
+ else
53
+ warnings.push('xeno-home-relative-ignored');
54
+ }
55
+ const overridden = base !== undefined;
56
+ if (base === undefined) {
57
+ if (!home || !isAbsolutePath(platform, home)) {
58
+ throw new DirsError('home-unresolvable', 'the home directory is unknown or relative, and no XENO_HOME override is set');
59
+ }
60
+ base = normalizeBase(platform, home) + sep + INPUTS_JSON.inputs.defaultHomeDir.value;
61
+ }
62
+ const roots = Object.fromEntries(KINDS.map((k) => [k, base + sep + k]));
63
+ return { platform, roots, warnings, overridden };
64
+ }
65
+ /**
66
+ * The platform-native placement of 0.1.x-0.2.x (XENO LOCAL HOME - SPEC.md section 4 before its 2026-10-25
67
+ * amendment). Not the default: the migrator reads it to find data those versions wrote.
68
+ */
69
+ export function resolvePlatformNativeRoots(input) {
36
70
  const { platform, home, env } = input;
37
71
  const warnings = [];
38
72
  const get = (n) => getEnv(platform, env, n);
@@ -109,6 +109,13 @@ export declare const INPUTS_JSON: {
109
109
  source: string;
110
110
  note: string;
111
111
  };
112
+ defaultHomeDir: {
113
+ value: string;
114
+ status: string;
115
+ decided: string;
116
+ source: string;
117
+ note: string;
118
+ };
112
119
  };
113
120
  legacyHomes: string[];
114
121
  windowsVendorDir: string;
@@ -195,6 +195,13 @@ export const INPUTS_JSON = {
195
195
  "decided": "2026-10-11",
196
196
  "source": "XENO LOCAL HOME - SPEC.md section 11.2",
197
197
  "note": "Releases after a product adopts the layout during which it still reads the legacy location. The legacy copy is never deleted automatically."
198
+ },
199
+ "defaultHomeDir": {
200
+ "value": ".xeno",
201
+ "status": "locked",
202
+ "decided": "2026-10-25",
203
+ "source": "XENO LOCAL HOME - SPEC.md section 4 (amended 2026-10-25)",
204
+ "note": "The default XENO home is <user home>/<value> on every OS, with config/data/secrets/state/cache/run inside. XENO_HOME overrides it. Platform folders (APPDATA, LOCALAPPDATA, XDG_*, TMPDIR) no longer place anything."
198
205
  }
199
206
  },
200
207
  "legacyHomes": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/primitives",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials) and updates (the gated app updater).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",