@xenosystem/primitives 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +29 -2
  2. package/dist/cjs/dirs/atomic.d.ts +9 -0
  3. package/dist/cjs/dirs/atomic.js +59 -0
  4. package/dist/cjs/dirs/check-cli.d.ts +2 -0
  5. package/dist/cjs/dirs/check-cli.js +50 -0
  6. package/dist/cjs/dirs/check.d.ts +49 -0
  7. package/dist/cjs/dirs/check.js +158 -0
  8. package/dist/cjs/dirs/cli.d.ts +2 -0
  9. package/dist/cjs/dirs/cli.js +72 -0
  10. package/dist/cjs/dirs/dirs.d.ts +57 -0
  11. package/dist/cjs/dirs/dirs.js +135 -0
  12. package/dist/cjs/dirs/doctor.d.ts +31 -0
  13. package/dist/cjs/dirs/doctor.js +80 -0
  14. package/dist/cjs/dirs/errors.d.ts +8 -0
  15. package/dist/cjs/dirs/errors.js +19 -0
  16. package/dist/cjs/dirs/host.d.ts +4 -0
  17. package/dist/cjs/dirs/host.js +26 -0
  18. package/dist/cjs/dirs/index.d.ts +13 -0
  19. package/dist/cjs/dirs/index.js +55 -0
  20. package/dist/cjs/dirs/inputs.d.ts +14 -0
  21. package/dist/cjs/dirs/inputs.js +14 -0
  22. package/dist/cjs/dirs/layout.d.ts +16 -0
  23. package/dist/cjs/dirs/layout.js +25 -0
  24. package/dist/cjs/dirs/lock.d.ts +38 -0
  25. package/dist/cjs/dirs/lock.js +128 -0
  26. package/dist/cjs/dirs/migrate.d.ts +134 -0
  27. package/dist/cjs/dirs/migrate.js +437 -0
  28. package/dist/cjs/dirs/procinfo.d.ts +10 -0
  29. package/dist/cjs/dirs/procinfo.js +67 -0
  30. package/dist/cjs/dirs/registry.d.ts +27 -0
  31. package/dist/cjs/dirs/registry.js +78 -0
  32. package/dist/cjs/dirs/roots.d.ts +23 -0
  33. package/dist/cjs/dirs/roots.js +114 -0
  34. package/dist/cjs/dirs/segments.d.ts +7 -0
  35. package/dist/cjs/dirs/segments.js +39 -0
  36. package/dist/cjs/generated/contract.d.ts +134 -0
  37. package/dist/cjs/generated/contract.js +233 -0
  38. package/dist/cjs/package.json +1 -0
  39. package/dist/cjs/secrets/envelope.d.ts +37 -0
  40. package/dist/cjs/secrets/envelope.js +90 -0
  41. package/dist/cjs/secrets/errors.d.ts +10 -0
  42. package/dist/cjs/secrets/errors.js +20 -0
  43. package/dist/cjs/secrets/index.d.ts +4 -0
  44. package/dist/cjs/secrets/index.js +17 -0
  45. package/dist/cjs/secrets/keystore.d.ts +37 -0
  46. package/dist/cjs/secrets/keystore.js +41 -0
  47. package/dist/cjs/secrets/os-stores.d.ts +17 -0
  48. package/dist/cjs/secrets/os-stores.js +195 -0
  49. package/dist/cjs/secrets/store.d.ts +32 -0
  50. package/dist/cjs/secrets/store.js +161 -0
  51. package/dist/cjs/secrets/testing.d.ts +5 -0
  52. package/dist/cjs/secrets/testing.js +20 -0
  53. package/dist/cjs/updates/index.d.ts +67 -0
  54. package/dist/cjs/updates/index.js +102 -0
  55. package/dist/esm/dirs/atomic.d.ts +9 -0
  56. package/dist/esm/dirs/atomic.js +56 -0
  57. package/dist/esm/dirs/check-cli.d.ts +2 -0
  58. package/dist/esm/dirs/check-cli.js +48 -0
  59. package/dist/esm/dirs/check.d.ts +49 -0
  60. package/dist/esm/dirs/check.js +152 -0
  61. package/dist/esm/dirs/cli.d.ts +2 -0
  62. package/dist/esm/dirs/cli.js +70 -0
  63. package/dist/esm/dirs/dirs.d.ts +57 -0
  64. package/dist/esm/dirs/dirs.js +129 -0
  65. package/dist/esm/dirs/doctor.d.ts +31 -0
  66. package/dist/esm/dirs/doctor.js +77 -0
  67. package/dist/esm/dirs/errors.d.ts +8 -0
  68. package/dist/esm/dirs/errors.js +14 -0
  69. package/dist/esm/dirs/host.d.ts +4 -0
  70. package/dist/esm/dirs/host.js +21 -0
  71. package/dist/esm/dirs/index.d.ts +13 -0
  72. package/dist/esm/dirs/index.js +13 -0
  73. package/dist/esm/dirs/inputs.d.ts +14 -0
  74. package/dist/esm/dirs/inputs.js +11 -0
  75. package/dist/esm/dirs/layout.d.ts +16 -0
  76. package/dist/esm/dirs/layout.js +21 -0
  77. package/dist/esm/dirs/lock.d.ts +38 -0
  78. package/dist/esm/dirs/lock.js +124 -0
  79. package/dist/esm/dirs/migrate.d.ts +134 -0
  80. package/dist/esm/dirs/migrate.js +428 -0
  81. package/dist/esm/dirs/procinfo.d.ts +10 -0
  82. package/dist/esm/dirs/procinfo.js +62 -0
  83. package/dist/esm/dirs/registry.d.ts +27 -0
  84. package/dist/esm/dirs/registry.js +71 -0
  85. package/dist/esm/dirs/roots.d.ts +23 -0
  86. package/dist/esm/dirs/roots.js +107 -0
  87. package/dist/esm/dirs/segments.d.ts +7 -0
  88. package/dist/esm/dirs/segments.js +35 -0
  89. package/dist/esm/generated/contract.d.ts +134 -0
  90. package/dist/esm/generated/contract.js +230 -0
  91. package/dist/esm/secrets/envelope.d.ts +37 -0
  92. package/dist/esm/secrets/envelope.js +81 -0
  93. package/dist/esm/secrets/errors.d.ts +10 -0
  94. package/dist/esm/secrets/errors.js +15 -0
  95. package/dist/esm/secrets/index.d.ts +4 -0
  96. package/dist/esm/secrets/index.js +4 -0
  97. package/dist/esm/secrets/keystore.d.ts +37 -0
  98. package/dist/esm/secrets/keystore.js +37 -0
  99. package/dist/esm/secrets/os-stores.d.ts +17 -0
  100. package/dist/esm/secrets/os-stores.js +189 -0
  101. package/dist/esm/secrets/store.d.ts +32 -0
  102. package/dist/esm/secrets/store.js +156 -0
  103. package/dist/esm/secrets/testing.d.ts +5 -0
  104. package/dist/esm/secrets/testing.js +12 -0
  105. package/dist/esm/updates/index.d.ts +67 -0
  106. package/dist/esm/updates/index.js +97 -0
  107. package/package.json +42 -4
