@ultimat3/cli 31.26.0 → 31.27.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 (117) hide show
  1. package/CLAUDE.md +44 -36
  2. package/README.md +5 -4
  3. package/package.json +29 -29
  4. package/src/app-mcp.ts +17 -3
  5. package/src/cmd-cache-spec.ts +5 -2
  6. package/src/cmd-db-spec.ts +2 -3
  7. package/src/cmd-db.ts +0 -2
  8. package/src/cmd-deploy-verify-sample.ts +93 -0
  9. package/src/cmd-deploy-verify.ts +2 -41
  10. package/src/cmd-dev-spec.ts +15 -1
  11. package/src/cmd-dev.ts +31 -4
  12. package/src/cmd-doctor.ts +4 -1
  13. package/src/cmd-exercise-spec.ts +7 -1
  14. package/src/cmd-exercise.ts +22 -10
  15. package/src/cmd-generate.ts +2 -0
  16. package/src/cmd-jobs-spec.ts +3 -6
  17. package/src/cmd-jobs.ts +1 -7
  18. package/src/cmd-logs-spec.ts +2 -1
  19. package/src/cmd-logs.ts +9 -28
  20. package/src/cmd-planned.ts +11 -45
  21. package/src/cmd-profile-frames.ts +99 -0
  22. package/src/cmd-profile-spec.ts +24 -0
  23. package/src/cmd-profile.ts +164 -0
  24. package/src/cmd-status-sample.ts +57 -0
  25. package/src/cmd-status-spec.ts +30 -0
  26. package/src/cmd-status.ts +108 -0
  27. package/src/cmd-token-spec.ts +5 -2
  28. package/src/cmd-token.ts +7 -3
  29. package/src/coverage-island.ts +121 -0
  30. package/src/coverage-lcov.ts +49 -5
  31. package/src/coverage-remap.ts +146 -0
  32. package/src/db-replay-engine-prepared.ts +66 -0
  33. package/src/db-replay-engine-template.ts +156 -0
  34. package/src/db-replay-engine.ts +4 -0
  35. package/src/db-replay-scratch-reap.ts +54 -0
  36. package/src/deploy-verify-flags.ts +9 -2
  37. package/src/deploy-verify-grade.ts +10 -3
  38. package/src/dev-boot.ts +14 -1
  39. package/src/dev-dashboard-guard.ts +57 -10
  40. package/src/dev-host.ts +46 -0
  41. package/src/dev-tls-cache.ts +103 -0
  42. package/src/dev-tls-der.ts +69 -0
  43. package/src/dev-tls.ts +120 -0
  44. package/src/doctor-browser.ts +60 -0
  45. package/src/error-codes-verify.ts +47 -0
  46. package/src/error-codes.ts +14 -23
  47. package/src/exercise-database.ts +40 -7
  48. package/src/exercise-push-device.ts +51 -0
  49. package/src/exercise-route-api.ts +74 -0
  50. package/src/exercise-routes.ts +14 -5
  51. package/src/exercise-services.ts +3 -1
  52. package/src/exercise-shard-flag.ts +47 -0
  53. package/src/fix-command.ts +2 -2
  54. package/src/generate-factories.ts +5 -11
  55. package/src/generate-feature-required.ts +9 -4
  56. package/src/generate-files.ts +20 -2
  57. package/src/generate-kinds.ts +5 -1
  58. package/src/guards.ts +21 -6
  59. package/src/island-bundle-options.ts +48 -0
  60. package/src/island-bundle.ts +18 -46
  61. package/src/island-link.ts +5 -0
  62. package/src/island-outputs.ts +5 -0
  63. package/src/mcp-errors-verify.ts +35 -0
  64. package/src/mcp-errors.ts +10 -19
  65. package/src/mcp-host-logs.ts +121 -0
  66. package/src/mcp-host.ts +12 -73
  67. package/src/messages-floor.ts +19 -0
  68. package/src/messages-status.ts +10 -0
  69. package/src/messages.ts +21 -0
  70. package/src/registry.ts +4 -0
  71. package/src/role-start-types.ts +7 -0
  72. package/src/role-start.ts +4 -0
  73. package/src/serve-boot.ts +7 -1
  74. package/src/serve-env-tls.ts +57 -0
  75. package/src/solid-loader.ts +27 -10
  76. package/src/templates/generate-export-rows.ts +136 -0
  77. package/src/templates/generate-import-rows.ts +186 -0
  78. package/src/templates/generate-rows-slice.ts +95 -0
  79. package/src/templates/github/ci.yml.ts +4 -0
  80. package/src/templates/scaffold-db-package.ts +3 -0
  81. package/src/templates/scaffold-docs.ts +8 -6
  82. package/src/templates/scaffold-repo.ts +2 -7
  83. package/src/templates/scaffold-site.ts +4 -1
  84. package/src/templates/scaffold-suites.ts +72 -0
  85. package/src/templates/scaffold-test-services.ts +35 -10
  86. package/src/templates/scaffold-verify-floor.ts +53 -31
  87. package/src/templates/shapes/api.ts +4 -0
  88. package/src/templates/slice-foundation.ts +3 -3
  89. package/src/unthrown-codes.ts +1 -1
  90. package/src/upgrade-gate.ts +6 -1
  91. package/src/upgrade-guards-baseline.ts +43 -0
  92. package/src/upgrade-guards.ts +37 -2
  93. package/src/upgrade-report.ts +3 -0
  94. package/src/verify-coverage-run.ts +42 -11
  95. package/src/verify-e2e.ts +115 -4
  96. package/src/verify-floor.ts +27 -0
  97. package/src/verify-guard-baseline.ts +109 -0
  98. package/src/verify-live.ts +72 -0
  99. package/src/verify-merge-skips.ts +51 -0
  100. package/src/verify-merge.ts +36 -2
  101. package/src/verify-run.ts +48 -7
  102. package/src/verify-services.ts +287 -0
  103. package/src/verify-skip-reason.ts +53 -0
  104. package/src/verify-strict.ts +108 -0
  105. package/src/verify-test-command.ts +129 -0
  106. package/src/verify-tests.ts +39 -126
  107. package/types/babel-modules.d.ts +2 -0
  108. package/wiki/CLI-Reference.md +142 -23
  109. package/wiki/Caching-And-Invalidation.md +1 -1
  110. package/wiki/Entities-And-Migrations.md +1 -1
  111. package/wiki/Jobs-And-Workflows.md +3 -3
  112. package/wiki/Known-Gaps.md +5 -1
  113. package/wiki/MCP-And-AI.md +1 -1
  114. package/wiki/PWA-And-Offline.md +1 -1
  115. package/wiki/Troubleshooting.md +3 -3
  116. package/wiki/Tutorial-05-Deploy-Free.md +2 -2
  117. package/wiki/Upgrading.md +3 -0
