@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.
Files changed (86) hide show
  1. package/README.md +7 -1
  2. package/package.json +29 -29
  3. package/src/cache-graph.ts +67 -0
  4. package/src/cmd-cache-spec.ts +25 -0
  5. package/src/cmd-cache.ts +187 -0
  6. package/src/cmd-config-spec.ts +23 -0
  7. package/src/cmd-config.ts +61 -0
  8. package/src/cmd-doctor.ts +47 -37
  9. package/src/cmd-exercise.ts +42 -5
  10. package/src/cmd-explain-spec.ts +24 -0
  11. package/src/cmd-explain.ts +201 -0
  12. package/src/cmd-logs-spec.ts +34 -0
  13. package/src/cmd-logs.ts +80 -0
  14. package/src/cmd-planned.ts +15 -29
  15. package/src/cmd-token-spec.ts +54 -0
  16. package/src/cmd-token.ts +173 -0
  17. package/src/cmd-upgrade.ts +19 -2
  18. package/src/cmd-verify-spec.ts +13 -3
  19. package/src/cmd-verify.ts +2 -0
  20. package/src/config-redact.ts +39 -0
  21. package/src/coverage-floor.ts +2 -2
  22. package/src/dev-boot-data-dir.ts +69 -0
  23. package/src/dev-boot.ts +26 -13
  24. package/src/doctor-env-reserved.ts +111 -0
  25. package/src/doctor-floor.ts +62 -0
  26. package/src/doctor-pins.ts +101 -0
  27. package/src/doctor-probe.ts +21 -1
  28. package/src/doctor-row-security.ts +119 -4
  29. package/src/doctor-warnings.ts +55 -0
  30. package/src/error-codes-doctor.ts +24 -0
  31. package/src/error-codes-tooling.ts +6 -4
  32. package/src/error-codes.ts +7 -0
  33. package/src/errors.ts +8 -2
  34. package/src/exercise-entry-edit.ts +5 -1
  35. package/src/exercise-floor-report.ts +138 -0
  36. package/src/exercise-floor-verdict.ts +98 -0
  37. package/src/exercise-floor.ts +158 -0
  38. package/src/exercise-routes.ts +59 -0
  39. package/src/explain-capture.ts +38 -0
  40. package/src/generate-exercise.ts +2 -2
  41. package/src/generate-factories.ts +133 -0
  42. package/src/generate-files.ts +11 -0
  43. package/src/generate-kinds.ts +13 -0
  44. package/src/mcp-db-target.ts +4 -3
  45. package/src/mcp-errors.ts +14 -0
  46. package/src/messages-gate.ts +2 -0
  47. package/src/messages-ops.ts +32 -0
  48. package/src/messages-upgrade.ts +14 -0
  49. package/src/messages.ts +5 -0
  50. package/src/otlp-export.ts +16 -2
  51. package/src/registry.ts +10 -0
  52. package/src/role-start.ts +11 -5
  53. package/src/runtime-services.ts +35 -19
  54. package/src/serve-boot-phases.ts +30 -0
  55. package/src/serve-boot-warnings.ts +62 -0
  56. package/src/serve-boot.ts +30 -11
  57. package/src/templates/generate-cron-job.ts +90 -0
  58. package/src/templates/generate-purge.ts +93 -0
  59. package/src/templates/generate-webhook-receiver.ts +274 -0
  60. package/src/templates/github/ci.yml.ts +101 -36
  61. package/src/templates/guard-repo-raw-sql-test.ts +174 -0
  62. package/src/templates/guard-repo-raw-sql.ts +115 -145
  63. package/src/templates/guard-unbounded-fanout.ts +170 -0
  64. package/src/templates/scaffold-claude-commands.ts +3 -2
  65. package/src/templates/scaffold-docs.ts +3 -2
  66. package/src/templates/scaffold-guards.ts +3 -0
  67. package/src/templates/scaffold-verify-floor.ts +4 -0
  68. package/src/test-dotenv.ts +15 -2
  69. package/src/upgrade-coverage.ts +109 -0
  70. package/src/upgrade-document.ts +18 -0
  71. package/src/upgrade-exercise-floor.ts +53 -0
  72. package/src/upgrade-gate.ts +84 -29
  73. package/src/upgrade-guards.ts +159 -0
  74. package/src/upgrade-report.ts +33 -1
  75. package/src/verify-checks.ts +3 -1
  76. package/src/verify-floor.ts +13 -0
  77. package/src/verify-plan.ts +127 -0
  78. package/wiki/CI-Parallel-Gate.md +38 -1
  79. package/wiki/CLI-Reference.md +115 -14
  80. package/wiki/Caching-And-Invalidation.md +10 -10
  81. package/wiki/Configuration.md +20 -2
  82. package/wiki/Known-Gaps.md +1 -1
  83. package/wiki/MCP-And-AI.md +1 -1
  84. package/wiki/Testing.md +96 -2
  85. package/wiki/Troubleshooting.md +3 -2
  86. package/wiki/Upgrading.md +9 -0
