@ultimat3/cli 31.15.0 → 31.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -1
- package/package.json +29 -29
- package/src/cache-graph.ts +67 -0
- package/src/cmd-cache-spec.ts +25 -0
- package/src/cmd-cache.ts +187 -0
- package/src/cmd-config-spec.ts +23 -0
- package/src/cmd-config.ts +61 -0
- package/src/cmd-doctor.ts +47 -37
- package/src/cmd-exercise.ts +42 -5
- package/src/cmd-explain-spec.ts +24 -0
- package/src/cmd-explain.ts +201 -0
- package/src/cmd-logs-spec.ts +34 -0
- package/src/cmd-logs.ts +80 -0
- package/src/cmd-planned.ts +15 -29
- package/src/cmd-token-spec.ts +54 -0
- package/src/cmd-token.ts +173 -0
- package/src/cmd-upgrade.ts +19 -2
- package/src/cmd-verify-spec.ts +13 -3
- package/src/cmd-verify.ts +2 -0
- package/src/config-redact.ts +39 -0
- package/src/coverage-floor.ts +2 -2
- package/src/dev-boot-data-dir.ts +69 -0
- package/src/dev-boot.ts +26 -13
- package/src/doctor-env-reserved.ts +111 -0
- package/src/doctor-floor.ts +62 -0
- package/src/doctor-pins.ts +101 -0
- package/src/doctor-probe.ts +21 -1
- package/src/doctor-row-security.ts +119 -4
- package/src/doctor-warnings.ts +55 -0
- package/src/error-codes-doctor.ts +24 -0
- package/src/error-codes-tooling.ts +6 -4
- package/src/error-codes.ts +7 -0
- package/src/errors.ts +8 -2
- package/src/exercise-entry-edit.ts +5 -1
- package/src/exercise-floor-report.ts +138 -0
- package/src/exercise-floor-verdict.ts +98 -0
- package/src/exercise-floor.ts +158 -0
- package/src/exercise-routes.ts +59 -0
- package/src/explain-capture.ts +38 -0
- package/src/generate-exercise.ts +2 -2
- package/src/generate-factories.ts +133 -0
- package/src/generate-files.ts +11 -0
- package/src/generate-kinds.ts +13 -0
- package/src/mcp-db-target.ts +4 -3
- package/src/mcp-errors.ts +14 -0
- package/src/messages-gate.ts +2 -0
- package/src/messages-ops.ts +32 -0
- package/src/messages-upgrade.ts +14 -0
- package/src/messages.ts +5 -0
- package/src/otlp-export.ts +16 -2
- package/src/registry.ts +10 -0
- package/src/role-start.ts +11 -5
- package/src/runtime-services.ts +35 -19
- package/src/serve-boot-phases.ts +30 -0
- package/src/serve-boot-warnings.ts +62 -0
- package/src/serve-boot.ts +30 -11
- package/src/templates/generate-cron-job.ts +90 -0
- package/src/templates/generate-purge.ts +93 -0
- package/src/templates/generate-webhook-receiver.ts +274 -0
- package/src/templates/github/ci.yml.ts +101 -36
- package/src/templates/guard-repo-raw-sql-test.ts +174 -0
- package/src/templates/guard-repo-raw-sql.ts +115 -145
- package/src/templates/guard-unbounded-fanout.ts +170 -0
- package/src/templates/scaffold-claude-commands.ts +3 -2
- package/src/templates/scaffold-docs.ts +3 -2
- package/src/templates/scaffold-guards.ts +3 -0
- package/src/templates/scaffold-verify-floor.ts +4 -0
- package/src/test-dotenv.ts +15 -2
- package/src/upgrade-coverage.ts +109 -0
- package/src/upgrade-document.ts +18 -0
- package/src/upgrade-exercise-floor.ts +53 -0
- package/src/upgrade-gate.ts +84 -29
- package/src/upgrade-guards.ts +159 -0
- package/src/upgrade-report.ts +33 -1
- package/src/verify-checks.ts +3 -1
- package/src/verify-floor.ts +13 -0
- package/src/verify-plan.ts +127 -0
- package/wiki/CI-Parallel-Gate.md +38 -1
- package/wiki/CLI-Reference.md +115 -14
- package/wiki/Caching-And-Invalidation.md +10 -10
- package/wiki/Configuration.md +20 -2
- package/wiki/Known-Gaps.md +1 -1
- package/wiki/MCP-And-AI.md +1 -1
- package/wiki/Testing.md +96 -2
- package/wiki/Troubleshooting.md +3 -2
- package/wiki/Upgrading.md +9 -0
package/src/cmd-token.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// `x token create|list|revoke` — the app's machine credentials, in its own `x_api_keys`, through
|
|
2
|
+
// `@ultimat3/auth`'s `issueApiKey` / `describeApiKey` / `revokeApiKey`: the keys an MCP endpoint's
|
|
3
|
+
// `apiKeyResolver` accepts. The plaintext is shown once, by `create`, and never logged; `list`
|
|
4
|
+
// answers `describeApiKey`'s shape, which holds no hash and no secret.
|
|
5
|
+
|
|
6
|
+
import type { ApiKeyStore, ApiKeySummary } from '@ultimat3/auth';
|
|
7
|
+
import { describeApiKey, issueApiKey, postgresAuthAdapter, revokeApiKey } from '@ultimat3/auth';
|
|
8
|
+
import { type Clock, systemClock, tryResolveEnvironment } from '@ultimat3/core';
|
|
9
|
+
import { requireAppRoot } from './app-root';
|
|
10
|
+
import { plannedSubcommand } from './cmd-planned';
|
|
11
|
+
import { TOKEN_MAX_DAYS, tokenSpec } from './cmd-token-spec';
|
|
12
|
+
import type { CliCommand, CommandContext } from './command';
|
|
13
|
+
import { ok } from './command';
|
|
14
|
+
import { BadFlagError, MissingPositionalError } from './errors';
|
|
15
|
+
import { parseIntFlag } from './flag-number';
|
|
16
|
+
import { readsAsProduction } from './mcp-db-target';
|
|
17
|
+
import { msg } from './messages';
|
|
18
|
+
import type { CommandResult, JsonValue } from './output';
|
|
19
|
+
import { flagList, flagString } from './parse';
|
|
20
|
+
import { openAppQueue } from './runtime-boot-ports';
|
|
21
|
+
|
|
22
|
+
export interface OpenTokenStore {
|
|
23
|
+
readonly store: ApiKeyStore;
|
|
24
|
+
close(): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The app's own database, opened as `x auth` opens it, and ALWAYS released (the PGlite lock). */
|
|
28
|
+
async function openAppTokenStore(root: string, ctx: CommandContext): Promise<OpenTokenStore> {
|
|
29
|
+
const queue = await openAppQueue(root, ctx.env);
|
|
30
|
+
return { store: postgresAuthAdapter(queue.db), close: () => queue.stop() };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const DAY_MS = 86_400_000;
|
|
34
|
+
|
|
35
|
+
/** A summary as JSON: dates as ISO-8601 UTC strings, `null` kept. */
|
|
36
|
+
const summaryJson = (key: ApiKeySummary): JsonValue => ({
|
|
37
|
+
id: key.id,
|
|
38
|
+
prefix: key.prefix,
|
|
39
|
+
scopes: [...key.scopes],
|
|
40
|
+
lastUsedAt: key.lastUsedAt?.toISOString() ?? null,
|
|
41
|
+
expiresAt: key.expiresAt?.toISOString() ?? null,
|
|
42
|
+
revokedAt: key.revokedAt?.toISOString() ?? null,
|
|
43
|
+
createdAt: key.createdAt.toISOString(),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** One human line per key: no secret is in a summary, so every field may be printed. */
|
|
47
|
+
const summaryLine = (key: ApiKeySummary): string =>
|
|
48
|
+
msg('cli.token.row', {
|
|
49
|
+
prefix: key.prefix,
|
|
50
|
+
scopes: key.scopes.join(','),
|
|
51
|
+
state:
|
|
52
|
+
key.revokedAt !== null
|
|
53
|
+
? msg('cli.token.revoked', { at: key.revokedAt.toISOString() })
|
|
54
|
+
: key.expiresAt === null
|
|
55
|
+
? msg('cli.token.noExpiry')
|
|
56
|
+
: msg('cli.token.expires', { at: key.expiresAt.toISOString() }),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* `--env` unsaid is the environment's own label, never a constant: a `dev` default stamped every
|
|
61
|
+
* key minted against production `ult_dev_…`, which reads as harmless in a log or a leak report.
|
|
62
|
+
* Unreadable `ULTIMATE_ENV` reads as production, as `x explain` and the MCP host read it.
|
|
63
|
+
*/
|
|
64
|
+
const envLabel = (env: CommandContext['env']): string => {
|
|
65
|
+
if (readsAsProduction(env)) return 'prod';
|
|
66
|
+
return tryResolveEnvironment({ env }) === 'staging' ? 'stage' : 'dev';
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Every flag `create` reads, held before the database opens: a typo costs no boot. */
|
|
70
|
+
function createInput(ctx: CommandContext, clock: Clock) {
|
|
71
|
+
const scopes = flagList(ctx.args, 'scopes');
|
|
72
|
+
if (scopes.length === 0) {
|
|
73
|
+
throw new BadFlagError({
|
|
74
|
+
flag: 'scopes',
|
|
75
|
+
command: 'token create',
|
|
76
|
+
reason: 'a token carries exactly the permissions it names, and none were named',
|
|
77
|
+
fix: 'x token create --scopes post:read --json',
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
const rawDays = flagString(ctx.args, 'days');
|
|
81
|
+
const days =
|
|
82
|
+
rawDays === undefined
|
|
83
|
+
? undefined
|
|
84
|
+
: parseIntFlag(rawDays, {
|
|
85
|
+
name: 'days',
|
|
86
|
+
command: 'token create',
|
|
87
|
+
min: 1,
|
|
88
|
+
max: TOKEN_MAX_DAYS,
|
|
89
|
+
example: 'x token create --scopes post:read --days 30 --json',
|
|
90
|
+
});
|
|
91
|
+
return {
|
|
92
|
+
env: flagString(ctx.args, 'env') ?? envLabel(ctx.env),
|
|
93
|
+
scopes,
|
|
94
|
+
userId: flagString(ctx.args, 'user') ?? null,
|
|
95
|
+
orgId: flagString(ctx.args, 'org') ?? null,
|
|
96
|
+
expiresAt: days === undefined ? null : new Date(clock.now().getTime() + days * DAY_MS),
|
|
97
|
+
clock,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function create(ctx: CommandContext, open: OpenToken, root: string, clock: Clock) {
|
|
102
|
+
// Issued before the store opens: `issueApiKey` refuses a wildcard scope or a bad env label, and
|
|
103
|
+
// a refusal must not cost a database boot.
|
|
104
|
+
const issued = issueApiKey(createInput(ctx, clock));
|
|
105
|
+
const handle = await open(root, ctx);
|
|
106
|
+
try {
|
|
107
|
+
await handle.store.putApiKey(issued.record);
|
|
108
|
+
} finally {
|
|
109
|
+
await handle.close();
|
|
110
|
+
}
|
|
111
|
+
const key = describeApiKey(issued.record);
|
|
112
|
+
// The plaintext once per render: the human one prints `lines`, `--json` prints `data`. Never in
|
|
113
|
+
// the summary, which both print.
|
|
114
|
+
return ok('token', msg('cli.token.created', { prefix: key.prefix, count: key.scopes.length }), {
|
|
115
|
+
lines: [msg('cli.token.plaintext', { token: issued.plaintext }), msg('cli.token.once')],
|
|
116
|
+
data: { token: issued.plaintext, key: summaryJson(key) },
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function list(ctx: CommandContext, open: OpenToken, root: string) {
|
|
121
|
+
const owner = flagString(ctx.args, 'owner');
|
|
122
|
+
if (owner === undefined) {
|
|
123
|
+
throw new BadFlagError({
|
|
124
|
+
flag: 'owner',
|
|
125
|
+
command: 'token list',
|
|
126
|
+
reason:
|
|
127
|
+
'tokens are listed by the user or org they belong to; a token issued with neither is listed by nobody and revoked by its id',
|
|
128
|
+
fix: 'x token list --owner <user-or-org-id> --json',
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const handle = await open(root, ctx);
|
|
132
|
+
const keys = await handle.store.listApiKeys(owner).finally(() => handle.close());
|
|
133
|
+
const summaries = keys.map(describeApiKey);
|
|
134
|
+
return ok('token', msg('cli.token.listed', { count: summaries.length, owner }), {
|
|
135
|
+
lines: summaries.map(summaryLine),
|
|
136
|
+
data: { owner, keys: summaries.map(summaryJson) },
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function revoke(ctx: CommandContext, open: OpenToken, root: string, clock: Clock) {
|
|
141
|
+
const id = ctx.args.positionals[0];
|
|
142
|
+
if (id === undefined) {
|
|
143
|
+
throw new MissingPositionalError({
|
|
144
|
+
command: 'token revoke',
|
|
145
|
+
positional: 'id',
|
|
146
|
+
example: 'x token list --owner <user-or-org-id> --json # then x token revoke <id>',
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
const handle = await open(root, ctx);
|
|
150
|
+
const revoked = await revokeApiKey(handle.store, id, clock).finally(() => handle.close());
|
|
151
|
+
// Unknown and already-revoked answer alike, as `verifyApiKey` does: neither is a key that works,
|
|
152
|
+
// so a second run of the same revoke is the same success — idempotent, like `x auth seal-mfa`.
|
|
153
|
+
return ok('token', msg(revoked ? 'cli.token.revokedOne' : 'cli.token.notLive', { id }), {
|
|
154
|
+
data: { id, revoked },
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type OpenToken = (root: string, ctx: CommandContext) => Promise<OpenTokenStore>;
|
|
159
|
+
|
|
160
|
+
/** `open` and `clock` are the seams a test drives; the shipped command opens the app's database. */
|
|
161
|
+
export const tokenCommandOver = (open: OpenToken, clock: Clock = systemClock): CliCommand => ({
|
|
162
|
+
spec: tokenSpec,
|
|
163
|
+
async run(ctx: CommandContext): Promise<CommandResult> {
|
|
164
|
+
const root = requireAppRoot('token', ctx.cwd).dir;
|
|
165
|
+
const sub = ctx.args.subcommand;
|
|
166
|
+
if (sub === 'create') return create(ctx, open, root, clock);
|
|
167
|
+
if (sub === 'list') return list(ctx, open, root);
|
|
168
|
+
if (sub === 'revoke') return revoke(ctx, open, root, clock);
|
|
169
|
+
throw plannedSubcommand('token', sub ?? 'grant');
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
export const tokenCommand: CliCommand = tokenCommandOver(openAppTokenStore);
|
package/src/cmd-upgrade.ts
CHANGED
|
@@ -146,7 +146,14 @@ async function withHeartbeat<T>(
|
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
|
|
149
|
+
/** `YYYY-MM-DD` in UTC: the day a rebaselined floor's `why` names. */
|
|
150
|
+
const utcDay = (at: Date): string => at.toISOString().slice(0, 10);
|
|
151
|
+
|
|
152
|
+
export const createUpgradeCommand = (
|
|
153
|
+
write: (line: string) => void,
|
|
154
|
+
/** The clock a rebaselined coverage floor is dated by; a test pins it. */
|
|
155
|
+
now: () => Date = () => new Date(),
|
|
156
|
+
): CliCommand => ({
|
|
150
157
|
spec: upgradeSpec,
|
|
151
158
|
async run(ctx: CommandContext): Promise<CommandResult> {
|
|
152
159
|
const { dir: root, app } = await findUpgradeRoot(ctx.cwd);
|
|
@@ -261,7 +268,17 @@ export const createUpgradeCommand = (write: (line: string) => void): CliCommand
|
|
|
261
268
|
});
|
|
262
269
|
return { gate: undefined, scripts: ran };
|
|
263
270
|
}
|
|
264
|
-
|
|
271
|
+
// Bun 1.4.4 counted functions differently: a hop that moves the floor re-measures coverage.
|
|
272
|
+
const bunMoved =
|
|
273
|
+
bunRange === undefined || bunRange === bunFrom
|
|
274
|
+
? undefined
|
|
275
|
+
: { release: hop.to, bunFrom, bunTo: bunRange, today: utcDay(now()) };
|
|
276
|
+
const hopGate = await runHopGate({
|
|
277
|
+
runner: ctx.runner,
|
|
278
|
+
root,
|
|
279
|
+
onStage: stageReached,
|
|
280
|
+
...(bunMoved === undefined ? {} : { bunMoved }),
|
|
281
|
+
});
|
|
265
282
|
return { gate: hopGate, scripts: [] };
|
|
266
283
|
});
|
|
267
284
|
|
package/src/cmd-verify-spec.ts
CHANGED
|
@@ -5,14 +5,17 @@ import { DEFAULT_BASE_HELP } from './affected-base';
|
|
|
5
5
|
import type { CommandSpec } from './parse';
|
|
6
6
|
import { BUDGET_RULE, WORKER_BYTES, WORKER_CEILING, WORKER_FLOOR } from './test-workers';
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
|
|
8
|
+
/**
|
|
9
|
+
* `run` is the gate (and what a bare `x verify` means); `merge` folds CI parts into its verdict;
|
|
10
|
+
* `plan` cuts the gate into those parts, as the matrix a workflow reads.
|
|
11
|
+
*/
|
|
12
|
+
export const VERIFY_SUBCOMMANDS = ['run', 'merge', 'plan'] as const;
|
|
10
13
|
|
|
11
14
|
export const verifySpec: CommandSpec = {
|
|
12
15
|
name: 'verify',
|
|
13
16
|
summary: 'the gate: typecheck, lint, boundaries, all tests, drift, contract, budgets',
|
|
14
17
|
usage:
|
|
15
|
-
'x verify [--only <step>[,<step>…] [--shard i/n [--timings file]] | --changed [--base <ref>] [--dirty]] [--workers N] [--isolate] [--json] · x verify merge <part.json…> [--json]',
|
|
18
|
+
'x verify [--only <step>[,<step>…] [--shard i/n [--timings file]] | --changed [--base <ref>] [--dirty]] [--workers N] [--isolate] [--json] · x verify merge <part.json…> [--json] · x verify plan [--parts n] [--json]',
|
|
16
19
|
requiresApp: true,
|
|
17
20
|
subcommands: VERIFY_SUBCOMMANDS,
|
|
18
21
|
defaultSubcommand: 'run',
|
|
@@ -74,5 +77,12 @@ export const verifySpec: CommandSpec = {
|
|
|
74
77
|
summary:
|
|
75
78
|
'a fresh global per test file (bun test --isolate) — off by default since 22.7; x.verify.json "isolate": true makes it the repo default',
|
|
76
79
|
},
|
|
80
|
+
{
|
|
81
|
+
name: 'parts',
|
|
82
|
+
type: 'string',
|
|
83
|
+
subcommands: ['plan'],
|
|
84
|
+
summary:
|
|
85
|
+
'runners to cut the gate into: 1, or 4 to 64 (default 4) — data.matrix is a GitHub strategy.matrix, each row an `x verify --only … [--shard i/n]`',
|
|
86
|
+
},
|
|
77
87
|
],
|
|
78
88
|
};
|
package/src/cmd-verify.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { readVerifyFloor } from './verify-floor';
|
|
|
26
26
|
import type { VerifyPart } from './verify-merge';
|
|
27
27
|
import { coverageRiders, mergeParts, parsePart, VerifyMergeInputError } from './verify-merge';
|
|
28
28
|
import { measurePace } from './verify-pace';
|
|
29
|
+
import { verifyPlanCommand } from './verify-plan';
|
|
29
30
|
import { withVerifyProgress } from './verify-progress';
|
|
30
31
|
import { runVerify } from './verify-run';
|
|
31
32
|
import type { ShardSpec, Timings } from './verify-shard';
|
|
@@ -45,6 +46,7 @@ export const verifyCommand: CliCommand = {
|
|
|
45
46
|
async run(ctx: CommandContext): Promise<CommandResult> {
|
|
46
47
|
const root = requireAppRoot('verify', ctx.cwd).dir;
|
|
47
48
|
if (ctx.args.subcommand === 'merge') return mergeCommand(root, ctx.args.positionals, ctx.cwd);
|
|
49
|
+
if (ctx.args.subcommand === 'plan') return verifyPlanCommand(ctx.args);
|
|
48
50
|
// Every reader before the run: an unrunnable flag must be refused in milliseconds, not after
|
|
49
51
|
// `tsc -b` has spent fourteen seconds on a run the caller cannot use.
|
|
50
52
|
const workers = readWorkers(ctx.args);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The resolved `AppConfig` as JSON an operator may paste into an issue: every credential-named key
|
|
2
|
+
// and every `secret()` value replaced, a URL's password cut out of its userinfo. The key rule is
|
|
3
|
+
// core's `isRedactedKey` — the logger's — so a field the log line hides is hidden here too.
|
|
4
|
+
|
|
5
|
+
import { isRedactedKey, isSecret, REDACTED } from '@ultimat3/core';
|
|
6
|
+
import type { JsonValue } from './output';
|
|
7
|
+
|
|
8
|
+
/** `scheme://user:password@host` → `scheme://user:[redacted]@host`. The user stays: it is no secret. */
|
|
9
|
+
const USERINFO_PASSWORD = /^([a-z][a-z0-9+.-]*:\/\/[^:/@\s]*):[^@/\s]*@/i;
|
|
10
|
+
|
|
11
|
+
/** Past this depth a config is not data an operator wrote; the walk stops rather than recurse. */
|
|
12
|
+
const MAX_DEPTH = 16;
|
|
13
|
+
|
|
14
|
+
export function redactConfigValue(value: unknown, depth = 0): JsonValue {
|
|
15
|
+
if (isSecret(value)) return REDACTED;
|
|
16
|
+
if (value === null || value === undefined) return null;
|
|
17
|
+
if (typeof value === 'string') return value.replace(USERINFO_PASSWORD, `$1:${REDACTED}@`);
|
|
18
|
+
if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);
|
|
19
|
+
if (typeof value === 'boolean') return value;
|
|
20
|
+
// A config may carry a callback (a `health` probe, a `resolve` hook): named, never its source.
|
|
21
|
+
if (typeof value === 'function') return '[function]';
|
|
22
|
+
if (typeof value === 'bigint' || typeof value === 'symbol') return String(value);
|
|
23
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString();
|
|
24
|
+
if (value instanceof RegExp) return String(value);
|
|
25
|
+
if (depth >= MAX_DEPTH) return '[nested too deep]';
|
|
26
|
+
if (Array.isArray(value)) return value.map((item: unknown) => redactConfigValue(item, depth + 1));
|
|
27
|
+
const out: Record<string, JsonValue> = {};
|
|
28
|
+
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
|
|
29
|
+
// `defineProperty`, never `out[key] =`: a config key is the app's string, and `__proto__`
|
|
30
|
+
// assigned would re-prototype the record instead of adding a field.
|
|
31
|
+
Object.defineProperty(out, key, {
|
|
32
|
+
value: isRedactedKey(key) ? REDACTED : redactConfigValue(item, depth + 1),
|
|
33
|
+
enumerable: true,
|
|
34
|
+
writable: true,
|
|
35
|
+
configurable: true,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
package/src/coverage-floor.ts
CHANGED
|
@@ -188,14 +188,14 @@ export async function measureCoverage(
|
|
|
188
188
|
}
|
|
189
189
|
|
|
190
190
|
/** One decimal, rounded DOWN: a printed number never claims more than was measured. */
|
|
191
|
-
const shown = (value: number): string => (Math.floor(value * 10) / 10).toFixed(1);
|
|
191
|
+
export const shown = (value: number): string => (Math.floor(value * 10) / 10).toFixed(1);
|
|
192
192
|
|
|
193
193
|
/**
|
|
194
194
|
* The floor a measured number supports: the bar once it clears it, the whole number under it
|
|
195
195
|
* below — up to a point of room, so one uncovered line in an unrelated file is not a red gate,
|
|
196
196
|
* and less than `FLOOR_SLACK`, so the floor it writes is never stale the moment it is written.
|
|
197
197
|
*/
|
|
198
|
-
const floorFor = (measured: number): number =>
|
|
198
|
+
export const floorFor = (measured: number): number =>
|
|
199
199
|
measured >= COVERAGE_BAR ? COVERAGE_BAR : Math.floor(measured);
|
|
200
200
|
|
|
201
201
|
const WHY_PLACEHOLDER = '<what is uncovered and who closes it>';
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// `x dev`'s answer to an embedded data directory that will not open: set it aside under a dated
|
|
2
|
+
// suffix, boot a fresh one, and say so (`X_DEV_DATA_UNOPENABLE`, a notice, never a refusal). The
|
|
3
|
+
// boot used to fail with `X_DB_UNAVAILABLE`, whose fix was to run the command that had just failed.
|
|
4
|
+
|
|
5
|
+
// why: Bun ships no rename or exists API for a directory.
|
|
6
|
+
import { existsSync, renameSync } from 'node:fs';
|
|
7
|
+
import { renderThrowable } from '@ultimat3/core';
|
|
8
|
+
import { pgliteClient, pgliteDataDir, sql } from '@ultimat3/db';
|
|
9
|
+
import type { Finding } from './output';
|
|
10
|
+
import type { ServiceBinding } from './runtime-bindings';
|
|
11
|
+
|
|
12
|
+
/** `<dir>.unopenable-<UTC instant>`: sorts by date, and no two boots a second apart collide. */
|
|
13
|
+
export const asideName = (dataDir: string, now: Date): string =>
|
|
14
|
+
`${dataDir}.unopenable-${now
|
|
15
|
+
.toISOString()
|
|
16
|
+
.replace(/[-:]/g, '')
|
|
17
|
+
.replace(/\.\d+Z$/, 'Z')}`;
|
|
18
|
+
|
|
19
|
+
/** Whether PGlite opens `dataDir` and answers one statement. Costs a PGlite boot. */
|
|
20
|
+
export async function pgliteOpens(
|
|
21
|
+
dataDir: string,
|
|
22
|
+
extensions: () => Promise<readonly string[]>,
|
|
23
|
+
): Promise<boolean> {
|
|
24
|
+
const client = pgliteClient({ dataDir, extensions });
|
|
25
|
+
try {
|
|
26
|
+
await client.query(sql`select 1`);
|
|
27
|
+
return true;
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
} finally {
|
|
31
|
+
await client.close().catch(() => undefined);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface StartOverOptions<T> {
|
|
36
|
+
/** The boot: `startServices`, run a second time over the fresh directory. */
|
|
37
|
+
readonly start: () => Promise<T>;
|
|
38
|
+
/** Asked only after `start` failed: does the directory open on its own? */
|
|
39
|
+
readonly opens: (dataDir: string) => Promise<boolean>;
|
|
40
|
+
readonly now: () => Date;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* `start()`, and when it fails over an embedded directory that exists and does not open by itself,
|
|
45
|
+
* that directory renamed aside and `start()` once more. Every other failure — an external database,
|
|
46
|
+
* a first boot with nothing on disk, a directory that opens — is rethrown untouched: moving a
|
|
47
|
+
* developer's data is only ever the answer to that data being unreadable. Renamed, never deleted.
|
|
48
|
+
*/
|
|
49
|
+
export async function startOverUnopenable<T>(
|
|
50
|
+
binding: ServiceBinding,
|
|
51
|
+
options: StartOverOptions<T>,
|
|
52
|
+
): Promise<{ readonly value: T; readonly notice?: Finding }> {
|
|
53
|
+
try {
|
|
54
|
+
return { value: await options.start() };
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (binding.mode !== 'embedded') throw error;
|
|
57
|
+
const dataDir = pgliteDataDir(binding.url);
|
|
58
|
+
if (!existsSync(dataDir) || (await options.opens(dataDir))) throw error;
|
|
59
|
+
const aside = asideName(dataDir, options.now());
|
|
60
|
+
renameSync(dataDir, aside);
|
|
61
|
+
const notice: Finding = {
|
|
62
|
+
code: 'X_DEV_DATA_UNOPENABLE',
|
|
63
|
+
cause: `the embedded database at ${dataDir} would not open (${renderThrowable(error)}), so it was moved to ${aside} and this boot started an empty one — the app's tables and rows are in the moved directory, not in this database`,
|
|
64
|
+
fix: 'x db migrate',
|
|
65
|
+
meta: { dataDir, aside },
|
|
66
|
+
};
|
|
67
|
+
return { value: await options.start(), notice };
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/dev-boot.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { devShellStyle } from '@ultimat3/admin/dev';
|
|
7
7
|
import type { Role } from '@ultimat3/core';
|
|
8
|
-
import { subscribe, subscribeSemconvMetrics } from '@ultimat3/core';
|
|
8
|
+
import { subscribe, subscribeSemconvMetrics, systemClock } from '@ultimat3/core';
|
|
9
9
|
import type { OverlayNotice, RequestContext } from '@ultimat3/http';
|
|
10
10
|
import { asCtx, subscribeRequestTimings } from '@ultimat3/http';
|
|
11
11
|
import { loadSignInPath } from './app-auth';
|
|
@@ -13,6 +13,7 @@ import { loadAppConfig } from './app-config-load';
|
|
|
13
13
|
import type { StalePin } from './app-reload-graph';
|
|
14
14
|
import { enableReloadTracking } from './app-reload-graph';
|
|
15
15
|
import { loadAppRuntime } from './app-runtime';
|
|
16
|
+
import { pgliteOpens, startOverUnopenable } from './dev-boot-data-dir';
|
|
16
17
|
import type { DevDashboardInput, DevStatus } from './dev-dashboard';
|
|
17
18
|
import { devPanels } from './dev-dashboard';
|
|
18
19
|
import { createInvalidationLog } from './dev-dashboard-invalidations';
|
|
@@ -25,6 +26,7 @@ import { createTraceRecorder } from './dev-traces';
|
|
|
25
26
|
import { watchTree } from './dev-watch-tree';
|
|
26
27
|
import { armFailureCapture } from './failure-capture-boot';
|
|
27
28
|
import { FRAME_STYLE } from './island-harness';
|
|
29
|
+
import { appExtensions } from './migration-extensions';
|
|
28
30
|
import type { Finding } from './output';
|
|
29
31
|
import { plainRoutes } from './plain-routes';
|
|
30
32
|
import type { RunningRoles } from './role-start';
|
|
@@ -118,22 +120,31 @@ export async function startDev(options: StartDevOptions): Promise<DevServer> {
|
|
|
118
120
|
// actions wrote to two different places in `x dev` and to one in production.
|
|
119
121
|
const appRuntime = await loadAppRuntime(options.root);
|
|
120
122
|
// The roles decide whether this boot waits for the bus, exactly as a container's one role does.
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
123
|
+
// An embedded data directory that will not open is set aside and the boot runs again over an
|
|
124
|
+
// empty one — the developer is told where it went (`dev-boot-data-dir.ts`).
|
|
125
|
+
const started = await startOverUnopenable(resolved.db, {
|
|
126
|
+
start: () =>
|
|
127
|
+
startServices(
|
|
128
|
+
resolved,
|
|
129
|
+
env,
|
|
130
|
+
appRuntime,
|
|
131
|
+
'apply',
|
|
132
|
+
options.roles ?? DEV_ROLES,
|
|
133
|
+
// Every role in one process: a bus that is away must not take the pages down with it.
|
|
134
|
+
true,
|
|
135
|
+
),
|
|
136
|
+
opens: (dataDir) => pgliteOpens(dataDir, () => appExtensions(options.root)),
|
|
137
|
+
now: () => (appRuntime?.clock ?? systemClock).now(),
|
|
138
|
+
});
|
|
139
|
+
const runtime: RunningServices = started.value;
|
|
140
|
+
const notices = started.notice === undefined ? [] : [started.notice];
|
|
130
141
|
// The events binding the boot line reports is the bus the runtime chose, read off it.
|
|
131
142
|
const services = withRealtimeEvents(resolved, env, appRuntime?.transport !== undefined);
|
|
132
143
|
// `serve.ts`'s `releaseBoot` shape: everything acquired from here on is released, newest first,
|
|
133
144
|
// if the boot throws — a failed `x dev` left PGlite holding `.x/pgdata` for the retry to meet.
|
|
134
145
|
const acquired: (() => void | Promise<void>)[] = [() => runtime.stop()];
|
|
135
146
|
try {
|
|
136
|
-
return await bootDev(options, services, runtime, acquired, appRuntime);
|
|
147
|
+
return await bootDev(options, services, runtime, acquired, appRuntime, notices);
|
|
137
148
|
} catch (error) {
|
|
138
149
|
await releaseBoot(acquired);
|
|
139
150
|
throw error;
|
|
@@ -146,6 +157,8 @@ async function bootDev(
|
|
|
146
157
|
runtime: RunningServices,
|
|
147
158
|
acquired: (() => void | Promise<void>)[],
|
|
148
159
|
appRuntime: RuntimeOverrides | undefined,
|
|
160
|
+
/** What the boot did on the developer's behalf and must say: a set-aside data directory. */
|
|
161
|
+
notices: readonly Finding[],
|
|
149
162
|
): Promise<DevServer> {
|
|
150
163
|
// Installed before the app loads, so a span opened during registration is already recorded.
|
|
151
164
|
// Tracing is always on in the framework and free until something subscribes to `span.end`;
|
|
@@ -321,8 +334,8 @@ async function bootDev(
|
|
|
321
334
|
get findings(): readonly Finding[] {
|
|
322
335
|
const loops = statements.repeats().map(loopFacts).map(loopFinding);
|
|
323
336
|
return state.reloadFinding === undefined
|
|
324
|
-
? [...state.appFindings, ...loops]
|
|
325
|
-
: [...state.appFindings, state.reloadFinding, ...loops];
|
|
337
|
+
? [...notices, ...state.appFindings, ...loops]
|
|
338
|
+
: [...notices, ...state.appFindings, state.reloadFinding, ...loops];
|
|
326
339
|
},
|
|
327
340
|
running,
|
|
328
341
|
runtime,
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// `x doctor`'s env-name check: an app's own variable — declared in `envSchema` or sealed in the
|
|
2
|
+
// secrets file — on a name the framework reads as a switch or for itself (`FRAMEWORK_ENV`). An
|
|
3
|
+
// adapter's settings (`S3_BUCKET`, `SMTP_URL`) are the contract: declaring them is the configuring.
|
|
4
|
+
|
|
5
|
+
// why: Bun exposes no path-join primitive; Bun.file takes one already joined.
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import type { FrameworkEnvName } from '@ultimat3/core';
|
|
8
|
+
import {
|
|
9
|
+
APP_CONFIG_FILE,
|
|
10
|
+
ERROR_DOCS_URL,
|
|
11
|
+
findMasterKey,
|
|
12
|
+
frameworkEnvEntry,
|
|
13
|
+
readSecretsFile,
|
|
14
|
+
secretsFileExists,
|
|
15
|
+
} from '@ultimat3/core';
|
|
16
|
+
import { ENV_SCHEMA_EXPORT, loadEnvSchema } from './app-env';
|
|
17
|
+
import type { Finding } from './output';
|
|
18
|
+
|
|
19
|
+
/** Where the app names its variables: what it declared, and what it sealed. */
|
|
20
|
+
export interface AppEnvNamesFact {
|
|
21
|
+
readonly declared: readonly string[];
|
|
22
|
+
/** The 1-based line of each declared key in `app.config.ts`, where the probe found one. */
|
|
23
|
+
readonly lines?: ReadonlyMap<string, number>;
|
|
24
|
+
/** Names in `secrets.enc.json`; empty when this machine has no key to open it with. */
|
|
25
|
+
readonly sealed: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const NO_APP_ENV_NAMES: AppEnvNamesFact = Object.freeze({ declared: [], sealed: [] });
|
|
29
|
+
|
|
30
|
+
export const ENV_NAME_RESERVED = 'X_ENV_NAME_RESERVED';
|
|
31
|
+
|
|
32
|
+
/** The prefix a renamed key takes: no framework entry starts with it. */
|
|
33
|
+
export const APP_ENV_PREFIX = 'APP_';
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A collision is a name the framework reads as a `switch` (its presence turns a behaviour on) or
|
|
37
|
+
* `internal` (the framework sets it, or a harness does). The deploy contract (`DATABASE_URL`,
|
|
38
|
+
* `PORT`) is what an app is meant to declare, and a `host` name is the platform's.
|
|
39
|
+
*/
|
|
40
|
+
const collides = (name: string): FrameworkEnvName | undefined => {
|
|
41
|
+
const entry = frameworkEnvEntry(name);
|
|
42
|
+
return entry !== undefined && (entry.use === 'switch' || entry.use === 'internal')
|
|
43
|
+
? entry
|
|
44
|
+
: undefined;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const what = (name: string, entry: FrameworkEnvName): string =>
|
|
48
|
+
entry.use === 'switch'
|
|
49
|
+
? `@ultimat3/${entry.owner} also reads ${name}: set, it switches that package's behaviour on with this value`
|
|
50
|
+
: `${entry.prefix === true ? `every ${entry.name}* name` : name} is @ultimat3/${entry.owner}'s own, set by the framework or its harness`;
|
|
51
|
+
|
|
52
|
+
/** The rule, pure. One finding per name, a sealed name and a declared one apart. */
|
|
53
|
+
export function reservedEnvFindings(fact: AppEnvNamesFact): readonly Finding[] {
|
|
54
|
+
const findings: Finding[] = [];
|
|
55
|
+
for (const name of [...new Set(fact.declared)].sort()) {
|
|
56
|
+
const entry = collides(name);
|
|
57
|
+
if (entry === undefined) continue;
|
|
58
|
+
findings.push({
|
|
59
|
+
code: ENV_NAME_RESERVED,
|
|
60
|
+
cause: `${ENV_SCHEMA_EXPORT} in ${APP_CONFIG_FILE} declares ${name}, and ${what(name, entry)}`,
|
|
61
|
+
// A rename, never an allow: a name meant for the framework needs no app declaration at all.
|
|
62
|
+
fix: `edit ${APP_CONFIG_FILE}:${fact.lines?.get(name) ?? 1} — rename ${name} in ${ENV_SCHEMA_EXPORT} to ${APP_ENV_PREFIX}${name} (or delete it where the value is meant for @ultimat3/${entry.owner}); then: x env example --json && x doctor --json`,
|
|
63
|
+
docs: ERROR_DOCS_URL,
|
|
64
|
+
at: APP_CONFIG_FILE,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
for (const name of [...new Set(fact.sealed)].sort()) {
|
|
68
|
+
const entry = collides(name);
|
|
69
|
+
if (entry === undefined) continue;
|
|
70
|
+
findings.push({
|
|
71
|
+
code: ENV_NAME_RESERVED,
|
|
72
|
+
cause: `secrets.enc.json seals ${name}, and ${what(name, entry)}`,
|
|
73
|
+
fix: `x secrets edit # rename ${name} to ${APP_ENV_PREFIX}${name} unless the value is meant for @ultimat3/${entry.owner}; then: x doctor --json`,
|
|
74
|
+
docs: ERROR_DOCS_URL,
|
|
75
|
+
at: 'secrets.enc.json',
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return findings;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The I/O half. A config that will not import, or a secrets file this key cannot open, is another
|
|
83
|
+
* probe's finding (`snapshots`, `sealedKeys`); here it is simply nothing to judge.
|
|
84
|
+
*/
|
|
85
|
+
export async function appEnvNamesProbe(
|
|
86
|
+
root: string,
|
|
87
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
88
|
+
): Promise<AppEnvNamesFact> {
|
|
89
|
+
const declared = await loadEnvSchema(root).then(
|
|
90
|
+
(schema) => Object.keys(schema ?? {}),
|
|
91
|
+
() => [],
|
|
92
|
+
);
|
|
93
|
+
const config = await Bun.file(join(root, APP_CONFIG_FILE))
|
|
94
|
+
.text()
|
|
95
|
+
.catch(() => '');
|
|
96
|
+
const lines = new Map<string, number>();
|
|
97
|
+
// A key that is not a plain identifier is never a framework name, and never a regex here.
|
|
98
|
+
for (const name of declared.filter((key) => /^[A-Za-z_]\w*$/.test(key))) {
|
|
99
|
+
const at = config.search(new RegExp(`^\\s*['"]?${name}['"]?\\s*:`, 'm'));
|
|
100
|
+
if (at >= 0) lines.set(name, config.slice(0, at).split('\n').length);
|
|
101
|
+
}
|
|
102
|
+
const key = findMasterKey(root, { ...env });
|
|
103
|
+
const sealed =
|
|
104
|
+
key === undefined || !secretsFileExists(root)
|
|
105
|
+
? []
|
|
106
|
+
: await readSecretsFile(root, key).then(
|
|
107
|
+
(values) => Object.keys(values),
|
|
108
|
+
() => [],
|
|
109
|
+
);
|
|
110
|
+
return { declared, lines, sealed };
|
|
111
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// `x doctor`'s floor check: a gate step that applies to this app — its suite files exist, its
|
|
2
|
+
// input is committed — and that `x.verify.json`'s `steps` does not hold. Unfloored, deleting the
|
|
3
|
+
// suite turns the step from green into skipped-and-green; floored, it is `X_VERIFY_SUITE_VANISHED`.
|
|
4
|
+
|
|
5
|
+
import { ERROR_DOCS_URL } from '@ultimat3/core';
|
|
6
|
+
import type { Runner } from './exec';
|
|
7
|
+
import type { Finding } from './output';
|
|
8
|
+
import { quoteArg } from './shell-quote';
|
|
9
|
+
import { VERIFY_STEPS } from './verify-checks';
|
|
10
|
+
import { floorRequires, readVerifyFloor, VERIFY_FLOOR_FILE } from './verify-floor';
|
|
11
|
+
import type { VerifyStep, VerifyStepName } from './verify-step';
|
|
12
|
+
|
|
13
|
+
export const STEP_UNFLOORED = 'X_VERIFY_STEP_UNFLOORED';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Never proposed. `x new` writes `e2e` as an `e2eTest` that skips until the app registers a
|
|
17
|
+
* browser driver, so its file exists while the step runs nothing: flooring it reds a fresh app's
|
|
18
|
+
* gate on the scaffold's own placeholder (`scaffold-verify-floor.ts`). The gate's summary already
|
|
19
|
+
* names it as skipped; the floor is the app's call once a driver makes it run.
|
|
20
|
+
*/
|
|
21
|
+
const NEVER_PROPOSED: ReadonlySet<VerifyStepName> = new Set<VerifyStepName>(['e2e']);
|
|
22
|
+
|
|
23
|
+
/** `applies` reads the disk alone: a step that spawned here would be asking the wrong question. */
|
|
24
|
+
const noRunner: Runner = async (command) => ({
|
|
25
|
+
command,
|
|
26
|
+
code: 1,
|
|
27
|
+
ok: false,
|
|
28
|
+
stdout: '',
|
|
29
|
+
stderr: '',
|
|
30
|
+
durationMs: 0,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** The I/O half: each step with an `applies`, asked of this root, that the floor does not hold. */
|
|
34
|
+
export async function unflooredStepsProbe(
|
|
35
|
+
root: string,
|
|
36
|
+
steps: readonly VerifyStep[] = VERIFY_STEPS,
|
|
37
|
+
): Promise<readonly VerifyStepName[]> {
|
|
38
|
+
const floor = await readVerifyFloor(root);
|
|
39
|
+
const unfloored: VerifyStepName[] = [];
|
|
40
|
+
for (const step of steps) {
|
|
41
|
+
if (step.applies === undefined || NEVER_PROPOSED.has(step.name)) continue;
|
|
42
|
+
if (floorRequires(floor, step.name)) continue;
|
|
43
|
+
const applies = await step.applies({ root, runner: noRunner }).catch(() => false);
|
|
44
|
+
if (applies) unfloored.push(step.name);
|
|
45
|
+
}
|
|
46
|
+
return unfloored;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The rule, pure: one finding naming every unfloored step, run-first, so the edit is proven. */
|
|
50
|
+
export function unflooredStepFindings(steps: readonly VerifyStepName[]): readonly Finding[] {
|
|
51
|
+
if (steps.length === 0) return [];
|
|
52
|
+
return [
|
|
53
|
+
{
|
|
54
|
+
code: STEP_UNFLOORED,
|
|
55
|
+
cause: `${steps.join(', ')} ${steps.length === 1 ? 'applies' : 'apply'} to this app and ${VERIFY_FLOOR_FILE} "steps" does not hold ${steps.length === 1 ? 'it' : 'them'}, so a deleted suite reads as skipped and the gate stays green`,
|
|
56
|
+
// Run first: a step that skips here would red the gate the moment the floor names it.
|
|
57
|
+
fix: `x verify --only ${quoteArg(steps.join(','))} --json # then add each step that passed, not skipped, to "steps" in ${VERIFY_FLOOR_FILE}`,
|
|
58
|
+
docs: ERROR_DOCS_URL,
|
|
59
|
+
at: VERIFY_FLOOR_FILE,
|
|
60
|
+
},
|
|
61
|
+
];
|
|
62
|
+
}
|