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