@ultimat3/cli 31.16.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 (65) 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-exercise.ts +34 -10
  9. package/src/cmd-explain-spec.ts +24 -0
  10. package/src/cmd-explain.ts +201 -0
  11. package/src/cmd-logs-spec.ts +34 -0
  12. package/src/cmd-logs.ts +80 -0
  13. package/src/cmd-planned.ts +15 -29
  14. package/src/cmd-token-spec.ts +54 -0
  15. package/src/cmd-token.ts +173 -0
  16. package/src/cmd-verify-spec.ts +13 -3
  17. package/src/cmd-verify.ts +2 -0
  18. package/src/config-redact.ts +39 -0
  19. package/src/dev-boot-data-dir.ts +69 -0
  20. package/src/dev-boot.ts +26 -13
  21. package/src/error-codes-tooling.ts +6 -4
  22. package/src/error-codes.ts +2 -0
  23. package/src/errors.ts +8 -2
  24. package/src/exercise-entry-edit.ts +5 -1
  25. package/src/exercise-routes.ts +59 -0
  26. package/src/explain-capture.ts +38 -0
  27. package/src/generate-exercise.ts +2 -2
  28. package/src/generate-factories.ts +133 -0
  29. package/src/generate-files.ts +11 -0
  30. package/src/generate-kinds.ts +13 -0
  31. package/src/mcp-db-target.ts +4 -3
  32. package/src/mcp-errors.ts +4 -0
  33. package/src/messages-gate.ts +2 -0
  34. package/src/messages-ops.ts +32 -0
  35. package/src/messages-upgrade.ts +1 -0
  36. package/src/messages.ts +2 -0
  37. package/src/otlp-export.ts +16 -2
  38. package/src/registry.ts +10 -0
  39. package/src/role-start.ts +11 -5
  40. package/src/runtime-services.ts +35 -19
  41. package/src/serve-boot-phases.ts +30 -0
  42. package/src/serve-boot-warnings.ts +62 -0
  43. package/src/serve-boot.ts +30 -11
  44. package/src/templates/generate-cron-job.ts +90 -0
  45. package/src/templates/generate-purge.ts +93 -0
  46. package/src/templates/generate-webhook-receiver.ts +274 -0
  47. package/src/templates/github/ci.yml.ts +101 -36
  48. package/src/templates/guard-repo-raw-sql-test.ts +174 -0
  49. package/src/templates/guard-repo-raw-sql.ts +115 -145
  50. package/src/templates/guard-unbounded-fanout.ts +170 -0
  51. package/src/templates/scaffold-claude-commands.ts +3 -2
  52. package/src/templates/scaffold-docs.ts +3 -2
  53. package/src/templates/scaffold-guards.ts +3 -0
  54. package/src/upgrade-gate.ts +18 -6
  55. package/src/upgrade-report.ts +4 -0
  56. package/src/verify-plan.ts +127 -0
  57. package/wiki/CI-Parallel-Gate.md +38 -1
  58. package/wiki/CLI-Reference.md +90 -12
  59. package/wiki/Caching-And-Invalidation.md +10 -10
  60. package/wiki/Configuration.md +4 -2
  61. package/wiki/Known-Gaps.md +1 -1
  62. package/wiki/MCP-And-AI.md +1 -1
  63. package/wiki/Testing.md +32 -0
  64. package/wiki/Troubleshooting.md +3 -2
  65. package/wiki/Upgrading.md +6 -0