package/src/cmd-dev.ts CHANGED
@@ -10,15 +10,18 @@ import { requireAppRoot } from './app-root';
10
10
  import { devSpec } from './cmd-dev-spec';
11
11
  import type { CliCommand, CommandContext } from './command';
12
12
  import { startDev } from './dev-boot';
13
+ import { dashboardUrl, devHostFor } from './dev-host';
13
14
  import { clearLock, preflight, writeLock } from './dev-lock';
14
15
  import { teeDevLog } from './dev-log';
15
16
  import { devPortFor } from './dev-port';
16
17
  import { childRestart } from './dev-supervisor';
18
+ import { certificateNames } from './dev-tls';
19
+ import { devCertificate } from './dev-tls-cache';
17
20
  import { holdUntilShutdown } from './hold';
18
21
  import { msg } from './messages';
19
22
  import type { CommandResult } from './output';
20
23
  import { flagString } from './parse';
21
- import { DEV_BINDING, selectRoles } from './role-start';
24
+ import { selectRoles } from './role-start';
22
25
  import { describeServices, reportedUrls, resolveServices } from './runtime-bindings';
23
26
  import { liveFeedLabel } from './runtime-live-feed';
24
27
  import { cdnLabel, describeCdn, describeMail, mailLabel } from './runtime-services';
@@ -36,6 +39,7 @@ export const devCommand: CliCommand = {
36
39
  // Validated, not `parseInt`'d: `x dev --port abc` handed `NaN` to `Bun.serve`, which binds an
37
40
  // arbitrary port — a dev server reachable at an address nothing printed.
38
41
  const port = devPortFor(ctx.args, ctx.env);
42
+ const hostname = devHostFor(ctx.args);
39
43
  const roles = selectRoles(flagString(ctx.args, 'role'));
40
44
  // BEFORE anything boots. Both failures this catches were reachable and both reported the wrong
41
45
  // thing: a taken port surfaced as X_CLI_UNEXPECTED wrapping "Is port 3000 in use?" with a `fix:`
@@ -48,7 +52,7 @@ export const devCommand: CliCommand = {
48
52
  port,
49
53
  // The address the web role will actually bind, never a wider one: probing `0.0.0.0` would
50
54
  // refuse a boot that a neighbour on one LAN interface does not actually block.
51
- hostname: DEV_BINDING.hostname,
55
+ hostname,
52
56
  embeddedDb: services.db.mode === 'embedded',
53
57
  });
54
58
  // The directory is CLAIMED from here down, so a boot that throws has to give it back — the
