@runeditrun/rer 0.2.100 → 0.2.102

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 (93) hide show
  1. package/README.md +30 -102
  2. package/cli/README.md +16 -89
  3. package/cli/app-address.mjs +2 -0
  4. package/cli/business/api.mjs +2 -1
  5. package/cli/business/choices.mjs +1 -1
  6. package/cli/business/command.mjs +36 -30
  7. package/cli/business/connect.mjs +1 -1
  8. package/cli/business/lease.mjs +0 -9
  9. package/cli/business/local-commands.mjs +1 -27
  10. package/cli/business/outbound.mjs +2 -14
  11. package/cli/business/questions.mjs +85 -48
  12. package/cli/business/service.mjs +1 -24
  13. package/cli/business/setup-command.mjs +33 -26
  14. package/cli/business/state.mjs +1 -1
  15. package/cli/business/supervisor.mjs +26 -91
  16. package/cli/companion/command.mjs +2 -0
  17. package/cli/demo-native.mjs +1 -1
  18. package/cli/parse.mjs +2 -1
  19. package/global/CHANGELOG.md +32 -0
  20. package/global/README.md +30 -102
  21. package/global/main.mjs +2 -0
  22. package/modules/container/adapters/d1-limits.mjs +2 -10
  23. package/modules/d1-transport/limits.d.mts +10 -0
  24. package/modules/d1-transport/limits.mjs +10 -0
  25. package/modules/demo-host/native/prepare.mjs +2 -1
  26. package/modules/deploy-kit/d1-import.mjs +11 -1
  27. package/modules/deploy-kit/migrations.mjs +14 -1
  28. package/modules/import-kit/schema/importers.schema.json +104 -2
  29. package/modules/import-kit/src/d1/README.md +14 -0
  30. package/modules/import-kit/src/d1/apply-reads.ts +74 -0
  31. package/modules/import-kit/src/d1/apply.ts +32 -9
  32. package/modules/import-kit/src/d1/history.ts +2 -2
  33. package/modules/import-kit/src/d1/redaction-step.ts +17 -7
  34. package/modules/import-kit/src/d1/types.ts +11 -0
  35. package/modules/import-kit/src/door/ADOPTING.md +0 -37
  36. package/modules/import-kit/src/door/README.md +0 -66
  37. package/modules/import-kit/src/door/admission.ts +3 -13
  38. package/modules/import-kit/src/door/authority.ts +0 -1
  39. package/modules/import-kit/src/door/failures.ts +1 -1
  40. package/modules/import-kit/src/door/grants.ts +5 -19
  41. package/modules/import-kit/src/door/handler.ts +1 -12
  42. package/modules/import-kit/src/door/index.ts +0 -6
  43. package/modules/import-kit/src/door/planning.ts +19 -44
  44. package/modules/import-kit/src/door/protocol.ts +2 -4
  45. package/modules/import-kit/src/door/schema.ts +0 -2
  46. package/modules/import-kit/src/door/store.ts +2 -2
  47. package/modules/import-kit/src/door/types.ts +1 -24
  48. package/modules/import-kit/src/provenance/credentials.ts +14 -5
  49. package/modules/import-kit/src/status/evidence.ts +3 -1
  50. package/modules/import-kit/src/status/index.ts +17 -2
  51. package/modules/import-kit/src/status/schema.ts +8 -0
  52. package/modules/import-kit/src/status/types.ts +25 -4
  53. package/package.json +1 -1
  54. package/cli/business/archive-task.mjs +0 -32
  55. package/cli/business/bounded-waves.d.mts +0 -23
  56. package/cli/business/bounded-waves.mjs +0 -57
  57. package/cli/business/catchup-task.mjs +0 -49
  58. package/cli/business/export-inputs.mjs +0 -79
  59. package/cli/business/export-task.mjs +0 -24
  60. package/cli/business/legacy-package.mjs +0 -117
  61. package/cli/business/package-transfer.mjs +0 -127
  62. package/cli/business/setup-demo.mjs +0 -95
  63. package/cli/business/vendor-door.mjs +0 -303
  64. package/cli/business/vendors/README.md +0 -215
  65. package/cli/business/vendors/calendly.mjs +0 -80
  66. package/cli/business/vendors/common.mjs +0 -280
  67. package/cli/business/vendors/credential-names.mjs +0 -124
  68. package/cli/business/vendors/index.mjs +0 -96
  69. package/cli/business/vendors/pagerduty.mjs +0 -61
  70. package/cli/business/vendors/sentry.mjs +0 -85
  71. package/cli/business/vendors/sorry.mjs +0 -106
  72. package/cli/business/vendors/uptimerobot.mjs +0 -21
  73. package/cli/business/vendors/zendesk-attachments.mjs +0 -57
  74. package/cli/business/vendors/zendesk-encode.mjs +0 -133
  75. package/cli/business/vendors/zendesk-guide.mjs +0 -34
  76. package/cli/business/vendors/zendesk-package.mjs +0 -28
  77. package/cli/business/vendors/zendesk-pages.mjs +0 -61
  78. package/cli/business/vendors/zendesk-people.mjs +0 -7
  79. package/cli/business/vendors/zendesk-store.mjs +0 -154
  80. package/cli/business/vendors/zendesk-tickets.mjs +0 -21
  81. package/cli/business/vendors/zendesk-token.mjs +0 -31
  82. package/cli/business/vendors/zendesk-transport.mjs +0 -48
  83. package/cli/business/vendors/zendesk.mjs +0 -61
  84. package/modules/import-kit/src/door/package.ts +0 -121
  85. package/modules/import-kit/src/door/waves/README.md +0 -158
  86. package/modules/import-kit/src/door/waves/digests.ts +0 -38
  87. package/modules/import-kit/src/door/waves/inventory.ts +0 -84
  88. package/modules/import-kit/src/door/waves/journal.ts +0 -19
  89. package/modules/import-kit/src/door/waves/lifecycle.ts +0 -242
  90. package/modules/import-kit/src/door/waves/preparation.ts +0 -190
  91. package/modules/import-kit/src/door/waves/schema.ts +0 -73
  92. package/modules/import-kit/src/door/waves/store.ts +0 -112
  93. package/modules/import-kit/src/door/waves/types.ts +0 -76