@@ -0,0 +1,201 @@
1
+ // `x explain <query> [--input '<json>']` — one declared query run once on the app's dev database
2
+ // (never production's), every statement it sent captured (`explain-capture.ts`) and planned by
3
+ // `sweepPlans`, the plan oracle the `exercise` gate step judges with. The rows are discarded.
4
+
5
+ import {
6
+ ctxOf,
7
+ isUltimateError,
8
+ nearestName,
9
+ renderFixShellArg,
10
+ runWithContext,
11
+ serviceActor,
12
+ UltimateError,
13
+ } from '@ultimat3/core';
14
+ import type { DbClient } from '@ultimat3/db';
15
+ import type { AnyQuery } from '@ultimat3/query';
16
+ import { getQuery, listQueries, queryName, sourceFor } from '@ultimat3/query';
17
+ import type { ExerciseRecord, PlanProof, SeedEntity, SentStatement } from '@ultimat3/testing';
18
+ import { planSweepFindings, sweepPlans } from '@ultimat3/testing';
19
+ import { loadApp } from './app-load';
20
+ import { requireAppRoot } from './app-root';
21
+ import { explainSpec } from './cmd-explain-spec';
22
+ import type { CliCommand, CommandContext } from './command';
23
+ import { registeredEntityCores } from './db-seed-generate';
24
+ import { BadFlagError, DeclarationUnknownError, MissingPositionalError } from './errors';
25
+ import { captureStatements } from './explain-capture';
26
+ import { readsAsProduction } from './mcp-db-target';
27
+ import { msg } from './messages';
28
+ import type { CommandResult, Finding, JsonValue } from './output';
29
+ import { flagString } from './parse';
30
+ import { resolveServices } from './runtime-bindings';
31
+ import { openAppQueue } from './runtime-boot-ports';
32
+
33
+ /** The dev database, open for one run and ALWAYS released (the PGlite lock). */
34
+ export interface OpenPlanDb {
35
+ readonly db: DbClient;
36
+ close(): Promise<void>;
37
+ }
38
+
39
+ export type OpenDb = (root: string, ctx: CommandContext) => Promise<OpenPlanDb>;
40
+
41
+ /** `openAppQueue` installs the ambient `db()` the query's repositories read through. */
42
+ const openDevDb: OpenDb = async (root, ctx) => {
43
+ const queue = await openAppQueue(root, ctx.env);
44
+ return { db: queue.db, close: () => queue.stop() };
45
+ };
46
+
47
+ /**
48
+ * The query is SENT, as a service actor with its policy skipped: on a production database that is
49
+ * an unauthorised read with production's load. Embedded is always a dev database; an external one
50
+ * is planned only where the environment says it is not production — an unreadable `ULTIMATE_ENV`
51
+ * reads as production (`readsAsProduction`, the MCP host's `db.migrate` reading). No override flag:
52
+ * a staging restore under `ULTIMATE_ENV=staging` is the copy of production's data this plans on.
53
+ */
54
+ export class ExplainProductionDatabaseError extends UltimateError {
55
+ constructor(query: string) {
56
+ super({
57
+ code: 'X_EXPLAIN_PRODUCTION_DATABASE',
58
+ cause: `DATABASE_URL names an external database and this environment reads as production, where x explain would send ${query} for real with its policy skipped`,
59
+ fix: `env -u DATABASE_URL x explain ${renderFixShellArg(query, '<query>')} --json # plans on the embedded dev database; for production's data, a staging restore with ULTIMATE_ENV=staging`,
60
+ });
61
+ }
62
+ }
63
+
64
+ /** `--input`, as JSON: the query's own schema judges the shape, this only the syntax. */
65
+ function readInput(ctx: CommandContext, name: string): unknown {
66
+ const raw = flagString(ctx.args, 'input');
67
+ if (raw === undefined) return {};
68
+ try {
69
+ return JSON.parse(raw) as unknown;
70
+ } catch {
71
+ throw new BadFlagError({
72
+ flag: 'input',
73
+ command: 'explain',
74
+ reason: 'is not JSON',
75
+ fix: `x explain ${renderFixShellArg(name, '<query>')} --input '{}' --json`,
76
+ });
77
+ }
78
+ }
79
+
80
+ function resolveQuery(name: string): AnyQuery {
81
+ const found = getQuery(name);
82
+ if (found !== undefined) return found;
83
+ const known = listQueries().map(queryName);
84
+ const suggestion = nearestName(name, known);
85
+ throw new DeclarationUnknownError({
86
+ kind: 'queries',
87
+ singular: 'query',
88
+ name,
89
+ known,
90
+ ...(suggestion === undefined ? {} : { suggestion }),
91
+ });
92
+ }
93
+
94
+ /**
95
+ * The query's statements, sent for real. Its policy is NOT asked — `explainQuery`'s rule: this is
96
+ * an operator command on the dev database, and what it prints is SQL and plans, never a row.
97
+ */
98
+ const runOnce = (target: AnyQuery, name: string, input: unknown, org: string | undefined) =>
99
+ captureStatements(name, () =>
100
+ runWithContext(
101
+ // A service actor, in the tenant `--org` names: the statement a tenant-scoped read sends
102
+ // carries its tenant predicate, and that predicate is part of what the plan is judged on.
103
+ ctxOf({
104
+ actor: serviceActor({ id: 'x-explain', ...(org === undefined ? {} : { orgId: org }) }),
105
+ }),
106
+ async () => {
107
+ const source = await sourceFor(target, input, {
108
+ unenforced: 'x explain plans the statements of one read and prints no row of it',
109
+ });
110
+ await source.execute();
111
+ },
112
+ ),
113
+ ).catch((error: unknown) => {
114
+ // The tenancy refusal's own fix names code; from this command, the flag is the answer.
115
+ if (!isUltimateError(error) || error.code !== 'X_TENANCY_ACTOR_ORG_REQUIRED') throw error;
116
+ throw new BadFlagError({
117
+ flag: 'org',
118
+ command: 'explain',
119
+ reason: `${name} reads a tenant-scoped entity, and a plan without the tenant predicate is not the plan production runs`,
120
+ fix: `x explain ${renderFixShellArg(name, '<query>')} --org <org-id> --json`,
121
+ });
122
+ });
123
+
124
+ /** The proof as the exercise report carries it, so its findings are the gate's own text. */
125
+ const asRecord = (name: string, plans: PlanProof): ExerciseRecord => ({
126
+ kind: 'query',
127
+ name,
128
+ outcome: 'reached',
129
+ statements: plans.planned,
130
+ effects: [],
131
+ ms: 0,
132
+ plans,
133
+ });
134
+
135
+ const listed = (entries: PlanProof['exempt']): JsonValue =>
136
+ entries.map((entry) => ({ statement: entry.statement, reason: entry.reason }));
137
+
138
+ function summaryOf(name: string, proof: PlanProof, sent: number, red: number): string {
139
+ if (sent === 0) return msg('cli.explain.none', { query: name });
140
+ if (proof.unplannable.length > 0) return msg('cli.explain.unplannable', { query: name });
141
+ return red === 0
142
+ ? msg('cli.explain.served', { query: name, planned: proof.planned })
143
+ : msg('cli.explain.red', { query: name, count: red });
144
+ }
145
+
146
+ /** `open` is the seam a test hands a database through; the shipped command opens the dev one. */
147
+ export const explainCommandOver = (open: OpenDb): CliCommand => ({
148
+ spec: explainSpec,
149
+ async run(ctx: CommandContext): Promise<CommandResult> {
150
+ const root = requireAppRoot('explain', ctx.cwd).dir;
151
+ const name = ctx.args.positionals[0];
152
+ if (name === undefined) {
153
+ throw new MissingPositionalError({
154
+ command: 'explain',
155
+ positional: 'query',
156
+ example: 'x queries list --json # then x explain <query> --json',
157
+ });
158
+ }
159
+ if (resolveServices(root, ctx.env).db.mode === 'external' && readsAsProduction(ctx.env)) {
160
+ throw new ExplainProductionDatabaseError(name);
161
+ }
162
+ const input = readInput(ctx, name);
163
+ const org = flagString(ctx.args, 'org');
164
+ const loaded = await loadApp(root);
165
+ const target = resolveQuery(name);
166
+ const entities: readonly SeedEntity[] = Object.values(registeredEntityCores());
167
+ const handle = await open(root, ctx);
168
+ let sent: ReadonlyMap<string, SentStatement> = new Map();
169
+ let proofs: ReadonlyMap<string, PlanProof> = new Map();
170
+ try {
171
+ sent = (await runOnce(target, name, input, org)).sent;
172
+ proofs = await sweepPlans(handle.db, sent, entities);
173
+ } finally {
174
+ await handle.close();
175
+ }
176
+ const proof = proofs.get(name) ?? { planned: 0, findings: [], exempt: [], unplannable: [] };
177
+ const verdicts: readonly Finding[] = planSweepFindings([asRecord(name, proof)]);
178
+ const findings = [...loaded.findings, ...verdicts];
179
+ const statements = [...sent.keys()];
180
+ return {
181
+ ok: findings.length === 0,
182
+ command: 'explain',
183
+ summary: summaryOf(name, proof, statements.length, verdicts.length),
184
+ findings,
185
+ lines: [
186
+ ...statements.map((statement) => ` ${statement}`),
187
+ ...proof.exempt.map((entry) => msg('cli.explain.exempt', { reason: entry.reason })),
188
+ ...proof.unplannable.map((entry) => msg('cli.explain.refused', { reason: entry.reason })),
189
+ ],
190
+ data: {
191
+ query: name,
192
+ statements,
193
+ planned: proof.planned,
194
+ exempt: listed(proof.exempt),
195
+ unplannable: listed(proof.unplannable),
196
+ },
197
+ };
198
+ },
199
+ });
200
+
201
+ export const explainCommand: CliCommand = explainCommandOver(openDevDb);
@@ -0,0 +1,34 @@
1
+ // `x logs`'s declaration, apart from its body: the parser, `x help` and the `errors` step
2
+ // read it without loading `cmd-logs.ts`, which `registry.ts` imports only when the command runs.
3
+
4
+ import type { CommandSpec } from './parse';
5
+
6
+ export const LOGS_SUBCOMMANDS = ['tail'] as const;
7
+
8
+ /** Lines a bare `x logs tail` prints: a screen, not a history. */
9
+ export const LOGS_DEFAULT_LINES = 100;
10
+ /** The most one call returns — `tailLines` stops reading at 1 MiB from the end either way. */
11
+ export const LOGS_MAX_LINES = 10_000;
12
+
13
+ export const logsSpec: CommandSpec = {
14
+ name: 'logs',
15
+ summary:
16
+ 'the last lines of the dev log, or of one role log, as the logs.tail MCP tool reads them',
17
+ usage: 'x logs tail [--lines n] [--role <role>] [--json]',
18
+ requiresApp: true,
19
+ subcommands: [...LOGS_SUBCOMMANDS],
20
+ // Read-only, so the bare form may mean it.
21
+ defaultSubcommand: 'tail',
22
+ flags: [
23
+ {
24
+ name: 'lines',
25
+ type: 'string',
26
+ summary: `how many lines from the end, 1 to ${LOGS_MAX_LINES} (default ${LOGS_DEFAULT_LINES})`,
27
+ },
28
+ {
29
+ name: 'role',
30
+ type: 'string',
31
+ summary: 'read .x/logs/<role>.log instead of the dev log (web, worker, scheduler, sync, …)',
32
+ },
33
+ ],
34
+ };
@@ -0,0 +1,80 @@
1
+ // `x logs tail` — the last lines of `.x/dev.log` (what `x dev` tees) or of one role's
2
+ // `.x/logs/<role>.log`. The same file, path rule and end-first reader as the `logs.tail` MCP tool
3
+ // (`mcp-host.ts`): a shell and an agent asking "what did the server just say" get one answer.
4
+
5
+ // why: Bun exposes no path joiner, and the fix names the logs directory on any platform.
6
+ import { join } from 'node:path';
7
+ import { isRole, NotImplementedError, ROLES, renderFixShellArg } from '@ultimat3/core';
8
+ import { requireAppRoot } from './app-root';
9
+ import { LOGS_DEFAULT_LINES, LOGS_MAX_LINES, logsSpec } from './cmd-logs-spec';
10
+ import type { CliCommand, CommandContext } from './command';
11
+ import { ok } from './command';
12
+ import { BadFlagError } from './errors';
13
+ import { parseIntFlag } from './flag-number';
14
+ import { logTailPath, type TailSource, tailLines } from './mcp-host';
15
+ import { msg } from './messages';
16
+ import type { CommandResult } from './output';
17
+ import { flagString } from './parse';
18
+ import { resolveServices } from './runtime-bindings';
19
+
20
+ /** A log on disk: its size and byte ranges, or nothing. `Bun.file` in the shipped command. */
21
+ export type LogOpener = (path: string) => Promise<TailSource | undefined>;
22
+
23
+ const openLog: LogOpener = async (path) => {
24
+ const file = Bun.file(path);
25
+ return (await file.exists()) ? file : undefined;
26
+ };
27
+
28
+ /** `--role`, held to the runtime's roles BEFORE it is joined into a path. */
29
+ function readRole(ctx: CommandContext): string | undefined {
30
+ const role = flagString(ctx.args, 'role');
31
+ if (role === undefined || isRole(role)) return role;
32
+ throw new BadFlagError({
33
+ flag: 'role',
34
+ command: 'logs tail',
35
+ reason: `"${role}" is not a runtime role (known: ${ROLES.join(', ')})`,
36
+ fix: 'x logs tail --role web --json',
37
+ });
38
+ }
39
+
40
+ /** `open` is the seam a test hands a log through; the shipped command reads the disk. */
41
+ export const logsCommandOver = (open: LogOpener): CliCommand => ({
42
+ spec: logsSpec,
43
+ async run(ctx: CommandContext): Promise<CommandResult> {
44
+ const root = requireAppRoot('logs', ctx.cwd).dir;
45
+ // Both flags read before any file is touched: a typo costs nothing to report.
46
+ const rawLines = flagString(ctx.args, 'lines');
47
+ const lines =
48
+ rawLines === undefined
49
+ ? LOGS_DEFAULT_LINES
50
+ : parseIntFlag(rawLines, {
51
+ name: 'lines',
52
+ command: 'logs tail',
53
+ min: 1,
54
+ max: LOGS_MAX_LINES,
55
+ example: 'x logs tail --lines 50 --json',
56
+ });
57
+ const role = readRole(ctx);
58
+ const { stateDir } = resolveServices(root, ctx.env);
59
+ const path = logTailPath(stateDir, role);
60
+ const log = await open(path);
61
+ if (log === undefined) {
62
+ // The MCP tool's answer, word for word in substance: no role writes a log of its own, so the
63
+ // fix is the process that does.
64
+ throw new NotImplementedError({
65
+ cause: `x logs tail without ${path} is not implemented in this build: x dev writes the dev log, and a role writes one only when its output is sent there`,
66
+ fix:
67
+ role === undefined
68
+ ? 'x dev'
69
+ : `mkdir -p ${renderFixShellArg(join(stateDir, 'logs'), '<the logs dir of the path the cause names>')} && x dev --role ${renderFixShellArg(role, '<role>')} > ${renderFixShellArg(path, '<the path the cause names>')} 2>&1`,
70
+ });
71
+ }
72
+ const tail = await tailLines(log, lines);
73
+ return ok('logs', msg('cli.logs.tail', { count: tail.length, path }), {
74
+ lines: tail,
75
+ data: { path, role: role ?? null, lines: [...tail] },
76
+ });
77
+ },
78
+ });
79
+
80
+ export const logsCommand: CliCommand = logsCommandOver(openLog);
@@ -1,5 +1,5 @@
1
1
  // The commands the design docs specify and this build does not yet implement. They are in the