@@ -57,10 +61,25 @@ export const devCommand: CliCommand = {
57
61
  // Before the boot, so its own lines are in it: `logs.tail` reads this file, and a dev server
58
62
  // that never wrote it answered every agent with X_NOT_IMPLEMENTED.
59
63
  const untee = teeDevLog(services.stateDir);
64
+ // Generated before the boot, inside the claim: the pair is cached in the state directory.
65
+ const tls =
66
+ ctx.args.flags.get('tls') === true
67
+ ? await devCertificate({
68
+ stateDir: services.stateDir,
69
+ names: certificateNames(hostname),
70
+ now: new Date(),
71
+ }).catch((error: unknown) => {
72
+ release();
73
+ untee();
74
+ throw error;
75
+ })
76
+ : undefined;
60
77
  const restart = childRestart(root, ctx.env);
61
78
  const server = await startDev({
62
79
  root,
63
80
  port,
81
+ hostname,
82
+ ...(tls === undefined ? {} : { tls: { cert: tls.cert, key: tls.key } }),
64
83
  roles,
65
84
  env: ctx.env,
66
85
  onReload: (file, durationMs) => {
@@ -75,6 +94,8 @@ export const devCommand: CliCommand = {
75
94
  });
76
95
  // A restart retires this worker before it drains, so a save never cancels a running job.
77
96
  restart.adopt(server.running.worker);
97
+ // A specific non-loopback bind has no loopback listener, and `/_x` answers loopback only.
98
+ const introspect = dashboardUrl(server.url);
78
99
  const result: CommandResult = {
79
100
  ok: server.findings.length === 0,
80
101
  command: 'dev',
@@ -90,6 +111,9 @@ export const devCommand: CliCommand = {
90
111
  // renderers have drifted and only one of them can be scripted against.
91
112
  data: {
92
113
  url: server.url,
114
+ host: hostname,
115
+ // Where the generated certificate is, to trust it (`curl --cacert`, the OS keychain).
116
+ tls: tls === undefined ? null : { certPath: tls.certPath },
93
117
  roles: [...server.roles],
94
118
  sync: server.running.syncUrl,
95
119
  // The scrape target, on its own port for every role: what an operator points a Prometheus
@@ -114,7 +138,7 @@ export const devCommand: CliCommand = {
114
138
  liveFeed: server.running.liveFeed,
115
139
  buildId: server.buildId,
116
140
  manifest: join(root, MANIFEST_FILENAME),
117
- introspect: `${server.url}/_x`,
141
+ introspect,
118
142
  panels: [...server.panels],
119
143
  mcp: server.mcp,
120
144
  mcpPaths: [...server.mcpPaths],
@@ -126,7 +150,10 @@ export const devCommand: CliCommand = {
126
150
  msg('cli.dev.roles', { roles: server.roles.join(', ') }),
127
151
  msg('cli.dev.panels', { panels: server.panels.join(', ') }),
128
152
  msg('cli.dev.manifest', { path: join(root, MANIFEST_FILENAME) }),
129
- msg('cli.dev.introspect', { url: `${server.url}/_x` }),
153
+ ...(tls === undefined ? [] : [msg('cli.dev.tls', { path: tls.certPath })]),
154
+ introspect === null
155
+ ? msg('cli.dev.introspectUnreachable', { url: server.url })
156
+ : msg('cli.dev.introspect', { url: introspect }),
130
157
  // Only when something was mounted: the unmounted case has already said why, once, as a
131
158
  // warning with a fix, and a summary line reading `mcp none` would be a second copy of it.
132
159
  // One line per endpoint, so an app serving customers, staff and affiliates sees all three.
package/src/cmd-doctor.ts CHANGED
@@ -8,6 +8,7 @@ import { doctorSpec } from './cmd-doctor-spec';
8
8
  import type { CliCommand, CommandContext } from './command';
9
9
  import { appUrlFindings } from './doctor-app-url';
10
10
  import { authStorageFindings } from './doctor-auth';
11
+ import { browserProbe, browserWarnings, withBrowserReport } from './doctor-browser';
11
12
  import { chartAlertsProbe, NOTHING_MISSING, withChartAlertsListing } from './doctor-chart-alerts';
12
13
  import { coverageExcludesProbe, withCoverageExcludes } from './doctor-coverage';
13
14
  import { embeddedDatabaseFinding } from './doctor-database';
@@ -184,9 +185,11 @@ export async function reportDoctor(probe: DoctorProbe): Promise<CommandResult> {
184
185
  );
185
186
  // Last, and beside the verdict on `main`: the 31.16.0 checks (`doctor-warnings.ts`).
186
187
  // A missing shipped guard among them (`X_SHIPPED_GUARD_MISSING`): a warning, so exit stays.
187
- return withDoctorWarnings(reminded, [
188
+ const browser = await browserProbe(probe.root);
189
+ return withDoctorWarnings(withBrowserReport(reminded, browser), [
188
190
  ...(await doctorWarnings(probe)),
189
191
  ...missingGuardWarnings(guardEntries),
192
+ ...browserWarnings(browser),
190
193
  ]);
191
194
  }
192
195
 
@@ -6,7 +6,7 @@ import type { CommandSpec } from './parse';
6
6
  export const exerciseSpec: CommandSpec = {
7
7
  name: 'exercise',
8
8
  summary: 'run every action, query and job once on generated rows, with no test written',
9
- usage: 'x exercise [<name>] [--seed n] [--json]',
9
+ usage: 'x exercise [<name>] [--seed n] [--shard i/n] [--json]',
10
10
  requiresApp: true,
11
11
  flags: [
12
12
  {
@@ -15,5 +15,11 @@ export const exerciseSpec: CommandSpec = {
15
15
  summary:
16
16
  'the integer the seed graph and every generated input are drawn from; same seed, same pass',
17
17
  },
18
+ {
19
+ name: 'shard',
20
+ type: 'string',
21
+ summary:
22
+ 'i/n: run the i-th of n disjoint slices of the pass, written to .x/exercise.<i>-of-<n>.json; the floor is judged unsharded',
23
+ },
18
24
  ],
19
25
  };
@@ -30,7 +30,6 @@ import { devActors } from './dev-policy';
30
30
  import { withExerciseDatabase, withExerciseProcess } from './exercise-database';
31
31
  import {
32
32
  crashFindingLines,
33
- EXERCISE_REPORT_FILE,
34
33
  exerciseFindings,
35
34
  exercisePhaseLine,
36
35
  exerciseReport,
@@ -39,10 +38,13 @@ import {
39
38
  } from './exercise-findings';
40
39
  import { exerciseFloorVerdict } from './exercise-floor-verdict';
41
40
  import { readExerciseOverrides } from './exercise-overrides';
41
+ import { EXERCISE_APP_URL, servedInProcess } from './exercise-route-api';
42
42
  import { emptyReachWarnings, routeLoadWarnings } from './exercise-routes';
43
+ import { readExerciseShard, shardReportFile } from './exercise-shard-flag';
43
44
  import { entityTenantFindings } from './exercise-static';
44
45
  import { subjectFindings, subjectProofFindings } from './exercise-subject';
45
46
  import { readIntFlag } from './flag-number';
47
+ import { withAppUrl } from './measure-scope';
46
48
  import { msg } from './messages';
47
49
  import { withOfflinePorts } from './offline-ports';
48
50
  import type { CommandResult, JsonValue } from './output';
@@ -71,6 +73,8 @@ export const exerciseCommand: CliCommand = {
71
73
  async run(ctx: CommandContext): Promise<CommandResult> {
72
74
  const root = requireAppRoot('exercise', ctx.cwd).dir;
73
75
  const seed = readSeed(ctx);
76
+ // Read before anything loads: a refused split runs nothing.
77
+ readExerciseShard(ctx.args, ctx.args.positionals[0]);
74
78
  return withExerciseProcess(root, ctx.env, () => exercise(ctx, root, seed));
75
79
  },
76
80
  };
@@ -83,7 +87,10 @@ async function exercise(
83
87
  const loaded = await loadApp(root);
84
88
  // `runtime.ts`'s ports, as a boot reads them — an `auditSink` declared there is what lets an
85
89
  // `audit: true` primitive run — through `offline-ports.ts`, so the pass reaches no real backend.
86
- return withOfflinePorts(root, () => exercisePass(ctx, root, seed, loaded));
90
+ // `APP_URL` named when the env names none: a load's typed client is answered in process.
91
+ return withAppUrl(EXERCISE_APP_URL, () =>
92
+ withOfflinePorts(root, () => exercisePass(ctx, root, seed, loaded)),
93
+ );
87
94
  }
88
95
 
89
96
  async function exercisePass(
@@ -93,14 +100,16 @@ async function exercisePass(
93
100
  loaded: Awaited<ReturnType<typeof loadApp>>,
94
101
  ): Promise<CommandResult> {
95
102
  const only = ctx.args.positionals[0];
103
+ const shard = readExerciseShard(ctx.args, only);
104
+ // The pass-wide halves — static findings, the subject proof — are the first slice's alone.
105
+ const whole = only === undefined && (shard === undefined || shard.index === 1);
96
106
  const overrides = await readExerciseOverrides(root);
97
107
  const cores = registeredEntityCores();
98
108
  const entities: readonly SeedEntity[] = Object.values(cores);
99
109
  // Static before any row: a subject whose plan is refused is not proved, it is reported.
100
- const subjectStatic =
101
- only === undefined ? subjectFindings(registeredSubjects(), registeredEntities()) : [];
110
+ const subjectStatic = whole ? subjectFindings(registeredSubjects(), registeredEntities()) : [];
102
111
  const proved = registeredSubjects().filter(
103
- (subject) => only === undefined && !subjectStatic.some((f) => f.at === subject.entity),
112
+ (subject) => whole && !subjectStatic.some((f) => f.at === subject.entity),
104
113
  );
105
114
  let pass: ExercisePhaseMs | undefined;
106
115
  let routes: readonly RouteLoadRecord[] = [];
@@ -112,9 +121,11 @@ async function exercisePass(
112
121
  ...(seed === undefined ? {} : { seed }),
113
122
  ...(overrides === undefined ? {} : { overrides }),
114
123
  ...(only === undefined ? {} : { only }),
124
+ ...(shard === undefined ? {} : { shard }),
115
125
  roles: exerciseRoles,
116
126
  // Every `app/` and `site/` route's `load`, after the primitives: a page read is measured too.
117
- ...(only === undefined ? { routes: routeSubjects } : {}),
127
+ // Served by the app's own API in process: a load reading its typed client is measured too.
128
+ ...(only === undefined ? { routes: servedInProcess(routeSubjects) } : {}),
118
129
  onPhases: (ms) => {
119
130
  pass = ms;
120
131
  },
@@ -142,7 +153,7 @@ async function exercisePass(
142
153
  // `x.verify.json`'s `exercise` key: red where the app opted in, a warning line where it has not.
143
154
  // A whole-pass floor, so never judged on a `<name>` run's slice: 1 of 1 unproven is no ratio.
144
155
  const floor =
145
- only === undefined
156
+ only === undefined && shard === undefined
146
157
  ? exerciseFloorVerdict(records, (await readVerifyFloor(root))?.exercise)
147
158
  : { findings: [], warnings: [] };
148
159
  // Warnings, never red on `main`: no floor key opts a page read in yet (`exercise-routes.ts`).
@@ -155,12 +166,13 @@ async function exercisePass(
155
166
  const document = warnings.length === 0 ? report : { ...report, warnings };
156
167
  // The whole pass, not a one-primitive run's slice of it, is what the file is for — but a
157
168
  // one-primitive run is still a fact worth keeping, so it is written either way.
158
- await Bun.write(join(root, EXERCISE_REPORT_FILE), `${JSON.stringify(document, null, 2)}\n`);
169
+ const reportFile = shardReportFile(shard);
170
+ await Bun.write(join(root, reportFile), `${JSON.stringify(document, null, 2)}\n`);
159
171
  const findings = [
160
172
  ...loaded.findings,
161
173
  // The static half of the tenant proof (`exercise-static.ts`): the pass's own question,
162
174
  // asked of the declarations before any row is written.
163
- ...(only === undefined ? entityTenantFindings(describeEntities()) : []),
175
+ ...(whole ? entityTenantFindings(describeEntities()) : []),
164
176
  ...subjectStatic,
165
177
  ...subjectProofs,
166
178
  // The fix pastes into the file the app has, or hands it the file it lacks.
@@ -173,7 +185,7 @@ async function exercisePass(
173
185
  summary:
174
186
  records.length === 0
175
187
  ? msg('cli.exercise.none')
176
- : msg('cli.exercise.summary', { ...report.counts, file: EXERCISE_REPORT_FILE }),
188
+ : msg('cli.exercise.summary', { ...report.counts, file: reportFile }),
177
189
  lines: [
178
190
  ...renderExerciseTable(records),
179
191
  ...(phases === undefined ? [] : [exercisePhaseLine(phases)]),
@@ -395,6 +395,8 @@ const READS_SLICE: ReadonlySet<Generator> = new Set([
395
395
  'mutator',
396
396
  'query',
397
397
  'backfill',
398
+ 'export-rows',
399
+ 'import-rows',
398
400
  ]);
399
401
 
400
402
  /**
@@ -17,20 +17,17 @@ export const JOBS_SUBCOMMANDS = [
17
17
  'resolve-step',
18
18
  'pause',
19
19
  'resume',
20
- 'drain',
21
20
  ] as const;
22
21
 
23
22
  export const jobsSpec: CommandSpec = {
24
23
  name: 'jobs',
25
- // Never ENDING in "(planned)": that suffix is how `x help` and the planned-table tests tell a
26
- // planned COMMAND from a shipped one, and `x jobs` ships — only its `drain` does not.
27
24
  summary:
28
- 'list, show, retry, cancel, delete and promote jobs; resolve a step; pause and resume a queue (drain is planned)',
25
+ 'list, show, retry, cancel, delete and promote jobs; resolve a step; pause and resume a queue',
29
26
  usage:
30
- 'x jobs [list|show <id>|retry <id>|cancel <id>|delete <id>|promote <id>|resolve-step <id> <step>|pause <queue>|resume <queue>|drain] [--queue q] [--state s] [--name n] [--limit n] [--after cursor] [--from-step name] [--reason text] [--ran|--not-ran] [--output json] [--json]',
27
+ 'x jobs [list|show <id>|retry <id>|cancel <id>|delete <id>|promote <id>|resolve-step <id> <step>|pause <queue>|resume <queue>] [--queue q] [--state s] [--name n] [--limit n] [--after cursor] [--from-step name] [--reason text] [--ran|--not-ran] [--output json] [--json]',
31
28
  requiresApp: true,
32
29
  subcommands: JOBS_SUBCOMMANDS,
33
- // The bare `x jobs` lists; it never retries, cancels or drains anything.
30
+ // The bare `x jobs` lists; it never retries, cancels or pauses anything.
34
31
  defaultSubcommand: 'list',
35
32
  flags: [
36
33
  { name: 'queue', type: 'string', summary: 'filter by queue name' },
package/src/cmd-jobs.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // `x jobs list|show|retry|cancel|delete|promote|resolve-step|pause|resume` — introspect and
2
2
  // recover the job queue, bound to `@ultimat3/jobs`'s own introspection so the CLI, `/_x` and MCP
3
- // report identically; `drain` is planned (`cmd-planned.ts`): Postgres is the one durable driver.
3
+ // report identically.
4
4
  // CLI wiring only: the driver-injected logic is `jobs-report.ts`, the `--json` shapes
5
5
  // `jobs-json.ts`, the table `jobs-table.ts`, the queue `jobs-driver.ts` — shared with `x db`.
6
6
 
@@ -18,7 +18,6 @@ import { loadApp } from './app-load';
18
18
  import { requireAppRoot } from './app-root';
19
19
  import { runResolveStep } from './cmd-jobs-resolve';
20
20
  import { jobsSpec } from './cmd-jobs-spec';
21
- import { plannedSubcommand } from './cmd-planned';
22
21
  import type { CliCommand, CommandContext } from './command';
23
22
  import { BadFlagError, JobUnknownError, MissingPositionalError } from './errors';
24
23
  import { withJobDriver } from './jobs-driver';
@@ -258,11 +257,6 @@ export const jobsCommand: CliCommand = {
258
257
  async run(ctx: CommandContext): Promise<CommandResult> {
259
258
  const root = requireAppRoot('jobs', ctx.cwd).dir;
260
259
  const sub = ctx.args.subcommand ?? 'list';
261
- // BEFORE `withJobDriver`, which boots the source queue: the answer needs no server, so a box
262
- // whose database is down gets it rather than the boot failure of a queue never to be used —
263
- // and nothing is leased. 24.x's `--to`/`--dry-run` are deleted, so the parser refuses them
264
- // (`X_CLI_BAD_FLAG`); only a bare `x jobs drain` reaches this answer.
265
- if (sub === 'drain') throw plannedSubcommand('jobs', 'drain');
266
260
  // A TRACE is the queue row projected through the job's own declaration — its concurrency key,
267
261
  // its retry schedule — and a declaration exists in this process only once the app is loaded.
268
262
  // Unloaded, `show` answered `concurrencyKey: null` and `retryDelaysMs: []` for every job of
@@ -28,7 +28,8 @@ export const logsSpec: CommandSpec = {
28
28
  {
29
29
  name: 'role',
30
30
  type: 'string',
31
- summary: 'read .x/logs/<role>.log instead of the dev log (web, worker, scheduler, sync, …)',
31
+ summary:
32
+ 'one role (web, worker, scheduler, sync, …): its .x/logs/<role>.log, else its lines of the dev log',
32
33
  },
33
34
  ],
34
35
  };
package/src/cmd-logs.ts CHANGED
@@ -1,29 +1,21 @@
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.
1
+ // `x logs tail` — the last lines of `.x/dev.log` (what `x dev` tees), or one role's: its
2
+ // `.x/logs/<role>.log`, else its lines of the dev log. The `logs.tail` MCP tool's reader
3
+ // (`mcp-host-logs.ts`): a shell and an agent asking "what did the server just say" get one answer.
4
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';
5
+ import { isRole, ROLES } from '@ultimat3/core';
8
6
  import { requireAppRoot } from './app-root';
9
7
  import { LOGS_DEFAULT_LINES, LOGS_MAX_LINES, logsSpec } from './cmd-logs-spec';
10
8
  import type { CliCommand, CommandContext } from './command';
11
9
  import { ok } from './command';
12
10
  import { BadFlagError } from './errors';
13
11
  import { parseIntFlag } from './flag-number';
14
- import { logTailPath, type TailSource, tailLines } from './mcp-host';
12
+ import { type LogOpener, openLog, readLogTail } from './mcp-host-logs';
15
13
  import { msg } from './messages';
16
14
  import type { CommandResult } from './output';
17
15
  import { flagString } from './parse';
18
16
  import { resolveServices } from './runtime-bindings';
19
17
 
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
- };
18
+ export type { LogOpener } from './mcp-host-logs';
27
19
 
28
20
  /** `--role`, held to the runtime's roles BEFORE it is joined into a path. */
29
21
  function readRole(ctx: CommandContext): string | undefined {
@@ -56,20 +48,9 @@ export const logsCommandOver = (open: LogOpener): CliCommand => ({
56
48
  });
57
49
  const role = readRole(ctx);
58
50
  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);
51
+ // The MCP tool's reader, not a copy: a role's own log, else its lines of the dev log, else
52
+ // X_DEV_LOG_ABSENT naming `x dev`.
53
+ const { path, lines: tail } = await readLogTail(stateDir, lines, role, open);
73
54
  return ok('logs', msg('cli.logs.tail', { count: tail.length, path }), {
74
55
  lines: tail,
75
56
  data: { path, role: role ?? null, lines: [...tail] },
@@ -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 status` exiting X_CLI_UNKNOWN_COMMAND says "you typed something that
2
+ // registry on purpose: `x branch` 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
 
@@ -29,12 +29,6 @@ export const PLANNED_COMMANDS: readonly PlannedCommand[] = [
29
29
  usage: 'x branch [<name>|delete <name>] [--json]',
30
30
  fix: 'x db branch list --json # the database half: list, create <name>, delete <name>',
31
31
  },
32
- {
33
- name: 'status',
34
- summary: 'role health and the build-ID distribution of connected clients',
35
- usage: 'x status [--json]',
36
- fix: 'x doctor --json',
37
- },
38
32
  {
39
33
  name: 'ai',
40
34
  summary: 'eval scores, semantic-cache stats, vector reindex',
@@ -46,8 +40,8 @@ export const PLANNED_COMMANDS: readonly PlannedCommand[] = [
46
40
  // What is planned is a GENERATOR — the one thing a process that exits can contribute, since a
47
41
  // registration has to land in the app's own source to survive the run — and a generator that
48
42
  // emits the one call is not a second path any more than `x g route` is a second way to declare a
49
- // route (axiom 1). The whole table is shaped this way: `x status` beside `x doctor`, `x cache`
50
- // beside the `/_x` panel. What changed is only that the `fix:` is now true.
43
+ // route (axiom 1). The whole table is shaped this way: `x branch` beside `x db branch`, `x ai`
44
+ // beside `x test eval`. What changed is only that the `fix:` is now true.
51
45
  {
52
46
  name: 'money',
53
47
  summary: 'extend the currency table',
@@ -79,44 +73,16 @@ export interface PlannedSubcommand {
79
73
 
80
74
  /**
81
75
  * A subcommand of a shipped command that this build does not implement. Same promise as the table
82
- * above, one level down: `x db studio` stays in `x db`'s subcommand list, so the parser accepts it
83
- * and `x help db` still lists it, and it exits X_NOT_IMPLEMENTED naming what to run instead.
76
+ * above, one level down: the subcommand stays in its command's list, so the parser accepts it and
77
+ * `x help <command>` lists it, and it exits X_NOT_IMPLEMENTED naming what to run instead.
84
78
  *
85
- * `studio` is here because the migration engine is `@ultimat3/db`'s and only that. It used to
86
- * shell out to `bunx drizzle-kit studio` — a second schema tool, fetched unpinned at run time,
87
- * declared in no `package.json` — while every other `x db` subcommand went through the framework's
88
- * own ledger. One subcommand is not worth a second engine.
79
+ * Empty, `As of 2026-11-15` (plan 101-finished-and-self-maintained G6). `x token grant`,
80
+ * `x cache stats`, `x db studio` and `x jobs drain` left the registry rather than stay planned:
81
+ * a key's scopes are never widened, hit rates are aggregated by no process, the `/_x` db panel is
82
+ * the one schema browser, and Postgres is the one durable job driver. Each reason is its row in
83
+ * `wiki/Known-Gaps.md`; the parser now refuses each, with the same exit code.
89
84
  */
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
- },
105
- {
106
- command: 'db',
107
- subcommand: 'studio',
108
- fix: 'x dev # then the db panel at /_x: schema, rows, and a guarded SQL console',
109
- },
110
- // Planned because Postgres is the one durable job driver: there is nowhere to drain to. The two
111
- // `--to` values, `redis` and `nats`, were `X_NOT_IMPLEMENTED` stubs on every method, so a drain
112
- // leased the production batch for five minutes, failed each enqueue and nacked it back. 25.0.0
113
- // deleted both stubs and the unreachable drain body; a real second driver writes a new one.
114
- {
115
- command: 'jobs',
116
- subcommand: 'drain',
117
- fix: 'x jobs list --json # the queue as it stands; Postgres is the only durable driver, so there is nowhere to drain to',
118
- },
119
- ];
85
+ export const PLANNED_SUBCOMMANDS: readonly PlannedSubcommand[] = [];
120
86
 
121
87
  /**
122
88
  * Thrown by the owning command, so the subcommand fails exactly where it would have run. Returns
@@ -0,0 +1,99 @@
1
+ // `x profile`'s reading of a JavaScriptCore sampling profile: which functions the samples landed
2
+ // in (self), and which were on the stack when they did (inclusive). Grouped per function — a line
3
+ // is where one sample landed, a function is what an author can go and change.
4
+
5
+ import type { SamplingProfileStackFrame, SamplingProfileStackTraces } from 'bun:jsc';
6
+
7
+ export interface HotFrame {
8
+ readonly name: string;
9
+ /** Root-relative when the file is the app's; `native` for a frame with no source. */
10
+ readonly file: string;
11
+ /** The line most of this function's self samples landed on; null when unknown. */
12
+ readonly line: number | null;
13
+ /** Samples whose innermost frame was this function. */
14
+ readonly self: number;
15
+ /** Samples with this function anywhere on the stack, each sample counted once. */
16
+ readonly total: number;
17
+ /** `self` over every sample, as a whole-number percent — never a float a script compares. */
18
+ readonly selfPercent: number;
19
+ }
20
+
21
+ export interface ProfileSummary {
22
+ readonly samples: number;
23
+ readonly intervalMicros: number;
24
+ readonly hottest: readonly HotFrame[];
25
+ }
26
+
27
+ const UNKNOWN_LINE = 4_294_967_295;
28
+
29
+ const fileOf = (frame: SamplingProfileStackFrame, root: string): string => {
30
+ const url = frame.sourceURL;
31
+ if (url === undefined || url === '') return 'native';
32
+ return url.startsWith(`${root}/`) ? url.slice(root.length + 1) : url;
33
+ };
34
+
35
+ const keyOf = (frame: SamplingProfileStackFrame): string =>
36
+ `${frame.name}\u0000${frame.sourceURL ?? ''}`;
37
+
38
+ interface Tally {
39
+ frame: SamplingProfileStackFrame;
40
+ self: number;
41
+ total: number;
42
+ lines: Map<number, number>;
43
+ }
44
+
45
+ const tallyFor = (tallies: Map<string, Tally>, frame: SamplingProfileStackFrame): Tally => {
46
+ const key = keyOf(frame);
47
+ const found = tallies.get(key);
48
+ if (found !== undefined) return found;
49
+ const fresh: Tally = { frame, self: 0, total: 0, lines: new Map() };
50
+ tallies.set(key, fresh);
51
+ return fresh;
52
+ };
53
+
54
+ const mostSampledLine = (lines: ReadonlyMap<number, number>): number | null => {
55
+ let best: [number, number] | undefined;
56
+ for (const entry of lines) if (best === undefined || entry[1] > best[1]) best = entry;
57
+ return best === undefined || best[0] === UNKNOWN_LINE ? null : best[0];
58
+ };
59
+
60
+ /** The `limit` hottest functions by self samples; ties broken by total, then name. */
61
+ export function hottestFrames(
62
+ traces: SamplingProfileStackTraces,
63
+ root: string,
64
+ limit: number,
65
+ ): ProfileSummary {
66
+ const tallies = new Map<string, Tally>();
67
+ for (const trace of traces.traces) {
68
+ const [innermost] = trace.frames;
69
+ if (innermost === undefined) continue;
70
+ const top = tallyFor(tallies, innermost);
71
+ top.self += 1;
72
+ top.lines.set(innermost.line, (top.lines.get(innermost.line) ?? 0) + 1);
73
+ const seen = new Set<string>();
74
+ for (const frame of trace.frames) {
75
+ const key = keyOf(frame);
76
+ if (seen.has(key)) continue; // recursion: one sample is one sample
77
+ seen.add(key);
78
+ tallyFor(tallies, frame).total += 1;
79
+ }
80
+ }
81
+ const samples = traces.traces.length;
82
+ const hottest = [...tallies.values()]
83
+ .filter((tally) => tally.self > 0)
84
+ .sort(
85
+ (a, b) => b.self - a.self || b.total - a.total || a.frame.name.localeCompare(b.frame.name),
86
+ )
87
+ .slice(0, limit)
88
+ .map(
89
+ (tally): HotFrame => ({
90
+ name: tally.frame.name === '' ? '(anonymous)' : tally.frame.name,
91
+ file: fileOf(tally.frame, root),
92
+ line: mostSampledLine(tally.lines),
93
+ self: tally.self,
94
+ total: tally.total,
95
+ selfPercent: samples === 0 ? 0 : Math.round((tally.self * 100) / samples),
96
+ }),
97
+ );
98
+ return { samples, intervalMicros: Math.round(traces.interval * 1_000_000), hottest };
99
+ }
@@ -0,0 +1,24 @@
1
+ // `x profile`'s declaration, apart from its body: the parser, `x help` and the `errors` step
2
+ // read it without loading `cmd-profile.ts`, which `registry.ts` imports only when the command runs.
3
+
4
+ import type { CommandSpec } from './parse';
5
+
6
+ export const profileSpec: CommandSpec = {
7
+ name: 'profile',
8
+ summary:
9
+ "a CPU profile of rendering one route in-process: the app booted, the route's hottest functions",
10
+ usage: 'x profile <route> [--runs 20] [--top 10] [--json]',
11
+ requiresApp: true,
12
+ flags: [
13
+ {
14
+ name: 'runs',
15
+ type: 'string',
16
+ summary: 'requests profiled after one warm-up request (default 20)',
17
+ },
18
+ {
19
+ name: 'top',
20
+ type: 'string',
21
+ summary: 'how many of the hottest functions to report (default 10)',
22
+ },
23
+ ],
24
+ };