@@ -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
+ }
@@ -0,0 +1,59 @@
1
+ // What `x exercise` says about the route `load`s the pass ran (`@ultimat3/testing`'s
2
+ // `exercise-route-loads.ts`), and about a primitive reached with nothing to prove: WARNING lines,
3
+ // each naming the route file or the primitive. Warnings on `main` — a page read was never judged
4
+ // before, and an app that has not opted in stays green (X_BREAKING_ON_MAIN); red needs a floor key.
5
+
6
+ import type { ExerciseRecord, RouteLoadRecord } from '@ultimat3/testing';
7
+
8
+ const where = (record: RouteLoadRecord): string => `route ${record.name} (${record.file})`;
9
+
10
+ /** Each route's load as warning lines: a loop, a call over the ceiling, a seq scan, or unrun. */
11
+ export function routeLoadWarnings(records: readonly RouteLoadRecord[]): readonly string[] {
12
+ return records.flatMap((record): readonly string[] => {
13
+ if (record.outcome !== 'reached') {
14
+ return [`${where(record)} · load not exercised: ${record.reason ?? record.outcome}`];
15
+ }
16
+ const lines: string[] = [];
17
+ if (record.scale?.verdict === 'grows') {
18
+ for (const shape of record.scale.shapes) {
19
+ lines.push(
20
+ `${where(record)} · X_QUERY_SCALES_WITH_ROWS ${shape.fingerprint} ${String(shape.small)}→${String(shape.large)} at 2→8 rows a table: its load reads once per row — fold it into one read, or wrap it in expectedQueryLoop('<why>', fn)`,
21
+ );
22
+ }
23
+ }
24
+ const ceiling = record.statementCeiling;
25
+ if (ceiling?.verdict === 'over') {
26
+ const top = ceiling.top.map((shape) => `${shape.fingerprint} ×${String(shape.count)}`);
27
+ lines.push(
28
+ `${where(record)} · X_STATEMENTS_OVER_BUDGET ${String(ceiling.statements)} statements in one load, max ${String(ceiling.max)}: ${top.join(', ')}`,
29
+ );
30
+ }
31
+ for (const finding of record.plans?.findings ?? []) {
32
+ lines.push(`${where(record)} · ${finding.code} ${finding.table}`);
33
+ }
34
+ return lines;
35
+ });
36
+ }
37
+
38
+ /** How many names an empty-reach line lists before it says how many more. */
39
+ const NAMED = 5;
40
+
41
+ /** The line's code (`@ultimat3/testing` registers it): a warning on `main`, never a finding. */
42
+ const EMPTY_REACH = 'X_EXERCISE_EMPTY_REACH';
43
+
44
+ /**
45
+ * Reached with no statement and no effect: every proof on it is vacuous — a scale sweep of nothing
46
+ * is "flat", a tenant proof over nothing is "proven". Said once, with the first few named.
47
+ */
48
+ export function emptyReachWarnings(records: readonly ExerciseRecord[]): readonly string[] {
49
+ const empty = records.filter(
50
+ (record) =>
51
+ record.outcome === 'reached' && record.statements === 0 && record.effects.length === 0,
52
+ );
53
+ if (empty.length === 0) return [];
54
+ const named = empty.slice(0, NAMED).map((record) => `${record.kind} ${record.name}`);
55
+ const more = empty.length > NAMED ? `, and ${String(empty.length - NAMED)} more` : '';
56
+ return [
57
+ `${EMPTY_REACH} ${String(empty.length)} reached primitive(s) sent no statement and had no effect, so their proofs prove nothing: ${named.join(', ')}${more} — fix: edit exercise.ts: give each an input that reaches its work, or { off: '<why>' }`,
58
+ ];
59
+ }
@@ -0,0 +1,38 @@
1
+ // The statements ONE call sends, as `x explain` plans them: every `db.statement` event the call
2
+ // made under a marker of its own (never by time — the bus is process-wide), its text whitespace
3
+ // collapsed and its `expectedSeqScan` reason kept, exactly as the exercise room records them.
4
+
5
+ import { asyncContext, subscribe } from '@ultimat3/core';
6
+ import { expectedSeqScanReason } from '@ultimat3/db';
7
+ import type { SentStatement } from '@ultimat3/testing';
8
+
9
+ const scope = asyncContext<object>('x explain');
10
+
11
+ export interface Captured<T> {
12
+ readonly value: T;
13
+ /** Statement text → who sent it and why it may scan, in the shape `sweepPlans` reads. */
14
+ readonly sent: ReadonlyMap<string, SentStatement>;
15
+ }
16
+
17
+ export async function captureStatements<T>(
18
+ subject: string,
19
+ fn: () => Promise<T>,
20
+ ): Promise<Captured<T>> {
21
+ const marker = {};
22
+ const sent = new Map<string, { primitives: Set<string>; scan?: string }>();
23
+ // The bus delivers synchronously in the sender's context, so the marker read is the sender's.
24
+ const off = subscribe('db.statement', (event) => {
25
+ if (scope.get() !== marker) return;
26
+ const text = event.payload.text.replace(/\s+/g, ' ').trim();
27
+ const one = sent.get(text) ?? { primitives: new Set([subject]) };
28
+ const scan = expectedSeqScanReason();
29
+ if (scan !== undefined) one.scan = scan;
30
+ sent.set(text, one);
31
+ });
32
+ try {
33
+ const value = await scope.run(marker, fn);
34
+ return { value, sent };
35
+ } finally {
36
+ off();
37
+ }
38
+ }
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { UltimateError } from '@ultimat3/core';
6
6
  import type { ExerciseEntry } from './exercise-entry-edit';