2
- // registry on purpose: `x cache bust` exiting X_CLI_UNKNOWN_COMMAND says "you typed something that
2
+ // registry on purpose: `x status` exiting X_CLI_UNKNOWN_COMMAND says "you typed something that
3
3
  // does not exist", which is false and sends an agent looking for a typo. X_NOT_IMPLEMENTED plus a
4
4
  // fix naming the closest shipped command says the true thing, and `x help` lists them honestly.
5
5
 
@@ -23,13 +23,6 @@ export interface PlannedCommand {
23
23
  * table exists to close, and `cmd-planned.test.ts` asserts the whole set against the registry.
24
24
  */
25
25
  export const PLANNED_COMMANDS: readonly PlannedCommand[] = [
26
- {
27
- name: 'cache',
28
- summary: 'the tag graph, targeted eviction, hit stats',
29
- usage: 'x cache [graph|bust <tag>|clear|stats] [--json]',
30
- subcommands: ['graph', 'bust', 'clear', 'stats'],
31
- fix: 'x dev # then the cache panel at /_x',
32
- },
33
26
  {
34
27
  name: 'branch',
35
28
  summary: 'copy-on-write branch environments with a preview URL',
@@ -42,20 +35,6 @@ export const PLANNED_COMMANDS: readonly PlannedCommand[] = [
42
35
  usage: 'x status [--json]',
43
36
  fix: 'x doctor --json',
44
37
  },
45
- {
46
- name: 'logs',
47
- summary: 'structured logs and OTel spans, filterable',
48
- usage: 'x logs tail [--json]',
49
- subcommands: ['tail'],
50
- fix: 'x dev # then the timeline panel at /_x',
51
- },
52
- {
53
- name: 'token',
54
- summary: 'create MCP tokens and grant scopes',
55
- usage: 'x token [create --scopes <s>|grant <scope>] [--json]',
56
- subcommands: ['create', 'grant'],
57
- fix: 'x mcp serve --help # the scopes this build serves',
58
- },
59
38
  {
60
39
  name: 'ai',
61
40
  summary: 'eval scores, semantic-cache stats, vector reindex',
@@ -76,13 +55,6 @@ export const PLANNED_COMMANDS: readonly PlannedCommand[] = [
76
55
  subcommands: ['add-currency'],
77
56
  fix: "x errors explain X_CURRENCY_UNKNOWN --json # extend it in code: registerCurrency({ code: 'GHS', exponent: 2, name: 'Ghana Cedi' }) at boot",
78
57
  },
79
- {
80
- name: 'config',
81
- summary: 'the resolved app.config.ts, defaults included',
82
- usage: 'x config show [--json]',
83
- subcommands: ['show'],
84
- fix: 'x manifest --json # the facts the resolved config produced',
85
- },
86
58
  ];
87
59
 
88
60
  /**
@@ -116,6 +88,20 @@ export interface PlannedSubcommand {
116
88
  * own ledger. One subcommand is not worth a second engine.
117
89
  */
118
90
  export const PLANNED_SUBCOMMANDS: readonly PlannedSubcommand[] = [
91
+ // A key's scopes are fixed when it is issued — `AuthApiKeyRecord.scopes` is "never widened" and
92
+ // `ApiKeyStore` has no update — so a grant is a NEW key with the wider set and a revoke of the old.
93
+ {
94
+ command: 'token',
95
+ subcommand: 'grant',
96
+ fix: 'x token create --scopes post:read,post:write --json # a key with the wider set; then x token revoke <old-id>',
97
+ },
98
+ // Hit rates live in the serving processes' tiers, and a CLI process has served nothing: the
99
+ // number is the running server's, which `/_x` already reads in that process.
100
+ {
101
+ command: 'cache',
102
+ subcommand: 'stats',
103
+ fix: 'x dev # then the cache panel at /_x',
104
+ },
119
105
  {
120
106
  command: 'db',
121
107
  subcommand: 'studio',
@@ -0,0 +1,54 @@
1
+ // `x token`'s declaration, apart from its body: the parser, `x help` and the `errors` step
2
+ // read it without loading `cmd-token.ts`, which `registry.ts` imports only when the command runs.
3
+
4
+ import type { CommandSpec } from './parse';
5
+
6
+ /** `grant` stays listed and answers X_NOT_IMPLEMENTED (`PLANNED_SUBCOMMANDS`): a key's scopes are fixed. */
7
+ export const TOKEN_SUBCOMMANDS = ['create', 'list', 'revoke', 'grant'] as const;
8
+
9
+ /** The longest lifetime `--days` takes: ten years is "no expiry" said out loud. */
10
+ export const TOKEN_MAX_DAYS = 3_650;
11
+
12
+ export const tokenSpec: CommandSpec = {
13
+ name: 'token',
14
+ summary: 'MCP and API tokens: issue one with exact scopes, list them by owner, revoke one',
15
+ usage:
16
+ 'x token create --scopes <a,b> [--user <id>] [--org <id>] [--env dev|stage|prod] [--days n] · x token list --owner <id> · x token revoke <id> [--json]',
17
+ requiresApp: true,
18
+ // No default: `create` WRITES a credential, and a bare `x token` must not.
19
+ subcommands: [...TOKEN_SUBCOMMANDS],
20
+ flags: [
21
+ {
22
+ name: 'scopes',
23
+ type: 'string',
24
+ summary: 'comma-separated permissions the token carries, each by name — never a wildcard',
25
+ subcommands: ['create'],
26
+ },
27
+ {
28
+ name: 'user',
29
+ type: 'string',
30
+ summary: 'the user the token belongs to: its scopes are cut to what that user may do',
31
+ subcommands: ['create'],
32
+ },
33
+ { name: 'org', type: 'string', summary: 'the org the token acts in', subcommands: ['create'] },
34
+ {
35
+ name: 'env',
36
+ type: 'string',
37
+ summary:
38
+ "the label inside the token (ult_<env>_…): dev, stage, prod — default: the environment's (ULTIMATE_ENV production → prod, staging → stage, else dev)",
39
+ subcommands: ['create'],
40
+ },
41
+ {
42
+ name: 'days',
43
+ type: 'string',
44
+ summary: `days until the token expires, 1 to ${TOKEN_MAX_DAYS} (default: never)`,
45
+ subcommands: ['create'],
46
+ },
47
+ {
48
+ name: 'owner',
49
+ type: 'string',
50
+ summary: 'list the tokens of this user or org id',
51
+ subcommands: ['list'],
52
+ },
53
+ ],
54
+ };
@@ -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);
@@ -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
- /** `run` is the gate (and what a bare `x verify` means); `merge` folds CI parts into its verdict. */
9
- export const VERIFY_SUBCOMMANDS = ['run', 'merge'] as const;
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);