@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
@@ -1,4 +1,4 @@
1
- // `x exercise [<name>] [--seed n]` — every action, query and job run once against generated rows,
1
+ // `x exercise [<name>] [--seed n]` — every action, query, job and route `load` run once on rows
2
2
  // with no test written: load the app, read `apps/web/exercise.ts`, run `@ultimat3/testing`'s pass
3
3
  // on a scratch database, write `.x/exercise.json`. CLI wiring only: the pass is testing's, the
4
4
  // verdict is `exercise-findings.ts`'s, so the gate step and this command read one rule.
@@ -8,10 +8,16 @@ import { join } from 'node:path';
8
8
  import { describeEntities, registeredEntities } from '@ultimat3/entity';
9
9
  import { registeredSubjects } from '@ultimat3/jobs';
10
10
  import type { NamedActor } from '@ultimat3/policy';
11
- import type { ExercisePhaseMs, ExerciseRecord, SeedEntity } from '@ultimat3/testing';
11
+ import type {
12
+ ExercisePhaseMs,
13
+ ExerciseRecord,
14
+ RouteLoadRecord,
15
+ SeedEntity,
16
+ } from '@ultimat3/testing';
12
17
  import {
13
18
  entitySeedWriter,
14
19
  planSweepLines,
20
+ routeLoadSubjects,
15
21
  runExercisePass,
16
22
  tenantFindingLines,
17
23
  } from '@ultimat3/testing';
@@ -31,13 +37,16 @@ import {
31
37
  renderExerciseTable,
32
38
  slowestProofLines,
33
39
  } from './exercise-findings';
40
+ import { exerciseFloorVerdict } from './exercise-floor-verdict';
34
41
  import { readExerciseOverrides } from './exercise-overrides';
42
+ import { emptyReachWarnings, routeLoadWarnings } from './exercise-routes';
35
43
  import { entityTenantFindings } from './exercise-static';
36
44
  import { subjectFindings, subjectProofFindings } from './exercise-subject';
37
45
  import { readIntFlag } from './flag-number';
38
46
  import { msg } from './messages';
39
47
  import { withOfflinePorts } from './offline-ports';
40
48
  import type { CommandResult, JsonValue } from './output';
49
+ import { readVerifyFloor } from './verify-floor';
41
50
 
42
51
  /**
43
52
  * The actors `x policy explain` evaluates — `devActors()`, the `/_x` panel's own set — each a
@@ -94,6 +103,8 @@ async function exercisePass(
94
103
  (subject) => only === undefined && !subjectStatic.some((f) => f.at === subject.entity),
95
104
  );
96
105
  let pass: ExercisePhaseMs | undefined;
106
+ let routes: readonly RouteLoadRecord[] = [];
107
+ const routeSubjects = await routeLoadSubjects();
97
108
  const records: readonly ExerciseRecord[] = await withExerciseDatabase(root, ctx.env, (client) =>
98
109
  runExercisePass({
99
110
  entities,
@@ -102,9 +113,14 @@ async function exercisePass(
102
113
  ...(overrides === undefined ? {} : { overrides }),
103
114
  ...(only === undefined ? {} : { only }),
104
115
  roles: exerciseRoles,
116
+ // Every `app/` and `site/` route's `load`, after the primitives: a page read is measured too.
117
+ ...(only === undefined ? { routes: routeSubjects } : {}),
105
118
  onPhases: (ms) => {
106
119
  pass = ms;
107
120
  },
121
+ onRoutes: (got) => {
122
+ routes = got;
123
+ },
108
124
  }),
109
125
  );
110
126
  const subjectStarted = performance.now();
@@ -118,10 +134,28 @@ async function exercisePass(
118
134
  );
119
135
  const subject = Math.round(performance.now() - subjectStarted);
120
136
  const phases = pass === undefined ? undefined : { ...pass, subject };
121
- const report = exerciseReport(records, seed, phases);
137
+ // `routes` beside `records`, never in it: every reader of `records` reads a primitive's.
138
+ const report = {
139
+ ...exerciseReport(records, seed, phases),
140
+ ...(routes.length === 0 ? {} : { routes }),
141
+ };
142
+ // `x.verify.json`'s `exercise` key: red where the app opted in, a warning line where it has not.
143
+ // A whole-pass floor, so never judged on a `<name>` run's slice: 1 of 1 unproven is no ratio.
144
+ const floor =
145
+ only === undefined
146
+ ? exerciseFloorVerdict(records, (await readVerifyFloor(root))?.exercise)
147
+ : { findings: [], warnings: [] };
148
+ // Warnings, never red on `main`: no floor key opts a page read in yet (`exercise-routes.ts`).
149
+ const warnings = [
150
+ ...floor.warnings,
151
+ ...routeLoadWarnings(routes),
152
+ ...(only === undefined ? emptyReachWarnings(records) : []),
153
+ ];
154
+ // One document, the file's and `--json`'s, its warnings in it (`lines` never holds what it lacks).
155
+ const document = warnings.length === 0 ? report : { ...report, warnings };
122
156
  // The whole pass, not a one-primitive run's slice of it, is what the file is for — but a
123
157
  // one-primitive run is still a fact worth keeping, so it is written either way.
124
- await Bun.write(join(root, EXERCISE_REPORT_FILE), `${JSON.stringify(report, null, 2)}\n`);
158
+ await Bun.write(join(root, EXERCISE_REPORT_FILE), `${JSON.stringify(document, null, 2)}\n`);
125
159
  const findings = [
126
160
  ...loaded.findings,
127
161
  // The static half of the tenant proof (`exercise-static.ts`): the pass's own question,
@@ -131,6 +165,7 @@ async function exercisePass(
131
165
  ...subjectProofs,
132
166
  // The fix pastes into the file the app has, or hands it the file it lacks.
133
167
  ...exerciseFindings(records, overrides === undefined ? 'absent' : 'present'),
168
+ ...floor.findings,
134
169
  ];
135
170
  return {
136
171
  ok: findings.length === 0,
@@ -146,8 +181,10 @@ async function exercisePass(
146
181
  ...tenantFindingLines(records),
147
182
  ...crashFindingLines(records),
148
183
  ...planSweepLines(records),
184
+ ...warnings.map((warning) => `! ${warning}`),
149
185
  ].map((line) => ` ${line}`),
150
186
  findings,
151
- data: report as unknown as JsonValue,
187
+ // The warning lines ride in `--json` too (`lines` never holds what the document lacks).
188
+ data: document as unknown as JsonValue,
152
189
  };
153
190
  }
@@ -0,0 +1,24 @@
1
+ // `x explain`'s declaration, apart from its body: the parser, `x help` and the `errors` step
2
+ // read it without loading `cmd-explain.ts`, which `registry.ts` imports only when the command runs.
3
+
4
+ import type { CommandSpec } from './parse';
5
+
6
+ export const explainSpec: CommandSpec = {
7
+ name: 'explain',
8
+ summary:
9
+ "one declared query's SQL, planned on the dev database by the exercise gate's plan oracle",
10
+ usage: "x explain <query> [--input '<json>'] [--org <id>] [--json]",
11
+ requiresApp: true,
12
+ flags: [
13
+ {
14
+ name: 'input',
15
+ type: 'string',
16
+ summary: "the query's input as JSON, parsed by its own schema (default {})",
17
+ },
18
+ {
19
+ name: 'org',
20
+ type: 'string',
21
+ summary: 'the tenant the read runs in — required when it reads a tenant-scoped entity',
22
+ },
23
+ ],
24
+ };
@@ -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
+ };