7
- import { editExerciseFile } from './exercise-entry-edit';
7
+ import { editExerciseFile, entryKey } from './exercise-entry-edit';
8
8
  import { EXERCISE_FILE } from './exercise-registration';
9
9
  import type { GenerateDisk } from './generate-disk';
10
10
  import type { Finding } from './output';
@@ -23,7 +23,7 @@ export const writtenExercises = (
23
23
 
24
24
  /** One line of an entry: what the fix asks to paste, whitespace folded. */
25
25
  const oneLine = (entry: ExerciseEntry): string =>
26
- `${entry.name}: ${entry.value.replace(/\s*\n\s*/g, ' ').replace(/, }/g, ' }')}`;
26
+ `${entryKey(entry.name)}: ${entry.value.replace(/\s*\n\s*/g, ' ').replace(/, }/g, ' }')}`;
27
27
 
28
28
  /** Inserts `entries` into the app's exercise file; answers the path when it changed, or a refusal. */
29
29
  export async function declareGeneratedExercises(
@@ -0,0 +1,133 @@
1
+ // Which `x g` generator scaffolds each primitive factory, or why none does. One row per
2
+ // `PRIMITIVE_FACTORIES` entry, held to it by `generate-factories.test.ts`: a factory that ships
3
+ // with neither a generator nor a reason is refused there, never noticed later.
4
+
5
+ import type { Generator } from './generate-kinds';
6
+
7
+ /** A factory `x g <generator>` scaffolds: the one call, its tests, in the feature's slice. */
8
+ interface Generated {
9
+ readonly factory: string;
10
+ readonly generator: Generator;
11
+ }
12
+
13
+ /** A factory no generator writes, and the sentence that says why — the decision, on the record. */
14
+ interface NotGenerated {
15
+ readonly factory: string;
16
+ readonly none: string;
17
+ }
18
+
19
+ export type FactoryGenerator = Generated | NotGenerated;
20
+
21
+ /** The model rule three AI factories share: the app registers every model, the framework none. */
22
+ const MODEL =
23
+ 'calls a model the app registers itself (registerModel, @ultimat3/ai) — the framework registers none, so a generated declaration would name an id that is X_AI_MODEL_UNKNOWN at its first call';
24
+
25
+ /** Sorted by factory name, as `PRIMITIVE_FACTORIES` is by package then name. */
26
+ export const FACTORY_GENERATORS: readonly FactoryGenerator[] = [
27
+ { factory: 'agent', none: MODEL },
28
+ {
29
+ factory: 'agentJob',
30
+ none: 'wraps an action the app already declares, and which one is a choice x g cannot read off the disk; deferred (plan 101 U6) until x g takes the action to wrap',
31
+ },
32
+ { factory: 'backfill', generator: 'backfill' },
33
+ {
34
+ factory: 'consumer',
35
+ none: 'subscribes to an event topic the app publishes — the topic and its payload are the app’s own vocabulary, and a generated consumer would subscribe to nothing',
36
+ },
37
+ { factory: 'cronJob', generator: 'cron-job' },
38
+ {
39
+ factory: 'deviceSocket',
40
+ none: 'a websocket mount speaking the app’s own device protocol; the protocol is the whole of the declaration, and only the app knows it',
41
+ },
42
+ {
43
+ factory: 'exportRows',
44
+ none: 'reads one table through the app’s typed handle into a storage disk; deferred (plan 101 U6) until x g can refuse a slice whose table is not the scaffolded one under its own code',
45
+ },
46
+ { factory: 'hive', none: MODEL },
47
+ {
48
+ factory: 'importRows',
49
+ none: 'writes an uploaded file into one table through the app’s typed handle; deferred (plan 101 U6) on the same refusal exportRows waits for',
50
+ },
51
+ {
52
+ factory: 'ledger',
53
+ none: 'the attempt table a webhook() delivery writes, declared once beside that webhook — it has no meaning without one, so it ships with it',
54
+ },
55
+ { factory: 'llm', none: MODEL },
56
+ {
57
+ factory: 'mcpConfirmations',
58
+ none: 'the MCP server’s own confirmation actions: an app lists the value @ultimat3/mcp returns in defineApi, and has no body of its own to write',
59
+ },
60
+ {
61
+ factory: 'notifier',
62
+ none: 'fans a notification out over the channels the app configures — mail, push, in-app — and which channels exist is the app’s configuration, not a template',
63
+ },
64
+ {
65
+ factory: 'partitions',
66
+ none: 'keeps a partitioned table’s partitions ahead of time, and only a table the schema declares partitioned has any; x db gen writes that declaration',
67
+ },
68
+ {
69
+ factory: 'pdf',
70
+ none: 'renders a page the app serves into a document; the page and its route are the declaration, and x g route writes the route',
71
+ },
72
+ { factory: 'purge', generator: 'purge' },
73
+ {
74
+ factory: 'pushRegister',
75
+ none: 'a framework action over the device registrations @ultimat3/notify stores; an app lists it in defineApi and writes no body',
76
+ },
77
+ {
78
+ factory: 'pushSubscribe',
79
+ none: 'a framework action over the Web Push subscriptions @ultimat3/pwa stores; an app lists it in defineApi and writes no body',
80
+ },
81
+ {
82
+ factory: 'pushUnregister',
83
+ none: 'the other half of pushRegister: a framework action an app lists in defineApi, with no body of its own',
84
+ },
85
+ {
86
+ factory: 'pushUnsubscribe',
87
+ none: 'the other half of pushSubscribe: a framework action an app lists in defineApi, with no body of its own',
88
+ },
89
+ {
90
+ factory: 'refreshView',
91
+ none: 'refreshes a materialized view the schema declares; with no view there is nothing to refresh, and the view is a migration, not a template',
92
+ },
93
+ {
94
+ factory: 'reindex',
95
+ none: 'rebuilds an index the schema declares, concurrently; which index bloats is a measurement on a live database, never a scaffold',
96
+ },
97
+ {
98
+ factory: 'rollup',
99
+ none: 'counts a source table into a destination entity by bucket; deferred (plan 101 U6) until x g plants the destination entity and its migration beside it',
100
+ },
101
+ {
102
+ factory: 'scrape',
103
+ none: 'fetches pages the app names and extracts what the app wants from them; the target and the extraction are the whole declaration',
104
+ },
105
+ {
106
+ factory: 'subjectErase',
107
+ none: 'erases one data subject across every table that holds one, which the app declares per entity — the coverage x verify holds is that declaration',
108
+ },
109
+ {
110
+ factory: 'subjectExport',
111
+ none: 'exports one data subject across the same declared tables subjectErase reads; one declaration per app, written beside the entities',
112
+ },
113
+ {
114
+ factory: 'transition',
115
+ none: 'declares the edges of an entity’s own status column — which states exist is the app’s business convention; x g mutator writes the mutator shape it returns',
116
+ },
117
+ {
118
+ factory: 'uploadFlow',
119
+ none: 'a request and a confirm action over the app’s storage bucket and the row an upload attaches to — both the app’s, and neither on the disk x g reads',
120
+ },
121
+ {
122
+ factory: 'webhook',
123
+ none: 'one signed delivery to an endpoint the app stores, with its ledger; deferred (plan 101 U6) until x g plants the endpoint table and the ledger it needs',
124
+ },
125
+ { factory: 'webhookReceiver', generator: 'webhook-receiver' },
126
+ ];
127
+
128
+ /** `x g llm` or `x g agent-job`: the factory a word names, when it is one no generator writes. */
129
+ export function factoryWithoutGenerator(raw: string): NotGenerated | undefined {
130
+ const camel = raw.replaceAll(/-([a-z])/g, (_match, letter: string) => letter.toUpperCase());
131
+ const row = FACTORY_GENERATORS.find((entry) => entry.factory === camel);
132
+ return row !== undefined && 'none' in row ? row : undefined;
133
+ }
@@ -28,6 +28,9 @@ import {
28
28
  taskFiles,
29
29
  } from './templates';
30
30
  import { adminCatalogFiles } from './templates/admin-catalog';
31
+ import { cronJobFiles } from './templates/generate-cron-job';
32
+ import { purgeFiles } from './templates/generate-purge';
33
+ import { webhookReceiverFiles } from './templates/generate-webhook-receiver';
31
34
  import { helmMonitoringFiles } from './templates/scaffold-helm-alerts';
32
35
  import { oidcSignInFiles } from './templates/sign-in-oidc';
33
36
  import { passwordSignInFiles } from './templates/sign-in-password';
@@ -195,6 +198,14 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
195
198
  ...(options.sliceRepo === undefined ? {} : { sliceRepo: options.sliceRepo }),
196
199
  }),