@@ -0,0 +1,437 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BUILTIN_RULES = void 0;
4
+ exports.planId = planId;
5
+ exports.planMigration = planMigration;
6
+ exports.journalPath = journalPath;
7
+ exports.readJournal = readJournal;
8
+ exports.runMigration = runMigration;
9
+ exports.verifyMigration = verifyMigration;
10
+ const node_crypto_1 = require("node:crypto");
11
+ const node_fs_1 = require("node:fs");
12
+ const node_path_1 = require("node:path");
13
+ const contract_ts_1 = require("../generated/contract.js");
14
+ const atomic_ts_1 = require("./atomic.js");
15
+ const errors_ts_1 = require("./errors.js");
16
+ const segments_ts_1 = require("./segments.js");
17
+ /** Rules the contract itself knows (only those the ecosystem documents state explicitly). Owners add their own. */
18
+ exports.BUILTIN_RULES = contract_ts_1.LEGACY_MAP_JSON.rules;
19
+ const SAMPLE = 200;
20
+ const WALK_CAP = 500_000;
21
+ const isLink = (p) => (0, node_fs_1.lstatSync)(p).isSymbolicLink();
22
+ function globMatch(pattern, name) {
23
+ if (!pattern.includes('*'))
24
+ return pattern === name;
25
+ const re = new RegExp('^' + pattern.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$');
26
+ return re.test(name);
27
+ }
28
+ function matchRule(rule, rel) {
29
+ const want = rule.match.split('/');
30
+ const got = rel.split('/');
31
+ if (want.length !== got.length)
32
+ return null;
33
+ for (let i = 0; i < want.length - 1; i++)
34
+ if (want[i] !== got[i])
35
+ return null;
36
+ const last = got[got.length - 1];
37
+ return globMatch(want[want.length - 1], last) ? { file: last } : null;
38
+ }
39
+ const fill = (s, file) => s.split('{file}').join(file);
40
+ /** Deterministic id: the same plan (rules, sources, destinations) always has the same journal. */
41
+ function planId(entries) {
42
+ const lines = entries.map((e) => `${e.rule}\t${e.legacyHome}\t${e.sourceRel}\t${e.destRel}`).sort().join('\n');
43
+ return 'm-' + (0, node_crypto_1.createHash)('sha256').update(lines).digest('hex').slice(0, 12);
44
+ }
45
+ function planMigration(options) {
46
+ const rules = [...exports.BUILTIN_RULES, ...(options.rules ?? [])];
47
+ const seen = new Set();
48
+ for (const r of rules) {
49
+ if (seen.has(r.id))
50
+ throw new errors_ts_1.DirsError('invalid-argument', `duplicate migration rule id: ${r.id}`);
51
+ seen.add(r.id);
52
+ }
53
+ const names = options.legacyHomes ?? contract_ts_1.INPUTS_JSON.legacyHomes;
54
+ const homes = [];
55
+ const entries = [];
56
+ const refused = [];
57
+ const unplaced = { count: 0, sample: [], truncated: false };
58
+ let visited = 0;
59
+ const sep = options.dirs.platform === 'windows' ? '\\' : '/';
60
+ for (const name of names) {
61
+ const path = options.home + sep + name;
62
+ let st;
63
+ try {
64
+ st = (0, node_fs_1.lstatSync)(path);
65
+ }
66
+ catch {
67
+ homes.push({ name, path, state: 'absent' });
68
+ continue;
69
+ }
70
+ if (st.isSymbolicLink()) {
71
+ homes.push({ name, path, state: 'refused-link' });
72
+ refused.push({ path, reason: 'the legacy home is a link or junction' });
73
+ continue;
74
+ }
75
+ if (!st.isDirectory()) {
76
+ homes.push({ name, path, state: 'absent' });
77
+ continue;
78
+ }
79
+ homes.push({ name, path, state: 'present' });
80
+ const mine = rules.filter((r) => r.legacyHome === name);
81
+ const walk = (dir, rel) => {
82
+ let list;
83
+ try {
84
+ list = (0, node_fs_1.readdirSync)(dir);
85
+ }
86
+ catch {
87
+ refused.push({ path: dir, reason: 'unreadable directory' });
88
+ return;
89
+ }
90
+ for (const entry of list) {
91
+ if (++visited > WALK_CAP) {
92
+ unplaced.truncated = true;
93
+ return;
94
+ }
95
+ const abs = dir + sep + entry;
96
+ const r = rel ? `${rel}/${entry}` : entry;
97
+ const s = (0, node_fs_1.lstatSync)(abs);
98
+ const hits = mine.map((rule) => ({ rule, m: matchRule(rule, r) })).filter((h) => h.m !== null);
99
+ if (s.isSymbolicLink()) {
100
+ if (hits.length > 0)
101
+ refused.push({ path: abs, reason: 'a link or junction is never followed' });
102
+ else {
103
+ unplaced.count++;
104
+ if (unplaced.sample.length < SAMPLE)
105
+ unplaced.sample.push(`${name}/${r} (link)`);
106
+ }
107
+ continue;
108
+ }
109
+ if (s.isDirectory()) {
110
+ walk(abs, r);
111
+ continue;
112
+ }
113
+ if (hits.length === 0) {
114
+ unplaced.count++;
115
+ if (unplaced.sample.length < SAMPLE)
116
+ unplaced.sample.push(`${name}/${r}`);
117
+ continue;
118
+ }
119
+ if (hits.length > 1) {
120
+ refused.push({ path: abs, reason: `ambiguous: rules ${hits.map((h) => h.rule.id).join(', ')} all match` });
121
+ continue;
122
+ }
123
+ const { rule, m } = hits[0];
124
+ try {
125
+ if (rule.action === 'copy') {
126
+ const segs = rule.target.segments.map((x) => fill(x, m.file));
127
+ const dest = options.dirs.path(rule.target.kind, rule.target.area, ...segs);
128
+ entries.push({ rule: rule.id, action: 'copy', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest, destRel: [rule.target.area, ...segs].join('/'), destKind: rule.target.kind });
129
+ }
130
+ else {
131
+ const sn = fill(rule.target.name, m.file);
132
+ (0, segments_ts_1.assertSegment)(sn, 'secret name');
133
+ options.dirs.path('secrets', rule.target.area, sn + '.secret'); // validates area and kind
134
+ entries.push({ rule: rule.id, action: 'secret', legacyHome: name, sourceRel: r, source: abs, bytes: s.size, dest: null, destRel: `${rule.target.area}/${sn}`, destKind: 'secret', secret: { area: rule.target.area, name: sn } });
135
+ }
136
+ }
137
+ catch (e) {
138
+ refused.push({ path: abs, reason: `rule ${rule.id}: ${e.message}` });
139
+ }
140
+ }
141
+ };
142
+ walk(path, '');
143
+ }
144
+ // Two sources must never map to one destination.
145
+ const byDest = new Map();
146
+ for (const e of entries)
147
+ byDest.set(`${e.destKind}:${e.destRel}`, [...(byDest.get(`${e.destKind}:${e.destRel}`) ?? []), e]);
148
+ const clean = [];
149
+ for (const group of byDest.values()) {
150
+ if (group.length === 1)
151
+ clean.push(group[0]);
152
+ else
153
+ for (const e of group)
154
+ refused.push({ path: e.source, reason: `destination collision: ${group.length} sources map to ${e.destRel}` });
155
+ }
156
+ clean.sort((a, b) => { const x = a.legacyHome + a.sourceRel, y = b.legacyHome + b.sourceRel; return x < y ? -1 : x > y ? 1 : 0; });
157
+ return { id: planId(clean), homes, entries: clean, refused, unplaced };
158
+ }
159
+ const BUF = 1 << 20;
160
+ function hashFile(path) {
161
+ return new Promise((resolve, reject) => {
162
+ const h = (0, node_crypto_1.createHash)('sha256');
163
+ (0, node_fs_1.createReadStream)(path, { highWaterMark: BUF }).on('data', (c) => h.update(c)).on('error', reject).on('end', () => resolve(h.digest('hex')));
164
+ });
165
+ }
166
+ function assertNoLinksBelow(root, parts, sep) {
167
+ let cur = root;
168
+ for (const p of parts) {
169
+ cur += sep + p;
170
+ let st;
171
+ try {
172
+ st = (0, node_fs_1.lstatSync)(cur);
173
+ }
174
+ catch {
175
+ return;
176
+ }
177
+ if (st.isSymbolicLink())
178
+ throw new errors_ts_1.DirsError('migration-refused', 'a link or junction on the path is never followed', { path: cur });
179
+ }
180
+ }
181
+ async function copyVerified(source, dest) {
182
+ await node_fs_1.promises.mkdir((0, node_path_1.dirname)(dest), { recursive: true });
183
+ const tmp = (0, node_path_1.join)((0, node_path_1.dirname)(dest), `.${(0, node_path_1.basename)(dest)}.${process.pid}.${(0, node_crypto_1.randomBytes)(6).toString('hex')}.migrating.tmp`);
184
+ const h = (0, node_crypto_1.createHash)('sha256');
185
+ let bytes = 0;
186
+ try {
187
+ await new Promise((resolve, reject) => {
188
+ const out = (0, node_fs_1.createWriteStream)(tmp, { flags: 'wx' });
189
+ const src = (0, node_fs_1.createReadStream)(source, { highWaterMark: BUF });
190
+ src.on('data', (c) => { h.update(c); bytes += c.length; });
191
+ src.on('error', reject);
192
+ out.on('error', reject);
193
+ out.on('finish', () => resolve());
194
+ src.pipe(out);
195
+ });
196
+ const fh = await node_fs_1.promises.open(tmp, 'r+');
197
+ try {
198
+ await fh.sync();
199
+ }
200
+ finally {
201
+ await fh.close();
202
+ }
203
+ const sha = h.digest('hex');
204
+ try {
205
+ await node_fs_1.promises.link(tmp, dest); // create-if-absent, atomically
206
+ }
207
+ catch (e) {
208
+ const code = e.code;
209
+ if (code === 'EEXIST')
210
+ return 'conflict';
211
+ if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EXDEV')
212
+ throw e;
213
+ // Filesystem without hard links: a no-clobber rename after re-checking the destination is still absent.
214
+ try {
215
+ await node_fs_1.promises.lstat(dest);
216
+ return 'conflict';
217
+ }
218
+ catch { /* absent */ }
219
+ await node_fs_1.promises.rename(tmp, dest);
220
+ }
221
+ if ((await hashFile(dest)) !== sha) {
222
+ await node_fs_1.promises.rm(dest, { force: true });
223
+ throw new errors_ts_1.DirsError('migration-refused', 'the copy did not verify by hash', { dest });
224
+ }
225
+ if ((await hashFile(source)) !== sha) {
226
+ await node_fs_1.promises.rm(dest, { force: true });
227
+ throw new errors_ts_1.DirsError('migration-refused', 'the source changed while it was being copied', { source });
228
+ }
229
+ return { sha256: sha, bytes };
230
+ }
231
+ finally {
232
+ await node_fs_1.promises.rm(tmp, { force: true }).catch(() => undefined);
233
+ }
234
+ }
235
+ function journalPath(dirs, id) {
236
+ return dirs.path('state', 'platform', 'migrations', `${id}.jsonl`);
237
+ }
238
+ async function appendJournal(path, record) {
239
+ await node_fs_1.promises.mkdir((0, node_path_1.dirname)(path), { recursive: true });
240
+ const fh = await node_fs_1.promises.open(path, 'a');
241
+ try {
242
+ await fh.writeFile(JSON.stringify(record) + '\n');
243
+ await fh.sync();
244
+ }
245
+ finally {
246
+ await fh.close();
247
+ }
248
+ }
249
+ async function readJournal(path) {
250
+ let text;
251
+ try {
252
+ text = await node_fs_1.promises.readFile(path, 'utf8');
253
+ }
254
+ catch (e) {
255
+ if (e.code === 'ENOENT')
256
+ return [];
257
+ throw e;
258
+ }
259
+ const out = [];
260
+ const lines = text.split('\n').filter((l) => l !== '');
261
+ lines.forEach((l, i) => {
262
+ try {
263
+ out.push(JSON.parse(l));
264
+ }
265
+ catch {
266
+ if (i !== lines.length - 1)
267
+ throw new errors_ts_1.DirsError('migration-refused', 'the migration journal is damaged before its last line', { path }); /* a torn last line is tolerated */
268
+ }
269
+ });
270
+ return out;
271
+ }
272
+ async function runMigration(plan, options) {
273
+ const { dirs } = options;
274
+ const sep = dirs.platform === 'windows' ? '\\' : '/';
275
+ const base = {
276
+ id: plan.id, confirmed: options.confirm === true, ok: false, entries: [], refused: plan.refused, unplaced: plan.unplaced, journal: null, plaintextRemains: [],
277
+ };
278
+ if (options.confirm !== true) {
279
+ base.entries = plan.entries.map((e) => ({ rule: e.rule, legacyHome: e.legacyHome, sourceRel: e.sourceRel, dest: e.dest, destRel: e.destRel, status: 'refused', bytes: e.bytes, reason: 'dry run: pass confirm to migrate' }));
280
+ return base;
281
+ }
282
+ await dirs.ensureLayout();
283
+ const journal = journalPath(dirs, plan.id);
284
+ base.journal = journal;
285
+ return dirs.withLock('platform', 'migrate', async () => {
286
+ const prior = await readJournal(journal);
287
+ await appendJournal(journal, { op: prior.length === 0 ? 'begin' : 'resume', id: plan.id, at: new Date().toISOString(), entries: plan.entries.length, refused: plan.refused.length });
288
+ const results = [];
289
+ for (const e of plan.entries) {
290
+ const r = { rule: e.rule, legacyHome: e.legacyHome, sourceRel: e.sourceRel, dest: e.dest, destRel: e.destRel, status: 'failed', bytes: e.bytes };
291
+ try {
292
+ const home = plan.homes.find((h) => h.name === e.legacyHome);
293
+ assertNoLinksBelow(home.path, e.sourceRel.split('/'), sep);
294
+ if (isLink(home.path))
295
+ throw new errors_ts_1.DirsError('migration-refused', 'the legacy home is a link or junction');
296
+ if (!(0, node_fs_1.lstatSync)(e.source).isFile())
297
+ throw new errors_ts_1.DirsError('migration-refused', 'the source is not a regular file');
298
+ if (e.action === 'copy') {
299
+ const dest = e.dest;
300
+ assertNoLinksBelow(dirs.root(e.destKind), e.destRel.split('/'), sep);
301
+ const srcHash = await hashFile(e.source);
302
+ let existing = null;
303
+ try {
304
+ if ((0, node_fs_1.lstatSync)(dest).isFile())
305
+ existing = await hashFile(dest);
306
+ else
307
+ throw new errors_ts_1.DirsError('migration-refused', 'the destination exists and is not a file');
308
+ }
309
+ catch (err) {
310
+ if (err instanceof errors_ts_1.DirsError)
311
+ throw err;
312
+ }
313
+ if (existing !== null) {
314
+ if (existing === srcHash) {
315
+ r.status = 'already';
316
+ r.sha256 = srcHash;
317
+ }
318
+ else {
319
+ r.status = 'conflict';
320
+ r.reason = 'the destination already holds different bytes; it is not overwritten';
321
+ }
322
+ }
323
+ else {
324
+ const c = await copyVerified(e.source, dest);
325
+ if (c === 'conflict') {
326
+ r.status = 'conflict';
327
+ r.reason = 'the destination appeared with different bytes; it is not overwritten';
328
+ }
329
+ else {
330
+ r.status = 'copied';
331
+ r.sha256 = c.sha256;
332
+ r.bytes = c.bytes;
333
+ }
334
+ }
335
+ }
336
+ else {
337
+ if (options.secrets === undefined) {
338
+ r.status = 'refused';
339
+ r.reason = 'no secret sink supplied; the plaintext file is left as it is';
340
+ }
341
+ else {
342
+ const { area, name } = e.secret;
343
+ const bytes = await node_fs_1.promises.readFile(e.source);
344
+ const existing = await options.secrets.get(area, name);
345
+ if (existing !== null && !Buffer.from(existing).equals(bytes)) {
346
+ r.status = 'conflict';
347
+ r.reason = 'a different secret already exists at the destination; it is not overwritten';
348
+ }
349
+ else {
350
+ if (existing === null)
351
+ await options.secrets.set(area, name, bytes);
352
+ const back = await options.secrets.get(area, name);
353
+ if (back === null || !Buffer.from(back).equals(bytes))
354
+ throw new errors_ts_1.DirsError('migration-refused', 'the secret did not verify after it was stored');
355
+ r.status = existing === null ? 'secret' : 'already';
356
+ }
357
+ bytes.fill(0);
358
+ }
359
+ }
360
+ }
361
+ catch (err) {
362
+ r.status = err instanceof errors_ts_1.DirsError && err.code === 'migration-refused' ? 'refused' : 'failed';
363
+ r.reason = err.message;
364
+ }
365
+ results.push(r);
366
+ await appendJournal(journal, { op: r.status, rule: r.rule, home: r.legacyHome, source: r.sourceRel, dest: r.destRel, destPath: r.dest, bytes: r.bytes, ...(r.sha256 ? { sha256: r.sha256 } : {}), ...(r.reason ? { reason: r.reason } : {}) });
367
+ }
368
+ const good = (s) => s === 'copied' || s === 'already' || s === 'secret';
369
+ const ok = results.every((r) => good(r.status)) && plan.refused.length === 0;
370
+ await appendJournal(journal, { op: 'end', ok, at: new Date().toISOString(), counts: results.reduce((m, r) => ({ ...m, [r.status]: (m[r.status] ?? 0) + 1 }), {}), unplaced: plan.unplaced.count });
371
+ if (options.writeNote !== false) {
372
+ for (const h of plan.homes.filter((x) => x.state === 'present')) {
373
+ const mine = results.filter((r) => r.legacyHome === h.name && good(r.status));
374
+ const note = [
375
+ 'XENO has copied what it recognised from this folder to the new XENO layout.',
376
+ 'Nothing here was deleted or moved. Removing this folder is a step only you confirm.',
377
+ '',
378
+ `Journal: ${journal}`,
379
+ `Layout roots: ${['config', 'data', 'secrets', 'state', 'cache', 'run'].map((k) => `${k}=${dirs.root(k)}`).join('; ')}`,
380
+ '',
381
+ ...(mine.length ? ['Copied or already present:', ...mine.map((r) => ` ${r.sourceRel} -> ${r.destRel}`)] : ['Nothing from this folder was copied.']),
382
+ '',
383
+ ].join('\n');
384
+ try {
385
+ await (0, atomic_ts_1.atomicWriteFile)(h.path + sep + 'XENO-MIGRATED.txt', note);
386
+ }
387
+ catch { /* a read-only legacy home is not a failure of the migration */ }
388
+ }
389
+ }
390
+ base.entries = results;
391
+ base.ok = ok;
392
+ base.plaintextRemains = plan.entries.filter((e) => e.action === 'secret' && results.some((r) => r.sourceRel === e.sourceRel && r.legacyHome === e.legacyHome && (r.status === 'secret' || r.status === 'already'))).map((e) => e.source);
393
+ return base;
394
+ }, { owner: 'migration', timeoutMs: 60_000 });
395
+ }
396
+ /**
397
+ * Re-checks a finished migration against its journal: every copied destination still exists and still hashes to the
398
+ * recorded SHA-256. A product switches to the new location only when `complete` is true.
399
+ */
400
+ async function verifyMigration(dirs, id) {
401
+ const records = await readJournal(journalPath(dirs, id));
402
+ const problems = [];
403
+ let checked = 0;
404
+ if (records.length === 0)
405
+ return { id, complete: false, checked, problems: ['no journal'] };
406
+ const ends = records.filter((r) => r['op'] === 'end');
407
+ const last = ends[ends.length - 1];
408
+ if (!last)
409
+ problems.push('the migration never finished');
410
+ else if (last['ok'] !== true)
411
+ problems.push('the last run did not finish cleanly');
412
+ const latest = new Map();
413
+ for (const r of records)
414
+ if (typeof r['dest'] === 'string' && typeof r['source'] === 'string')
415
+ latest.set(`${String(r['home'])}:${String(r['source'])}`, r);
416
+ for (const r of latest.values()) {
417
+ const op = r['op'];
418
+ if ((op === 'copied' || op === 'already') && r['destPath'] !== null) {
419
+ checked++;
420
+ const dest = r['destPath'];
421
+ if (typeof dest !== 'string') {
422
+ problems.push(`${String(r['dest'])}: journal has no destination path`);
423
+ continue;
424
+ }
425
+ try {
426
+ if ((await hashFile(dest)) !== r['sha256'])
427
+ problems.push(`${String(r['dest'])}: bytes differ from the journal`);
428
+ }
429
+ catch {
430
+ problems.push(`${String(r['dest'])}: missing`);
431
+ }
432
+ }
433
+ else if (op !== 'secret' && op !== 'already')
434
+ problems.push(`${String(r['source'])}: ${String(op)}`);
435
+ }
436
+ return { id, complete: problems.length === 0, checked, problems };
437
+ }
@@ -0,0 +1,10 @@
1
+ /** True when a process with this pid exists (a process we may not signal still exists). */
2
+ export declare function isProcessAlive(pid: number): boolean;
3
+ /**
4
+ * An opaque, stable identifier for "this process, started at this moment", or null when it cannot be read.
5
+ * A pid alone is not an identity (pids are reused); pid + start time is. The value is only ever compared for
6
+ * equality with one this function returned earlier on the same machine.
7
+ */
8
+ export declare function processStartTime(pid: number): Promise<string | null>;
9
+ /** Start-time identity of this process, computed once. */
10
+ export declare function ownProcessStartTime(): Promise<string | null>;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isProcessAlive = isProcessAlive;
4
+ exports.processStartTime = processStartTime;
5
+ exports.ownProcessStartTime = ownProcessStartTime;
6
+ const node_child_process_1 = require("node:child_process");
7
+ const promises_1 = require("node:fs/promises");
8
+ /** True when a process with this pid exists (a process we may not signal still exists). */
9
+ function isProcessAlive(pid) {
10
+ if (!Number.isInteger(pid) || pid <= 0)
11
+ return false;
12
+ try {
13
+ process.kill(pid, 0);
14
+ return true;
15
+ }
16
+ catch (e) {
17
+ return e.code === 'EPERM';
18
+ }
19
+ }
20
+ function run(file, args, timeoutMs = 10_000) {
21
+ return new Promise((resolve) => {
22
+ (0, node_child_process_1.execFile)(file, args, { timeout: timeoutMs, windowsHide: true }, (err, stdout) => resolve(err ? null : String(stdout).trim()));
23
+ });
24
+ }
25
+ /**
26
+ * An opaque, stable identifier for "this process, started at this moment", or null when it cannot be read.
27
+ * A pid alone is not an identity (pids are reused); pid + start time is. The value is only ever compared for
28
+ * equality with one this function returned earlier on the same machine.
29
+ */
30
+ async function processStartTime(pid) {
31
+ if (!Number.isInteger(pid) || pid <= 0)
32
+ return null;
33
+ try {
34
+ if (process.platform === 'linux') {
35
+ const stat = await (0, promises_1.readFile)(`/proc/${pid}/stat`, 'utf8');
36
+ const rest = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
37
+ const ticks = rest[19];
38
+ if (!ticks)
39
+ return null;
40
+ const boot = (await (0, promises_1.readFile)('/proc/sys/kernel/random/boot_id', 'utf8').catch(() => '')).trim();
41
+ return `linux:${boot}:${ticks}`;
42
+ }
43
+ if (process.platform === 'darwin') {
44
+ const out = await run('ps', ['-o', 'lstart=', '-p', String(pid)]);
45
+ return out ? `darwin:${out}` : null;
46
+ }
47
+ if (process.platform === 'win32') {
48
+ const root = process.env['SystemRoot'] ?? 'C:\\Windows';
49
+ const ps = `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
50
+ const out = await run(ps, [
51
+ '-NoProfile', '-NonInteractive', '-Command',
52
+ `$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue; if ($p) { $p.StartTime.ToFileTimeUtc() }`,
53
+ ], 30_000);
54
+ return out && /^\d+$/.test(out) ? `win32:${out}` : null;
55
+ }
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ return null;
61
+ }
62
+ let ownStart = null;
63
+ /** Start-time identity of this process, computed once. */
64
+ function ownProcessStartTime() {
65
+ ownStart ??= processStartTime(process.pid);
66
+ return ownStart;
67
+ }
@@ -0,0 +1,27 @@
1
+ import { type Kind } from './roots.ts';
2
+ export interface AreaEntry {
3
+ /** Registered name, e.g. `agents/environments` or the pattern `apps/<slug>`. */
4
+ area: string;
5
+ owner: string;
6
+ responsibility: string;
7
+ uses: readonly Kind[];
8
+ slugPattern?: string;
9
+ kindNotes?: Readonly<Record<string, string>>;
10
+ }
11
+ export declare const AREAS: readonly AreaEntry[];
12
+ export declare const LOCK_SUFFIX: string;
13
+ /** Finds the registered entry for a concrete area name, or null. `apps/<slug>` matches by slug pattern. */
14
+ export declare function findArea(area: string): AreaEntry | null;
15
+ /**
16
+ * Resolves (kind, area, segments) against the registry and returns the path relative to the kind root with `/`
17
+ * separators. Refuses anything unregistered. A `run` entry for an area that does not use `run` accepts locks only.
18
+ */
19
+ export declare function registeredRelativePath(kind: string, area: string, segments: readonly string[]): string;
20
+ /** Relative path of a lock file under the run root. Every registered area may hold locks (spec section 8). */
21
+ export declare function lockRelativePath(area: string, name: string): string;
22
+ /** Top-level directory names a root may legitimately hold, derived from the registry (used by doctor). */
23
+ export declare function expectedTopLevel(kind: Kind): {
24
+ names: Set<string>;
25
+ appSlugs: boolean;
26
+ nested: Map<string, Set<string>>;
27
+ };
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LOCK_SUFFIX = exports.AREAS = void 0;
4
+ exports.findArea = findArea;
5
+ exports.registeredRelativePath = registeredRelativePath;
6
+ exports.lockRelativePath = lockRelativePath;
7
+ exports.expectedTopLevel = expectedTopLevel;
8
+ const contract_ts_1 = require("../generated/contract.js");
9
+ const errors_ts_1 = require("./errors.js");
10
+ const roots_ts_1 = require("./roots.js");
11
+ const segments_ts_1 = require("./segments.js");
12
+ exports.AREAS = contract_ts_1.REGISTRY_JSON.areas;
13
+ exports.LOCK_SUFFIX = contract_ts_1.REGISTRY_JSON.locks.suffix;
14
+ const isKind = (k) => roots_ts_1.KINDS.includes(k);
15
+ /** Finds the registered entry for a concrete area name, or null. `apps/<slug>` matches by slug pattern. */
16
+ function findArea(area) {
17
+ for (const entry of exports.AREAS) {
18
+ if (entry.slugPattern !== undefined) {
19
+ const prefix = entry.area.slice(0, entry.area.indexOf('<'));
20
+ if (area.startsWith(prefix) && new RegExp(entry.slugPattern).test(area.slice(prefix.length)))
21
+ return entry;
22
+ }
23
+ else if (entry.area === area)
24
+ return entry;
25
+ }
26
+ return null;
27
+ }
28
+ /**
29
+ * Resolves (kind, area, segments) against the registry and returns the path relative to the kind root with `/`
30
+ * separators. Refuses anything unregistered. A `run` entry for an area that does not use `run` accepts locks only.
31
+ */
32
+ function registeredRelativePath(kind, area, segments) {
33
+ if (!isKind(kind))
34
+ throw new errors_ts_1.DirsError('unregistered-area', 'unknown kind', { kind });
35
+ const entry = findArea(area);
36
+ if (entry === null)
37
+ throw new errors_ts_1.DirsError('unregistered-area', `area is not registered: ${JSON.stringify(area)}`, { area });
38
+ if (!entry.uses.includes(kind)) {
39
+ if (kind === 'run')
40
+ throw new errors_ts_1.DirsError('locks-only', `run/${area} holds lock files only; use lockPath`, { area });
41
+ throw new errors_ts_1.DirsError('kind-not-used', `area ${area} does not use kind ${kind}`, { area, kind });
42
+ }
43
+ for (const s of segments)
44
+ (0, segments_ts_1.assertSegment)(s);
45
+ return [area, ...segments].join('/');
46
+ }
47
+ /** Relative path of a lock file under the run root. Every registered area may hold locks (spec section 8). */
48
+ function lockRelativePath(area, name) {
49
+ const entry = findArea(area);
50
+ if (entry === null)
51
+ throw new errors_ts_1.DirsError('unregistered-area', `area is not registered: ${JSON.stringify(area)}`, { area });
52
+ (0, segments_ts_1.assertSegment)(name, 'lock name');
53
+ return `${area}/${name}${exports.LOCK_SUFFIX}`;
54
+ }
55
+ /** Top-level directory names a root may legitimately hold, derived from the registry (used by doctor). */
56
+ function expectedTopLevel(kind) {
57
+ const names = new Set();
58
+ const nested = new Map();
59
+ let appSlugs = false;
60
+ for (const e of exports.AREAS) {
61
+ if (!e.uses.includes(kind) && kind !== 'run')
62
+ continue;
63
+ const parts = e.area.split('/');
64
+ const top = parts[0];
65
+ if (e.slugPattern !== undefined) {
66
+ appSlugs = true;
67
+ names.add(top);
68
+ continue;
69
+ }
70
+ names.add(top);
71
+ if (parts.length > 1) {
72
+ const set = nested.get(top) ?? new Set();
73
+ set.add(parts.slice(1).join('/'));
74
+ nested.set(top, set);
75
+ }
76
+ }
77
+ return { names, appSlugs, nested };
78
+ }
@@ -0,0 +1,23 @@
1
+ export type Platform = 'windows' | 'macos' | 'linux';
2
+ export type Kind = 'config' | 'data' | 'secrets' | 'state' | 'cache' | 'run';
3
+ export declare const KINDS: readonly Kind[];
4
+ export interface ResolveInput {
5
+ platform: Platform;
6
+ /** The person's home directory. Only consulted when no override supplies a location. */
7
+ home: string;
8
+ env: Readonly<Record<string, string | undefined>>;
9
+ }
10
+ export interface ResolvedRoots {
11
+ platform: Platform;
12
+ roots: Readonly<Record<Kind, string>>;
13
+ /** Sorted, `code` or `code:detail`. */
14
+ warnings: readonly string[];
15
+ /** True when XENO_HOME supplied the layout. */
16
+ overridden: boolean;
17
+ }
18
+ export declare const SEP: Readonly<Record<Platform, string>>;
19
+ export declare function isAbsolutePath(platform: Platform, p: string): boolean;
20
+ /** Normalises separators and drops trailing ones, so `base + sep + name` is always well formed. */
21
+ export declare function normalizeBase(platform: Platform, p: string): string;
22
+ export declare function joinPath(platform: Platform, base: string, ...parts: string[]): string;
23
+ export declare function resolveRoots(input: ResolveInput): ResolvedRoots;