@runeditrun/rer 0.2.84 → 0.2.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -50
- package/cli/README.md +78 -2
- package/cli/agent-door.mjs +149 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-mail.mjs +54 -0
- package/cli/agent-network.mjs +64 -0
- package/cli/agent-reviewers.mjs +110 -0
- package/cli/agent-secrets.mjs +23 -0
- package/cli/agent-sponsors.mjs +43 -0
- package/cli/agent-surface.mjs +34 -0
- package/cli/agent-webhooks.mjs +19 -0
- package/cli/authoring.mjs +2 -1
- package/cli/bounded.mjs +1 -1
- package/cli/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +151 -0
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +29 -6
- package/cli/business/connect.mjs +20 -8
- package/cli/business/detector.mjs +4 -1
- package/cli/business/device.mjs +13 -0
- package/cli/business/export-inputs.mjs +69 -0
- package/cli/business/export-task.mjs +17 -0
- package/cli/business/invocation.mjs +8 -1
- package/cli/business/keychain.mjs +8 -1
- package/cli/business/lease.mjs +11 -1
- package/cli/business/local-commands.mjs +80 -30
- package/cli/business/outbound.mjs +9 -4
- package/cli/business/parsers-config.mjs +8 -7
- package/cli/business/parsers-syntax.mjs +7 -3
- package/cli/business/permissions.mjs +2 -0
- package/cli/business/questions.mjs +89 -6
- package/cli/business/setup-command.mjs +49 -0
- package/cli/business/setup-company.json +15 -0
- package/cli/business/setup-demo.mjs +95 -0
- package/cli/business/state.mjs +44 -10
- package/cli/business/supervisor.mjs +97 -32
- package/cli/business/vendor-door.mjs +230 -0
- package/cli/business/vendors/README.md +29 -3
- package/cli/business/vendors/common.mjs +8 -6
- package/cli/business/vendors/index.mjs +22 -11
- package/cli/business/vendors/sorry.mjs +106 -0
- package/cli/container-transfer.mjs +2 -2
- package/cli/contract.mjs +7 -7
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +6 -2
- package/cli/deploy-command.mjs +6 -4
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +58 -0
- package/cli/deploy.mjs +9 -7
- package/cli/door-clauses.mjs +157 -0
- package/cli/errors.mjs +1 -1
- package/cli/export.mjs +16 -4
- package/cli/hosted-output.mjs +17 -7
- package/cli/human-error.mjs +20 -0
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +26 -6
- package/cli/main.mjs +2 -1
- package/cli/managed-data-schema.mjs +127 -0
- package/cli/managed-data-zip.mjs +116 -0
- package/cli/managed-data.mjs +110 -0
- package/cli/managed-server.mjs +25 -14
- package/cli/native-owner-entry.mjs +86 -0
- package/cli/output.mjs +3 -2
- package/cli/parse.mjs +2 -2
- package/cli/portability-empty.mjs +65 -0
- package/cli/portability-migrations.mjs +33 -9
- package/cli/portability-policy.mjs +5 -2
- package/cli/portability-worker.mjs +15 -6
- package/cli/portability.mjs +30 -8
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +8 -2
- package/cli/ready-summary.mjs +9 -0
- package/cli/run-transfers.mjs +37 -0
- package/cli/runtime-front-door.mjs +4 -4
- package/cli/server-proxy.mjs +4 -3
- package/cli/server-registry.mjs +13 -8
- package/cli/site.mjs +6 -1
- package/cli/transfers.mjs +17 -4
- package/edition-authoring/archive-source.mjs +59 -0
- package/edition-authoring/base-copies.mjs +147 -25
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/module-closure.mjs +2 -16
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +218 -34
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/foundation/runtime/run-data.d.mts +1 -0
- package/foundation/runtime/run-data.mjs +2 -0
- package/global/CHANGELOG.md +126 -0
- package/global/README.md +156 -50
- package/global/cli/command.mjs +8 -2
- package/global/cli/install.mjs +4 -5
- package/global/cli/path-link.mjs +3 -2
- package/global/cli/repo-command.mjs +3 -7
- package/global/door/command.mjs +3 -1
- package/global/launch/dev.mjs +12 -2
- package/global/launch/facts.mjs +2 -2
- package/global/launch/render.mjs +16 -9
- package/global/launch/state.mjs +4 -4
- package/global/main.mjs +13 -8
- package/install.sh +17 -6
- package/modules/agent-door/CLAUSES.md +215 -0
- package/modules/agent-door/conformance/audit.mjs +66 -0
- package/modules/agent-door/conformance/authority.d.mts +2 -0
- package/modules/agent-door/conformance/authority.mjs +17 -0
- package/modules/agent-door/conformance/crypto.mjs +36 -0
- package/modules/agent-door/conformance/discovery.mjs +61 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/invocation.mjs +32 -0
- package/modules/agent-door/conformance/journey.mjs +112 -0
- package/modules/agent-door/conformance/narrowing.d.mts +1 -0
- package/modules/agent-door/conformance/narrowing.mjs +21 -0
- package/modules/agent-door/conformance/negative.mjs +47 -0
- package/modules/agent-door/conformance/network-modules.mjs +86 -0
- package/modules/agent-door/conformance/network-runtime.mjs +46 -0
- package/modules/agent-door/conformance/policy-phases.mjs +75 -0
- package/modules/agent-door/conformance/protocol.mjs +145 -0
- package/modules/agent-door/conformance/replay.mjs +38 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +33 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/surface.mjs +89 -0
- package/modules/agent-door/conformance/target.mjs +18 -0
- package/modules/agent-door/conformance/tool-name.d.mts +1 -0
- package/modules/agent-door/conformance/tool-name.mjs +7 -0
- package/modules/agent-door/conformance/webhooks.mjs +30 -0
- package/modules/container/README.md +6 -1
- package/modules/container/adapters/d1-limits.mjs +286 -0
- package/modules/container/adapters/d1-sqlite.mjs +95 -0
- package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
- package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
- package/modules/container/adapters/d1-workerd.mjs +5 -0
- package/modules/container/adapters/sqlite-worker.mjs +5 -3
- package/modules/container/build.mjs +1 -0
- package/modules/container/image-variables.mjs +14 -3
- package/modules/container/transfer.mjs +14 -4
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/demo-host/README.md +6 -0
- package/modules/demo-host/build.mjs +1 -0
- package/modules/demo-host/native/prepare.mjs +2 -1
- package/modules/demo-host/native/sql.mjs +7 -2
- package/modules/demo-host/ownership.mjs +39 -0
- package/modules/demo-host/plan.mjs +2 -1
- package/modules/demo-host/remove.mjs +6 -1
- package/modules/deploy-kit/README.md +22 -2
- package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
- package/modules/deploy-kit/d1-import.mjs +17 -5
- package/modules/deploy-kit/diagnostics.mjs +29 -3
- package/modules/deploy-kit/owner-cli.mjs +20 -7
- package/modules/deploy-kit/provider-transport.mjs +19 -4
- package/modules/deploy-kit/provider.mjs +57 -22
- package/modules/deploy-kit/readiness-window.mjs +1 -1
- package/modules/deploy-kit/site.mjs +8 -3
- package/modules/deploy-kit/worker.mjs +4 -4
- package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
- package/modules/import-kit/schema/importers.schema.json +107 -0
- package/modules/import-kit/src/d1/README.md +23 -4
- package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
- package/modules/import-kit/src/d1/budget.ts +15 -7
- package/modules/import-kit/src/d1/column-layout.ts +5 -0
- package/modules/import-kit/src/d1/creation.ts +15 -8
- package/modules/import-kit/src/d1/database.ts +3 -3
- package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
- package/modules/import-kit/src/d1/erasure.ts +2 -2
- package/modules/import-kit/src/d1/jobs.ts +10 -6
- package/modules/import-kit/src/d1/plans.ts +14 -8
- package/modules/import-kit/src/d1/retirement.ts +2 -2
- package/modules/import-kit/src/d1/sets.ts +1 -3
- package/modules/import-kit/src/d1/staged-creation.ts +3 -3
- package/modules/import-kit/src/door/ADOPTING.md +20 -0
- package/modules/import-kit/src/door/README.md +2 -1
- package/modules/import-kit/src/door/admission.ts +5 -3
- package/modules/import-kit/src/door/archive.ts +5 -2
- package/modules/import-kit/src/door/authority.ts +1 -0
- package/modules/import-kit/src/door/grants.ts +1 -1
- package/modules/import-kit/src/door/handler.ts +14 -8
- package/modules/import-kit/src/door/index.ts +1 -1
- package/modules/import-kit/src/door/jobs.ts +40 -0
- package/modules/import-kit/src/door/limits.ts +1 -1
- package/modules/import-kit/src/door/operator.ts +3 -3
- package/modules/import-kit/src/door/planning.ts +10 -6
- package/modules/import-kit/src/door/protocol.ts +2 -2
- package/modules/import-kit/src/door/raw.ts +25 -0
- package/modules/import-kit/src/door/refusals.ts +2 -1
- package/modules/import-kit/src/door/types.ts +26 -6
- package/modules/import-kit/src/receipt/encoding.ts +37 -0
- package/modules/import-kit/src/receipt/index.ts +69 -0
- package/modules/import-kit/src/receipt/policy.ts +24 -0
- package/modules/import-kit/src/receipt/types.ts +64 -0
- package/modules/import-kit/src/receipt/uri.ts +45 -0
- package/modules/import-kit/src/receipt/validation.ts +87 -0
- package/modules/import-kit/src/status/encoding.ts +13 -0
- package/modules/import-kit/src/status/evidence.ts +218 -0
- package/modules/import-kit/src/status/index.ts +56 -0
- package/modules/import-kit/src/status/schema.ts +208 -0
- package/modules/import-kit/src/status/types.ts +86 -0
- package/modules/operator-auth/accounts/delegated.mjs +48 -0
- package/modules/operator-auth/index.d.mts +7 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +138 -9
- package/modules/portability/backfills.mjs +9 -8
- package/modules/portability/bridge.mjs +32 -5
- package/modules/portability/catalogue.mjs +12 -5
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/files.mjs +4 -3
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/http.mjs +3 -3
- package/modules/portability/import.mjs +29 -13
- package/modules/portability/index.d.mts +4 -3
- package/modules/portability/index.mjs +1 -1
- package/modules/portability/ledgers.mjs +3 -2
- package/modules/portability/legacy-safety.mjs +11 -2
- package/modules/portability/migration-history.mjs +2 -2
- package/modules/portability/progress.mjs +1 -0
- package/modules/portability/restore-empty.mjs +12 -0
- package/modules/release/github-verify.mjs +11 -2
- package/onboarding/adapter.mjs +35 -6
- package/onboarding/app-fetch.mjs +6 -4
- package/onboarding/development-runtime.mjs +19 -0
- package/onboarding/local/operation.mjs +45 -27
- package/onboarding/loopback-fetch.mjs +16 -0
- package/onboarding/operator-installer.mjs +2 -4
- package/onboarding/process-diagnostics.mjs +6 -2
- package/onboarding/production-runtime.mjs +4 -2
- package/onboarding/readiness.mjs +1 -0
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/scripts/publish-check/public_hygiene.py +1 -1
- package/cli/business/opt-ins.mjs +0 -33
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { object, list, assertCount, shape, fail } from './common.mjs';
|
|
2
|
+
|
|
3
|
+
// Sorry's public status page API, read anonymously from the page's own HTTPS
|
|
4
|
+
// address, as Lamp's Move in reads it (statuspage-import/sorry/fetch.ts,
|
|
5
|
+
// fetchSorryPublicResponses): /api/v1/status, the components and notices lists
|
|
6
|
+
// (25 a page, `meta.next_page`), then every notice's detail with its components
|
|
7
|
+
// and full update history. No key is sent or accepted.
|
|
8
|
+
|
|
9
|
+
const label = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/u;
|
|
10
|
+
/** The page's public HTTPS origin from its host name alone: no scheme, port,
|
|
11
|
+
* path, credentials, IP address or local name can come from the inputs. */
|
|
12
|
+
export function originOf(inputs) {
|
|
13
|
+
const page = object(inputs.page);
|
|
14
|
+
if (Object.keys(page).some(key => key !== 'host')) fail('INVALID_INPUT');
|
|
15
|
+
const host = page.host;
|
|
16
|
+
if (typeof host !== 'string' || host.length > 253) fail('INVALID_INPUT');
|
|
17
|
+
const labels = host.split('.');
|
|
18
|
+
if (labels.length < 2 || !labels.every(part => label.test(part)) || /^[0-9]+$/u.test(labels.at(-1))
|
|
19
|
+
|| ['localhost', 'local', 'internal', 'invalid', 'test'].includes(labels.at(-1))) fail('INVALID_INPUT');
|
|
20
|
+
return `https://${host}`;
|
|
21
|
+
}
|
|
22
|
+
export const route = url => /^\/api\/v1\/(?:status|components|notices(?:\/(?:0|[1-9][0-9]{0,127}))?)$/u.test(url.pathname)
|
|
23
|
+
&& [...url.searchParams.keys()].every(key => key === 'page');
|
|
24
|
+
|
|
25
|
+
const resources = ['components', 'notices'];
|
|
26
|
+
/** The documented next page of one public list: the same collection, page n+1, or null. */
|
|
27
|
+
function nextPage(value, path, current) {
|
|
28
|
+
if (value == null) return null;
|
|
29
|
+
if (typeof value !== 'string' || value.length > 2048) fail('INVALID_PAGINATION');
|
|
30
|
+
let next;
|
|
31
|
+
try { next = new URL(value, 'https://sorry.invalid'); } catch { fail('INVALID_PAGINATION'); }
|
|
32
|
+
const params = [...next.searchParams];
|
|
33
|
+
if (next.username || next.password || next.hash || ![path, path.replace('/api/v1/', '/v1/')].includes(next.pathname)
|
|
34
|
+
|| params.length !== 1 || params[0][0] !== 'page' || params[0][1] !== String(current + 1)) fail('INVALID_PAGINATION');
|
|
35
|
+
return `${path}?page=${current + 1}`;
|
|
36
|
+
}
|
|
37
|
+
/** Notice ids exactly as Sorry wrote them (large integers never pass through Number). */
|
|
38
|
+
function noticeIds(text) {
|
|
39
|
+
const ids = [];
|
|
40
|
+
JSON.parse(text, function (key, value, context) {
|
|
41
|
+
// A notice is the object with a subject; its components and updates have none.
|
|
42
|
+
if (key === 'id' && this && !Array.isArray(this) && Object.hasOwn(this, 'subject')) {
|
|
43
|
+
const lexeme = typeof value === 'string' ? value : context?.source;
|
|
44
|
+
if (typeof lexeme !== 'string' || !/^(?:0|[1-9][0-9]{0,127})$/u.test(lexeme)) fail('INVALID_RESPONSE');
|
|
45
|
+
ids.push(lexeme);
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
});
|
|
49
|
+
return ids;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The bundle Lamp's import door reads for its `sorry` source (door-plan.ts
|
|
53
|
+
* `doorExport`): the public page address, the saved responses under the file
|
|
54
|
+
* names Lamp's Sorry reader requires, each with its original text, and the
|
|
55
|
+
* acknowledgement that they are public. Every response here came from the
|
|
56
|
+
* page's own unauthenticated API, so it is public by construction; Lamp still
|
|
57
|
+
* refuses any private, unpublished or audience-scoped record, and the owner
|
|
58
|
+
* reviews the plan before anything is imported. */
|
|
59
|
+
export async function* run(ctx) {
|
|
60
|
+
const origin = originOf(ctx.inputs);
|
|
61
|
+
const s = ctx.state ?? { phase: 0, page: 1, total: null, rows: 0, notices: [], index: 0 };
|
|
62
|
+
shape(s, ['phase', 'page', 'total', 'rows', 'notices', 'index']);
|
|
63
|
+
assertCount(s.phase, 4); assertCount(s.page, 50); assertCount(s.rows, 5000); assertCount(s.index, 5000);
|
|
64
|
+
if (s.total !== null) assertCount(s.total, 5000);
|
|
65
|
+
if (!Array.isArray(s.notices) || s.notices.length > 1250 || s.notices.some(id => typeof id !== 'string' || !/^(?:0|[1-9][0-9]{0,127})$/u.test(id))) fail('INVALID_CHECKPOINT');
|
|
66
|
+
const file = (name, text, first = false) => (first ? '' : ',') + JSON.stringify({ name, text });
|
|
67
|
+
while (s.phase < 4) {
|
|
68
|
+
let bytes;
|
|
69
|
+
if (s.phase === 0) {
|
|
70
|
+
const { body, text } = await ctx.get('/api/v1/status');
|
|
71
|
+
const page = object(object(body).page);
|
|
72
|
+
if (typeof page.name !== 'string' || typeof page.url !== 'string') fail();
|
|
73
|
+
ctx.records(1);
|
|
74
|
+
s.phase = 1;
|
|
75
|
+
bytes = JSON.stringify({ source: 'sorry', publicUrl: origin, publicAccessAcknowledged: true }).slice(0, -1) + ',"files":[' + file('sorry-status.json', text, true);
|
|
76
|
+
} else if (s.phase <= 2) {
|
|
77
|
+
const resource = resources[s.phase - 1], path = `/api/v1/${resource}`;
|
|
78
|
+
const { body, text } = await ctx.get(s.page === 1 ? path : `${path}?page=${s.page}`);
|
|
79
|
+
object(body); const rows = list(body[resource], 25), meta = object(body.meta);
|
|
80
|
+
if (meta.count !== rows.length || !Number.isSafeInteger(meta.total_count) || s.total !== null && meta.total_count !== s.total) fail('INVALID_PAGINATION');
|
|
81
|
+
ctx.records(rows.length);
|
|
82
|
+
if (resource === 'notices') {
|
|
83
|
+
const ids = noticeIds(text);
|
|
84
|
+
if (ids.length !== rows.length || ids.some(id => s.notices.includes(id))) fail('DUPLICATE_ID');
|
|
85
|
+
s.notices.push(...ids);
|
|
86
|
+
}
|
|
87
|
+
s.rows += rows.length; s.total = meta.total_count;
|
|
88
|
+
const next = nextPage(meta.next_page, path, s.page);
|
|
89
|
+
if (s.rows > s.total || Boolean(next) !== s.rows < s.total || next && !rows.length) fail('INVALID_PAGINATION');
|
|
90
|
+
bytes = file(`sorry-${resource}${s.page === 1 ? '' : `-${s.page}`}.json`, text);
|
|
91
|
+
if (next) { if (++s.page > 50) fail('PAGE_LIMIT'); }
|
|
92
|
+
else { s.phase++; s.page = 1; s.total = null; s.rows = 0; }
|
|
93
|
+
} else {
|
|
94
|
+
if (s.index === s.notices.length) { s.phase = 4; yield ctx.item(']}\n', s); break; }
|
|
95
|
+
const id = s.notices[s.index];
|
|
96
|
+
const { body, text } = await ctx.get(`/api/v1/notices/${id}`);
|
|
97
|
+
const notice = object(object(body).notice);
|
|
98
|
+
const ids = noticeIds(text);
|
|
99
|
+
if (ids.length !== 1 || ids[0] !== id || !Array.isArray(notice.components) || !Array.isArray(notice.updates)) fail('INVALID_RESPONSE');
|
|
100
|
+
ctx.records(1 + notice.updates.length);
|
|
101
|
+
bytes = file(`sorry-notice-${id}.json`, text);
|
|
102
|
+
s.index++;
|
|
103
|
+
}
|
|
104
|
+
yield ctx.item(bytes, s);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -5,9 +5,9 @@ import { execFile } from 'node:child_process';
|
|
|
5
5
|
import { promisify } from 'node:util';
|
|
6
6
|
import { fileRecords } from '../modules/portability/files.mjs';
|
|
7
7
|
const execute=promisify(execFile);
|
|
8
|
-
export async function containerTransfer({root,path,journal,store,signal,direction,binding,buckets,policy,transient}) {
|
|
8
|
+
export async function containerTransfer({root,path,journal,store,signal,direction,binding,buckets,policy,transient,acknowledgeUnverifiedSchemaObjects}) {
|
|
9
9
|
if(direction==='import')for(const file of [path,journal].filter(Boolean))for await(const record of fileRecords(file)){}
|
|
10
|
-
const spec={direction,binding,buckets,policy,transient,file:basename(path),journal:journal?'/private/later.rer':undefined};
|
|
10
|
+
const spec={acknowledgeUnverifiedSchemaObjects,direction,binding,buckets,policy,transient,file:basename(path),journal:journal?'/private/later.rer':undefined};
|
|
11
11
|
const encoded=JSON.stringify(spec,(_key,value)=>{if(typeof value==='function')throw new Error('Container local transfer needs a serializable archive policy; use native remote transport for this product');return value;});
|
|
12
12
|
const configuration=join(root,'.rer/container/transfer.json');await mkdir(dirname(configuration),{recursive:true,mode:0o700});await mkdir(dirname(path),{recursive:true,mode:0o700});await writeFile(configuration,encoded,{mode:0o600});
|
|
13
13
|
const identity='rer-local-'+createHash('sha256').update(root).digest('hex').slice(0,16),image=identity+':candidate',name='rer-transfer-'+randomUUID();
|
package/cli/contract.mjs
CHANGED
|
@@ -5,15 +5,15 @@ export const serverDefaults = Object.freeze({ serverLimit: 10, idleSeconds: 4320
|
|
|
5
5
|
export const commonFlags = ['--help', '--cwd', '--non-interactive', '--json'];
|
|
6
6
|
const definitions = {
|
|
7
7
|
install: [[], 'Frozen dependency installation; no setup or global tool changes.'],
|
|
8
|
-
setup: [['--owner-email', '--owner-name', '--port', '--host', '--answers', '--door'], 'Build, migrate, prepare private settings and first owner; stop the temporary app. --door sets a fresh checkout up at its front-door origin http://NAME.localhost:PORT (after rer door enable).'],
|
|
9
|
-
dev: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--as', '--login', '--models', '--models-service', '--door', '--direct', '--demo'], 'Development with assets, HMR and the declared scheduled triggers run locally on their schedule. --detach returns once ready; --foreground keeps this command serving. With devIdentity it opens signed in as the owner; --as PERSONA or --as EMAIL picks a persona or an invited/active person. The legacy --login flag is accepted and uses the same automatic sign-in. --door moves this checkout to its front-door origin http://NAME.localhost:PORT, keeping its data; --direct moves it back; --port and --host serve directly. --demo (or rer demo) serves a throwaway demo: fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).', 'launch'],
|
|
10
|
-
preview: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground'], 'Production output; --detach returns once ready, --foreground keeps this command serving. Reuse intact build, refresh changed assets, preserve owner/state, idle timeout and explicit stop.'],
|
|
8
|
+
setup: [['--owner-email', '--owner-name', '--port', '--host', '--answers', '--door'], 'Build, migrate, prepare private settings and first owner; stop the temporary app. Next, rer dev opens the owner persona; rer preview offers single-use native owner entry on loopback, and rer demo also offers that native entry alongside its persona. --door sets a fresh checkout up at its front-door origin http://NAME.localhost:PORT (after rer door enable).'],
|
|
9
|
+
dev: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--as', '--login', '--models', '--models-service', '--door', '--direct', '--demo'], 'Development with assets, HMR and the declared scheduled triggers run locally on their schedule. --detach returns once ready; --foreground keeps this command serving. With devIdentity it opens signed in as the owner; --as PERSONA or --as EMAIL picks a persona or an invited/active person. The legacy --login flag is accepted and uses the same automatic sign-in. --door moves this checkout to its front-door origin http://NAME.localhost:PORT, keeping its data; --direct moves it back; --port and --host serve directly. --demo (or rer demo) serves a throwaway demo: fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in through the demo persona, a separate RER_OWNER_OPEN link for single-use native owner entry on loopback (15-minute expiry; never saved), the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).', 'launch'],
|
|
10
|
+
preview: [['--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground'], 'Production output; --detach returns once ready, --foreground keeps this command serving. Reuse intact build, refresh changed assets, preserve owner/state, idle timeout and explicit stop. On loopback, seeds declaring devIdentity print a single-use native owner RER_OPEN link; it expires within 15 minutes and is not saved.'],
|
|
11
11
|
build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
|
|
12
12
|
verify: [[], 'Run the complete internal verification target.'],
|
|
13
13
|
reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
|
|
14
|
-
deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret', '--reopen-installation-key'], 'Owner-account deployment and health; dry run
|
|
14
|
+
deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret', '--reopen-installation-key'], 'Owner-account deployment and health; dry run builds and validates the local deployment plan, printing target names, bindings and migration names. No Cloudflare credentials or requests are needed and nothing changes remotely. Valid fixture senders on .test, .example, .invalid, .localhost and example.com, example.net or example.org (including subdomains) are accepted only in a dry run; real deploys refuse placeholder senders. Dry run never prompts for or requires a missing owner name, saves no name and bypasses custom deploy hooks and their owner-email preflight. Target secrets, permissions and remote readiness are checked only by a real deploy. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. For a real deploy, the managed adapter checks its hosted owner email before rer resolves the owner name, so its placeholder-email refusal comes first. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --reopen-installation-key KID temporarily binds a retired installation key from private custody, reseals restored dependency keys under the current key, verifies them and removes the previous binding. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
|
|
15
15
|
export: [['--target', '--output', '--origin', '--session-file'], 'For owner move-in, run rer dev and open /app/import: export people there, then upload through the destination door. Developer-only installation backup: complete supported archive of the local copy on this computer, with integrity and exclusions, written to --output. The hosted install cannot be exported yet: --origin or --target remote refuses (exit 2) before any effect and names the command that saves the hosted database.'],
|
|
16
|
-
import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'For owner move-in, run rer dev and open /app/import: upload, review and apply through the door. Developer-only installation recovery: confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
|
|
16
|
+
import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--acknowledge-unverified-schema-objects', '--output'], 'For owner move-in, run rer dev and open /app/import: upload, review and apply through the door. Developer-only installation recovery: confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import. A v2 archive without schemaObjects requires --acknowledge-unverified-schema-objects, an empty destination and compatible destination migration history; its receipt records schemaUnverified. A fresh export from current rer is preferred; current archives need no acknowledgment.'],
|
|
17
17
|
doctor: [[], 'Read-only installed tool, configuration and state diagnostics.', 'never'],
|
|
18
18
|
describe: [[], 'Read-only description of actual command capabilities.'],
|
|
19
19
|
check: [['--profile'], 'Read-only structural command contract and operations validation.'],
|
|
@@ -21,7 +21,7 @@ const definitions = {
|
|
|
21
21
|
export const verbs = Object.fromEntries(Object.entries(definitions).map(([name, [flags, effects, bootstrap = 'before']]) => [name, { bootstrap, flags: [...commonFlags, ...flags, ...(['build','deploy','dev','preview','export','import'].includes(name)?['--platform']:[]), ...(['install','setup','dev','preview','build','verify','deploy','export','import'].includes(name)?['--no-queue']:[])], effects }]));
|
|
22
22
|
// `rer demo` is `rer dev --demo`; describe lists it as a verb with the dev
|
|
23
23
|
// flags a demo takes whenever the seed's dev takes --demo.
|
|
24
|
-
export const demoVerb = Object.freeze({ bootstrap: 'before', flags: [...commonFlags, '--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--no-queue'], effects: 'A throwaway demo of this seed (rer dev --demo): fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in, the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).' });
|
|
24
|
+
export const demoVerb = Object.freeze({ bootstrap: 'before', flags: [...commonFlags, '--port', '--host', '--idle-timeout', '--stop', '--detach', '--foreground', '--no-queue'], effects: 'A throwaway demo of this seed (rer dev --demo): fresh data in .rer/demo/START (deleted when it stops: --stop, Ctrl-C or its end, one hour by default or --idle-timeout), the saved owner signed in through the demo persona, a separate RER_OWNER_OPEN link for single-use native owner entry on loopback (15-minute expiry; never saved), the seed\'s demo data, Demo in the app name and title, real public reads/checks and simulated external writes (RER_DEMO=1; the checkout\'s own data is never touched).' });
|
|
25
25
|
// `rer signin` is rer's own, not a seed operation: any seed rer deploys, it can
|
|
26
26
|
// sign the owner in to, so no seed declares it and check does not ask for it.
|
|
27
27
|
export const signinVerb = Object.freeze({ bootstrap: 'before', flags: [...commonFlags, '--environment', '--env-file'], effects: 'A one-time sign-in link for the hosted owner, without mail. Uses the Cloudflare credentials that deployed --environment (default production; from the environment or --env-file) to write a single-use grant for the recorded owner into that deployment\'s auth database, then prints the link once to this terminal; it is never saved. The link works once, only for that owner, expires within 15 minutes, and its use is recorded in the owner\'s audit log. Signed in this way, the owner can correct a wrong email in settings.' });
|
|
@@ -29,7 +29,7 @@ export const signinVerb = Object.freeze({ bootstrap: 'before', flags: [...common
|
|
|
29
29
|
// Their project-package bootstrap uses the same contract as every checkout verb.
|
|
30
30
|
export const authoringVerbs = Object.freeze({
|
|
31
31
|
'adopt-edition': {bootstrap: 'before', flags: [...commonFlags], effects: 'Add edition.json and sources.lock.json for the existing tracked local source, preserving declared project identity and existing copy/composition records. Create an empty base-copies.json only when none exists. Review and stage the new authoring inputs; no source regeneration, install setup or commit.'},
|
|
32
|
-
'refresh-base': {bootstrap: 'before', flags: [...commonFlags, '--ref', '--base', '--record', '--offline', '--edition-migration'], effects: 'Consent to each declared edition edit with repeatable --edition-migration ID; refresh leaves the edit owed. Refresh recorded Base copies to --ref FULL_COMMIT, preserving acknowledged adaptations and applied migrations; announce removed singleton retirement. Deliver invoked workflow helpers atomically; adopt tracked known historical Verify templates and preserve divergent workflows with adoption notices. Acquire committed source from the declared Base repository (default https://github.com/runeditrun/base.git), or use --base CHECKOUT. --offline requires --base and never acquires remote source. Refuse incomplete Git checkouts without changing their records. Review the diff and run edition tests before committing.'},
|
|
32
|
+
'refresh-base': {bootstrap: 'before', flags: [...commonFlags, '--ref', '--base', '--base-archive', '--record', '--offline', '--edition-migration'], effects: 'Consent to each declared edition edit with repeatable --edition-migration ID; refresh leaves the edit owed. Refresh recorded Base copies to --ref FULL_COMMIT, preserving acknowledged adaptations and applied migrations; announce removed singleton retirement. Deliver invoked workflow helpers atomically; adopt tracked known historical Verify templates and preserve divergent workflows with adoption notices. Acquire committed source from the declared Base repository (default https://github.com/runeditrun/base.git), or use --base CHECKOUT or --base-archive DIRECTORY with --ref FULL_COMMIT for an exported source tree. --offline requires --base and never acquires remote source. Refuse incomplete Git checkouts without changing their records. Review the diff and run edition tests before committing.'},
|
|
33
33
|
});
|
|
34
34
|
export const aliases = Object.fromEntries([...Object.keys(verbs).filter(v => v !== 'install'), 'release', 'deps', 'rer'].map(name => [name, name === 'deps' ? 'install' : name === 'rer' ? null : name]));
|
|
35
35
|
export const releaseFlags = ['--repo', '--project', '--repository', '--output', '--ref', '--public-base', '--dry-run', '--local-verify', '--verify-workflow', '--scan-timeout-seconds', '--tag', '--clean-history', '--onto', '--env-file', '--allow-placeholder-mark', '--no-queue'];
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { RerError } from './errors.mjs';
|
|
2
|
+
|
|
3
|
+
// Approve only known ownership failures; arbitrary provider error text stays
|
|
4
|
+
// behind the usual redacted capture boundary.
|
|
5
|
+
export function demoDeployFailure(error, store) {
|
|
6
|
+
const codes = ['resource-name-collision', 'owned-resource-replaced', 'resource-not-in-record', 'uncertain-resource-create'];
|
|
7
|
+
if (!codes.includes(error.message)) return error;
|
|
8
|
+
const resource = typeof error.resource === 'string' && /^[a-z-]+:[a-z0-9.-]+$/.test(error.resource) ? ` ${error.resource}` : '';
|
|
9
|
+
const reason = error.ownershipReason === 'missing-annotation'
|
|
10
|
+
? ': served version has no workers/message ownership annotation; unchanged secret-only history matching the previous rer deployment record could not be verified'
|
|
11
|
+
: error.ownershipReason === 'different-annotation' ? ': served version workers/message ownership annotation does not match this demo' : '';
|
|
12
|
+
const recovery = 'Nothing was changed. For your own demo, restore the verified previous rer deployment and its workers/message ownership annotation, then rerun the same command. For a foreign resource, choose another --environment name or remove it yourself.';
|
|
13
|
+
return new RerError('deploy_refused', store.redact(`Demo deploy refused: ${error.message}${resource}${reason}. ${recovery}`), 1);
|
|
14
|
+
}
|
package/cli/demo-native.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { cloudflare } from '../modules/deploy-kit/provider.mjs';
|
|
|
10
10
|
import { RUNTIME_FILES } from '../modules/demo-host/native/config.mjs';
|
|
11
11
|
import { prepareNative } from '../modules/demo-host/native/prepare.mjs';
|
|
12
12
|
import { TESTING_SECRET } from '../modules/demo-host/measurement.mjs';
|
|
13
|
+
import { demoDeployFailure } from './demo-deploy-error.mjs';
|
|
13
14
|
import { awaitCertificates } from '../modules/demo-host/certificate.mjs';
|
|
14
15
|
|
|
15
16
|
export async function nativeDemoCommand(project, options, store, signal, out, operation, app, plan) {
|
|
@@ -22,7 +23,8 @@ export async function nativeDemoCommand(project, options, store, signal, out, op
|
|
|
22
23
|
for (const file of DEMO_FILES) await cp(new URL(`../modules/demo-host/${file}`, import.meta.url), join(folder, 'modules/demo-host', file));
|
|
23
24
|
for (const file of RUNTIME_FILES) await cp(new URL(`../modules/demo-host/native/${file}.mjs`, import.meta.url), join(folder, `modules/demo-host/native/${file}.mjs`));
|
|
24
25
|
for (const directory of ['deploy-kit']) await cp(new URL(`../modules/${directory}/`, import.meta.url), join(folder, 'modules', directory), { recursive: true });
|
|
25
|
-
await mkdir(join(folder, 'modules/container'), { recursive: true });
|
|
26
|
+
await mkdir(join(folder, 'modules/container/adapters'), { recursive: true });
|
|
27
|
+
await cp(new URL('../modules/container/adapters/d1-limits.mjs', import.meta.url), join(folder, 'modules/container/adapters/d1-limits.mjs'));
|
|
26
28
|
for (const file of ['migrations.mjs', 'demo-egress.mjs']) await cp(new URL(`../modules/container/${file}`, import.meta.url), join(folder, 'modules/container', file));
|
|
27
29
|
// Runtime imports use the same module topology as the maintained source.
|
|
28
30
|
let bundle;
|
|
@@ -51,7 +53,9 @@ export async function nativeDemoCommand(project, options, store, signal, out, op
|
|
|
51
53
|
const required = ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN', 'TURNSTILE_SITE_KEY', 'TURNSTILE_SECRET_KEY'];
|
|
52
54
|
if (required.some(name => !process.env[name]?.trim())) throw missing(`${required.join(', ')} are required`);
|
|
53
55
|
const api = cloudflare({ accountId: process.env.CLOUDFLARE_ACCOUNT_ID, token: process.env.CLOUDFLARE_API_TOKEN });
|
|
54
|
-
|
|
56
|
+
await store.step(`Checking ownership of the demo Worker ${plan.worker}`);
|
|
57
|
+
try { config.migrations = await upgradeDemo({ api, plan, report: line => store.report(line) }); }
|
|
58
|
+
catch (error) { throw demoDeployFailure(error, store); }
|
|
55
59
|
await writeFile(join(folder, 'wrangler.json'), JSON.stringify(config, null, 2) + '\n');
|
|
56
60
|
const testing = TESTING_SECRET.test(process.env.TURNSTILE_SECRET_KEY);
|
|
57
61
|
const measurement = testing ? process.env.RER_DEMO_MEASUREMENT_TOKEN || randomBytes(32).toString('base64url') : undefined;
|
package/cli/deploy-command.mjs
CHANGED
|
@@ -17,7 +17,7 @@ import { rememberHookState, hookState } from './deploy-hook-record.mjs';
|
|
|
17
17
|
import { main as owner } from '../modules/deploy-kit/owner-cli.mjs';
|
|
18
18
|
import { localOnlyBinding, ownerWorkerName } from '../modules/deploy-kit/owner.mjs';
|
|
19
19
|
import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
|
|
20
|
-
import { migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
|
|
20
|
+
import { deployDiagnostic, migrationFailure, providerFailure, assetFailure } from '../modules/deploy-kit/diagnostics.mjs';
|
|
21
21
|
import { shared } from './shared.mjs';
|
|
22
22
|
import { settingKinds } from './deploy-settings.mjs';
|
|
23
23
|
import { deployGuide, neededForRealDeploy, reportNeeded } from './deploy-needs.mjs';
|
|
@@ -84,7 +84,7 @@ export async function deployCommand(context) {
|
|
|
84
84
|
const dryRun = async result => {
|
|
85
85
|
const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
|
|
86
86
|
const { signIn } = await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options }) ?? {};
|
|
87
|
-
const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked:
|
|
87
|
+
const needed = neededForRealDeploy({ declaration, env: production.env, signIn, secretsChecked: false });
|
|
88
88
|
reportNeeded(store, needed);
|
|
89
89
|
if (declaration.secrets?.some(item => item.binding === 'INSTALLATION_KEY')) store.report('deploy: INSTALLATION_KEY is a private generated binding; INSTALLATION_KEY_PREVIOUS is optional and managed only during rotation or an explicit retired-key reopen. Values are withheld.');
|
|
90
90
|
return needed.length && result && typeof result === 'object' ? { ...result, neededForRealDeploy: needed } : result;
|
|
@@ -95,7 +95,8 @@ export async function deployCommand(context) {
|
|
|
95
95
|
if (options.rotateSecret?.split(',').includes('INSTALLATION_KEY')) return ownerDeploy(path, adapter)(context);
|
|
96
96
|
// A hook that deployed through the kit keeps what its Worker holds: rotate there as a secret change.
|
|
97
97
|
if (options.rotateSecret && !adapter.deploy.managesHostedOwner && await hookState(root, options.environment ?? 'production')) return ownerDeploy(path, adapter)(context);
|
|
98
|
-
if (
|
|
98
|
+
if (options.dryRun) return dryRun(await ownerDeploy(path, adapter)(context));
|
|
99
|
+
if (adapter.deploy.managesHostedOwner) return adapter.deploy(context);
|
|
99
100
|
const productDirectory = deployProductDirectory(declaration);
|
|
100
101
|
const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
|
|
101
102
|
await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options });
|
|
@@ -189,6 +190,7 @@ export async function deployCommand(context) {
|
|
|
189
190
|
const refused = [providerFailure(error,redact), assetFailure(error)].filter(Boolean).join('; '), migration = migrationFailure(error, again);
|
|
190
191
|
const exchange = error.ownerExchange ?? (error.message === 'owner-claim-failed' ? observedClaims.lastExchange ?? observedClaims.at(-1) : undefined);
|
|
191
192
|
const ownerCause = ownerExchangeFailure(exchange);
|
|
192
|
-
|
|
193
|
+
const d1Import = deployDiagnostic(error,redact)?.d1Import;
|
|
194
|
+
throw commandFailure(redact(`${state} Failed at ${step}: ${error.message}${refused ? ` (${refused})` : ''}${ownerCause ? ` (${ownerCause})` : ''}${error.cause ? ` (${error.cause})` : ''}.${migration ? ` ${migration}` : ''} Fix the cause and run ${again} again using the same environment credentials. ${outcome && recorded ? `To retire the token without rebuilding: ${again} --unset-secret ${setupManifest?.steps?.find(item => item.type === 'owner-claim')?.tokenField ?? 'SETUP_TOKEN'}.` : ''}`), d1Import ? {d1Import} : {});
|
|
193
195
|
}
|
|
194
196
|
}
|
package/cli/deploy-config.mjs
CHANGED
|
@@ -28,7 +28,7 @@ export function tomlMain(source) {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
export function jsoncMain(source) {
|
|
31
|
-
try { return
|
|
31
|
+
try { return parseJsonc(source).main; } catch { return undefined; }
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
// The deployed Worker entry (`main`) from the first of those files that exists.
|
|
@@ -22,10 +22,12 @@ export async function deployOwnerInput({ root, adapter, setupSeed, options, sign
|
|
|
22
22
|
}
|
|
23
23
|
const advice = 'Deploy needs your owner name; run rer deploy --owner-name "Your name" (or rer setup --owner-name "Your name"). Nothing was uploaded.';
|
|
24
24
|
if (!displayName?.trim()) {
|
|
25
|
+
// A local plan never bootstraps an owner or asks for their name.
|
|
26
|
+
if (options.dryRun) return { input };
|
|
25
27
|
// A recorded bootstrap keeps its owner; resolving inputs needs no provider read.
|
|
26
28
|
const held = (await heldDeployments(root)).find(item => item.environment === (options.environment ?? 'production'));
|
|
27
29
|
if (['claimed', 'kept'].includes(held?.record.ownerClaim?.outcome)) return { input };
|
|
28
|
-
if (options.
|
|
30
|
+
if (options.nonInteractive || options.json || !process.stdin.isTTY) throw missing(advice);
|
|
29
31
|
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
30
32
|
const closed = new Promise((_, reject) => prompt.once('close', () => reject(missing(advice))));
|
|
31
33
|
try { displayName = await Promise.race([prompt.question('Your name (hosted owner): ', { signal }), closed]); }
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { contained } from './project.mjs';
|
|
3
|
+
import { deployConfigPaths } from './deploy-config.mjs';
|
|
4
|
+
import { parseJsonc } from './jsonc.mjs';
|
|
5
|
+
import { comments } from './business/parsers-syntax.mjs';
|
|
6
|
+
import { tomlEntries } from './business/parsers-config.mjs';
|
|
7
|
+
import { imageVariableSecrets } from '../modules/container/image-variables.mjs';
|
|
8
|
+
|
|
9
|
+
const id = 'deploy.vars-secrets';
|
|
10
|
+
const lineAt = (source, offset) => source.slice(0, offset).split('\n').length;
|
|
11
|
+
const variablePath = path => path[0] === 'vars' && path.length === 2 ||
|
|
12
|
+
path[0] === 'env' && path[2] === 'vars' && path.length === 4;
|
|
13
|
+
|
|
14
|
+
async function sourceFile(root, path) {
|
|
15
|
+
try { return await readFile(await contained(root, path, { optional: true }), 'utf8'); }
|
|
16
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Reuse the image builder's JSONC reader and binding comparison. Source checks
|
|
20
|
+
// deliberately reject even empty placeholders and legacy public-mail overlaps:
|
|
21
|
+
// a declaration belongs in vars or secrets, before any build normalizes it.
|
|
22
|
+
export async function deployVariableClause(root, adapter) {
|
|
23
|
+
try {
|
|
24
|
+
const declarationPath = adapter?.deploy?.declaration ?? 'deploy.json';
|
|
25
|
+
const declarationSource = await sourceFile(root, declarationPath);
|
|
26
|
+
if (declarationSource === null) return { id, ok: true };
|
|
27
|
+
const secretLocations = new Map();
|
|
28
|
+
const declaration = parseJsonc(declarationSource, (path, offset) => {
|
|
29
|
+
if (path.length === 3 && path[0] === 'secrets' && path[2] === 'binding') secretLocations.set(path[1], lineAt(declarationSource, offset));
|
|
30
|
+
});
|
|
31
|
+
// deploy.json uses strict JSON in both native and container builds.
|
|
32
|
+
try { JSON.parse(declarationSource); } catch { throw Error(`${declarationPath}: invalid JSON declaration.`); }
|
|
33
|
+
const secrets = declaration.secrets ?? [];
|
|
34
|
+
if (!Array.isArray(secrets) || secrets.some(secret => typeof secret?.binding !== 'string')) throw Error(`${declarationPath}: secrets must be an array of binding declarations.`);
|
|
35
|
+
const overlaps = [];
|
|
36
|
+
for (const path of deployConfigPaths(adapter)) {
|
|
37
|
+
const source = await sourceFile(root, path);
|
|
38
|
+
if (source === null) continue;
|
|
39
|
+
const entries = [];
|
|
40
|
+
let config;
|
|
41
|
+
try {
|
|
42
|
+
if (path.endsWith('.toml')) entries.push(...tomlEntries(comments(source).clean, { locations: true }));
|
|
43
|
+
else config = parseJsonc(source, (path, offset) => entries.push({ path, offset }));
|
|
44
|
+
} catch (error) { throw Error(`${path}: ${error.message}`); }
|
|
45
|
+
for (const entry of entries.filter(entry => variablePath(entry.path))) {
|
|
46
|
+
const binding = entry.path.at(-1);
|
|
47
|
+
// TOML entries describe declared keys; JSONC values come from the very
|
|
48
|
+
// same reader the node image builder uses (including escaped key names).
|
|
49
|
+
const vars = config ? entry.path.slice(0, -1).reduce((value, key) => value?.[key], config) : { [binding]: entry.value };
|
|
50
|
+
const matched = new Set(imageVariableSecrets(vars ?? {}, secrets).map(secret => secret.binding));
|
|
51
|
+
if (!matched.has(binding)) continue;
|
|
52
|
+
for (const [index, secret] of secrets.entries()) if (secret.binding === binding) overlaps.push(
|
|
53
|
+
`${binding}: ${path}:${lineAt(source, entry.offset)} (${entry.path.slice(0, -1).join('.')}) and ${declarationPath}:${secretLocations.get(index)} (secrets)`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return overlaps.length ? { id, ok: false, message: overlaps.join('\n') + '\nremove it from wrangler vars; the deploy sets it as a secret' } : { id, ok: true };
|
|
57
|
+
} catch (error) { return { id, ok: false, message: error.message }; }
|
|
58
|
+
}
|
package/cli/deploy.mjs
CHANGED
|
@@ -54,23 +54,23 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
54
54
|
const { env, supplied, generated, reused, rotated } = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
|
|
55
55
|
if (options.setSecret || options.unsetSecret) secretChangeInputs(declaration, options, env, again);
|
|
56
56
|
const kept = keptSecrets(declaration, setupManifest);
|
|
57
|
-
if (cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env, {dryRun:options.dryRun,signIn}));
|
|
57
|
+
if (!options.dryRun && cloudflareCredentials.some(name => !env[name]?.trim())) throw missing(missingCredentialsMessage(declaration, env, {dryRun:options.dryRun,signIn}));
|
|
58
58
|
const { main } = await import('../modules/deploy-kit/owner-cli.mjs');
|
|
59
59
|
const { createRedaction } = await shared('redaction.mjs');
|
|
60
60
|
const redaction = createRedaction();
|
|
61
61
|
redaction.addSecrets([...(await settingKinds({ declaration, setupManifest })).privateValues(env), env.CLOUDFLARE_ACCOUNT_ID, ...(declaration.secrets ?? []).map(item => env[item.environment]).filter(Boolean)]);
|
|
62
62
|
const claim = setupManifest?.steps?.find(item => item.type === 'owner-claim');
|
|
63
63
|
const declared = binding => (Array.isArray(declaration.secrets) ? declaration.secrets : []).find(item => item?.binding === binding);
|
|
64
|
-
const owner = async (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...(['dry-run', 'deploy', 'health'].includes(command) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
64
|
+
const owner = async (command, extra = [], values = env, more = {}) => main([command, '--declaration', declarationPath, '--environment', environment, ...(['dry-run', 'local-plan', 'deploy', 'health'].includes(command) ? await deployProductArguments(root, productDirectory) : []), ...extra], values, { cwd: root, localOnlyKeys, ...more });
|
|
65
65
|
// Keep confirmed creation events across deploy and the independent health call.
|
|
66
66
|
const created = [];
|
|
67
67
|
let step = 'deploy', deployed;
|
|
68
68
|
try {
|
|
69
69
|
if (options.dryRun) {
|
|
70
|
-
const {
|
|
71
|
-
|
|
72
|
-
store.report('deploy: dry run complete;
|
|
73
|
-
return { dryRun: true, deployed: false };
|
|
70
|
+
const {plan} = await owner('local-plan');
|
|
71
|
+
store.report(`Would deploy: ${JSON.stringify(plan)}`);
|
|
72
|
+
store.report('deploy: local dry run complete; no credentials were needed, no Cloudflare requests were made and nothing was changed remotely. Target secrets and remote readiness were not checked.');
|
|
73
|
+
return { dryRun: true, deployed: false, plan };
|
|
74
74
|
}
|
|
75
75
|
// A custom hook's own state file, when its deploy named one.
|
|
76
76
|
const state = change.length ? recordedState : await hookState(root, environment);
|
|
@@ -137,7 +137,9 @@ export function ownerDeploy(declarationPath, lifecycle) {
|
|
|
137
137
|
} catch (error) {
|
|
138
138
|
if (error instanceof RerError) throw error;
|
|
139
139
|
const { commandFailure } = await shared('failures.mjs');
|
|
140
|
-
|
|
140
|
+
const d1Import = deployDiagnostic(error,redaction.redact)?.d1Import;
|
|
141
|
+
throw commandFailure(failureText({ error, step, created, again, retry, secretChange: Boolean(change.length && !options.remove), deployed, redact: redaction.redact }),
|
|
142
|
+
d1Import ? {d1Import} : {});
|
|
141
143
|
}
|
|
142
144
|
}, { declaration: declarationPath, managesHostedOwner: true });
|
|
143
145
|
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { resolve, relative, isAbsolute } from 'node:path';
|
|
5
|
+
import { parseContract } from '../foundation/runtime/seed-contract.mjs';
|
|
6
|
+
import { RerError } from './errors.mjs';
|
|
7
|
+
|
|
8
|
+
export const clausesHelp = `Usage: rer door clauses (--write | --check) [--cwd DIR]
|
|
9
|
+
|
|
10
|
+
Synchronize BASE-AGENT-001 through BASE-AGENT-013 in CONTRACT.md.
|
|
11
|
+
--write adds or updates Base's requirements, preserving existing status,
|
|
12
|
+
evidence and gaps, then runs the seed's contract-docs write and check.
|
|
13
|
+
--check is read-only and names missing or stale clauses (exit 1).
|
|
14
|
+
Seed-owned clauses and the judged revision stay unchanged. Newly added clauses
|
|
15
|
+
start missing. Regenerate the seed's source lock last, before committing.
|
|
16
|
+
`;
|
|
17
|
+
const fail = message => { throw new RerError('agent_clauses_invalid', message, 1); };
|
|
18
|
+
const read = file => readFileSync(file, 'utf8');
|
|
19
|
+
const area = '### Agent surface (Base-delivered)';
|
|
20
|
+
|
|
21
|
+
// Directory records deliver new non-code files on refresh, too. A recorded
|
|
22
|
+
// clause copy selects its immutable text; older runtime pins without this file
|
|
23
|
+
// can still sync their contract using the CLI's independently delivered source.
|
|
24
|
+
function canonical(root) {
|
|
25
|
+
const record = resolve(root, 'base-copies.json');
|
|
26
|
+
if (existsSync(record)) {
|
|
27
|
+
const origin = 'modules/agent-door/CLAUSES.md';
|
|
28
|
+
const candidates = JSON.parse(read(record)).copies?.filter(copy => origin === copy.originPath || origin.startsWith(copy.originPath + '/')) ?? [];
|
|
29
|
+
if (candidates.length > 1) fail('Overlapping agent-door copy records; repair base-copies.json first.');
|
|
30
|
+
if (candidates.length) {
|
|
31
|
+
const copy = candidates[0], name = copy.path + origin.slice(copy.originPath.length), file = resolve(root, name);
|
|
32
|
+
const inside = relative(root, file);
|
|
33
|
+
if (isAbsolute(inside) || inside === '..' || inside.startsWith('../')) fail('Agent clause copy must stay inside this seed.');
|
|
34
|
+
if (!copy.files?.[name]) return read(new URL('../modules/agent-door/CLAUSES.md', import.meta.url));
|
|
35
|
+
if (!existsSync(file)) fail(`Restore the recorded agent clause source ${name} before syncing.`);
|
|
36
|
+
const bytes = readFileSync(file);
|
|
37
|
+
if (createHash('sha256').update(bytes).digest('hex') !== copy.files[name]) fail(`Recorded agent clause source ${name} has local edits; restore or refresh it first.`);
|
|
38
|
+
return bytes.toString('utf8');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return read(new URL('../modules/agent-door/CLAUSES.md', import.meta.url));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function definitions(source) {
|
|
45
|
+
const blocks = [...source.matchAll(/^#### (BASE-AGENT-\d{3}) — ([^\n]+)\n([\s\S]*?)(?=^#{1,4} |$(?![\s\S]))/gm)];
|
|
46
|
+
const result = blocks.map(([, id, title, body]) => ({ id, title, text: `#### ${id} — ${title}\n${body.trimEnd()}`, row: source.split('\n').find(line => line.startsWith(`| \`${id}\` |`)) }));
|
|
47
|
+
for (const clause of result) {
|
|
48
|
+
const acceptance = clause.text.split('\n**Acceptance.**\n')[1];
|
|
49
|
+
const points = [...(acceptance ?? '').matchAll(/^(\d+)\. /gm)];
|
|
50
|
+
if (!points.length || points.length > 8 || points.some((point, index) => Number(point[1]) !== index + 1)) fail(`${clause.id} needs one to eight consecutive acceptance points in its canonical source.`);
|
|
51
|
+
}
|
|
52
|
+
const ids = Array.from({ length: 13 }, (_, i) => `BASE-AGENT-${String(i + 1).padStart(3, '0')}`);
|
|
53
|
+
if (result.map(item => item.id).join() !== ids.join() || result.some(item => !item.row)) fail('Canonical agent clauses must define BASE-AGENT-001 through 013 with initial Status rows.');
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function headings(lines) {
|
|
58
|
+
let fence;
|
|
59
|
+
return lines.flatMap((line, index) => {
|
|
60
|
+
const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
|
|
61
|
+
if (mark) { if (!fence) fence = mark[0]; else if (fence === mark[0]) fence = undefined; return []; }
|
|
62
|
+
const match = !fence && /^(#{1,6}) ([^\r\n]+)/.exec(line);
|
|
63
|
+
return match ? [{ index, level: match[1].length, title: match[2] }] : [];
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// contract-docs owns summary generation. Suppress only its three derived rows
|
|
68
|
+
// for structural validation while a contract is awaiting regeneration.
|
|
69
|
+
function withoutSummary(text) {
|
|
70
|
+
return text.replace(/^(\| Clauses \| Done \| Partial \| Missing \| Total \|\r?\n[^\n]*\n)((?:\|[^\n]*\n)+)/m, (_, header, rows) => header + rows.replace(/[^\r\n]+/g, ''));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function synchronize(original, clauses) {
|
|
74
|
+
const parsed = parseContract(withoutSummary(original));
|
|
75
|
+
const lines = original.match(/[^\n]*\n|[^\n]+$/g) ?? [], outline = headings(lines);
|
|
76
|
+
const newline = original.includes('\r\n') ? '\r\n' : '\n';
|
|
77
|
+
const edits = [], missing = [], changed = [];
|
|
78
|
+
const target = outline.find(item => item.level === 2 && item.title === 'Target clauses');
|
|
79
|
+
if (!target) fail('CONTRACT.md needs the standard ## Target clauses section. Convert the contract before syncing.');
|
|
80
|
+
const targetEnd = outline.find(item => item.index > target.index && item.level <= 2)?.index ?? lines.length;
|
|
81
|
+
for (const clause of clauses) {
|
|
82
|
+
const old = parsed.clauses.find(item => item.id === clause.id);
|
|
83
|
+
if (!old) { missing.push(clause); changed.push(`${clause.id} missing`); continue; }
|
|
84
|
+
if (!lines[old.line - 1].startsWith('#### ') || old.kind !== 'target') fail(`${clause.id} must be a standard level-four Target clause before syncing; preserve its judgment when converting.`);
|
|
85
|
+
const start = old.line - 1, end = outline.find(item => item.index > start)?.index ?? lines.length;
|
|
86
|
+
const before = lines.slice(start, end).join(''), trailing = /\s*$/.exec(before)[0];
|
|
87
|
+
const after = clause.text.replaceAll('\n', newline) + trailing;
|
|
88
|
+
const row = lines[old.row - 1];
|
|
89
|
+
// A changed canonical title updates only the title cell, never the seed's
|
|
90
|
+
// kind, status, evidence or gap cells (or their original spacing).
|
|
91
|
+
const updatedRow = row.replace(/^(\s*\|[^|]*\|)([^|]*)(\|.*)/, (_, first, title, rest) => first + title.replace(/\S(?:[\s\S]*\S)?/, clause.title) + rest);
|
|
92
|
+
if (before !== after || row !== updatedRow) {
|
|
93
|
+
changed.push(`${clause.id} stale`);
|
|
94
|
+
edits.push({ start, end, text: after }, { start: old.row - 1, end: old.row, text: updatedRow });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (missing.length) {
|
|
98
|
+
const delivered = outline.find(item => item.index > target.index && item.index < targetEnd && lines[item.index].trimEnd() === area);
|
|
99
|
+
const agent = outline.find(item => item.index > target.index && item.index < targetEnd && item.level === 3 && item.title === 'Agent surface');
|
|
100
|
+
const at = delivered ? outline.find(item => item.index > delivered.index && item.level <= 3)?.index ?? targetEnd : agent?.index ?? targetEnd;
|
|
101
|
+
const text = (delivered ? '' : area + '\n\n') + missing.map(item => item.text).join('\n\n') + '\n\n';
|
|
102
|
+
edits.push({ start: at, end: at, text: (at && !lines[at - 1].trim() ? '' : newline) + text.replaceAll('\n', newline) });
|
|
103
|
+
const status = outline.find(item => item.level === 2 && item.title === 'Status');
|
|
104
|
+
const header = lines.findIndex((line, index) => index > status?.index && /^\| Clause \| Title \| Kind \| Status \| Evidence \| Gap \|/.test(line));
|
|
105
|
+
if (header < 0) fail('CONTRACT.md needs the standard Status clause table.');
|
|
106
|
+
let end = header + 2;
|
|
107
|
+
while (lines[end]?.trimStart().startsWith('|')) end++;
|
|
108
|
+
edits.push({ start: end, end, text: (end && !lines[end - 1].endsWith('\n') ? newline : '') + missing.map(item => item.row).join(newline) + newline });
|
|
109
|
+
}
|
|
110
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) lines.splice(edit.start, edit.end - edit.start, edit.text);
|
|
111
|
+
const text = lines.join('');
|
|
112
|
+
parseContract(withoutSummary(text));
|
|
113
|
+
return { text, changed };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function generator(root) {
|
|
117
|
+
const agents = resolve(root, 'AGENTS.md');
|
|
118
|
+
const declared = existsSync(agents) ? [...read(agents).matchAll(/^Lander-Regenerate:\s*(.+)$/gm)].map(match => match[1].trim()) : [];
|
|
119
|
+
const command = declared.find(line => /contract-docs\.mjs\s+write\b/.test(line)) ?? 'node src/base/contract-docs.mjs write';
|
|
120
|
+
if (!declared.some(line => /contract-docs\.mjs\s+write\b/.test(line)) && !existsSync(resolve(root, 'src/base/contract-docs.mjs'))) fail('No contract-docs generator found. Restore the seed\'s Lander-Regenerate contract generator before writing.');
|
|
121
|
+
return { write: command, check: command.replace(/(contract-docs\.mjs\s+)write\b/, '$1check') };
|
|
122
|
+
}
|
|
123
|
+
function generate(command, root, env) {
|
|
124
|
+
const result = spawnSync(command, { cwd: root, env, shell: true, stdio: 'inherit' });
|
|
125
|
+
if (result.error || result.status !== 0) fail(`Contract generation failed: ${command}. Inspect the diff and repair the generator before committing.`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function doorClausesCommand(args, env = process.env) {
|
|
129
|
+
if (args.includes('--help') || args.includes('-h')) { console.log(clausesHelp); return 0; }
|
|
130
|
+
let root = process.cwd(), mode;
|
|
131
|
+
try {
|
|
132
|
+
for (let i = 0; i < args.length; i++) {
|
|
133
|
+
const arg = args[i];
|
|
134
|
+
if (arg === '--cwd' && args[i + 1] && !args[i + 1].startsWith('-')) root = resolve(args[++i]);
|
|
135
|
+
else if (['--write', '--check'].includes(arg) && !mode) mode = arg;
|
|
136
|
+
else throw new RerError('invalid_arguments', clausesHelp, 2);
|
|
137
|
+
}
|
|
138
|
+
if (!mode) throw new RerError('invalid_arguments', clausesHelp, 2);
|
|
139
|
+
root = resolve(root);
|
|
140
|
+
const file = resolve(root, 'CONTRACT.md');
|
|
141
|
+
if (!existsSync(file)) fail('No CONTRACT.md found. Run rer door clauses from the seed root or pass --cwd DIR.');
|
|
142
|
+
const original = read(file), { text, changed } = synchronize(original, definitions(canonical(root)));
|
|
143
|
+
if (changed.length) console.log(`Agent clauses: ${changed.join(', ')}.`);
|
|
144
|
+
if (mode === '--check' && changed.length) return 1;
|
|
145
|
+
const commands = generator(root);
|
|
146
|
+
if (mode === '--write') {
|
|
147
|
+
if (text !== original) writeFileSync(file, text);
|
|
148
|
+
generate(commands.write, root, env);
|
|
149
|
+
}
|
|
150
|
+
generate(commands.check, root, env);
|
|
151
|
+
console.log(changed.length ? `Synchronized ${changed.length} Base-delivered agent clauses; existing judgments preserved. Regenerate the source lock last.` : 'Base-delivered agent clauses are current; no clause changes.');
|
|
152
|
+
return 0;
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (!(error instanceof RerError)) throw error;
|
|
155
|
+
console.error(error.message); return error.exitCode;
|
|
156
|
+
}
|
|
157
|
+
}
|
package/cli/errors.mjs
CHANGED
|
@@ -14,5 +14,5 @@ export async function lifecycleError(error, store) {
|
|
|
14
14
|
const {shared}=await import('./shared.mjs');
|
|
15
15
|
const {approvedFailure}=await shared('failures.mjs');
|
|
16
16
|
const approved=approvedFailure(error);
|
|
17
|
-
return new RerError(['owner_conflict','machine_busy'].includes(approved?.code)?'safety_refusal':'command_failed', approved?.message ?? `${store?.state?.step ?? 'Local lifecycle'} failed. Inspect the private redacted capture log.`, approved?.exitCode ?? 1, {childExitCode:approved?.childExitCode,signal:approved?.signal});
|
|
17
|
+
return new RerError(['owner_conflict','machine_busy'].includes(approved?.code)?'safety_refusal':'command_failed', approved?.message ?? `${store?.state?.step ?? 'Local lifecycle'} failed. Inspect the private redacted capture log.`, approved?.exitCode ?? 1, {childExitCode:approved?.childExitCode,signal:approved?.signal,...(approved?.d1Import ? {d1Import:approved.d1Import} : {})});
|
|
18
18
|
}
|