@ultimat3/cli 31.27.0 → 31.29.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 (134) hide show
  1. package/CLAUDE.md +4 -1
  2. package/README.md +14 -4
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/app-migrations-verdict.ts +84 -0
  6. package/src/cmd-doctor.ts +11 -3
  7. package/src/cmd-drill.ts +23 -9
  8. package/src/cmd-repro-spec.ts +13 -1
  9. package/src/cmd-repro.ts +37 -5
  10. package/src/cmd-upgrade-codemods.ts +71 -0
  11. package/src/cmd-upgrade-spec.ts +19 -5
  12. package/src/cmd-upgrade.ts +91 -34
  13. package/src/codemods/agents-dev-mcp.ts +50 -0
  14. package/src/codemods/authenticator-session-refusal.ts +214 -0
  15. package/src/codemods/biome-no-default-export.ts +58 -0
  16. package/src/codemods/bunfig-island-coverage.ts +33 -0
  17. package/src/codemods/chart-dashboard.ts +73 -0
  18. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  19. package/src/codemods/ci-e2e-browser.ts +63 -0
  20. package/src/codemods/codemod.ts +58 -0
  21. package/src/codemods/define-error-leaf.ts +73 -0
  22. package/src/codemods/docs-ci-parts.ts +65 -0
  23. package/src/codemods/docs-gate-prose.ts +53 -0
  24. package/src/codemods/docs-island-rows.ts +31 -0
  25. package/src/codemods/docs-shipped-guards.ts +100 -0
  26. package/src/codemods/docs-test-services.ts +62 -0
  27. package/src/codemods/engine-diff.ts +104 -0
  28. package/src/codemods/engine-edits.ts +111 -0
  29. package/src/codemods/engine-fs.ts +95 -0
  30. package/src/codemods/engine.ts +191 -0
  31. package/src/codemods/format-edited-hook-3122.ts +28 -0
  32. package/src/codemods/format-edited-hook.ts +152 -0
  33. package/src/codemods/helm-alerts-deploy.ts +85 -0
  34. package/src/codemods/helm-alerts-objective.ts +105 -0
  35. package/src/codemods/helm-alerts-stock.ts +108 -0
  36. package/src/codemods/index.ts +60 -0
  37. package/src/codemods/metrics-probe-healthz.ts +47 -0
  38. package/src/codemods/migrate-job-ordered.ts +81 -0
  39. package/src/codemods/migrate-job-stock.ts +41 -0
  40. package/src/codemods/pending.ts +36 -0
  41. package/src/codemods/repro-gitignore.ts +40 -0
  42. package/src/codemods/runtime-pin-lines.ts +109 -0
  43. package/src/codemods/runtime-pin.ts +116 -0
  44. package/src/codemods/solid-floor.ts +63 -0
  45. package/src/codemods/test-ports.ts +86 -0
  46. package/src/codemods/test-suites.ts +37 -0
  47. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  48. package/src/codemods/vendored-guards.ts +186 -0
  49. package/src/codemods/verify-floor-skips.ts +88 -0
  50. package/src/codemods/verify-floor-steps.ts +90 -0
  51. package/src/doctor-advisory-floors.ts +113 -0
  52. package/src/doctor-guards.ts +39 -86
  53. package/src/doctor-superseded.ts +67 -0
  54. package/src/drill-schema-behind.ts +26 -0
  55. package/src/error-codes-doctor.ts +12 -4
  56. package/src/error-codes.ts +9 -0
  57. package/src/exercise-database.ts +7 -2
  58. package/src/framework-schema-apply.ts +7 -19
  59. package/src/framework-schema-stamp.ts +38 -3
  60. package/src/framework-schema-verify.ts +120 -0
  61. package/src/framework-schema-wait.ts +125 -0
  62. package/src/generate-files.ts +6 -5
  63. package/src/guards-built-in-codes.ts +36 -0
  64. package/src/guards-built-in-refusal.ts +25 -0
  65. package/src/guards-built-in.ts +134 -0
  66. package/src/guards-materialize.ts +42 -0
  67. package/src/guards-paths.ts +37 -0
  68. package/src/guards-shipped-names.ts +38 -0
  69. package/src/guards-vendored.ts +73 -0
  70. package/src/guards.ts +90 -34
  71. package/src/index.ts +10 -0
  72. package/src/lint-findings.ts +3 -3
  73. package/src/mcp-errors.ts +12 -1
  74. package/src/measure-scope.ts +23 -3
  75. package/src/messages-repro.ts +16 -2
  76. package/src/messages-upgrade.ts +15 -0
  77. package/src/messages.ts +1 -1
  78. package/src/repro-archive-collect.ts +161 -0
  79. package/src/repro-archive-write.ts +96 -0
  80. package/src/repro-archive.ts +161 -0
  81. package/src/repro-bundle.ts +8 -16
  82. package/src/repro-errors.ts +14 -2
  83. package/src/repro-framework.ts +53 -0
  84. package/src/repro-parse.ts +87 -0
  85. package/src/repro-redact.ts +218 -0
  86. package/src/repro-scrub.ts +257 -0
  87. package/src/role-pg-stats.ts +21 -0
  88. package/src/role-start.ts +4 -0
  89. package/src/runtime-queue.ts +27 -6
  90. package/src/serve-boot-probe.ts +97 -0
  91. package/src/serve-boot.ts +26 -1
  92. package/src/serve-retire.ts +16 -3
  93. package/src/superseded-match.ts +87 -0
  94. package/src/superseded.ts +84 -0
  95. package/src/templates/bun-image.ts +48 -0
  96. package/src/templates/chart-dashboard-panels.ts +178 -0
  97. package/src/templates/chart-dashboard.ts +9 -135
  98. package/src/templates/github/ci.yml.ts +1 -1
  99. package/src/templates/guard-released-forms.ts +112 -0
  100. package/src/templates/guard-runtime-pin-test.ts +54 -0
  101. package/src/templates/guard-runtime-pin.ts +189 -0
  102. package/src/templates/scaffold-claude-agents.ts +6 -6
  103. package/src/templates/scaffold-claude-commands.ts +1 -1
  104. package/src/templates/scaffold-claude-hook.ts +18 -8
  105. package/src/templates/scaffold-claude.ts +2 -2
  106. package/src/templates/scaffold-container.ts +2 -2
  107. package/src/templates/scaffold-docs.ts +26 -24
  108. package/src/templates/scaffold-guards.ts +73 -39
  109. package/src/templates/scaffold-helm-alert-deploy.ts +105 -0
  110. package/src/templates/scaffold-helm-alert-rules.ts +7 -1
  111. package/src/templates/scaffold-helm-alerts.ts +3 -0
  112. package/src/templates/scaffold-helm-migrate.ts +85 -0
  113. package/src/templates/scaffold-helm-templates.ts +2 -36
  114. package/src/templates/scaffold-helm.ts +1 -0
  115. package/src/templates/scaffold-repo.ts +2 -1
  116. package/src/unthrown-codes.ts +2 -0
  117. package/src/upgrade-bun-floor.ts +4 -0
  118. package/src/upgrade-clean-tree.ts +54 -0
  119. package/src/upgrade-gate-codemods-install.ts +40 -0
  120. package/src/upgrade-gate-codemods.ts +151 -0
  121. package/src/upgrade-gate.ts +38 -6
  122. package/src/upgrade-lock.ts +118 -0
  123. package/src/upgrade-plan.ts +2 -1
  124. package/src/upgrade-report-codemods.ts +54 -0
  125. package/src/upgrade-report.ts +52 -27
  126. package/src/upgrade-signals.ts +91 -0
  127. package/src/upgrade-unfinished.ts +61 -0
  128. package/wiki/CLI-Reference.md +70 -5
  129. package/wiki/Deployment.md +2 -1
  130. package/wiki/Interface-Rules.md +17 -8
  131. package/wiki/Known-Gaps.md +1 -1
  132. package/wiki/Observability.md +1 -0
  133. package/wiki/Project-Layout.md +4 -4
  134. package/wiki/Upgrading.md +6 -0