197
200
  );
201
+ // A primitive factory's one call, in the feature's slice. None reads the slice: each declares
202
+ // no table of its own, so it compiles in a feature that has no entity yet.
203
+ case 'cron-job':
204
+ return dedupe(cronJobFiles(options.name, target));
205
+ case 'purge':
206
+ return dedupe(purgeFiles(options.name, target));
207
+ case 'webhook-receiver':
208
+ return dedupe(webhookReceiverFiles(options.name, target));
198
209
  case 'entity':
199
210
  // With the labels the admin reads for it: the entity is an admin screen once it is in the
200
211
  // handle, whether or not a resource was generated around it.
@@ -9,6 +9,7 @@ import {
9
9
  MissingSubcommandError,
10
10
  UnknownCommandError,
11
11
  } from './errors';
12
+ import { factoryWithoutGenerator } from './generate-factories';
12
13
  import { quoteArg } from './shell-quote';
13
14
  import type { Surface } from './templates';
14
15
  import { camel, kebab } from './templates/naming';
@@ -18,6 +19,11 @@ export const GENERATORS = [
18
19
  'action',
19
20
  'mutator',
20
21
  'backfill',
22
+ // Three primitive factories, each its one call in the feature's `jobs/`. Which factories have a
23
+ // generator, and why the rest have none, is `FACTORY_GENERATORS` (`generate-factories.ts`).
24
+ 'cron-job',
25
+ 'purge',
26
+ 'webhook-receiver',
21
27
  'job',
22
28
  'route',
23
29
  'policy',
@@ -102,12 +108,16 @@ export function readKind(raw: string | undefined): Generator {
102
108
  // deliberately never asked about an absent word, since the empty string is within `job`'s
103
109
  // cutoff and would "suggest" a generator nobody typed.
104
110
  if (raw === undefined) throw new MissingSubcommandError({ command: 'g', known: GENERATORS });
111
+ const decided = factoryWithoutGenerator(raw);
105
112
  const near = nearestName(raw, kinds);
106
113
  const suggestion = GENERATORS.find((kind) => kind === near);
107
114
  throw new UnknownCommandError({
108
115
  path: `g ${raw}`.trim(),
109
116
  known: GENERATORS,
110
117
  suggestion: suggestion === undefined ? 'help g' : `g ${suggestion} ${EXAMPLE_NAME[suggestion]}`,
118
+ ...(decided === undefined
119
+ ? {}
120
+ : { why: `${decided.factory}() has no generator: ${decided.none}` }),
111
121
  });
112
122
  }
113
123
 
@@ -275,6 +285,9 @@ const EXAMPLE_NAME: Readonly<Record<Generator, string>> = {
275
285
  action: 'publish-post',
276
286
  mutator: 'rename-post',
277
287
  backfill: 'backfill-slugs',
288
+ 'cron-job': 'nightly-report',
289
+ purge: 'purge-retained',
290
+ 'webhook-receiver': 'billing-events',
278
291
  job: 'send-digest',
279
292
  route: 'posts',
280
293
  policy: 'post',
@@ -27,7 +27,7 @@ import { safeUrlLabel } from './safe-url-label';
27
27
  */
28
28
  export function databaseTarget(services: DevServices, env: Env): DatabaseTarget {
29
29
  const url = services.db.url;
30
- const production = isProduction(env);
30
+ const production = readsAsProduction(env);
31
31
  return services.db.mode === 'embedded'
32
32
  ? { label: url, branch: pgliteBranch(url, services.stateDir), production }
33
33
  : {
@@ -46,9 +46,10 @@ export function databaseTarget(services: DevServices, env: Env): DatabaseTarget
46
46
  * `undefined` is answered **true**, and that is the whole point of using it here. It means exactly
47
47
  * one thing: `ULTIMATE_ENV` is set to something that is not an environment. Reading a typo as "not
48
48
  * production" would let the single misconfiguration this guard exists to survive defeat it — so an
49
- * environment that cannot be read is treated as the most dangerous one it could be.
49
+ * environment that cannot be read is treated as the most dangerous one it could be. `x explain` and
50
+ * `x token` ask the same question through this one reader (`cmd-explain.ts`, `cmd-token.ts`).
50
51
  */
51
- const isProduction = (env: Env): boolean => {
52
+ export const readsAsProduction = (env: Env): boolean => {
52
53
  const environment = tryResolveEnvironment({ env });
53
54
  return environment === undefined || environment === 'production';
54
55
  };
package/src/mcp-errors.ts CHANGED
@@ -384,6 +384,20 @@ 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',
397
+ X_DEV_DATA_UNOPENABLE:
398
+ 'x db migrate --json # the fresh database has no tables yet; then x db seed --json if the app declares a seed. The moved directory (meta.aside) is kept: delete it once its rows are not needed',
399
+ X_EXPLAIN_PRODUCTION_DATABASE:
400
+ 'env -u DATABASE_URL x queries list --json # then the same prefix on x explain <query> --json: it plans on the embedded dev database; for a copy of production data, point DATABASE_URL at a staging restore with ULTIMATE_ENV=staging',
387
401
  };
388
402
 
389
403
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -73,6 +73,8 @@ export const GATE_MESSAGES = {
73
73
  'cli.verify.notAGateRun': 'NOT A GATE RUN — {summary}',
74
74
  'cli.verify.pass': 'all {count} steps passed in {ms}ms',
75
75
  'cli.verify.fail': '{failed} of {count} steps failed',
76
+ 'cli.verify.plan':
77
+ 'the gate in {parts} part(s) over {steps} steps — the CI matrix is data.matrix',
76
78
  // The budgets step built before it weighed (`verify-budgets-build.ts`): which stats state made it.
77
79
  'cli.verify.budgets.built':
78
80
  'built first: build stats were {state} — x build --target static --out {out} ({ms}ms)',