@ultimat3/cli 31.15.0 → 31.16.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 +1 -1
- package/package.json +29 -29
- package/src/cmd-doctor.ts +47 -37
- package/src/cmd-exercise.ts +14 -1
- package/src/cmd-upgrade.ts +19 -2
- package/src/coverage-floor.ts +2 -2
- 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.ts +5 -0
- 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/mcp-errors.ts +10 -0
- package/src/messages-upgrade.ts +13 -0
- package/src/messages.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 +68 -25
- package/src/upgrade-guards.ts +159 -0
- package/src/upgrade-report.ts +29 -1
- package/src/verify-checks.ts +3 -1
- package/src/verify-floor.ts +13 -0
- package/wiki/CLI-Reference.md +26 -3
- package/wiki/Configuration.md +16 -0
- package/wiki/Testing.md +64 -2
- package/wiki/Upgrading.md +3 -0
|
@@ -1,14 +1,28 @@
|
|
|
1
|
-
// Single responsibility: `x doctor`'s row-security
|
|
2
|
-
// `database.rowSecurity` on, is the role
|
|
3
|
-
//
|
|
1
|
+
// Single responsibility: `x doctor`'s row-security questions, asked without booting — with
|
|
2
|
+
// `database.rowSecurity` on, is the serving role one Postgres applies policies to (the boot's own
|
|
3
|
+
// `X_DB_ROW_SECURITY_BYPASSED`); with it off, does raw `sql` reach a tenant table the policy would guard.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
// why: Bun exposes no path-join primitive; Bun.file takes one already joined.
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import {
|
|
8
|
+
APP_CONFIG_FILE,
|
|
9
|
+
ERROR_DOCS_URL,
|
|
10
|
+
endOfLiteral,
|
|
11
|
+
maskLiterals,
|
|
12
|
+
resolveRole,
|
|
13
|
+
stripComments,
|
|
14
|
+
} from '@ultimat3/core';
|
|
6
15
|
import { assertRowSecurityBinds, DbError, postgresClient } from '@ultimat3/db';
|
|
16
|
+
import { describeTenancy } from '@ultimat3/entity';
|
|
17
|
+
import { statementTables } from '@ultimat3/testing';
|
|
7
18
|
import { loadAppConfig } from './app-config-load';
|
|
19
|
+
import { loadApp } from './app-load';
|
|
8
20
|
import type { Finding } from './output';
|
|
9
21
|
import { findingFrom } from './output';
|
|
10
22
|
import { rowSecurityDeclared } from './row-security-boot';
|
|
11
23
|
|
|
24
|
+
import { eachSourceFile } from './source-files';
|
|
25
|
+
|
|
12
26
|
/**
|
|
13
27
|
* External databases only: an embedded one serves as `x_app` by construction (`serveAsAppRole`).
|
|
14
28
|
* An unreachable server is `database()`'s finding to make, so only the exemption is reported here.
|
|
@@ -38,3 +52,104 @@ export async function rowSecurityProbe(
|
|
|
38
52
|
await client.close();
|
|
39
53
|
}
|
|
40
54
|
}
|
|
55
|
+
|
|
56
|
+
export const ROW_SECURITY_OFF = 'X_DB_ROW_SECURITY_OFF';
|
|
57
|
+
|
|
58
|
+
/** One raw `sql\`…\`` statement in the app's source naming a tenant table. */
|
|
59
|
+
export interface RawTenantSql {
|
|
60
|
+
readonly at: string;
|
|
61
|
+
readonly table: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The other question: with `database.rowSecurity` OFF, does raw SQL reach a tenant table? */
|
|
65
|
+
export interface RowSecurityOffFact {
|
|
66
|
+
readonly declared: boolean;
|
|
67
|
+
readonly touches: readonly RawTenantSql[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The repository scopes every entity read by its tenant column; a raw `sql\`…\`` statement is
|
|
72
|
+
* outside that scope, and only the database's own policy (`database.rowSecurity`) holds there. Off
|
|
73
|
+
* with no raw tenant SQL is a decision with nothing riding on it, and is not reported.
|
|
74
|
+
*/
|
|
75
|
+
export function rowSecurityOffFindings(fact: RowSecurityOffFact): readonly Finding[] {
|
|
76
|
+
if (fact.declared || fact.touches.length === 0) return [];
|
|
77
|
+
const tables = [...new Set(fact.touches.map((touch) => touch.table))].sort();
|
|
78
|
+
const sites = fact.touches.slice(0, 5).map((touch) => `${touch.at} (${touch.table})`);
|
|
79
|
+
return [
|
|
80
|
+
{
|
|
81
|
+
code: ROW_SECURITY_OFF,
|
|
82
|
+
cause: `database.rowSecurity is off and ${fact.touches.length} raw sql statement(s) name tenant table(s) ${tables.join(', ')} — ${sites.join(', ')}: the repository's tenant scope does not reach a raw statement, so one missing tenant predicate reads every tenant's rows`,
|
|
83
|
+
fix: `database: { rowSecurity: true } # in defineConfig, ${APP_CONFIG_FILE}; then: x db gen "row security" --json && x db migrate --json && x doctor --json`,
|
|
84
|
+
docs: ERROR_DOCS_URL,
|
|
85
|
+
at: APP_CONFIG_FILE,
|
|
86
|
+
},
|
|
87
|
+
];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A tagged `sql` template — `@ultimat3/db`'s, Bun's own `Bun.sql`, or a handle's `tx.sql` — found
|
|
92
|
+
* in the masked text so a quoted or commented one is not one; `mysql\`` is a longer name, not it.
|
|
93
|
+
*/
|
|
94
|
+
const SQL_TAG = /(?<![\w$])sql\s*`/g;
|
|
95
|
+
/** `raw('…')` (a statement) and `identifier('…')` (a table name): SQL built outside a template. */
|
|
96
|
+
const SQL_CALL = /(?<![\w$.])(raw|identifier)\s*\(\s*/g;
|
|
97
|
+
|
|
98
|
+
/** The rule's scan, pure: each raw `sql` template or call in `source` naming one of `tables`. */
|
|
99
|
+
export function rawTenantSql(
|
|
100
|
+
path: string,
|
|
101
|
+
source: string,
|
|
102
|
+
tables: ReadonlySet<string>,
|
|
103
|
+
): readonly RawTenantSql[] {
|
|
104
|
+
if (tables.size === 0 || !/sql|raw|identifier/.test(source)) return [];
|
|
105
|
+
const masked = maskLiterals(source);
|
|
106
|
+
const text = stripComments(source);
|
|
107
|
+
const found: RawTenantSql[] = [];
|
|
108
|
+
const report = (index: number, named: readonly string[]) => {
|
|
109
|
+
const line = text.slice(0, index).split('\n').length;
|
|
110
|
+
for (const table of new Set(named)) {
|
|
111
|
+
if (tables.has(table)) found.push({ at: `${path}:${line}`, table });
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
// `scope` is masked text or a template's own body, `offset` where it starts in `text`.
|
|
115
|
+
const calls = (scope: string, offset: number) => {
|
|
116
|
+
for (const call of scope.matchAll(SQL_CALL)) {
|
|
117
|
+
const open = offset + call.index + call[0].length;
|
|
118
|
+
const quote = text[open];
|
|
119
|
+
if (quote !== "'" && quote !== '"' && quote !== '`') continue;
|
|
120
|
+
const literal = text.slice(open + 1, endOfLiteral(text, open) - 1);
|
|
121
|
+
const named = call[1] === 'raw' ? statementTables(literal) : [literal.toLowerCase()];
|
|
122
|
+
report(offset + call.index, named);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
for (const tag of masked.matchAll(SQL_TAG)) {
|
|
126
|
+
const open = tag.index + tag[0].length - 1;
|
|
127
|
+
const body = text.slice(open + 1, endOfLiteral(text, open) - 1);
|
|
128
|
+
report(tag.index, statementTables(body));
|
|
129
|
+
// Masking blanks a template's `${…}` too: `${identifier('posts')}` is read off the body.
|
|
130
|
+
calls(body, open + 1);
|
|
131
|
+
}
|
|
132
|
+
calls(masked, 0);
|
|
133
|
+
return found;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Migrations and seeds are SQL by design; tests are fixtures. */
|
|
137
|
+
const NOT_JUDGED = /(?:^|\/)(?:migrations|seeds?)\/|\.test\.tsx?$|\.d\.ts$/;
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The I/O half: the flag, and the app's raw tenant SQL. An app that will not load declares no
|
|
141
|
+
* tenant table here — `snapshots()` already reports why it will not load.
|
|
142
|
+
*/
|
|
143
|
+
export async function rowSecurityOffProbe(root: string): Promise<RowSecurityOffFact> {
|
|
144
|
+
const declared = rowSecurityDeclared(await loadAppConfig(root).catch(() => undefined));
|
|
145
|
+
if (declared) return { declared, touches: [] };
|
|
146
|
+
const loaded = await loadApp(root);
|
|
147
|
+
if (loaded.findings.length > 0) return { declared, touches: [] };
|
|
148
|
+
const tables = new Set(describeTenancy().map((tenant) => tenant.table.toLowerCase()));
|
|
149
|
+
const touches: RawTenantSql[] = [];
|
|
150
|
+
for await (const path of eachSourceFile(root)) {
|
|
151
|
+
if (NOT_JUDGED.test(path)) continue;
|
|
152
|
+
touches.push(...rawTenantSql(path, await Bun.file(join(root, path)).text(), tables));
|
|
153
|
+
}
|
|
154
|
+
return { declared, touches };
|
|
155
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// `x doctor`'s warnings: the 31.16.0 checks on how an app is held, reported BESIDE the verdict and
|
|
2
|
+
// never in it. On `main` an app that upgrades with no change keeps a green doctor
|
|
3
|
+
// (`X_BREAKING_ON_MAIN`); on `next` these move into `runDoctor`'s findings and the verdict.
|
|
4
|
+
|
|
5
|
+
import { reservedEnvFindings } from './doctor-env-reserved';
|
|
6
|
+
import { unflooredStepFindings } from './doctor-floor';
|
|
7
|
+
import { pinRangeFindings } from './doctor-pins';
|
|
8
|
+
import type { DoctorProbe } from './doctor-probe';
|
|
9
|
+
import { rowSecurityOffFindings } from './doctor-row-security';
|
|
10
|
+
import { msg } from './messages';
|
|
11
|
+
import type { CommandResult, Finding, JsonValue } from './output';
|
|
12
|
+
|
|
13
|
+
/** The probes that only warn on `main`. Asked inside an app only; outside one there is no app. */
|
|
14
|
+
export async function doctorWarnings(probe: DoctorProbe): Promise<readonly Finding[]> {
|
|
15
|
+
if (probe.root === undefined) return [];
|
|
16
|
+
return [
|
|
17
|
+
// A ranged pin moves one package on the next install.
|
|
18
|
+
...pinRangeFindings(await probe.pins()),
|
|
19
|
+
// An app's own name the framework reads too (`FRAMEWORK_ENV`).
|
|
20
|
+
...reservedEnvFindings(await probe.envNames()),
|
|
21
|
+
// Static, so asked whatever the database answered: raw tenant SQL with the policy off.
|
|
22
|
+
...rowSecurityOffFindings(await probe.rowSecurityOff()),
|
|
23
|
+
// A floor gap is the gate's blind spot, never a reason anything else is red.
|
|
24
|
+
...unflooredStepFindings(await probe.unflooredSteps()),
|
|
25
|
+
];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const asJson = (warning: Finding): JsonValue => ({
|
|
29
|
+
code: warning.code,
|
|
30
|
+
cause: warning.cause,
|
|
31
|
+
fix: warning.fix,
|
|
32
|
+
...(warning.docs === undefined ? {} : { docs: warning.docs }),
|
|
33
|
+
...(warning.at === undefined ? {} : { at: warning.at }),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The warnings, on a result `x doctor` already decided: `data.warnings[]` (`{ code, cause, fix,
|
|
38
|
+
* docs, at }`) for a machine, a line each for a person. `ok`, the summary and findings stay.
|
|
39
|
+
*/
|
|
40
|
+
export function withDoctorWarnings(
|
|
41
|
+
result: CommandResult,
|
|
42
|
+
warnings: readonly Finding[],
|
|
43
|
+
): CommandResult {
|
|
44
|
+
if (warnings.length === 0) return result;
|
|
45
|
+
const data = typeof result.data === 'object' && result.data !== null ? result.data : {};
|
|
46
|
+
return {
|
|
47
|
+
...result,
|
|
48
|
+
data: { ...(data as Record<string, JsonValue>), warnings: warnings.map(asJson) },
|
|
49
|
+
lines: [
|
|
50
|
+
...(result.lines ?? []),
|
|
51
|
+
msg('cli.doctor.warnings', { count: warnings.length }),
|
|
52
|
+
...warnings.map(({ code, cause, fix }) => msg('cli.doctor.warning', { code, cause, fix })),
|
|
53
|
+
],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The X_* codes of how an app is HELD — `x doctor`'s floor, pin, env-name and row-security checks
|
|
2
|
+
// and the `exercise` floor in `x.verify.json` — split out of `error-codes.ts` at its 500-line
|
|
3
|
+
// ceiling, as `error-codes-shot.ts` was. `error-codes.ts` folds these into the CLI's one owned union
|
|
4
|
+
// and registers them in its one call; nothing else imports this file.
|
|
5
|
+
|
|
6
|
+
/** Codes `x doctor` and the `exercise` floor declare and own. */
|
|
7
|
+
export const CLI_DOCTOR_ERROR_CODES = [
|
|
8
|
+
'X_EXERCISE_UNPROVEN_ABOVE_FLOOR',
|
|
9
|
+
'X_ENV_NAME_RESERVED',
|
|
10
|
+
'X_FRAMEWORK_PIN_RANGE',
|
|
11
|
+
'X_VERIFY_STEP_UNFLOORED',
|
|
12
|
+
'X_DB_ROW_SECURITY_OFF',
|
|
13
|
+
] as const;
|
|
14
|
+
|
|
15
|
+
export type CliDoctorErrorCode = (typeof CLI_DOCTOR_ERROR_CODES)[number];
|
|
16
|
+
|
|
17
|
+
export const CLI_DOCTOR_ERROR_TITLES: Readonly<Record<CliDoctorErrorCode, string>> = {
|
|
18
|
+
X_EXERCISE_UNPROVEN_ABOVE_FLOOR:
|
|
19
|
+
'The exercise pass left more primitives unproven than x.verify.json allows',
|
|
20
|
+
X_ENV_NAME_RESERVED: 'An app variable is named on a name the framework reads',
|
|
21
|
+
X_FRAMEWORK_PIN_RANGE: 'An @ultimat3/* dependency is pinned as a range',
|
|
22
|
+
X_VERIFY_STEP_UNFLOORED: 'A gate step applies to this app but x.verify.json does not floor it',
|
|
23
|
+
X_DB_ROW_SECURITY_OFF: 'Raw sql reaches tenant tables while database.rowSecurity is off',
|
|
24
|
+
};
|
package/src/error-codes.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
import { registerErrorCodes } from '@ultimat3/core';
|
|
6
6
|
import type { CliBoundaryErrorCode } from './error-codes-boundary';
|
|
7
7
|
import { CLI_BOUNDARY_ERROR_CODES, CLI_BOUNDARY_ERROR_TITLES } from './error-codes-boundary';
|
|
8
|
+
import type { CliDoctorErrorCode } from './error-codes-doctor';
|
|
9
|
+
import { CLI_DOCTOR_ERROR_CODES, CLI_DOCTOR_ERROR_TITLES } from './error-codes-doctor';
|
|
8
10
|
import type { CliPackageErrorCode } from './error-codes-package';
|
|
9
11
|
import { CLI_PACKAGE_ERROR_CODES, CLI_PACKAGE_ERROR_TITLES } from './error-codes-package';
|
|
10
12
|
import type { CliShotErrorCode } from './error-codes-shot';
|
|
@@ -276,6 +278,7 @@ export const CLI_BORROWED_ERROR_CODES = [
|
|
|
276
278
|
export const CLI_ERROR_CODES = [
|
|
277
279
|
...CLI_OWNED_ERROR_CODES,
|
|
278
280
|
...CLI_BOUNDARY_ERROR_CODES,
|
|
281
|
+
...CLI_DOCTOR_ERROR_CODES,
|
|
279
282
|
...CLI_PACKAGE_ERROR_CODES,
|
|
280
283
|
...CLI_SHOT_ERROR_CODES,
|
|
281
284
|
...CLI_TOOLING_ERROR_CODES,
|
|
@@ -287,6 +290,7 @@ type CliListedErrorCode = (typeof CLI_OWNED_ERROR_CODES)[number];
|
|
|
287
290
|
export type CliOwnedErrorCode =
|
|
288
291
|
| CliListedErrorCode
|
|
289
292
|
| CliBoundaryErrorCode
|
|
293
|
+
| CliDoctorErrorCode
|
|
290
294
|
| CliPackageErrorCode
|
|
291
295
|
| CliShotErrorCode
|
|
292
296
|
| CliToolingErrorCode;
|
|
@@ -475,6 +479,7 @@ registerErrorCodes(
|
|
|
475
479
|
Object.entries({
|
|
476
480
|
...CLI_ERROR_TITLES,
|
|
477
481
|
...CLI_BOUNDARY_ERROR_TITLES,
|
|
482
|
+
...CLI_DOCTOR_ERROR_TITLES,
|
|
478
483
|
...CLI_PACKAGE_ERROR_TITLES,
|
|
479
484
|
...CLI_SHOT_ERROR_TITLES,
|
|
480
485
|
...CLI_TOOLING_ERROR_TITLES,
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// The `exercise` floor applied where the verdict is: the gate step reads the `.x/exercise.json` its
|
|
2
|
+
// child just wrote and judges it (`exercise-floor-verdict.ts`), and `x upgrade` reads the same file
|
|
3
|
+
// for the figures an upgraded app's ratchet starts at. A report the run did not rewrite is never
|
|
4
|
+
// judged — a child that died before writing would otherwise be judged by the last pass's numbers.
|
|
5
|
+
|
|
6
|
+
// why: Bun ships no path joiner.
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { t } from '@ultimat3/schema';
|
|
9
|
+
import { EXERCISE_REPORT_FILE } from './exercise-findings';
|
|
10
|
+
import type { ExerciseFloor } from './exercise-floor';
|
|
11
|
+
import { EXERCISE_FIELD, unprovenTally } from './exercise-floor';
|
|
12
|
+
import type { FloorRecord } from './exercise-floor-verdict';
|
|
13
|
+
import { exerciseFloorVerdict, FLOOR_CODES, measuredStatementsMax } from './exercise-floor-verdict';
|
|
14
|
+
import { readVerifyFloor } from './verify-floor';
|
|
15
|
+
import type { VerifyStep } from './verify-step';
|
|
16
|
+
|
|
17
|
+
const PROOF = t.optional(
|
|
18
|
+
t.object({
|
|
19
|
+
verdict: t.string,
|
|
20
|
+
reason: t.optional(t.string),
|
|
21
|
+
seed: t.optional(t.object({ entity: t.string, table: t.string, cause: t.string })),
|
|
22
|
+
}),
|
|
23
|
+
);
|
|
24
|
+
const CEILING = t.optional(
|
|
25
|
+
t.object({
|
|
26
|
+
verdict: t.string,
|
|
27
|
+
statements: t.number,
|
|
28
|
+
max: t.number,
|
|
29
|
+
why: t.optional(t.string),
|
|
30
|
+
declared: t.optional(t.boolean),
|
|
31
|
+
top: t.optional(t.array(t.object({ fingerprint: t.string, count: t.number }))),
|
|
32
|
+
}),
|
|
33
|
+
);
|
|
34
|
+
const REPORT = t.object({
|
|
35
|
+
records: t.array(
|
|
36
|
+
t.object({
|
|
37
|
+
kind: t.string,
|
|
38
|
+
name: t.string,
|
|
39
|
+
outcome: t.string,
|
|
40
|
+
tenant: PROOF,
|
|
41
|
+
crash: PROOF,
|
|
42
|
+
scale: PROOF,
|
|
43
|
+
statementCeiling: CEILING,
|
|
44
|
+
}),
|
|
45
|
+
),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const reportFile = (root: string): Bun.BunFile => Bun.file(join(root, EXERCISE_REPORT_FILE));
|
|
49
|
+
|
|
50
|
+
/** The report's modification stamp, or `undefined` with no report: what "rewritten" is judged by. */
|
|
51
|
+
export const exerciseReportStamp = async (root: string): Promise<number | undefined> => {
|
|
52
|
+
const file = reportFile(root);
|
|
53
|
+
return (await file.exists()) ? file.lastModified : undefined;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** The report's records, when the file exists and parses. */
|
|
57
|
+
export async function readExerciseRecords(
|
|
58
|
+
root: string,
|
|
59
|
+
): Promise<readonly FloorRecord[] | undefined> {
|
|
60
|
+
const file = reportFile(root);
|
|
61
|
+
if (!(await file.exists())) return undefined;
|
|
62
|
+
const parsed = REPORT.safeParse(await file.json().catch(() => undefined));
|
|
63
|
+
// The schema checked every field the verdict reads; verdict strings are compared, never trusted.
|
|
64
|
+
return parsed.issues === undefined ? (parsed.value.records as readonly FloorRecord[]) : undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* `step` (the `exercise` gate step), then the floor's verdict on the report it wrote. The child
|
|
69
|
+
* judged the same report with the same function; its copies of the floor's codes are dropped so
|
|
70
|
+
* each is said once, and a child red only on them is green here when the verdict is.
|
|
71
|
+
*/
|
|
72
|
+
export function withUnprovenFloor(step: VerifyStep): VerifyStep {
|
|
73
|
+
return {
|
|
74
|
+
...step,
|
|
75
|
+
async run(ctx) {
|
|
76
|
+
// The file's own stamp before and after, never the clock: a test's frozen `Date.now` and the
|
|
77
|
+
// filesystem's real one are two clocks, and a report this run did not rewrite is not judged.
|
|
78
|
+
const before = await exerciseReportStamp(ctx.root);
|
|
79
|
+
const outcome = await step.run(ctx);
|
|
80
|
+
const after = await exerciseReportStamp(ctx.root);
|
|
81
|
+
if (after === undefined || after === before) return outcome;
|
|
82
|
+
const records = await readExerciseRecords(ctx.root);
|
|
83
|
+
if (records === undefined) return outcome;
|
|
84
|
+
const verdict = exerciseFloorVerdict(records, (await readVerifyFloor(ctx.root))?.exercise);
|
|
85
|
+
const own = outcome.findings.filter((finding) => !FLOOR_CODES.has(finding.code));
|
|
86
|
+
const onlyFloor = !outcome.ok && outcome.findings.length > 0 && own.length === 0;
|
|
87
|
+
const warnings = [...(outcome.warnings ?? []), ...verdict.warnings];
|
|
88
|
+
return {
|
|
89
|
+
...outcome,
|
|
90
|
+
ok: (outcome.ok || onlyFloor) && verdict.findings.length === 0,
|
|
91
|
+
findings: [...own, ...verdict.findings],
|
|
92
|
+
...(warnings.length === 0 ? {} : { warnings }),
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The figures `x upgrade` writes as the app's ratchet: the last pass's, or `undefined` with none. */
|
|
99
|
+
export async function measuredExerciseFloor(
|
|
100
|
+
root: string,
|
|
101
|
+
): Promise<Required<ExerciseFloor> | undefined> {
|
|
102
|
+
const records = await readExerciseRecords(root);
|
|
103
|
+
return records === undefined
|
|
104
|
+
? undefined
|
|
105
|
+
: { unprovenMax: unprovenTally(records).figure, statementsMax: measuredStatementsMax(records) };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* `x.verify.json`'s text with each `exercise` figure given, every other key untouched. A figure
|
|
110
|
+
* already at or under the one given is kept: the ratchet only falls. Text that is not a JSON
|
|
111
|
+
* object is returned as it was — the `manifest` step already reports that file's problems.
|
|
112
|
+
*/
|
|
113
|
+
export function withExerciseFloor(text: string, figures: ExerciseFloor): string {
|
|
114
|
+
let payload: unknown;
|
|
115
|
+
try {
|
|
116
|
+
payload = JSON.parse(text);
|
|
117
|
+
} catch {
|
|
118
|
+
return text;
|
|
119
|
+
}
|
|
120
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return text;
|
|
121
|
+
const record = payload as Record<string, unknown>;
|
|
122
|
+
const current = record[EXERCISE_FIELD];
|
|
123
|
+
const section =
|
|
124
|
+
typeof current === 'object' && current !== null && !Array.isArray(current)
|
|
125
|
+
? (current as Record<string, unknown>)
|
|
126
|
+
: {};
|
|
127
|
+
const next: Record<string, unknown> = { ...section };
|
|
128
|
+
let changed = false;
|
|
129
|
+
for (const [key, figure] of Object.entries(figures)) {
|
|
130
|
+
if (typeof figure !== 'number') continue;
|
|
131
|
+
const held = section[key];
|
|
132
|
+
if (typeof held === 'number' && held <= figure) continue;
|
|
133
|
+
next[key] = figure;
|
|
134
|
+
changed = true;
|
|
135
|
+
}
|
|
136
|
+
if (!changed) return text;
|
|
137
|
+
return `${JSON.stringify({ ...record, [EXERCISE_FIELD]: next }, null, 2)}\n`;
|
|
138
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The whole `exercise` floor verdict, one function for `x exercise` and the gate step alike: the
|
|
2
|
+
// unproven ratio (`exercise-floor.ts`), the sized-seed failures that explain it, and the statement
|
|
3
|
+
// ceiling. Each is red only where `x.verify.json`'s `exercise` key opted in; otherwise a warning,
|
|
4
|
+
// so an app that has not opted in stays green on `main` (X_BREAKING_ON_MAIN).
|
|
5
|
+
|
|
6
|
+
import { ERROR_DOCS_URL } from '@ultimat3/core';
|
|
7
|
+
import type { ExerciseRecord } from '@ultimat3/testing';
|
|
8
|
+
import { STATEMENTS_MAX, scaleSeedFindings, statementCeilingFindings } from '@ultimat3/testing';
|
|
9
|
+
import type { ExerciseFloor } from './exercise-floor';
|
|
10
|
+
import { judgeUnproven } from './exercise-floor';
|
|
11
|
+
import type { Finding } from './output';
|
|
12
|
+
|
|
13
|
+
/** What the verdict reads of a record: who it is and its three proofs. */
|
|
14
|
+
export type FloorRecord = Pick<
|
|
15
|
+
ExerciseRecord,
|
|
16
|
+
'kind' | 'name' | 'outcome' | 'tenant' | 'crash' | 'scale' | 'statementCeiling'
|
|
17
|
+
>;
|
|
18
|
+
|
|
19
|
+
/** The codes this verdict owns: the gate drops the child's copies and states its own. */
|
|
20
|
+
export const FLOOR_CODES: ReadonlySet<string> = new Set([
|
|
21
|
+
'X_EXERCISE_UNPROVEN_ABOVE_FLOOR',
|
|
22
|
+
'X_EXERCISE_SEED_FAILED',
|
|
23
|
+
'X_STATEMENTS_OVER_BUDGET',
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
export interface FloorVerdict {
|
|
27
|
+
readonly findings: readonly Finding[];
|
|
28
|
+
readonly warnings: readonly string[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A finding a floor did not opt into, as the one warning line a gate prints for it. */
|
|
32
|
+
const asWarning = (finding: Omit<Finding, 'docs'>): string =>
|
|
33
|
+
`${finding.code} ${finding.cause} — fix: ${finding.fix}`;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A within proof the entry declared: `declared`, or — in a report written before it carried that —
|
|
37
|
+
* a max other than the default. `statements: { max: 100, why }` is the default figure, declared.
|
|
38
|
+
*/
|
|
39
|
+
const declaredWithin = (proof: { readonly max: number; readonly declared?: true }): boolean =>
|
|
40
|
+
proof.declared === true || proof.max !== STATEMENTS_MAX;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `statementsMax` replaces the default ceiling for every primitive whose entry declared none; an
|
|
44
|
+
* entry's own `statements: { max, why }` stands. The pass judged against `STATEMENTS_MAX`, so the
|
|
45
|
+
* floor re-judges from the counts it recorded.
|
|
46
|
+
*/
|
|
47
|
+
const rejudged = (records: readonly FloorRecord[], max: number): readonly FloorRecord[] =>
|
|
48
|
+
records.map((record) => {
|
|
49
|
+
const proof = record.statementCeiling;
|
|
50
|
+
if (proof === undefined || (proof.verdict === 'over' && proof.why !== undefined)) return record;
|
|
51
|
+
if (proof.verdict === 'within' && declaredWithin(proof)) return record;
|
|
52
|
+
// The excluded `expectedQueryLoop` count rides along: the judged count alone reads as a typo.
|
|
53
|
+
const { statements } = proof;
|
|
54
|
+
const expected = proof.expected === undefined ? {} : { expected: proof.expected };
|
|
55
|
+
if (statements <= max) {
|
|
56
|
+
return { ...record, statementCeiling: { verdict: 'within', statements, max, ...expected } };
|
|
57
|
+
}
|
|
58
|
+
const top = proof.verdict === 'over' ? proof.top : [];
|
|
59
|
+
return {
|
|
60
|
+
...record,
|
|
61
|
+
statementCeiling: { verdict: 'over', statements, max, ...expected, top },
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
/** The figure `x upgrade` writes: the busiest undeclared call, never under the default. */
|
|
66
|
+
export function measuredStatementsMax(records: readonly FloorRecord[]): number {
|
|
67
|
+
return records.reduce((top, record) => {
|
|
68
|
+
const proof = record.statementCeiling;
|
|
69
|
+
if (proof === undefined) return top;
|
|
70
|
+
const declared = proof.verdict === 'over' ? proof.why !== undefined : declaredWithin(proof);
|
|
71
|
+
return declared ? top : Math.max(top, proof.statements);
|
|
72
|
+
}, STATEMENTS_MAX);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function exerciseFloorVerdict(
|
|
76
|
+
records: readonly FloorRecord[],
|
|
77
|
+
floor: ExerciseFloor | undefined,
|
|
78
|
+
): FloorVerdict {
|
|
79
|
+
const unproven = judgeUnproven(records, floor);
|
|
80
|
+
const seeds = scaleSeedFindings(records);
|
|
81
|
+
// A seed failure is the reason behind an unproven ratio: red exactly when that ratio is.
|
|
82
|
+
const seedRed = unproven.findings.length > 0;
|
|
83
|
+
const max = floor?.statementsMax;
|
|
84
|
+
const statements = statementCeilingFindings(max === undefined ? records : rejudged(records, max));
|
|
85
|
+
const docs = (finding: Omit<Finding, 'docs'>): Finding => ({ ...finding, docs: ERROR_DOCS_URL });
|
|
86
|
+
return {
|
|
87
|
+
findings: [
|
|
88
|
+
...unproven.findings,
|
|
89
|
+
...(seedRed ? seeds.map(docs) : []),
|
|
90
|
+
...(max === undefined ? [] : statements.map(docs)),
|
|
91
|
+
],
|
|
92
|
+
warnings: [
|
|
93
|
+
...unproven.warnings,
|
|
94
|
+
...(seedRed ? [] : seeds.map(asWarning)),
|
|
95
|
+
...(max === undefined ? statements.map(asWarning) : []),
|
|
96
|
+
],
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// The `exercise` key of `x.verify.json`: how many reached primitives the pass may leave `unproven`,
|
|
2
|
+
// as a ratio of the reached, and the verdict on a report against it. Absent is a WARNING naming the
|
|
3
|
+
// figure to write (an app that never opted in stays green on `main`); present, above it is red.
|
|
4
|
+
// The ratchet only falls: a figure under the floor is a warning naming the lower number.
|
|
5
|
+
|
|
6
|
+
import { ERROR_DOCS_URL, renderCauseValue } from '@ultimat3/core';
|
|
7
|
+
import type { ExerciseRecord } from '@ultimat3/testing';
|
|
8
|
+
import type { Finding } from './output';
|
|
9
|
+
|
|
10
|
+
/** The floor's exercise key. Named once: the problem quotes it and the fix repairs it. */
|
|
11
|
+
export const EXERCISE_FIELD = 'exercise';
|
|
12
|
+
|
|
13
|
+
export interface ExerciseFloor {
|
|
14
|
+
/** Unproven ÷ reached the pass may report, `0` to `1`. `x new` writes `0`; `x upgrade` the measured figure. */
|
|
15
|
+
readonly unprovenMax?: number;
|
|
16
|
+
/** Statements one primitive call may issue before the pass reports it (`@ultimat3/testing`'s X4). */
|
|
17
|
+
readonly statementsMax?: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const KEYS = ['unprovenMax', 'statementsMax'] as const;
|
|
21
|
+
|
|
22
|
+
/** `{ "unprovenMax": 0.05, "statementsMax": 100 }`, or the problems — a typo covers nothing. */
|
|
23
|
+
export function readExerciseFloor(payload: Record<string, unknown> | undefined): {
|
|
24
|
+
floor?: ExerciseFloor;
|
|
25
|
+
problems: readonly string[];
|
|
26
|
+
} {
|
|
27
|
+
const raw = payload?.[EXERCISE_FIELD];
|
|
28
|
+
if (raw === undefined) return { problems: [] };
|
|
29
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
30
|
+
return { problems: [`"${EXERCISE_FIELD}" is not an object of { "unprovenMax": ratio }`] };
|
|
31
|
+
}
|
|
32
|
+
const problems: string[] = [];
|
|
33
|
+
const floor: { unprovenMax?: number; statementsMax?: number } = {};
|
|
34
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
35
|
+
if (key === 'unprovenMax') {
|
|
36
|
+
if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1) {
|
|
37
|
+
floor.unprovenMax = value;
|
|
38
|
+
} else {
|
|
39
|
+
problems.push(
|
|
40
|
+
`"${EXERCISE_FIELD}.unprovenMax" is ${JSON.stringify(value)}, which is not a ratio from 0 to 1`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
} else if (key === 'statementsMax') {
|
|
44
|
+
if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 1) {
|
|
45
|
+
floor.statementsMax = value;
|
|
46
|
+
} else {
|
|
47
|
+
problems.push(
|
|
48
|
+
`"${EXERCISE_FIELD}.statementsMax" is ${JSON.stringify(value)}, which is not a whole number of statements`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
} else {
|
|
52
|
+
problems.push(`"${EXERCISE_FIELD}" names ${key}, which is not one of ${KEYS.join(', ')}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { ...(Object.keys(floor).length === 0 ? {} : { floor }), problems };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type Proven = Pick<ExerciseRecord, 'kind' | 'name' | 'outcome' | 'tenant' | 'crash' | 'scale'>;
|
|
59
|
+
|
|
60
|
+
/** The first proof that could not ask, with the reason it gave. */
|
|
61
|
+
const unprovenReason = (record: Proven): string | undefined => {
|
|
62
|
+
for (const [proof, verdict] of [
|
|
63
|
+
['tenant', record.tenant],
|
|
64
|
+
['crash', record.crash],
|
|
65
|
+
['scale', record.scale],
|
|
66
|
+
] as const) {
|
|
67
|
+
if (verdict?.verdict === 'unproven') return `${proof}: ${verdict.reason}`;
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export interface UnprovenTally {
|
|
73
|
+
readonly reached: number;
|
|
74
|
+
readonly unproven: readonly { readonly name: string; readonly reason: string }[];
|
|
75
|
+
/** Unproven ÷ reached, rounded UP to 4 places so a written figure always holds its own run. */
|
|
76
|
+
readonly figure: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function unprovenTally(records: readonly Proven[]): UnprovenTally {
|
|
80
|
+
const reached = records.filter((one) => one.outcome === 'reached');
|
|
81
|
+
const unproven = reached.flatMap((one) => {
|
|
82
|
+
const reason = unprovenReason(one);
|
|
83
|
+
return reason === undefined ? [] : [{ name: `${one.kind} ${one.name}`, reason }];
|
|
84
|
+
});
|
|
85
|
+
// Integers first: `7 / 100 * 10_000` is 700.0000000000001 and ceil'd to 0.0701, over its own run.
|
|
86
|
+
const units = reached.length === 0 ? 0 : Math.ceil((unproven.length * 10_000) / reached.length);
|
|
87
|
+
return { reached: reached.length, unproven, figure: units / 10_000 };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** `value` as `digits ÷ 10^scale`, read off its shortest decimal spelling (`0.07`, `1e-7`): exact. */
|
|
91
|
+
const decimal = (value: number): { readonly digits: bigint; readonly scale: bigint } => {
|
|
92
|
+
const [mantissa = '0', exponent = '0'] = String(value).toLowerCase().split('e');
|
|
93
|
+
const [whole = '0', fraction = ''] = mantissa.split('.');
|
|
94
|
+
const scale = fraction.length - Number(exponent);
|
|
95
|
+
const digits = BigInt(`${whole}${fraction}`);
|
|
96
|
+
return scale < 0
|
|
97
|
+
? { digits: digits * 10n ** BigInt(-scale), scale: 0n }
|
|
98
|
+
: { digits, scale: BigInt(scale) };
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* `unproven ÷ reached > max`, in integers: `0.29 * 100` is 28.999999999999996 in floats, and a pass
|
|
103
|
+
* exactly at the floor it wrote read red. Not money — a ratio — so a bigint holds the cross product.
|
|
104
|
+
*/
|
|
105
|
+
const aboveFloor = (unproven: number, reached: number, max: number): boolean => {
|
|
106
|
+
const { digits, scale } = decimal(max);
|
|
107
|
+
return BigInt(unproven) * 10n ** scale > digits * BigInt(reached);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** How many unproven records a finding names: the head is where to start. */
|
|
111
|
+
const NAMED = 3;
|
|
112
|
+
|
|
113
|
+
/** The verdict: red above a declared floor, a warning without one, a warning when it can fall. */
|
|
114
|
+
export function judgeUnproven(
|
|
115
|
+
records: readonly Proven[],
|
|
116
|
+
floor: ExerciseFloor | undefined,
|
|
117
|
+
): { readonly findings: readonly Finding[]; readonly warnings: readonly string[] } {
|
|
118
|
+
const tally = unprovenTally(records);
|
|
119
|
+
const count = `${String(tally.unproven.length)} of ${String(tally.reached)} reached primitive(s)`;
|
|
120
|
+
const max = floor?.unprovenMax;
|
|
121
|
+
const hold = `"${EXERCISE_FIELD}": { "unprovenMax": ${String(tally.figure)} }`;
|
|
122
|
+
if (max === undefined) {
|
|
123
|
+
return tally.unproven.length === 0
|
|
124
|
+
? { findings: [], warnings: [] }
|
|
125
|
+
: {
|
|
126
|
+
findings: [],
|
|
127
|
+
warnings: [
|
|
128
|
+
`exercise left ${count} unproven (${String(tally.figure)}): hold it with ${hold} in x.verify.json, 0 to require every proof`,
|
|
129
|
+
],
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (aboveFloor(tally.unproven.length, tally.reached, max)) {
|
|
133
|
+
const named = tally.unproven
|
|
134
|
+
.slice(0, NAMED)
|
|
135
|
+
.map((one) => `${one.name} (${renderCauseValue(one.reason)})`)
|
|
136
|
+
.join(', ');
|
|
137
|
+
return {
|
|
138
|
+
findings: [
|
|
139
|
+
{
|
|
140
|
+
code: 'X_EXERCISE_UNPROVEN_ABOVE_FLOOR',
|
|
141
|
+
cause: `exercise left ${count} unproven, ${String(tally.figure)} of the reached; x.verify.json "${EXERCISE_FIELD}.unprovenMax" allows ${String(max)}: ${named}`,
|
|
142
|
+
fix: 'x exercise --json # each unproven record in .x/exercise.json names the proof and its reason: fix the seed or the override it names; the floor only falls',
|
|
143
|
+
docs: ERROR_DOCS_URL,
|
|
144
|
+
at: 'x.verify.json',
|
|
145
|
+
},
|
|
146
|
+
],
|
|
147
|
+
warnings: [],
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
return tally.figure < max
|
|
151
|
+
? {
|
|
152
|
+
findings: [],
|
|
153
|
+
warnings: [
|
|
154
|
+
`exercise left ${count} unproven (${String(tally.figure)}), under "${EXERCISE_FIELD}.unprovenMax" ${String(max)}: lower it to ${hold} in x.verify.json`,
|
|
155
|
+
],
|
|
156
|
+
}
|
|
157
|
+
: { findings: [], warnings: [] };
|
|
158
|
+
}
|
package/src/mcp-errors.ts
CHANGED
|
@@ -384,6 +384,16 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
|
|
|
384
384
|
"native: { success: (output) => '/where-it-lands' } in the action's declaration, then x verify --only manifest",
|
|
385
385
|
X_ASSET_RETAIN_UNDECLARED:
|
|
386
386
|
"edit app.config.ts: add assets: { retain: { disk: 'assets', builds: 3 } }, naming a disk your defineStorage({ disks }) declares that every web pod reads",
|
|
387
|
+
X_EXERCISE_UNPROVEN_ABOVE_FLOOR:
|
|
388
|
+
'x exercise --json # each unproven record in .x/exercise.json names the proof and its reason: fix the seed or the override it names; the floor only falls',
|
|
389
|
+
X_ENV_NAME_RESERVED:
|
|
390
|
+
'edit app.config.ts: add an APP_ prefix to the envSchema name the finding cites (or delete it where the value is meant for the framework); then: x env example --json && x doctor --json',
|
|
391
|
+
X_FRAMEWORK_PIN_RANGE:
|
|
392
|
+
'x doctor --json # each X_FRAMEWORK_PIN_RANGE names a package.json line and the exact version: write it there, then: bun install',
|
|
393
|
+
X_VERIFY_STEP_UNFLOORED:
|
|
394
|
+
'x doctor --json # its X_VERIFY_STEP_UNFLOORED fix names the steps: run that x verify --only, then add each step that passed, not skipped, to "steps" in x.verify.json',
|
|
395
|
+
X_DB_ROW_SECURITY_OFF:
|
|
396
|
+
'database: { rowSecurity: true } # in defineConfig, app.config.ts; then: x db gen "row security" --json && x db migrate --json && x doctor --json',
|
|
387
397
|
};
|
|
388
398
|
|
|
389
399
|
const isCliCode = (code: string): code is CliErrorCode =>
|