@@ -1,8 +1,8 @@
1
1
  // The three ways a boot meets the framework schema (plan 101, s1-con #5): `applyLockedSchema` runs
2
2
  // the DDL in ONE transaction behind the migration advisory lock with a bounded `lock_timeout`, then
3
- // stamps the build; `verifySchema` runs no DDL and refuses a database this build was never applied
4
- // to; `ensureSchema` reads the stamp and applies only when this build is absent from it. Which boot
5
- // takes which is `runtime-queue.ts`'s `SchemaMode`.
3
+ // stamps the build; `verifySchema` (`framework-schema-verify.ts`) runs none; `ensureSchema` reads
4
+ // the stamp and applies only when this build is absent from it. Which boot takes which is
5
+ // `runtime-queue.ts`'s `SchemaMode`.
6
6
 
7
7
  import { frameworkVersion, logger } from '@ultimat3/core';
8
8
  import type { DbClient } from '@ultimat3/db';
@@ -16,7 +16,6 @@ import {
16
16
  } from '@ultimat3/db';
17
17
  import { applyFrameworkSchema } from './framework-schema';
18
18
  import {
19
- FrameworkSchemaUnappliedError,
20
19
  frameworkSchemaHash,
21
20
  nextStamp,
22
21
  parseStamp,
@@ -25,13 +24,14 @@ import {
25
24
  stampVerdict,
26
25
  } from './framework-schema-stamp';
27
26
 
28
- const thisBuild = (): StampEntry => ({
27
+ /** This process's build, as the stamp records one. */
28
+ export const thisBuild = (): StampEntry => ({
29
29
  version: frameworkVersion(),
30
30
  schema: frameworkSchemaHash(),
31
31
  });
32
32
 
33
33
  /** The stamp as the catalog holds it; `null` when the relation or its comment is absent. */
34
- async function readStamp(client: DbClient): Promise<string | null> {
34
+ export async function readStamp(client: DbClient): Promise<string | null> {
35
35
  const rows = await client.query<{ readonly stamp: string | null }>(
36
36
  raw(`select obj_description(to_regclass('${STAMP_RELATION}'), 'pg_class') as stamp`),
37
37
  );
@@ -62,18 +62,6 @@ export async function applyLockedSchema(client: DbClient): Promise<void> {
62
62
  );
63
63
  }
64
64
 
65
- /**
66
- * One catalog read. A build absent from the stamp is refused with the command that applies it; a
67
- * fleet straddling a major is reported once and served — refusing it would crash-loop the old pods
68
- * of every rolling deploy across a breaking release.
69
- */
70
- export async function verifySchema(client: DbClient): Promise<void> {
71
- const mine = thisBuild();
72
- const verdict = stampVerdict(parseStamp(await readStamp(client)), mine);
73
- if (!verdict.applied) throw new FrameworkSchemaUnappliedError({ mine, newest: verdict.newest });
74
- reportSkew(mine, verdict.skew);
75
- }
76
-
77
65
  /**
78
66
  * A CLI command's boot — `x db backfill`, `x jobs`, `x auth`: no DDL when this build's stamp is
79
67
  * already there, the locked apply when it is not.
@@ -100,7 +88,7 @@ export async function ensureSchema(client: DbClient): Promise<void> {
100
88
  * A fleet straddling a major is reported once and served — refusing it would crash-loop the old
101
89
  * pods of every rolling deploy across a breaking release.
102
90
  */
103
- function reportSkew(mine: StampEntry, skew: StampEntry | undefined): void {
91
+ export function reportSkew(mine: StampEntry, skew: StampEntry | undefined): void {
104
92
  if (skew === undefined) return;
105
93
  logger.warn('ultimate framework major skew', {
106
94
  cause: `this process runs ${mine.version} and the database's framework schema was last applied by ${skew.version}: a fleet across a major boundary is mid-rollout or half rolled back`,
@@ -54,6 +54,22 @@ export function nextStamp(previous: string | null | undefined, mine: StampEntry)
54
54
 
55
55
  const majorOf = (version: string): string => version.split('.')[0] ?? version;
56
56
 
57
+ /**
58
+ * A newest build whose major is numerically above this one's: a database a later breaking release
59
+ * migrated. A serving role of the older build does not wait on it — no migrate of this build is
60
+ * coming in that rollout — and is refused at once.
61
+ */
62
+ export function aheadByMajor(newest: StampEntry | undefined, mine: StampEntry): boolean {
63
+ if (newest === undefined) return false;
64
+ const theirs = Number(majorOf(newest.version));
65
+ const ours = Number(majorOf(mine.version));
66
+ return Number.isFinite(theirs) && Number.isFinite(ours) && theirs > ours;
67
+ }
68
+
69
+ /** Whether `newest` is another major than this build, in either direction — the skew gauge's fact. */
70
+ export const otherMajor = (newest: StampEntry | undefined, mine: StampEntry): boolean =>
71
+ newest !== undefined && majorOf(newest.version) !== majorOf(mine.version);
72
+
57
73
  export type StampVerdict =
58
74
  | { readonly applied: true; readonly skew?: StampEntry }
59
75
  | { readonly applied: false; readonly newest?: StampEntry };
@@ -68,14 +84,27 @@ export function stampVerdict(entries: readonly StampEntry[], mine: StampEntry):
68
84
  if (!entries.some((entry) => entry.schema === mine.schema)) {
69
85
  return newest === undefined ? { applied: false } : { applied: false, newest };
70
86
  }
71
- return newest !== undefined && majorOf(newest.version) !== majorOf(mine.version)
87
+ return newest !== undefined && otherMajor(newest, mine)
72
88
  ? { applied: true, skew: newest }
73
89
  : { applied: true };
74
90
  }
75
91
 
92
+ /** The variable that bounds a serving role's wait for the migrate step (`framework-schema-wait.ts`). */
93
+ export const SCHEMA_WAIT_ENV = 'ULTIMATE_SCHEMA_WAIT_MS';
94
+
76
95
  /** A serving role over a database its build's framework tables were never applied to. */
77
96
  export class FrameworkSchemaUnappliedError extends UltimateError {
78
- constructor(input: { readonly mine: StampEntry; readonly newest: StampEntry | undefined }) {
97
+ constructor(input: {
98
+ readonly mine: StampEntry;
99
+ readonly newest: StampEntry | undefined;
100
+ /** How long the role waited for the migrate step before this refusal; absent when it did not. */
101
+ readonly waitedMs?: number;
102
+ }) {
103
+ const ahead = aheadByMajor(input.newest, input.mine);
104
+ const waited =
105
+ input.waitedMs === undefined
106
+ ? ''
107
+ : `. This role waited ${String(Math.round(input.waitedMs))}ms (${SCHEMA_WAIT_ENV}) for it`;
79
108
  super({
80
109
  code: 'X_FRAMEWORK_SCHEMA_UNAPPLIED',
81
110
  cause:
@@ -84,12 +113,18 @@ export class FrameworkSchemaUnappliedError extends UltimateError {
84
113
  input.newest === undefined
85
114
  ? `${STAMP_RELATION} carries no stamp, so no ROLE=migrate of this release ran`
86
115
  : `the newest applied build is ${input.newest.version} (${input.newest.schema})`
87
- }. A serving role verifies and never runs DDL: the migrate step must run first`,
116
+ }${
117
+ ahead
118
+ ? ', a newer major: this role refuses without waiting, since no migrate of this build is coming'
119
+ : ''
120
+ }. A serving role verifies and never runs DDL: the migrate step must run first${waited}`,
88
121
  fix: 'x db migrate',
89
122
  meta: {
90
123
  version: input.mine.version,
91
124
  schema: input.mine.schema,
92
125
  ...(input.newest === undefined ? {} : { newest: { ...input.newest } }),
126
+ ...(ahead ? { aheadByMajor: true } : {}),
127
+ ...(input.waitedMs === undefined ? {} : { waitedMs: Math.round(input.waitedMs) }),
93
128
  },
94
129
  });
95
130
  }
@@ -0,0 +1,120 @@
1
+ // A serving role's boot over an external database: no DDL, one statement per attempt once a
2
+ // migrate has run — the framework stamp and the app's `x_migrations` ledger together — and the
3
+ // wait for the migrate step when either is behind this build (`framework-schema-wait.ts`).
4
+
5
+ import { recordFrameworkSchema } from '@ultimat3/core';
6
+ import type { DbClient } from '@ultimat3/db';
7
+ import { isLedgerMissing, LEDGER_TABLE, raw } from '@ultimat3/db';
8
+ import {
9
+ AppMigrationsUnappliedError,
10
+ appMigrationsVerdict,
11
+ parseAppliedIds,
12
+ reportAppMigrationsAhead,
13
+ } from './app-migrations-verdict';
14
+ import { readStamp, reportSkew, thisBuild } from './framework-schema-apply';
15
+ import {
16
+ aheadByMajor,
17
+ FrameworkSchemaUnappliedError,
18
+ otherMajor,
19
+ parseStamp,
20
+ STAMP_RELATION,
21
+ type StampEntry,
22
+ stampVerdict,
23
+ } from './framework-schema-stamp';
24
+ import { type SchemaCheck, type SchemaWaitOptions, waitForSchema } from './framework-schema-wait';
25
+
26
+ export interface VerifySchemaOptions extends SchemaWaitOptions {
27
+ /** The migration ids this build ships (`readMigrations(root)`), oldest first. None: not read. */
28
+ readonly shipped?: readonly string[];
29
+ }
30
+
31
+ interface BootRead {
32
+ readonly stamp: string | null;
33
+ /** `undefined` when `x_migrations` does not exist. */
34
+ readonly applied: readonly string[] | undefined;
35
+ }
36
+
37
+ /**
38
+ * ONE statement on every database a migrate step has touched: the stamp and the ledger together.
39
+ * A missing ledger fails the whole of it (`42P01`) — Postgres resolves a relation when it PARSES,
40
+ * so no `case when to_regclass(…)` guard can name a table that may not exist — and only then is
41
+ * the stamp read alone: a second statement on a database no migrate has ever run on, never after.
42
+ */
43
+ async function readBoot(client: DbClient, withLedger: boolean): Promise<BootRead> {
44
+ if (!withLedger) return { stamp: await readStamp(client), applied: [] };
45
+ try {
46
+ const rows = await client.query<{ readonly stamp: string | null; readonly applied: unknown }>(
47
+ raw(
48
+ `select obj_description(to_regclass('${STAMP_RELATION}'), 'pg_class') as stamp, ` +
49
+ `(select coalesce(json_agg(id order by id), '[]'::json)::text from ${LEDGER_TABLE}) as applied`,
50
+ ),
51
+ );
52
+ return { stamp: rows[0]?.stamp ?? null, applied: parseAppliedIds(rows[0]?.applied) };
53
+ } catch (error) {
54
+ if (!isLedgerMissing(error)) throw error;
55
+ return { stamp: await readStamp(client), applied: undefined };
56
+ }
57
+ }
58
+
59
+ interface Served {
60
+ readonly skew: StampEntry | undefined;
61
+ readonly unknown: readonly string[];
62
+ }
63
+
64
+ function judge(read: BootRead, mine: StampEntry, shipped: readonly string[]): SchemaCheck<Served> {
65
+ const framework = stampVerdict(parseStamp(read.stamp), mine);
66
+ const app = appMigrationsVerdict(shipped, read.applied);
67
+ // Every read, each round of a wait included, scraped off the metrics listener `serveApp` opened
68
+ // before this boot began. `applied` is 0 while the role waits for EITHER half: what the alert
69
+ // reads is "this role is not serving because its schema is not applied".
70
+ recordFrameworkSchema({
71
+ applied: framework.applied && app.missing.length === 0,
72
+ majorSkew: framework.applied
73
+ ? framework.skew !== undefined
74
+ : otherMajor(framework.newest, mine),
75
+ });
76
+ if (!framework.applied) {
77
+ const { newest } = framework;
78
+ return {
79
+ ready: false,
80
+ atOnce: aheadByMajor(newest, mine),
81
+ refuse: (waitedMs) =>
82
+ new FrameworkSchemaUnappliedError({
83
+ mine,
84
+ newest,
85
+ ...(waitedMs === undefined ? {} : { waitedMs }),
86
+ }),
87
+ };
88
+ }
89
+ if (app.missing.length > 0) {
90
+ return {
91
+ ready: false,
92
+ refuse: (waitedMs) =>
93
+ new AppMigrationsUnappliedError({
94
+ missing: app.missing,
95
+ ledger: read.applied !== undefined,
96
+ ...(waitedMs === undefined ? {} : { waitedMs }),
97
+ }),
98
+ };
99
+ }
100
+ return { ready: true, value: { skew: framework.skew, unknown: app.unknown } };
101
+ }
102
+
103
+ /**
104
+ * Served once the framework stamp holds this build and the ledger holds every migration it ships.
105
+ * Behind on either WAITS — a rollout that starts the roles before the migrate Job finishes is a
106
+ * normal deploy, and refusing at once crash-looped it — then is refused with the command that
107
+ * applies. A database a newer major stamped is refused at once. Ahead is served and said once: a
108
+ * fleet straddling a major (`reportSkew`), a ledger holding migrations this build does not ship
109
+ * (`reportAppMigrationsAhead`) — both are the old pods of a rollout or a rollback.
110
+ */
111
+ export async function verifySchema(client: DbClient, options: VerifySchemaOptions): Promise<void> {
112
+ const mine = thisBuild();
113
+ const shipped = options.shipped ?? [];
114
+ const served = await waitForSchema(
115
+ async () => judge(await readBoot(client, shipped.length > 0), mine, shipped),
116
+ options,
117
+ );
118
+ reportSkew(mine, served.skew);
119
+ reportAppMigrationsAhead(served.unknown);
120
+ }
@@ -0,0 +1,125 @@
1
+ // A serving role over a schema still behind its build — the framework stamp or the app's ledger:
2
+ // wait for the migrate step, bounded by `ULTIMATE_SCHEMA_WAIT_MS`, on core's one backoff curve,
3
+ // saying so once — never exit at once and crash-loop a rollout that started the roles before the
4
+ // migrate Job finished (plan 101, D2). A SIGTERM mid-wait is a drain, never a wait to the deadline.
5
+
6
+ import type { Random, SleepClock } from '@ultimat3/core';
7
+ import {
8
+ ambientClock,
9
+ backoffDelay,
10
+ failureStreak,
11
+ isDraining,
12
+ onShutdown,
13
+ UltimateError,
14
+ } from '@ultimat3/core';
15
+ import { SCHEMA_WAIT_ENV } from './framework-schema-stamp';
16
+
17
+ export { SCHEMA_WAIT_ENV };
18
+
19
+ /**
20
+ * Five minutes: a migrate Job that has not stamped the database by then is failing, not slow, and
21
+ * it is the default `helm --wait` budget, so a rollout gives up on the pod no sooner than this.
22
+ */
23
+ export const DEFAULT_SCHEMA_WAIT_MS = 300_000;
24
+
25
+ /** The first wait and the ceiling of any one: a catalog read every 15s at worst, per pod. */
26
+ const WAIT_BASE_MS = 1_000;
27
+ const WAIT_MAX_MS = 15_000;
28
+
29
+ /** `X_CONFIG_INVALID`: a deadline that is not whole milliseconds is refused, never read as NaN. */
30
+ export class SchemaWaitInvalidError extends UltimateError {
31
+ constructor(value: string) {
32
+ super({
33
+ code: 'X_CONFIG_INVALID',
34
+ cause: `${SCHEMA_WAIT_ENV} is "${value}"; it is the whole number of milliseconds a serving role waits for the migrate step to bring the schema to its build, 0 to refuse at once`,
35
+ // Literal: a spliced value in a command position is what the fix-shell-arg ratchet refuses.
36
+ // `framework-schema-wait.test.ts` holds it equal to the two constants.
37
+ fix: 'docker run -e ULTIMATE_SCHEMA_WAIT_MS=300000 <image> # or unset it for the default',
38
+ meta: { key: SCHEMA_WAIT_ENV },
39
+ });
40
+ }
41
+ }
42
+
43
+ /** The declared deadline: unset or blank is the default; anything but decimal digits is refused. */
44
+ export function schemaWaitMsFromEnv(env: Readonly<Record<string, string | undefined>>): number {
45
+ const raw = env[SCHEMA_WAIT_ENV]?.trim();
46
+ if (raw === undefined || raw.length === 0) return DEFAULT_SCHEMA_WAIT_MS;
47
+ const ms = Number(raw);
48
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(ms)) throw new SchemaWaitInvalidError(raw);
49
+ return ms;
50
+ }
51
+
52
+ export interface SchemaWaitOptions {
53
+ /** How long to wait; the boot's `schemaWaitMsFromEnv(env)`. `0` refuses on the first read. */
54
+ readonly deadlineMs: number;
55
+ readonly clock?: SleepClock;
56
+ readonly random?: Random;
57
+ }
58
+
59
+ /** One read's answer: ready with what the caller reports, or the refusal it would end in. */
60
+ export type SchemaCheck<T> =
61
+ | { readonly ready: true; readonly value: T }
62
+ | {
63
+ readonly ready: false;
64
+ /** Built with how long the role waited, or without when it refuses on the first read. */
65
+ readonly refuse: (waitedMs?: number) => UltimateError;
66
+ /** No wait can help — a newer major migrated: refused on this read. */
67
+ readonly atOnce?: boolean;
68
+ };
69
+
70
+ /**
71
+ * `check` until it is ready, the deadline passes, or a drain begins. One line when the wait opens
72
+ * and one if its cause changes — the framework stamp landing with the app's migrations still
73
+ * pending is news — and one when it ends; never a line per read per pod.
74
+ */
75
+ export async function waitForSchema<T>(
76
+ check: () => Promise<SchemaCheck<T>>,
77
+ options: SchemaWaitOptions,
78
+ ): Promise<T> {
79
+ const { deadlineMs } = options;
80
+ const clock = options.clock ?? ambientClock();
81
+ const startedAt = clock.monotonic();
82
+ const streak = failureStreak({
83
+ event: 'ultimate schema waiting',
84
+ recoveredEvent: 'ultimate schema applied',
85
+ level: 'warn',
86
+ fields: { deadlineMs },
87
+ });
88
+ const stop = new AbortController();
89
+ // The `accept` phase, the first: the boot is under `holdWhileBooting`'s handlers, so a SIGTERM
90
+ // here is a drain, and this wait is the boot work it must end.
91
+ const unregister = onShutdown('cli:schema-wait', () => stop.abort(), { phase: 'accept' });
92
+ try {
93
+ for (let attempt = 1; ; attempt += 1) {
94
+ const verdict = await check();
95
+ if (verdict.ready) {
96
+ streak.passed();
97
+ return verdict.value;
98
+ }
99
+ const waitedMs = clock.monotonic() - startedAt;
100
+ if (verdict.atOnce === true || deadlineMs === 0) throw verdict.refuse();
101
+ if (waitedMs >= deadlineMs || stop.signal.aborted || isDraining()) {
102
+ throw verdict.refuse(waitedMs);
103
+ }
104
+ streak.failed(verdict.refuse());
105
+ const delay = backoffDelay({
106
+ attempt,
107
+ base: WAIT_BASE_MS,
108
+ max: WAIT_MAX_MS,
109
+ jitter: 'equal',
110
+ random: options.random,
111
+ });
112
+ try {
113
+ // Cut to the deadline: the last read lands ON it, never a whole backoff past it.
114
+ await clock.sleep(Math.min(delay, deadlineMs - waitedMs), stop.signal);
115
+ } catch (error) {
116
+ // The drain's abort ends the wait with the refusal `holdWhileBooting` turns into an exit
117
+ // of `drainExitCode()`; any other rejection is the clock's own, and is rethrown as it came.
118
+ if (!stop.signal.aborted) throw error;
119
+ throw verdict.refuse(clock.monotonic() - startedAt);
120
+ }
121
+ }
122
+ } finally {
123
+ unregister();
124
+ }
125
+ }
@@ -8,6 +8,7 @@ import type { Generator } from './generate-kinds';
8
8
  import { assertLiveSupported, assertSurfaceSupported, GENERATORS } from './generate-kinds';
9
9
  import type { SignInMode } from './generate-sign-in-mode';
10
10
  import { dedupe } from './generate-write';
11
+ import { refuseShippedGuardName } from './guards-built-in-refusal';
11
12
  import { quoteArg } from './shell-quote';
12
13
  import type { GeneratedFile, Surface } from './templates';
13
14
  import {
@@ -24,7 +25,6 @@ import {
24
25
  queryFiles,
25
26
  resourceFiles,
26
27
  routeFiles,
27
- shippedGuardFiles,
28
28
  taskFiles,
29
29
  } from './templates';
30
30
  import { adminCatalogFiles } from './templates/admin-catalog';
@@ -265,11 +265,12 @@ export function generate(options: GenerateOptions): readonly GeneratedFile[] {
265
265
  return dedupe(islandFiles(options.name, { dir: options.at ?? `${surfaceDir}/${feature}` }));
266
266
  // No `--at`, no surface, no feature: `guards/` is the one directory the gate discovers, and a
267
267
  // guard that lived anywhere else would need an app-side registration to be found.
268
- // A name the framework ships a guard under gets THAT guard — how an app adopts one it does
269
- // not have (`x doctor` names them). Any other name is the app's own convention, from the blank
270
- // template.
268
+ // A name the framework ships a guard under is refused: that guard already runs, built in, and
269
+ // installing the framework is the one way to get it (`guards-built-in-refusal.ts`). Any other
270
+ // name is the app's own convention, from the blank template.
271
271
  case 'guard':
272
- return dedupe(shippedGuardFiles(kebab(options.name)) ?? guardFiles(options.name));
272
+ refuseShippedGuardName(kebab(options.name));
273
+ return dedupe(guardFiles(options.name));
273
274
  case 'admin:page':
274
275
  // A default permission, never none: an empty list is `X_ADMIN_PAGE_UNGUARDED` on sight.
275
276
  return dedupe(
@@ -0,0 +1,36 @@
1
+ // The codes the shipped guards raise, as `x.manifest.json` facts: a built-in guard that runs is a
2
+ // code this app's gate emits, exactly as a vendored copy's was, so moving the guard into the
3
+ // framework (`vendored-guards`) removes no code from the app's contract. Owned by `@ultimat3/cli`.
4
+
5
+ import type { ErrorCodeFact } from '@ultimat3/manifest';
6
+ import { planBuiltIns, readShippedConfig } from './guards-built-in';
7
+ import { guardPaths } from './guards-paths';
8
+ import { shippedGuardCode } from './guards-shipped-names';
9
+
10
+ /** The package a built-in's code is declared by: the CLI that ships and runs it. */
11
+ export const BUILT_IN_GUARD_PACKAGE = '@ultimat3/cli';
12
+
13
+ const byCode = (a: ErrorCodeFact, b: ErrorCodeFact): number => a.code.localeCompare(b.code);
14
+
15
+ /** Every built-in guard this app runs — any mode but `"off"`, never one it holds a copy of. */
16
+ export async function builtInGuardCodes(root: string): Promise<readonly ErrorCodeFact[]> {
17
+ const { builtIn } = planBuiltIns(
18
+ await guardPaths(root),
19
+ (await readShippedConfig(root)).severity,
20
+ );
21
+ return builtIn
22
+ .map(({ name }) => ({
23
+ code: shippedGuardCode(name),
24
+ package: BUILT_IN_GUARD_PACKAGE,
25
+ }))
26
+ .sort(byCode);
27
+ }
28
+
29
+ /** The app's own declarations win a code both name; the built-ins fill the rest, sorted by code. */
30
+ export const withBuiltInGuardCodes = (
31
+ app: readonly ErrorCodeFact[],
32
+ builtIn: readonly ErrorCodeFact[],
33
+ ): readonly ErrorCodeFact[] => {
34
+ const declared = new Set(app.map(({ code }) => code));
35
+ return [...app, ...builtIn.filter(({ code }) => !declared.has(code))].sort(byCode);
36
+ };
@@ -0,0 +1,25 @@
1
+ // `x g guard <shipped name>` refused: installing the framework is the one way to get a shipped
2
+ // guard (axiom 1), so writing a copy is a second path — and a copy runs in place of the installed
3
+ // guard, never receiving a fix. The refusal names the row that changes how it reports instead.
4
+
5
+ import { UltimateError } from '@ultimat3/core';
6
+ import { SHIPPED_GUARD_CONFIG } from './guards-built-in';
7
+ import { SHIPPED_GUARD_NAMES } from './templates/scaffold-guards';
8
+
9
+ /** A string here until the coordinator registers it in `error-codes.ts`. */
10
+ export const GUARD_BUILT_IN_CODE = 'X_GUARD_BUILT_IN';
11
+
12
+ export class GuardBuiltInError extends UltimateError {
13
+ constructor(name: string) {
14
+ super({
15
+ code: GUARD_BUILT_IN_CODE,
16
+ cause: `${name} is a guard the framework ships, and it already runs on x verify's boundaries step from the installed version — a copy in guards/ would run in its place and never receive a fix`,
17
+ fix: `x verify --only boundaries --json # ${name} already runs: set "${name}": "error", "warning" or "off" in ${SHIPPED_GUARD_CONFIG}, or x g guard app-${name} for a rule of your own`,
18
+ });
19
+ }
20
+ }
21
+
22
+ /** Throws for a shipped name (already kebab-cased, as the generator reads it); any other is the app's. */
23
+ export function refuseShippedGuardName(name: string): void {
24
+ if (SHIPPED_GUARD_NAMES.includes(name)) throw new GuardBuiltInError(name);
25
+ }
@@ -0,0 +1,134 @@
1
+ // The shipped guards, run from the INSTALLED framework instead of from copies in the app: which
2
+ // ones run for this app, at what severity, and the module each is imported from. An app's
3
+ // `guards/` holds its own rules and `guards/shipped.json` — a severity per shipped guard, never a
4
+ // copy of one — so a fixed guard reaches every app on its next install, with no hand edit.
5
+
6
+ // why: Bun ships no path joiner; `guards/shipped.json` sits under the app root.
7
+ import { join } from 'node:path';
8
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
9
+ import { SHIPPED_GUARD_NAMES, type ShippedGuardName } from './guards-shipped-names';
10
+ import type { Finding } from './output';
11
+
12
+ /** The app's one file about shipped guards. Its presence is the opt-in: absent, an app is legacy. */
13
+ export const SHIPPED_GUARD_CONFIG = 'guards/shipped.json';
14
+
15
+ /** The key inside it. Named once: the problem quotes it and the fix repairs it. */
16
+ export const SHIPPED_SEVERITY_FIELD = 'severity';
17
+
18
+ /** Where a built-in guard says it lives, in a finding: the package that ships it, never the app. */
19
+ export const BUILT_IN_GUARD_PREFIX = '@ultimat3/cli/guards';
20
+
21
+ /** A vendored copy of a shipped guard. A string here until the coordinator registers it. */
22
+ export const GUARD_VENDORED_CODE = 'X_GUARD_VENDORED';
23
+
24
+ /** `"error"` gates, `"warning"` reports only, `"off"` does not run. Absent: the guard's own. */
25
+ export type ShippedSeverity = 'error' | 'warning' | 'off';
26
+ export type ShippedSeverities = Readonly<Record<string, ShippedSeverity>>;
27
+
28
+ const SEVERITIES: readonly string[] = ['error', 'warning', 'off'];
29
+
30
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
31
+ typeof value === 'object' && value !== null && !Array.isArray(value);
32
+
33
+ /**
34
+ * `{ "severity": { "<shipped guard>": "error" | "warning" | "off" } }`, or the problems. A row
35
+ * naming a guard the framework does not ship is a problem, never ignored: a typo covers nothing.
36
+ */
37
+ export function parseShippedConfig(
38
+ text: string,
39
+ names: readonly string[] = SHIPPED_GUARD_NAMES,
40
+ ): { readonly severity: ShippedSeverities; readonly problems: readonly string[] } {
41
+ let payload: unknown;
42
+ try {
43
+ payload = JSON.parse(text);
44
+ } catch {
45
+ return { severity: {}, problems: ['it does not parse as JSON'] };
46
+ }
47
+ if (!isRecord(payload)) return { severity: {}, problems: ['it is not a JSON object'] };
48
+ const problems: string[] = Object.keys(payload)
49
+ .filter((key) => key !== SHIPPED_SEVERITY_FIELD)
50
+ .map((key) => `${JSON.stringify(key)} is not a key it reads — "${SHIPPED_SEVERITY_FIELD}" is`);
51
+ const raw = payload[SHIPPED_SEVERITY_FIELD];
52
+ if (raw === undefined) return { severity: {}, problems };
53
+ if (!isRecord(raw)) {
54
+ return {
55
+ severity: {},
56
+ problems: [...problems, `"${SHIPPED_SEVERITY_FIELD}" is not an object of guard → severity`],
57
+ };
58
+ }
59
+ const severity: Record<string, ShippedSeverity> = {};
60
+ for (const [name, value] of Object.entries(raw)) {
61
+ if (!names.includes(name)) {
62
+ problems.push(
63
+ `"${SHIPPED_SEVERITY_FIELD}" names ${JSON.stringify(name)}, not a shipped guard`,
64
+ );
65
+ } else if (typeof value !== 'string' || !SEVERITIES.includes(value)) {
66
+ problems.push(
67
+ `"${SHIPPED_SEVERITY_FIELD}" gives ${name} ${JSON.stringify(value)}, not "error", "warning" or "off"`,
68
+ );
69
+ } else severity[name] = value as ShippedSeverity;
70
+ }
71
+ return { severity, problems };
72
+ }
73
+
74
+ /** The app's config; `severity` undefined when it has none — a legacy app, not yet migrated. */
75
+ export async function readShippedConfig(
76
+ root: string,
77
+ ): Promise<{ readonly severity?: ShippedSeverities; readonly problems: readonly string[] }> {
78
+ const file = Bun.file(join(root, SHIPPED_GUARD_CONFIG));
79
+ if (!(await file.exists())) return { problems: [] };
80
+ return parseShippedConfig(await file.text());
81
+ }
82
+
83
+ /**
84
+ * How a built-in runs. `default`: as the guard declares itself. `error`/`warning`: the app's row
85
+ * over it. `legacy`: an app with no `guards/shipped.json` never had this guard gate it, so on
86
+ * `main` everything it says — a broken finding too — is a warning, never red.
87
+ */
88
+ export type BuiltInMode = 'default' | 'error' | 'warning' | 'legacy';
89
+
90
+ export interface BuiltInGuard {
91
+ readonly name: ShippedGuardName;
92
+ /** What a finding names as its source when the guard does not say: the package, not a file. */
93
+ readonly display: string;
94
+ readonly mode: BuiltInMode;
95
+ }
96
+
97
+ /** A shipped name's file in the app's own directory, `.ts` or `.tsx`, or undefined. */
98
+ export const vendoredPath = (paths: readonly string[], name: string): string | undefined =>
99
+ paths.find((path) => path === `guards/${name}.ts` || path === `guards/${name}.tsx`);
100
+
101
+ /**
102
+ * The rule, pure: every shipped guard this app runs built in, and the shipped names it holds a
103
+ * copy of. A copy wins — the app's file runs in its place — so an app that has not upgraded keeps
104
+ * exactly the rule it committed; the copy is reported (`vendoredWarning`) and never run twice.
105
+ */
106
+ export function planBuiltIns(
107
+ appPaths: readonly string[],
108
+ severity: ShippedSeverities | undefined,
109
+ ): { readonly builtIn: readonly BuiltInGuard[]; readonly vendored: readonly string[] } {
110
+ const builtIn: BuiltInGuard[] = [];
111
+ const vendored: string[] = [];
112
+ for (const name of SHIPPED_GUARD_NAMES) {
113
+ if (vendoredPath(appPaths, name) !== undefined) {
114
+ vendored.push(name);
115
+ continue;
116
+ }
117
+ const row =
118
+ severity !== undefined && Object.hasOwn(severity, name) ? severity[name] : undefined;
119
+ if (row === 'off') continue;
120
+ const mode: BuiltInMode = severity === undefined ? 'legacy' : (row ?? 'default');
121
+ builtIn.push({ name, display: `${BUILT_IN_GUARD_PREFIX}/${name}.ts`, mode });
122
+ }
123
+ return { builtIn, vendored };
124
+ }
125
+
126
+ /** The config's own problems: red, because a row the gate cannot read covers nothing. */
127
+ export const shippedConfigFindings = (problems: readonly string[]): readonly Finding[] =>
128
+ problems.map((problem) => ({
129
+ code: 'X_CONFIG_INVALID',
130
+ cause: `${SHIPPED_GUARD_CONFIG} is not a shipped-guard config: ${problem}`,
131
+ fix: `x verify --only boundaries --json # then write ${SHIPPED_GUARD_CONFIG} as { "${SHIPPED_SEVERITY_FIELD}": { "<guard>": "off" } } — "error", "warning" or "off" per shipped guard: ${SHIPPED_GUARD_NAMES.join(', ')}`,
132
+ docs: ERROR_DOCS_URL,
133
+ at: SHIPPED_GUARD_CONFIG,
134
+ }));
@@ -0,0 +1,42 @@
1
+ // A built-in guard's module on disk, so the gate can `import()` the installed framework's rule. Its
2
+ // own file, apart from `guards-built-in.ts`, because it reads the guard TEMPLATES — which the
3
+ // serving roles' graph never may, and that file is read by the manifest projection on it.
4
+
5
+ // why: Bun ships no rename, no forced remove and no path joiner; the module is written then renamed
6
+ // so a concurrent gate run never imports half a file.
7
+ import { rename, rm } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import { shippedGuardSource } from './templates/scaffold-guards';
10
+
11
+ /**
12
+ * The built-in's module, under the app's ignored `.x/cache/` (never a shared temp dir, where
13
+ * another user could plant the file first), named by its text's hash: a newer install is a new
14
+ * path, so a long-lived process never imports a stale copy from its module cache. Written to a temp
15
+ * file of its own per call — parallel calls in one process never share one — then renamed; the
16
+ * temp is gone either way, and so is a module an older install wrote for the same guard.
17
+ */
18
+ export async function materializeGuard(root: string, name: string): Promise<string> {
19
+ const source = shippedGuardSource(name) ?? '';
20
+ const dir = join(root, '.x', 'cache', 'guards');
21
+ const file = `${name}-${Bun.hash(source).toString(36)}.ts`;
22
+ const path = join(dir, file);
23
+ const existing = Bun.file(path);
24
+ if ((await existing.exists()) && (await existing.text()) === source) return path;
25
+ const temp = `${path}.${String(process.pid)}.${crypto.randomUUID().slice(0, 8)}.tmp`;
26
+ try {
27
+ await Bun.write(temp, source);
28
+ await rename(temp, path);
29
+ } finally {
30
+ await rm(temp, { force: true });
31
+ }
32
+ await removeStale(dir, name, file);
33
+ return path;
34
+ }
35
+
36
+ /** `<name>-<hash>.ts` an older install wrote — never `file`, never another guard sharing a prefix. */
37
+ async function removeStale(dir: string, name: string, file: string): Promise<void> {
38
+ const own = new RegExp(`^${name.replaceAll('-', '\\-')}-[0-9a-z]+\\.ts$`);
39
+ for await (const entry of new Bun.Glob(`${name}-*.ts`).scan({ cwd: dir })) {
40
+ if (entry !== file && own.test(entry)) await rm(join(dir, entry), { force: true });
41
+ }
42
+ }