@@ -1,117 +0,0 @@
1
- import { constants } from 'node:fs';
2
- import { open, readFile, realpath, mkdir, chmod, rename, unlink, writeFile } from 'node:fs/promises';
3
- import { join, resolve } from 'node:path';
4
- import { createHash, randomUUID } from 'node:crypto';
5
- import { assertChunk } from './outbound.mjs';
6
- import { stateDirectory } from './state.mjs';
7
-
8
- export const LEGACY_FORMAT = 'happytohelp-legacy-chunks-v1';
9
- const MAX_BYTES = 32 * 1024 ** 3, MAX_JSON = 32 * 1024 ** 2, MAX_FILES = 100_000;
10
- const sha = bytes => createHash('sha256').update(bytes).digest('hex');
11
- const count = n => Number.isSafeInteger(n) && n >= 0;
12
- const registrationPath = () => join(stateDirectory(), 'legacy-package.json');
13
- const refused = (file, row, reason) => { throw Error(`Legacy package refused: ${file}, row ${row}: ${reason}. Use HappyToHelp's repass, then register the package again.`); };
14
- const filename = name => typeof name === 'string' && /^\w[\w.-]*$/.test(name) && name !== 'index.ndjson' && name !== 'rer-package.json';
15
-
16
- /** Every opened source is a regular file, never a symlink; hashing is streamed. */
17
- async function inspect(root, name, expected, json = false) {
18
- if (!filename(name)) refused('manifest.json', 1, 'invalid filename');
19
- let file;
20
- try { file = await open(join(root, name), constants.O_RDONLY | constants.O_NOFOLLOW); }
21
- catch { refused(name, 0, 'file unavailable'); }
22
- try {
23
- const info = await file.stat();
24
- if (!info.isFile() || !count(expected.bytes) || info.size !== expected.bytes || info.size > (json ? MAX_JSON : MAX_BYTES)) refused(name, 0, 'size mismatch or limit');
25
- const hash = createHash('sha256'), chunks = [];
26
- for await (const chunk of file.createReadStream({ autoClose: false })) { hash.update(chunk); if (json) chunks.push(chunk); }
27
- if (!/^[a-f0-9]{64}$/.test(expected.sha256 ?? '') || hash.digest('hex') !== expected.sha256) refused(name, 0, 'SHA-256 mismatch');
28
- if (!json) return;
29
- let value;
30
- try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch { refused(name, 1, 'invalid JSON'); }
31
- const rows = Array.isArray(value) ? value : [value];
32
- // Check decoded strings as well as raw JSON, so escaping cannot hide a token.
33
- const detect = value => {
34
- if (typeof value === 'string') assertChunk(Buffer.from(value), []);
35
- else if (value && typeof value === 'object') for (const [key, child] of Object.entries(value)) { assertChunk(Buffer.from(key), []); detect(child); }
36
- };
37
- for (let i = 0; i < rows.length; i++) {
38
- try { assertChunk(Buffer.from(JSON.stringify(rows[i])), []); detect(rows[i]); } catch { refused(name, i + 1, 'outbound detector'); }
39
- }
40
- return value;
41
- } finally { await file.close(); }
42
- }
43
-
44
- /** Validate the complete legacy database package before any upload. Media are customer originals. */
45
- export async function verifyLegacyPackage(directory) {
46
- let path, handle, manifestBytes;
47
- try { path = await realpath(resolve(directory)); handle = await open(join(path, 'manifest.json'), constants.O_RDONLY | constants.O_NOFOLLOW); }
48
- catch { refused('manifest.json', 0, 'file unavailable'); }
49
- try { const info = await handle.stat(); if (!info.isFile() || info.size > MAX_JSON) refused('manifest.json', 1, 'manifest size'); manifestBytes = await handle.readFile(); }
50
- finally { await handle.close(); }
51
- let manifest;
52
- try { manifest = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifestBytes)); } catch { refused('manifest.json', 1, 'invalid JSON'); }
53
- if (manifest?.format !== LEGACY_FORMAT || !Array.isArray(manifest.chunks) || !Array.isArray(manifest.context) || !Array.isArray(manifest.objects)
54
- || !manifest.source?.rowCounts || typeof manifest.source.rowCounts !== 'object' || Array.isArray(manifest.source.rowCounts)
55
- || !Array.isArray(manifest.source.attachments) || manifest.attachmentsComplete !== true) refused('manifest.json', 1, 'invalid legacy manifest');
56
- await inspect(path, 'manifest.json', { bytes: manifestBytes.length, sha256: sha(manifestBytes) }, true);
57
- const files = [{ path: 'manifest.json', file: join(path, 'manifest.json'), bytes: manifestBytes.length, sha256: sha(manifestBytes) }], seen = new Set(['manifest.json']), rowCounts = {};
58
- let totalBytes = manifestBytes.length;
59
- const add = (name, bytes, sha256) => {
60
- if (!filename(name) || seen.has(name) || files.length >= MAX_FILES) refused('manifest.json', 1, 'duplicate filename or file limit');
61
- if (!count(bytes) || (totalBytes += bytes) > MAX_BYTES) refused(name, 0, 'package byte limit');
62
- seen.add(name); files.push({ path: name, file: join(path, name), bytes, sha256 });
63
- };
64
- for (const [name, n] of Object.entries(manifest.source.rowCounts)) if (!name || !count(n)) refused('manifest.json', 1, 'invalid row counts');
65
- for (const [parts, primary] of [[manifest.chunks, true], [manifest.context, false]]) for (const part of parts) {
66
- if (!part || typeof part.table !== 'string' || !Object.hasOwn(manifest.source.rowCounts, part.table) || !count(part.count)) refused('manifest.json', 1, 'invalid chunk count or table');
67
- add(part.file, part.bytes, part.sha256);
68
- const rows = await inspect(path, part.file, part, true);
69
- if (!Array.isArray(rows) || rows.length !== part.count) refused(part.file, 0, 'row count mismatch');
70
- if (primary) Object.defineProperty(rowCounts, part.table, { value: (Object.hasOwn(rowCounts, part.table) ? rowCounts[part.table] : 0) + rows.length, enumerable: true, configurable: true });
71
- }
72
- for (const [table, n] of Object.entries(manifest.source.rowCounts)) if ((Object.hasOwn(rowCounts, table) ? rowCounts[table] : 0) !== n) refused('manifest.json', 1, 'table count mismatch');
73
- const keys = new Map(), media = new Set(); let objectBytes = 0;
74
- for (const object of manifest.objects) {
75
- if (!object || typeof object.key !== 'string' || !object.key.startsWith('legacy/') || object.key.split('/').includes('..') || object.mediaId == null
76
- || keys.has(object.key) || media.has(String(object.mediaId)) || !count(object.size)) refused('manifest.json', 1, 'invalid object identity');
77
- keys.set(object.key, String(object.mediaId)); media.add(String(object.mediaId));
78
- add(object.file, object.size, object.sha256);
79
- await inspect(path, object.file, { bytes: object.size, sha256: object.sha256 });
80
- objectBytes += object.size;
81
- }
82
- const attachments = manifest.source.attachments;
83
- if (attachments.length !== manifest.objects.length || new Set(attachments.map(e => e?.key)).size !== attachments.length
84
- || attachments.some(e => !e || keys.get(e.key) !== String(e.mediaId))) refused('manifest.json', 1, 'attachment count or identity mismatch');
85
- const bytes = files.reduce((n, f) => n + f.bytes, 0);
86
- if (!count(bytes) || bytes > MAX_BYTES) refused('manifest.json', 1, 'package byte limit');
87
- return { path, manifestSha256: sha(manifestBytes), bytes, rowCounts: { ...manifest.source.rowCounts }, objects: { count: manifest.objects.length, bytes: objectBytes }, files, manifest };
88
- }
89
-
90
- export async function loadLegacyRegistration() {
91
- try { return JSON.parse(await readFile(registrationPath(), 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
92
- }
93
- export async function registeredLegacyPackage() {
94
- const saved = await loadLegacyRegistration();
95
- if (!saved) throw Error('No legacy package is registered. Run rer business legacy-package add DIR.');
96
- let current;
97
- try { current = await verifyLegacyPackage(saved.path); } catch { throw Error(`Legacy package changed or is unavailable: ${saved.path}. Use HappyToHelp's repass and register it again.`); }
98
- if (JSON.stringify(summary(current)) !== JSON.stringify(saved)) throw Error(`Legacy package changed: ${saved.path}. Register the package again.`);
99
- return current;
100
- }
101
- const summary = ({ path, manifestSha256, bytes, rowCounts, objects }) => ({ path, manifestSha256, bytes, rowCounts, objects });
102
- export async function legacyPackage(action, directory) {
103
- if (!['add', 'remove', 'status'].includes(action)) throw Error('Usage: rer business legacy-package add|remove|status DIR');
104
- if (action === 'add') {
105
- const verified = await verifyLegacyPackage(directory), target = registrationPath();
106
- await mkdir(stateDirectory(), { recursive: true, mode: 0o700 }); await chmod(stateDirectory(), 0o700);
107
- const temporary = target + '.' + randomUUID() + '.tmp';
108
- try { await writeFile(temporary, JSON.stringify(summary(verified)), { mode: 0o600, flag: 'wx' }); await rename(temporary, target); }
109
- finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
110
- }
111
- const saved = await loadLegacyRegistration();
112
- if (saved && saved.path !== await realpath(resolve(directory))) throw Error('That directory is not the registered legacy package.');
113
- if (action === 'remove') await unlink(registrationPath()).catch(error => { if (error.code !== 'ENOENT') throw error; });
114
- const result = action === 'remove' ? null : saved;
115
- // Registration never prints paths or customer rows; a changed task names its package locally.
116
- process.stdout.write(JSON.stringify(result ? { bytes: result.bytes, rowCounts: result.rowCounts, objects: result.objects, manifestSha256: result.manifestSha256 } : { registered: false }) + '\n');
117
- }
@@ -1,127 +0,0 @@
1
- import { constants } from 'node:fs';
2
- import { open, mkdir, chmod, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { createHash, randomUUID } from 'node:crypto';
5
-
6
- const CHUNK = 65_536, MAX_BYTES = 32 * 1024 ** 3;
7
- const hash = bytes => createHash('sha256').update(bytes).digest('hex');
8
- const id = value => typeof value === 'string' && /^[0-9A-Za-z][0-9A-Za-z_-]{0,127}$/.test(value);
9
- const pathValid = value => typeof value === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_./-]*$/.test(value) && !value.split('/').some(p => !p || p === '.' || p === '..');
10
- async function durableJson(path, value) {
11
- const temporary = path + '.' + randomUUID() + '.tmp';
12
- const file = await open(temporary, 'wx', 0o600);
13
- try { await file.writeFile(JSON.stringify(value)); await file.sync(); } finally { await file.close(); }
14
- try { await rename(temporary, path); } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
15
- }
16
-
17
- /** Concatenated index and exact source files; no JSON reserialization of the package files. */
18
- export async function buildPackage({ files, source, mode = 'snapshot', records, totals, quota, directory, signal }) {
19
- if (!Number.isSafeInteger(quota) || quota < CHUNK || quota > 2 * 1024 ** 2) throw Error('Unsupported package grant byte quota.');
20
- if (!Array.isArray(files) || !files.length || files.length > 100_000) throw Error('Invalid package files.');
21
- let offset = 0; const names = new Set();
22
- const entries = files.map(file => {
23
- if (!pathValid(file.path) || file.path === 'index.ndjson' || names.has(file.path) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !/^[a-f0-9]{64}$/.test(file.sha256)) throw Error('Invalid package file.');
24
- names.add(file.path);
25
- const entry = { path: file.path, bytes: file.bytes, sha256: file.sha256, offset };
26
- offset += file.bytes;
27
- if (!Number.isSafeInteger(offset) || offset > MAX_BYTES) throw Error('Package byte limit.');
28
- return entry;
29
- });
30
- const index = Buffer.from(entries.map(row => JSON.stringify(row) + '\n').join(''));
31
- if (index.length > quota || index.length + offset > MAX_BYTES) throw Error('Package index or stream byte limit.');
32
- await mkdir(directory, { recursive: true, mode: 0o700 }); await chmod(directory, 0o700);
33
- const segments = [], streamHash = createHash('sha256'); let pending = Buffer.alloc(0), bytes = 0;
34
- const save = async value => {
35
- const ordinal = segments.length, path = join(directory, `segment-${ordinal}`), temporary = path + '.tmp';
36
- const file = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o600);
37
- try { await file.writeFile(value); await file.sync(); } finally { await file.close(); }
38
- await rename(temporary, path); segments.push({ bytes: value.length, sha256: hash(value), file: path });
39
- };
40
- const feed = async value => {
41
- signal?.throwIfAborted(); streamHash.update(value); bytes += value.length;
42
- let position = 0;
43
- while (position < value.length) {
44
- const length = Math.min(quota - pending.length, value.length - position);
45
- pending = Buffer.concat([pending, value.subarray(position, position + length)]); position += length;
46
- if (pending.length === quota) { await save(pending); pending = Buffer.alloc(0); }
47
- }
48
- };
49
- await feed(index);
50
- for (const file of files) {
51
- const handle = await open(file.file, constants.O_RDONLY | constants.O_NOFOLLOW), digest = createHash('sha256'); let size = 0;
52
- try {
53
- const info = await handle.stat(); if (!info.isFile() || info.size !== file.bytes) throw Error('Package source changed before upload.');
54
- for await (const chunk of handle.createReadStream({ autoClose: false, highWaterMark: CHUNK })) {
55
- size += chunk.length; if (size > file.bytes) throw Error('Package source changed before upload.');
56
- digest.update(chunk); await feed(chunk);
57
- }
58
- if (size !== file.bytes || digest.digest('hex') !== file.sha256) throw Error('Package source changed before upload.');
59
- } finally { await handle.close(); }
60
- }
61
- if (pending.length) await save(pending);
62
- const manifest = { format: 'rer-door-package/1', source, mode, stream: { bytes, sha256: streamHash.digest('hex') },
63
- segments: segments.map(({ bytes, sha256 }) => ({ bytes, sha256 })), index: { path: 'index.ndjson', bytes: index.length, sha256: hash(index) }, records, totals };
64
- const manifestBytes = Buffer.from(JSON.stringify(manifest));
65
- if (manifestBytes.length > quota) throw Error('Package manifest exceeds the grant byte quota.');
66
- const manifestPath = join(directory, 'rer-package.json'); await writeFile(manifestPath, manifestBytes, { mode: 0o600 });
67
- return { manifest, directory, segments, manifestFile: { bytes: manifestBytes.length, sha256: hash(manifestBytes), file: manifestPath } };
68
- }
69
-
70
- /** Persist upload ids before their first request. Inventory is the authority after an interrupted ACK. */
71
- export async function transferPackage({ prepared, fresh, request, signal, checkpoint, catchup = false, planAction = 'plan', planInput = {} }) {
72
- const { manifestFile, segments, directory } = prepared, journalPath = join(directory, 'journal.json');
73
- let journal;
74
- try { journal = JSON.parse(await readFile(journalPath, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
75
- if (!journal || journal.manifestSha256 !== manifestFile.sha256) journal = { manifestSha256: manifestFile.sha256, uploads: {}, supported: false };
76
- if (!journal.uploads || typeof journal.uploads !== 'object') throw Error('Invalid package journal.');
77
- const save = () => durableJson(journalPath, journal);
78
- let done = 0;
79
- async function upload(file, name, key) {
80
- let uploadId = journal.uploads[key], inventory = null;
81
- if (uploadId !== undefined && !id(uploadId)) throw Error('Invalid package journal upload id.');
82
- if (uploadId) {
83
- try { inventory = await request(await fresh('uploads'), { uploadId }, signal); }
84
- catch (error) { if (error.doorStatus !== 404) throw error; uploadId = null; }
85
- }
86
- if (!uploadId) { uploadId = randomUUID(); journal.uploads[key] = uploadId; await save(); }
87
- const handle = await open(file.file, constants.O_RDONLY | constants.O_NOFOLLOW);
88
- try {
89
- const totalChunks = Math.ceil(file.bytes / CHUNK), received = new Map();
90
- if (inventory) {
91
- if (inventory.uploadId !== uploadId || inventory.bundleSha256 !== file.sha256 || !Array.isArray(inventory.received)) throw Error('Invalid package inventory.');
92
- for (const row of inventory.received) {
93
- if (!Number.isSafeInteger(row.ordinal) || row.ordinal < 0 || row.ordinal >= totalChunks || received.has(row.ordinal)) throw Error('Invalid package chunk inventory.');
94
- received.set(row.ordinal, row);
95
- }
96
- }
97
- for (let index = 0; index < totalChunks; index++) {
98
- signal.throwIfAborted();
99
- const bytes = Buffer.alloc(Math.min(CHUNK, file.bytes - index * CHUNK)), { bytesRead } = await handle.read(bytes, 0, bytes.length, index * CHUNK);
100
- if (bytesRead !== bytes.length) throw Error('Package spool changed.');
101
- const row = received.get(index);
102
- if (row && (row.sha256 !== hash(bytes) || row.size !== bytes.length)) throw Error('Package inventory differs from local bytes.');
103
- if (!row) {
104
- const result = await request(await fresh('uploads'), { uploadId, name, bundleSha256: file.sha256, totalBytes: file.bytes, totalChunks, index, chunkSha256: hash(bytes), base64: bytes.toString('base64') }, signal);
105
- if (result.uploadId !== uploadId || result.bundleSha256 !== file.sha256 || index === totalChunks - 1 && result.complete !== true) throw Error('Invalid package upload answer.');
106
- }
107
- done += bytes.length;
108
- await checkpoint({ bytes_done: done });
109
- }
110
- } finally { await handle.close(); }
111
- return uploadId;
112
- }
113
- const uploadId = await upload(manifestFile, 'rer-package.json', 'manifest');
114
- let preview;
115
- try { preview = await request(await fresh(planAction), { ...planInput, uploadId, ...(catchup ? { catchup: true } : {}) }, signal); }
116
- catch (error) {
117
- if (error.doorStatus !== 409 || error.doorCode !== 'package_segment_missing' || !Array.isArray(error.doorDetails?.missing) || !error.doorDetails.missing.length
118
- || error.doorDetails.missing.some(row => !segments.some(s => s.sha256 === row.sha256 && s.bytes === row.bytes))) {
119
- throw Object.assign(Error('SEED_PACKAGE_UNSUPPORTED: the seed did not accept a manifest-first package probe. No segments were sent.'), { cause: error });
120
- }
121
- journal.supported = true; await save();
122
- }
123
- if (preview && !journal.supported && planAction==='prepare' && preview.protocol==='rer-bounded-waves/1' && typeof preview.parentId==='string') {journal.supported=true;await save();}
124
- if (preview && !journal.supported) throw Error('SEED_PACKAGE_UNSUPPORTED: the seed did not request package segments. No segments were sent.');
125
- if (!preview) for (let index = 0; index < segments.length; index++) await upload(segments[index], 'rer-segment', String(index));
126
- return { uploadId, bundle: { size: manifestFile.bytes, sha256: manifestFile.sha256 }, ...(preview ? { preview } : {}) };
127
- }
@@ -1,95 +0,0 @@
1
- // Mirrored from runeditrun/platform 0261033177e8e05284c037369ee9c3a85922a8aa, scripts/business/demo.mjs.
2
- import { readFile } from 'node:fs/promises';
3
- const company = JSON.parse(await readFile(new URL('./setup-company.json', import.meta.url), 'utf8'));
4
- export const demoPolicy={schema:'rer-agent-policy/1',catalogue:'rer-agent-classes/1',rules:[
5
- {id:'internal',class:'standard',do:'autonomous'},
6
- {id:'context',class:'sensitive',do:'autonomous'},
7
- {id:'owner',class:'*',do:'approval',approver:['role:owner'],wait:'P1D'},
8
- ],spend:{none:true}};
9
-
10
- /** The only injectable boundary is HTTP. Tokens, cookies, policy envelopes and peer bodies never enter the receipt. */
11
- export async function setupDemo({origin,cookie,hosting='managed',waitSeconds=240,fetch:request=globalThis.fetch,now=Date.now,wait=ms=>new Promise(resolve=>setTimeout(resolve,ms))}) {
12
- const api=async(path,method='GET',body,token)=>{
13
- let response;
14
- try{response=await request(new URL(path,origin),{method,redirect:'manual',signal:AbortSignal.timeout(60000),headers:{Origin:origin,Cookie:cookie,'Content-Type':'application/json',...(token?{'X-RER-Demo-Seed-Token':token}:{})},...(body===undefined?{}:{body:JSON.stringify(body)})});}
15
- catch{throw Error('platform_transport_unavailable');}
16
- let answer;try{answer=await response.json();}catch{throw Error(`platform_http_${response.status}`);}
17
- if(!response.ok){const code=answer?.code;throw Error(typeof code==='string'&&/^[a-z0-9_]{1,100}$/.test(code)?code:`platform_http_${response.status}`);}
18
- return answer;
19
- };
20
- const businesses=(await api('/api/business')).businesses;
21
- let business=businesses.find(row=>row.name===company.name);
22
- if(!business){
23
- business=(await api('/api/business','POST',{name:company.name,default_hosting:hosting,executor_preference:hosting==='self_host'?'local':'managed'})).business;
24
- await api('/api/business/'+encodeURIComponent(business.id)+'/profile','PUT',company.profile);
25
- }
26
- if(business.default_hosting!==hosting)throw Error('existing_demo_hosting_differs');
27
- const root='/api/business/'+encodeURIComponent(business.id),initial=await api(root+'/demo');
28
- // Return exactly the same projection after the first successful run and on every repeat.
29
- if(initial.complete)return initial;
30
- const pending=initial.seeds.filter(seed=>seed.adopted&&!seed.complete);
31
- if(!pending.length)return initial;
32
- let policy=await api(root+'/agents/policy');
33
- if(policy.paused)throw Error('demo_is_paused_resume_as_owner');
34
- const errors=new Map(),credentials=new Map(),ready=pending.filter(seed=>seed.provisioned);
35
- let waiting=pending.filter(seed=>!seed.provisioned);
36
- if(waiting.length){
37
- const plan=await api(root+'/demo/plan','POST',{confirmed:true});
38
- if(plan.plan_id&&!plan.approved)await api(root+'/plans/'+encodeURIComponent(plan.plan_id)+'/approve','POST',{});
39
- const deadline=now()+waitSeconds*1000;
40
- do{
41
- await api(root+'/demo/advance','POST',{});
42
- const status=await api(root+'/demo'),apps=(await api(root+'/apps')).apps,next=[];
43
- for(const seed of waiting){
44
- const current=status.seeds.find(row=>row.app===seed.app),installed=apps.find(row=>row.app===seed.app);
45
- if(current?.provisioned)ready.push(current);
46
- else if(installed?.failure||installed?.stage==='failed')errors.set(seed.app,'M4 provisioning failed');
47
- else if(installed?.waits?.length||installed?.answers_needed?.length)errors.set(seed.app,'M4 setup needs hosting, payment, domain or app answers');
48
- else next.push(seed);
49
- }
50
- waiting=next;
51
- if(waiting.length&&now()<deadline)await wait(Math.min(3000,Math.max(0,deadline-now())));
52
- }while(waiting.length&&now()<deadline);
53
- for(const seed of waiting)errors.set(seed.app,'Run the same command to resume provisioning');
54
- }
55
- const eligible=[];
56
- for(const seed of ready){
57
- try{
58
- // This is the shared Business sender, not a demo-specific settings signer or transport.
59
- const settings=await api(root+'/settings/deliver','POST',{});
60
- const delivery=settings.deliveries.find(row=>row.installation_id===seed.installation_id);
61
- if(!delivery||delivery.state!=='delivered')throw Error(delivery?.code??'settings_not_delivered');
62
- if(policy.revision&&!seed.no_policy_refused)throw Error('no_policy_probe_requires_fresh_demo');
63
- const issued=await api(root+'/agents/seed-token','POST',{seed:seed.app,installation_id:seed.installation_id,
64
- agent:{id:'demo:'+business.id,name:'Synthetic demo setup'},scopes:seed.scopes});
65
- credentials.set(seed.app,issued.access_token);
66
- if(!policy.revision&&!seed.no_policy_refused)await api(root+'/demo/apps/'+encodeURIComponent(seed.app)+'/door','POST',{phase:'unset'},issued.access_token);
67
- eligible.push(seed);
68
- }catch(error){errors.set(seed.app,error.message);}
69
- }
70
- if(eligible.length&&!policy.revision){
71
- let draft=policy.draft;
72
- if(draft&&JSON.stringify(draft.document)!==JSON.stringify(demoPolicy))throw Error('existing_policy_draft_requires_owner_review');
73
- if(!draft)draft=(await api(root+'/agents/policy/revisions','POST',{document:demoPolicy})).revision;
74
- await api(root+'/agents/policy/revisions/'+draft.revision+'/confirm','POST',{digest:draft.document_sha256});
75
- policy=await api(root+'/agents/policy');
76
- }
77
- const seeded=[];
78
- for(const seed of eligible){
79
- try{await api(root+'/demo/apps/'+encodeURIComponent(seed.app)+'/door','POST',{phase:'seed'},credentials.get(seed.app));seeded.push(seed);}
80
- catch(error){errors.set(seed.app,error.message);}
81
- }
82
- if(seeded.length){
83
- await api(root+'/pause','POST',{paused:true});
84
- let allPaused=true;
85
- for(const seed of seeded){
86
- try{await api(root+'/demo/apps/'+encodeURIComponent(seed.app)+'/door','POST',{phase:'paused'},credentials.get(seed.app));}
87
- catch(error){allPaused=false;errors.set(seed.app,error.message);}
88
- }
89
- if(allPaused)await api(root+'/pause','POST',{paused:false});
90
- }
91
- credentials.clear();
92
- const receipt=await api(root+'/demo');
93
- for(const seed of receipt.seeds)if(!seed.complete&&errors.has(seed.app))seed.cause=errors.get(seed.app);
94
- return receipt;
95
- }