@ultimat3/cli 31.42.1 → 31.44.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/cli",
3
- "version": "31.42.1",
3
+ "version": "31.44.0",
4
4
  "description": "The `x` binary: new, dev, build, verify, generate, db, mcp, doctor, deploy",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -53,34 +53,34 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@babel/core": "^8.0.10",
56
- "@ultimat3/action": "31.42.1",
57
- "@ultimat3/admin": "31.42.1",
58
- "@ultimat3/ai": "31.42.1",
59
- "@ultimat3/auth": "31.42.1",
60
- "@ultimat3/cache": "31.42.1",
61
- "@ultimat3/core": "31.42.1",
62
- "@ultimat3/db": "31.42.1",
63
- "@ultimat3/entity": "31.42.1",
64
- "@ultimat3/flags": "31.42.1",
65
- "@ultimat3/http": "31.42.1",
66
- "@ultimat3/i18n": "31.42.1",
67
- "@ultimat3/jobs": "31.42.1",
68
- "@ultimat3/mail": "31.42.1",
69
- "@ultimat3/manifest": "31.42.1",
70
- "@ultimat3/mcp": "31.42.1",
71
- "@ultimat3/money": "31.42.1",
72
- "@ultimat3/notify": "31.42.1",
73
- "@ultimat3/policy": "31.42.1",
74
- "@ultimat3/pwa": "31.42.1",
75
- "@ultimat3/query": "31.42.1",
76
- "@ultimat3/realtime": "31.42.1",
77
- "@ultimat3/render": "31.42.1",
78
- "@ultimat3/schema": "31.42.1",
79
- "@ultimat3/scraping": "31.42.1",
80
- "@ultimat3/seo": "31.42.1",
81
- "@ultimat3/storage": "31.42.1",
82
- "@ultimat3/testing": "31.42.1",
83
- "@ultimat3/time": "31.42.1",
56
+ "@ultimat3/action": "31.44.0",
57
+ "@ultimat3/admin": "31.44.0",
58
+ "@ultimat3/ai": "31.44.0",
59
+ "@ultimat3/auth": "31.44.0",
60
+ "@ultimat3/cache": "31.44.0",
61
+ "@ultimat3/core": "31.44.0",
62
+ "@ultimat3/db": "31.44.0",
63
+ "@ultimat3/entity": "31.44.0",
64
+ "@ultimat3/flags": "31.44.0",
65
+ "@ultimat3/http": "31.44.0",
66
+ "@ultimat3/i18n": "31.44.0",
67
+ "@ultimat3/jobs": "31.44.0",
68
+ "@ultimat3/mail": "31.44.0",
69
+ "@ultimat3/manifest": "31.44.0",
70
+ "@ultimat3/mcp": "31.44.0",
71
+ "@ultimat3/money": "31.44.0",
72
+ "@ultimat3/notify": "31.44.0",
73
+ "@ultimat3/policy": "31.44.0",
74
+ "@ultimat3/pwa": "31.44.0",
75
+ "@ultimat3/query": "31.44.0",
76
+ "@ultimat3/realtime": "31.44.0",
77
+ "@ultimat3/render": "31.44.0",
78
+ "@ultimat3/schema": "31.44.0",
79
+ "@ultimat3/scraping": "31.44.0",
80
+ "@ultimat3/seo": "31.44.0",
81
+ "@ultimat3/storage": "31.44.0",
82
+ "@ultimat3/testing": "31.44.0",
83
+ "@ultimat3/time": "31.44.0",
84
84
  "babel-preset-solid": "^1.9.16"
85
85
  }
86
86
  }
package/src/app-env.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  APP_CONFIG_FILE,
10
10
  ENV_EXAMPLE_PATH,
11
11
  ERROR_DOCS_URL,
12
+ isJsonObject,
12
13
  parseEnvKeys,
13
14
  pushWired,
14
15
  } from '@ultimat3/core';
@@ -35,15 +36,15 @@ export const ENV_SCHEMA_EXPORT = 'envSchema';
35
36
 
36
37
  const ENV_TYPES = new Set(['string', 'url', 'number', 'integer', 'port', 'boolean', 'enum']);
37
38
 
38
- const isRecord = (value: unknown): value is Record<string, unknown> =>
39
- typeof value === 'object' && value !== null;
40
-
41
39
  const isDecl = (value: unknown): value is EnvVarDecl =>
42
- isRecord(value) && typeof value['type'] === 'string' && ENV_TYPES.has(value['type']);
40
+ isJsonObject(value) && typeof value['type'] === 'string' && ENV_TYPES.has(value['type']);
43
41
 
44
- /** Structural, not `instanceof`: the schema is a plain record the app authored, never a class. */
42
+ /**
43
+ * Structural, not `instanceof`: the schema is a plain record the app authored, never a class — and
44
+ * never an array, whose values would otherwise pass as declarations keyed `0`, `1`, ….
45
+ */
45
46
  export const isEnvSchema = (value: unknown): value is EnvSchema =>
46
- isRecord(value) && Object.values(value).every(isDecl);
47
+ isJsonObject(value) && Object.values(value).every(isDecl);
47
48
 
48
49
  /**
49
50
  * The declaration `app.config.ts` exports, through the one loader (`app-config-load.ts`).
package/src/cmd-env.ts CHANGED
@@ -97,9 +97,16 @@ async function checkProcessEnv(ctx: CommandContext): Promise<CommandResult> {
97
97
  ...framework,
98
98
  ];
99
99
  const ok = findings.length === 0;
100
- const verdict = ok
101
- ? msg('cli.env.checked', { count: total })
102
- : msg('cli.env.invalid', { count: findings.length, total });
100
+ // The count is of DECLARED variables: a framework secret is no key of `envSchema`, so it is
101
+ // named by its code beside the count rather than counted into it ("3 of 2 declared").
102
+ const declared =
103
+ report.issues.length === 0
104
+ ? msg('cli.env.checked', { count: total })
105
+ : msg('cli.env.invalid', { count: report.issues.length, total });
106
+ const verdict =
107
+ framework.length === 0
108
+ ? declared
109
+ : `${declared} — ${framework.map((finding) => finding.code).join(', ')}`;
103
110
  return {
104
111
  ok,
105
112
  command: 'env',
@@ -354,7 +354,7 @@ export const createUpgradeCommand = (
354
354
  const to = readTarget(ctx);
355
355
  // One hop per app at a time, and a stopped hop stops its children: every spawn below is
356
356
  // tagged, and SIGINT/SIGTERM kill that tree and release the lock before the signal lands.
357
- const release = acquireUpgradeLock(root);
357
+ const release = await acquireUpgradeLock(root);
358
358
  const tag = upgradeTag();
359
359
  const pids = new Set<number>();
360
360
  const undoSignals = stopChildrenOnSignal({ tag, pids, cleanup: release });
@@ -0,0 +1,75 @@
1
+ // 31.43.0: the workflows `x new` writes run every action by commit SHA (`templates/github/
2
+ // actions.ts`), and ci.yml's checkouts drop the job token before `bun install`. Each stock line is
3
+ // swapped wherever it stands — every occurrence is the template's, so many is no guess — and a
4
+ // file still holding a movable `actions/*` tag after the swap is the author's, reported whole.
5
+
6
+ import { CACHE, CHECKOUT, DOWNLOAD_ARTIFACT, UPLOAD_ARTIFACT } from '../templates/github/actions';
7
+ import { CI_WORKFLOW_PATH } from '../templates/github/ci.yml';
8
+ import { IMAGE_WORKFLOW_PATH } from '../templates/github/image.yml';
9
+ import type { Codemod, CodemodApp, CodemodResult } from './codemod';
10
+ import { unifiedDiff } from './engine-diff';
11
+ import type { SnippetEdit } from './engine-edits';
12
+ import { mergeResults, readText } from './engine-edits';
13
+
14
+ const SETUP_BUN = ' - uses: oven-sh/setup-bun@';
15
+
16
+ /** ci.yml: each checkout is followed by setup-bun, so it has no `with:` of its own to collide. */
17
+ export const CI_PINNED_EDITS: readonly SnippetEdit[] = [
18
+ {
19
+ from: ` - uses: actions/checkout@v7\n${SETUP_BUN}`,
20
+ to: ` - uses: ${CHECKOUT}\n with:\n persist-credentials: false\n${SETUP_BUN}`,
21
+ },
22
+ { from: ' - uses: actions/cache@v6\n', to: ` - uses: ${CACHE}\n` },
23
+ { from: ' - uses: actions/upload-artifact@v7\n', to: ` - uses: ${UPLOAD_ARTIFACT}\n` },
24
+ {
25
+ from: ' - uses: actions/download-artifact@v8\n',
26
+ to: ` - uses: ${DOWNLOAD_ARTIFACT}\n`,
27
+ },
28
+ ];
29
+
30
+ /** image.yml: its checkout already set `persist-credentials: false`; only the pin moves. */
31
+ export const IMAGE_PINNED_EDITS: readonly SnippetEdit[] = [
32
+ { from: ' - uses: actions/checkout@v7\n', to: ` - uses: ${CHECKOUT}\n` },
33
+ ];
34
+
35
+ /** A GitHub-owned action still on a tag: what a stock file never holds once the edits ran. */
36
+ const MOVABLE = /uses:\s*actions\/[\w./-]+@v\d[^\n]*$/m;
37
+
38
+ const NOTHING: CodemodResult = { changed: [], skipped: [] };
39
+
40
+ async function pin(
41
+ app: CodemodApp,
42
+ path: string,
43
+ edits: readonly SnippetEdit[],
44
+ ): Promise<CodemodResult> {
45
+ const file = await readText(app, path);
46
+ if (file === undefined) return NOTHING;
47
+ const next = edits.reduce((source, edit) => source.replaceAll(edit.from, edit.to), file.text);
48
+ if (MOVABLE.test(next)) {
49
+ const side = (key: 'from' | 'to') => `${edits.map((edit) => edit[key]).join('\n')}\n`;
50
+ return {
51
+ changed: [],
52
+ skipped: [
53
+ {
54
+ path,
55
+ reason: `${path} runs an actions/* step by movable tag in a shape the scaffold never wrote (${MOVABLE.exec(next)?.[0].trim() ?? ''}), so the diff below is the template's change, to make by hand`,
56
+ diff: unifiedDiff(path, side('from'), side('to')),
57
+ },
58
+ ],
59
+ };
60
+ }
61
+ if (next === file.text) return NOTHING;
62
+ await app.write(path, file.restore(next));
63
+ return { changed: [path], skipped: [] };
64
+ }
65
+
66
+ export const codemod: Codemod = {
67
+ id: 'ci-pinned-actions',
68
+ since: '31.43.0',
69
+ summary: `${CI_WORKFLOW_PATH}, ${IMAGE_WORKFLOW_PATH}: every actions/* step pinned by commit SHA, and ci.yml's checkouts keep no git credential`,
70
+ run: async (app) =>
71
+ mergeResults([
72
+ await pin(app, CI_WORKFLOW_PATH, CI_PINNED_EDITS),
73
+ await pin(app, IMAGE_WORKFLOW_PATH, IMAGE_PINNED_EDITS),
74
+ ]),
75
+ };
@@ -8,6 +8,7 @@ import { codemod as biomeNoDefaultExport } from './biome-no-default-export';
8
8
  import { codemod as bunfigIslandCoverage } from './bunfig-island-coverage';
9
9
  import { codemod as chartDashboard } from './chart-dashboard';
10
10
  import { codemod as ciE2eBrowser } from './ci-e2e-browser';
11
+ import { codemod as ciPinnedActions } from './ci-pinned-actions';
11
12
  import { codemod as ciServicesEnv } from './ci-services-env';
12
13
  import type { Codemod } from './codemod';
13
14
  import { codemod as defineErrorLeaf } from './define-error-leaf';
@@ -63,4 +64,5 @@ export const CODEMODS: readonly Codemod[] = [
63
64
  ciServicesEnv,
64
65
  docsEnvGuard,
65
66
  testServices,
67
+ ciPinnedActions,
66
68
  ];
@@ -1,20 +1,17 @@
1
1
  // The resolved `AppConfig` as JSON an operator may paste into an issue: every credential-named key
2
- // and every `secret()` value replaced, a URL's password cut out of its userinfo. The key rule is
3
- // core's `isRedactedKey` — the logger's — so a field the log line hides is hidden here too.
2
+ // and every `secret()` value replaced, a URL's password cut out of its userinfo. Both rules are
3
+ // core's — `isRedactedKey` (the logger's) and `redactUrlPassword` — so a field hidden there is here.
4
4
 
5
- import { isRedactedKey, isSecret, REDACTED } from '@ultimat3/core';
5
+ import { isRedactedKey, isSecret, REDACTED, redactUrlPassword } from '@ultimat3/core';
6
6
  import type { JsonValue } from './output';
7
7
 
8
- /** `scheme://user:password@host` → `scheme://user:[redacted]@host`. The user stays: it is no secret. */
9
- const USERINFO_PASSWORD = /^([a-z][a-z0-9+.-]*:\/\/[^:/@\s]*):[^@/\s]*@/i;
10
-
11
8
  /** Past this depth a config is not data an operator wrote; the walk stops rather than recurse. */
12
9
  const MAX_DEPTH = 16;
13
10
 
14
11
  export function redactConfigValue(value: unknown, depth = 0): JsonValue {
15
12
  if (isSecret(value)) return REDACTED;
16
13
  if (value === null || value === undefined) return null;
17
- if (typeof value === 'string') return value.replace(USERINFO_PASSWORD, `$1:${REDACTED}@`);
14
+ if (typeof value === 'string') return redactUrlPassword(value);
18
15
  if (typeof value === 'number') return Number.isFinite(value) ? value : String(value);
19
16
  if (typeof value === 'boolean') return value;
20
17
  // A config may carry a callback (a `health` probe, a `resolve` hook): named, never its source.
@@ -4,7 +4,6 @@
4
4
 
5
5
  // why: /proc files report size 0, and Bun.file reads a file by its size — it answers ''.
6
6
  import { readFile } from 'node:fs/promises';
7
- import type { DevLock } from './dev-lock';
8
7
  import type { Runner } from './exec';
9
8
  import { exec } from './exec';
10
9
 
@@ -48,7 +47,10 @@ export async function processStartTime(
48
47
  * The lock's pid is alive but is not the process that wrote it: its start time differs from the one
49
48
  * recorded. Compared only where both are known (no start time on Windows, or in a pre-30 lock).
50
49
  */
51
- export const reusedPid = async (lock: DevLock): Promise<boolean> => {
50
+ export const reusedPid = async (lock: {
51
+ readonly pid: number;
52
+ readonly started?: string;
53
+ }): Promise<boolean> => {
52
54
  if (lock.started === undefined) return false;
53
55
  const now = await processStartTime(lock.pid);
54
56
  return now !== undefined && now !== lock.started;
@@ -12,6 +12,7 @@ import {
12
12
  onShutdown,
13
13
  UltimateError,
14
14
  } from '@ultimat3/core';
15
+ import { dbUnavailable } from '@ultimat3/db';
15
16
  import { SCHEMA_WAIT_ENV } from './framework-schema-stamp';
16
17
 
17
18
  export { SCHEMA_WAIT_ENV };
@@ -26,6 +27,14 @@ export const DEFAULT_SCHEMA_WAIT_MS = 300_000;
26
27
  const WAIT_BASE_MS = 1_000;
27
28
  const WAIT_MAX_MS = 15_000;
28
29
 
30
+ /**
31
+ * The least any one schema read is given, deadline or none. The deadline bounds a read too — a
32
+ * catalog read on a blackholed database hangs until the pool gives up, ~125 s on a worker — but a
33
+ * read must be ALLOWED to answer: `0` is "refuse at once if behind", and the last read lands on the
34
+ * deadline by design. A reachable database answers a catalog read well inside a second.
35
+ */
36
+ export const SCHEMA_READ_FLOOR_MS = 1_000;
37
+
29
38
  /** `X_CONFIG_INVALID`: a deadline that is not whole milliseconds is refused, never read as NaN. */
30
39
  export class SchemaWaitInvalidError extends UltimateError {
31
40
  constructor(value: string) {
@@ -100,8 +109,12 @@ export async function waitForSchema<T>(
100
109
  if (isDraining()) throw drained();
101
110
  for (let attempt = 1; ; attempt += 1) {
102
111
  // Raced against the drain like the sleep below: a read on an unreachable database hangs
103
- // until the pool gives up — ~125 s on a worker, past the pod's grace, so SIGKILL (137).
104
- const verdict = await untilAborted(check(), stop.signal, drained);
112
+ // until the pool gives up — ~125 s on a worker, past the pod's grace, so SIGKILL (137). And
113
+ // against the deadline, which the read would otherwise outlive by that same ~125 s.
114
+ const boundMs = Math.max(deadlineMs - (clock.monotonic() - startedAt), SCHEMA_READ_FLOOR_MS);
115
+ const unanswered = (): UltimateError =>
116
+ refuse?.(clock.monotonic() - startedAt) ?? readUnanswered(boundMs, deadlineMs);
117
+ const verdict = await bounded(check(), stop.signal, drained, boundMs, unanswered);
105
118
  if (verdict.ready) {
106
119
  streak.passed();
107
120
  return verdict.value;
@@ -150,19 +163,38 @@ function waitDrained(waitedMs = 0): UltimateError {
150
163
  }
151
164
 
152
165
  /**
153
- * `work`, unless `signal` aborts first — then `refusal()`, thrown. The abandoned read is not
154
- * cancelled (the pool's own bound retires it); `Promise.race` keeps its late rejection handled.
166
+ * `X_DB_UNAVAILABLE`, `@ultimat3/db`'s own refusal: the FIRST read never answered inside its bound,
167
+ * so there is no verdict to refuse with — only a database that does not answer.
168
+ */
169
+ function readUnanswered(boundMs: number, deadlineMs: number): UltimateError {
170
+ return dbUnavailable(
171
+ `this role's first schema read did not answer within ${String(Math.round(boundMs))} ms (${SCHEMA_WAIT_ENV} is ${String(deadlineMs)}; a read is given at least ${String(SCHEMA_READ_FLOOR_MS)} ms)`,
172
+ );
173
+ }
174
+
175
+ /**
176
+ * `work`, unless `signal` aborts first — then `drained()` — or `boundMs` of REAL time pass — then
177
+ * `unanswered()`. Real time, never the injected clock: a database hangs in real time, and a frozen
178
+ * clock's `sleep` returns at once, which would cut every read a test makes. The abandoned read is
179
+ * not cancelled (the pool's own bound retires it); `Promise.race` keeps its late rejection handled.
155
180
  */
156
- function untilAborted<V>(
181
+ function bounded<V>(
157
182
  work: Promise<V>,
158
183
  signal: AbortSignal,
159
- refusal: () => UltimateError,
184
+ drained: () => UltimateError,
185
+ boundMs: number,
186
+ unanswered: () => UltimateError,
160
187
  ): Promise<V> {
161
188
  let onAbort: () => void = () => undefined;
162
- const aborted = new Promise<never>((_resolve, reject) => {
163
- onAbort = () => reject(refusal());
189
+ let timer: ReturnType<typeof setTimeout> | undefined;
190
+ const cut = new Promise<never>((_resolve, reject) => {
191
+ onAbort = () => reject(drained());
164
192
  if (signal.aborted) onAbort();
165
193
  else signal.addEventListener('abort', onAbort, { once: true });
194
+ timer = setTimeout(() => reject(unanswered()), boundMs);
195
+ });
196
+ return Promise.race([work, cut]).finally(() => {
197
+ clearTimeout(timer);
198
+ signal.removeEventListener('abort', onAbort);
166
199
  });
167
- return Promise.race([work, aborted]).finally(() => signal.removeEventListener('abort', onAbort));
168
200
  }
@@ -3,7 +3,7 @@
3
3
  // config hostnames, any URL's userinfo and query values, emails and IPs become tokens; a frame's
4
4
  // absolute path is made relative. A value it was never told about is NOT found: say so to the user.
5
5
 
6
- import { isRedactedKey } from '@ultimat3/core';
6
+ import { isRedactedKey, replaceUrlUserinfo } from '@ultimat3/core';
7
7
 
8
8
  export interface ScrubEnv {
9
9
  readonly name: string;
@@ -153,12 +153,12 @@ const literal = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\
153
153
 
154
154
  /** A URL in prose: its scheme, then everything up to a space, a quote or a bracket. */
155
155
  const URL_TEXT = /\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`<>()]+/gi;
156
- /** Any URL's userinfo and query VALUES: credentials and tokens ride in both. */
156
+ /** Any URL's userinfo (to its LAST `@`) and query VALUES: credentials and tokens ride in both. */
157
157
  function withoutUrlSecrets(text: string): string {
158
158
  return text.replace(URL_TEXT, (url) =>
159
- url
160
- .replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, '$1[cred]@')
161
- .replace(/\?[^#]*/, (query) => query.replace(/=[^&]*/g, '=[redacted]')),
159
+ replaceUrlUserinfo(url, () => '[cred]').replace(/\?[^#]*/, (query) =>
160
+ query.replace(/=[^&]*/g, '=[redacted]'),
161
+ ),
162
162
  );
163
163
  }
164
164
 
@@ -0,0 +1,99 @@
1
+ // The sweep's deletes, fenced against a publish that lands after its last manifest read: the disk
2
+ // has no conditional delete, so each file's bytes are held across its delete, the manifests are
3
+ // read once more AFTER it, and every file a manifest now names is put back.
4
+
5
+ import { isUltimateError } from '@ultimat3/core';
6
+ import type { RetainedScope, StoredManifest } from './retained-assets-layout';
7
+ import { inBatches, readManifests, retainedFileKey } from './retained-assets-layout';
8
+
9
+ /** Files deleted per fence: the bytes held between a delete and its fence stay bounded. */
10
+ const FENCE_CHUNK = 64;
11
+
12
+ interface Held {
13
+ readonly key: string;
14
+ readonly bytes: Uint8Array;
15
+ readonly contentType: string;
16
+ }
17
+
18
+ const isCode = (error: unknown, code: string): boolean =>
19
+ isUltimateError(error) && error.code === code;
20
+
21
+ /** The file's bytes, or `undefined` when it is gone or too large to hold — then it is spared. */
22
+ async function hold(scope: RetainedScope, key: string): Promise<Held | undefined> {
23
+ try {
24
+ const read = await scope.disk.get(key);
25
+ return { key, bytes: read.bytes, contentType: read.object.contentType };
26
+ } catch (error) {
27
+ if (isCode(error, 'X_STORAGE_NOT_FOUND') || isCode(error, 'X_STORAGE_TOO_LARGE')) {
28
+ return undefined;
29
+ }
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Delete `doomed`, a chunk at a time, then read the manifests and put back what any manifest
36
+ * `counts` names. Correct against a publisher that writes its manifest and THEN ensures its files:
37
+ * a manifest written before the fence read is seen there; one written after it is followed by that
38
+ * publisher's own ensure, which runs after these deletes and puts the file back itself. A manifest
39
+ * that does not parse names nothing knowable, so the chunk is put back whole. Returns the deleted.
40
+ */
41
+ export async function deleteFenced(
42
+ scope: RetainedScope,
43
+ doomed: readonly string[],
44
+ counts: (one: StoredManifest) => boolean,
45
+ ): Promise<number> {
46
+ let deleted = 0;
47
+ for (let at = 0; at < doomed.length; at += FENCE_CHUNK) {
48
+ const held: Held[] = [];
49
+ await inBatches(doomed.slice(at, at + FENCE_CHUNK), async (key) => {
50
+ const one = await hold(scope, key);
51
+ if (one !== undefined) held.push(one);
52
+ });
53
+ await inBatches(held, ({ key }) => scope.disk.delete(key));
54
+ const fence = await readManifests(scope);
55
+ const named =
56
+ fence === undefined
57
+ ? undefined
58
+ : new Set(
59
+ fence
60
+ .filter(counts)
61
+ .flatMap(({ manifest }) => manifest.urls)
62
+ .map((url) => retainedFileKey(scope.prefix, url)),
63
+ );
64
+ const back = held.filter(({ key }) => named === undefined || named.has(key));
65
+ await inBatches(back, async ({ key, bytes, contentType }) => {
66
+ await scope.disk.put(key, bytes, { contentType });
67
+ });
68
+ deleted += held.length - back.length;
69
+ }
70
+ return deleted;
71
+ }
72
+
73
+ /**
74
+ * Delete a dropped manifest only if it still holds the date it was dropped at, read just before
75
+ * the delete: a rollback re-dates it, and then it is the newest build, not this sweep's to drop.
76
+ * The read and the delete are two calls, so a re-date landing between them is still lost — the
77
+ * disk offers no delete conditional on a revision; that build's next pod re-publishes it.
78
+ */
79
+ export async function deleteManifestIfUnchanged(
80
+ scope: RetainedScope,
81
+ key: string,
82
+ publishedAt: number,
83
+ ): Promise<void> {
84
+ let bytes: Uint8Array;
85
+ try {
86
+ bytes = (await scope.disk.get(key)).bytes;
87
+ } catch (error) {
88
+ if (isCode(error, 'X_STORAGE_NOT_FOUND')) return;
89
+ throw error;
90
+ }
91
+ let now: unknown;
92
+ try {
93
+ now = (JSON.parse(new TextDecoder().decode(bytes)) as { publishedAt?: unknown }).publishedAt;
94
+ } catch {
95
+ // Unparseable now: not the manifest judged, so not this sweep's to delete.
96
+ return;
97
+ }
98
+ if (now === publishedAt) await scope.disk.delete(key);
99
+ }
@@ -1,6 +1,6 @@
1
1
  // The `assets.retain` sweep: keep the newest `builds` manifests of one app-and-environment scope
2
- // and delete the files none of them names — without ever deleting what another pod is publishing
3
- // at the same moment. Run at the end of a publish.
2
+ // and delete the files none of them names, fenced against a publish on another pod at the same
3
+ // moment. Run at the end of a publish.
4
4
 
5
5
  import type { RetainedScope, StoredManifest } from './retained-assets-layout';
6
6
  import {
@@ -10,6 +10,7 @@ import {
10
10
  readManifests,
11
11
  retainedFileKey,
12
12
  } from './retained-assets-layout';
13
+ import { deleteFenced, deleteManifestIfUnchanged } from './retained-assets-sweep-fence';
13
14
 
14
15
  /**
15
16
  * A file put this recently is spared whatever the manifests say: it may belong to a publish still
@@ -22,10 +23,13 @@ const urlsOf = (manifests: readonly StoredManifest[]): readonly string[] =>
22
23
  manifests.flatMap(({ manifest }) => manifest.urls);
23
24
 
24
25
  /**
25
- * Manifests, then files, then the dropped manifests: a pod killed anywhere leaves extra objects,
26
- * never a missing one. Three guards against a concurrent publish: a file younger than the grace
27
- * stays; the manifests are read AGAIN just before deleting, and any that appeared keeps what it
28
- * names; a manifest that does not parse stops the sweep. Returns the files deleted.
26
+ * Manifests, then files, then the dropped manifests. Guards against a concurrent publish: a file
27
+ * younger than the grace stays; the manifests are read again before deleting, and any that
28
+ * appeared keeps what it names; the deletes are fenced (`deleteFenced`), so a manifest written
29
+ * after that read still gets back every file it names; a dropped manifest is re-read just before
30
+ * its delete (`deleteManifestIfUnchanged`); a manifest that does not parse stops the sweep. A pod
31
+ * killed mid-fence can lose a file a racing build reuses; that build's next pod puts it back.
32
+ * Returns the files deleted.
29
33
  */
30
34
  export async function sweepRetained(
31
35
  scope: RetainedScope,
@@ -63,8 +67,10 @@ export async function sweepRetained(
63
67
  // Unknown age is spared, as `sweepOrphans` spares it: never epoch 0, never "old enough".
64
68
  .filter((entry) => entry.lastModified !== undefined && entry.lastModified.getTime() < cutoff)
65
69
  .map((entry) => entry.key);
66
- await inBatches(doomed, (key) => scope.disk.delete(key));
70
+ const deleted = await deleteFenced(scope, doomed, (one) => !stillDropped(one));
67
71
  const drop = dropped.filter(({ key }) => !redated.has(key));
68
- await inBatches(drop, ({ key }) => scope.disk.delete(key));
69
- return doomed.length;
72
+ await inBatches(drop, ({ key, manifest }) =>
73
+ deleteManifestIfUnchanged(scope, key, manifest.publishedAt),
74
+ );
75
+ return deleted;
70
76
  }
@@ -0,0 +1,14 @@
1
+ // The GitHub-owned actions the workflows `x new` writes run, each pinned by commit SHA with its
2
+ // version in the trailing comment: a major tag is a pointer its owner (or whoever holds its token)
3
+ // can move under every app at once. The framework's own workflows run these exact pins, and the
4
+ // app's Dependabot `github-actions` group moves SHA and comment together.
5
+
6
+ export const CHECKOUT = 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1';
7
+
8
+ export const CACHE = 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0';
9
+
10
+ export const UPLOAD_ARTIFACT =
11
+ 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2';
12
+
13
+ export const DOWNLOAD_ARTIFACT =
14
+ 'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2';
@@ -7,6 +7,7 @@ import { REQUIRED_BUN } from '../../app-root';
7
7
  import { DEFAULT_PLAN_PARTS } from '../../verify-plan';
8
8
  import type { GeneratedFile, NameSet } from '../naming';
9
9
  import { TEST_COMPOSE_PATH, TEST_ENV_PATH } from '../scaffold-test-services';
10
+ import { CACHE, CHECKOUT, DOWNLOAD_ARTIFACT, UPLOAD_ARTIFACT } from './actions';
10
11
  import { DEPENDABOT_PATH, dependabot } from './dependabot.yml';
11
12
  import { IMAGE_WORKFLOW_PATH, imageWorkflow } from './image.yml';
12
13
  import { RUNS_ON } from './runner';
@@ -19,9 +20,8 @@ const CI_WORKFLOW_NAME = 'ci';
19
20
 
20
21
  /**
21
22
  * Pinned by commit SHA with the version in the trailing comment, because this step runs before any
22
- * code of yours does and `@v2` is a tag its owner can move. `actions/*` follows its major tag
23
- * instead: GitHub owns the runner and the tag together. Same rule the framework's own
24
- * `.github/actions/setup/action.yml` states, and the same SHA.
23
+ * code of yours does and `@v2` is a tag its owner can move. Every `actions/*` step is pinned the
24
+ * same way (`actions.ts`): the framework's own workflows pin each `uses:`, and run these SHAs.
25
25
  */
26
26
  export const SETUP_BUN = 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0';
27
27
 
@@ -29,17 +29,21 @@ export const SETUP_BUN = 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c624218
29
29
  export const PLAN_COMMAND = `bun run verify plan --parts ${String(DEFAULT_PLAN_PARTS)} --json`;
30
30
 
31
31
  /**
32
- * Every job's first three steps: the tree, the Bun floor, the install cache. `bun-version` is
32
+ * Every job's first three steps: the tree, the Bun floor, the install cache. The checkout keeps no
33
+ * git credential: `bun install` runs a dependency's lifecycle scripts next, and the job token left
34
+ * in `.git/config` would be theirs to read. `bun-version` is
33
35
  * `package.json`'s `engines.bun` floor exactly — the OLDEST runtime the app declares, so a call
34
36
  * that needs a newer Bun fails here rather than in the install of whoever took the app at its
35
37
  * word; never `latest`, a runtime change nobody chose. The cache is keyed on the lockfile.
36
38
  */
37
- const SETUP_STEPS = ` - uses: actions/checkout@v7
39
+ const SETUP_STEPS = ` - uses: ${CHECKOUT}
40
+ with:
41
+ persist-credentials: false
38
42
  - uses: ${SETUP_BUN}
39
43
  with:
40
44
  # engines.bun in package.json, exactly: the oldest Bun this app says it runs on.
41
45
  bun-version: '${REQUIRED_BUN}'
42
- - uses: actions/cache@v6
46
+ - uses: ${CACHE}
43
47
  with:
44
48
  path: ~/.bun/install/cache
45
49
  key: bun-\${{ runner.os }}-\${{ hashFiles('bun.lock') }}
@@ -140,7 +144,7 @@ ${SETUP_STEPS}
140
144
  bun run verify --only "$ONLY" \${SHARD:+--shard "$SHARD"} --json > "$RUNNER_TEMP/parts/$PART.json"
141
145
  # Uploaded when the part is RED too: a part with no document reads, in the merge, as a step
142
146
  # nobody ran. \`overwrite\`, so a re-run's document replaces the attempt it re-ran.
143
- - uses: actions/upload-artifact@v7
147
+ - uses: ${UPLOAD_ARTIFACT}
144
148
  if: \${{ !cancelled() }}
145
149
  with:
146
150
  name: verify-part-\${{ matrix.part }}
@@ -159,7 +163,7 @@ ${SETUP_STEPS}
159
163
  steps:
160
164
  ${SETUP_STEPS}
161
165
  - run: bun install
162
- - uses: actions/download-artifact@v8
166
+ - uses: ${DOWNLOAD_ARTIFACT}
163
167
  with:
164
168
  pattern: verify-part-*
165
169
  path: \${{ runner.temp }}/parts
@@ -3,6 +3,7 @@
3
3
  // default branch. It runs no gate of its own — a second gate is a second definition of one — and
4
4
  // it deploys nothing: the image digest is the handoff, axiom 7's one deploy artifact.
5
5
 
6
+ import { CHECKOUT } from './actions';
6
7
  import { DEFAULT_RUNNER } from './runner';
7
8
 
8
9
  /** Where the workflow lands, beside the gate it waits on. */
@@ -55,7 +56,7 @@ jobs:
55
56
  timeout-minutes: 30
56
57
  steps:
57
58
  # The commit the gate judged, not the tip of the branch when this run started.
58
- - uses: actions/checkout@v7
59
+ - uses: ${CHECKOUT}
59
60
  with:
60
61
  ref: \${{ github.event.workflow_run.head_sha }}
61
62
  persist-credentials: false
@@ -71,6 +71,8 @@ export const RELEASED_GUARD_FORMS: Readonly<
71
71
  ['3b0u9i8hze00x', 'error'],
72
72
  ],
73
73
  'undeclared-env': [
74
+ ['1xkusngzbabza', 'error'],
75
+ ['2jbihvbp83mb4', 'error'],
74
76
  ['3gsy96z8bgrrl', 'error'],
75
77
  ['81vvl6xx5bb8', 'error'],
76
78
  ],
@@ -81,6 +83,7 @@ export const RELEASED_GUARD_FORMS: Readonly<
81
83
  'untranslated-string': [
82
84
  ['2x85ib5eqdxzi', 'error'],
83
85
  ['3j5e8t1k120u3', 'error'],
86
+ ['d6gyn0l6szj8', 'error'],
84
87
  ['h57qtdwn7inz', 'error'],
85
88
  ],
86
89
  'unzoned-date': [
@@ -114,7 +117,7 @@ export const RELEASED_GUARD_TEST_FORMS: Readonly<Record<string, readonly string[
114
117
  'semantic-interactive': ['2uh0p6xoh996t', '393msxyy1bz36'],
115
118
  'unbounded-fanout': ['key86lol3wnh'],
116
119
  'undeclared-custom-property': ['30bi2v92swukf', 'svuf8sm14fm8'],
117
- 'undeclared-env': ['38run3rew6y0c'],
120
+ 'undeclared-env': ['38run3rew6y0c', '8xdp7gp7hol7'],
118
121
  'undefined-style-class': ['1uy88gpk5k8p8', '2sy8me3i3bmzw'],
119
122
  'untranslated-string': ['30q3u45cey2eq', 'cgvfv231gnvg'],
120
123
  'unzoned-date': ['1siep3fqscks4', '20x6l238r09jk'],
@@ -45,8 +45,11 @@ const source =
45
45
  // step — nothing registers this file, so nothing can forget to.
46
46
  //
47
47
  // Read: \`process.env.X\`, \`Bun.env.X\`, \`import.meta.env.X\` and the \`['X']\` forms, in app source
48
- // (\`apps/**\`, \`packages/**\`; never a test). Declared: a key of \`envSchema\` or of the object
49
- // \`defineEnv({ … })\` is handed, in \`app.config.ts\` — the declaration \`x env check\` reads.
48
+ // (\`apps/**\`, \`packages/**\`; never a test). Declared: a key of the \`envSchema\` export of
49
+ // \`app.config.ts\` — the one declaration \`x env check\` reads. A \`defineEnv(\` handed anything
50
+ // else (an inline \`{ … }\`) is refused: its record is unreachable once \`defineEnv\` returns values.
51
+ // Elsewhere, a record handed to \`defineEnv(\` — inline or a same-file \`const\` — names only keys
52
+ // \`envSchema\` declares: one built from \`envSchema.X\` reads it twice, never a second declaration.
50
53
  // Allowed: every name the framework reads itself, \`NODE_ENV\` among them, and the OS's own.
51
54
 
52
55
  import type { Finding, Guard } from '@ultimat3/cli';
@@ -67,8 +70,12 @@ const FRAMEWORK_PREFIXES = [${frameworkPrefixes()}];
67
70
  /** A literal read: \`process.env.X\` / \`Bun.env['X']\`. A computed key names nothing to check. */
68
71
  const READ =
69
72
  /\\b(?:process\\.env|Bun\\.env|import\\.meta\\.env)(?:\\.([A-Za-z_$][\\w$]*)|\\[\\s*(['"\`])([A-Za-z_$][\\w$]*)\\2\\s*\\])/g;
70
- /** Where the declaration opens: the \`envSchema\` export, or an object handed to \`defineEnv(\`. */
71
- const OPENS = /\\bexport\\s+const\\s+envSchema\\b[^=]*=\\s*\\{|\\bdefineEnv\\(\\s*\\{/g;
73
+ /** Where the declaration opens: the \`envSchema\` export, the one form every \`x\` command reads. */
74
+ const OPENS = /\\bexport\\s+const\\s+envSchema\\b[^=]*=\\s*\\{/g;
75
+ /** A \`defineEnv(\` handed anything but \`envSchema\`: a declaration no command can read back. */
76
+ const OTHER_FORM = /\\bdefineEnv\\(\\s*(?!envSchema\\s*[,)])/g;
77
+ /** A \`defineEnv(\` call in app source: its record inline (\`{\`) or a name to resolve in the file. */
78
+ const CALL = /\\bdefineEnv\\(\\s*(?:(\\{)|([A-Za-z_$][\\w$]*))/g;
72
79
  /** A key at the declaration's top level, once every nested group is emptied. */
73
80
  const KEY = /(?:^|[{,\\s])['"]?([A-Za-z_$][\\w$]*)['"]?\\s*:/g;
74
81
 
@@ -97,18 +104,23 @@ const groupAt = (text: string, open: number): string => {
97
104
  return text.slice(open + 1);
98
105
  };
99
106
 
107
+ /** The top-level keys of the record opening at \`open\`, every nested group emptied first. */
108
+ const topLevelKeys = (text: string, open: number): readonly string[] => {
109
+ let body = groupAt(text, open);
110
+ // Innermost first, until none is left: a declaration's own \`{ type: … }\` keys are not names.
111
+ for (let before = ''; before !== body; ) {
112
+ before = body;
113
+ body = body.replaceAll(/\\{[^{}]*\\}|\\[[^[\\]]*\\]/g, ' ');
114
+ }
115
+ return [...body.matchAll(KEY)].map((key) => key[1] ?? '');
116
+ };
117
+
100
118
  /** Every name \`app.config.ts\` declares: the top-level keys of each declaration it opens. */
101
119
  export function declaredNames(config: string): ReadonlySet<string> {
102
120
  const names = new Set<string>();
103
121
  const text = blank(config);
104
122
  for (const open of text.matchAll(OPENS)) {
105
- let body = groupAt(text, open.index + open[0].length - 1);
106
- // Innermost first, until none is left: a declaration's own \`{ type: … }\` keys are not names.
107
- for (let before = ''; before !== body; ) {
108
- before = body;
109
- body = body.replaceAll(/\\{[^{}]*\\}|\\[[^[\\]]*\\]/g, ' ');
110
- }
111
- for (const key of body.matchAll(KEY)) names.add(key[1] ?? '');
123
+ for (const key of topLevelKeys(text, open.index + open[0].length - 1)) names.add(key);
112
124
  }
113
125
  return names;
114
126
  }
@@ -153,14 +165,57 @@ const codeOnly = (text: string): string => {
153
165
  return out.join('');
154
166
  };
155
167
 
168
+ /** \`app.config.ts\` declaring its env any other way than the \`envSchema\` export. */
169
+ const formFindings = (config: string): readonly Finding[] => {
170
+ const text = blank(config);
171
+ const code = codeOnly(text);
172
+ return [...text.matchAll(OTHER_FORM)]
173
+ .filter((match) => code.charAt(match.index) !== ' ')
174
+ .map((match) => ({
175
+ code: CODE,
176
+ cause: \`app.config.ts:\${lineOf(text, match.index)} hands defineEnv a record that is not the envSchema export — defineEnv returns values, so x env check, x env example, x secrets and x deploy read no declaration\`,
177
+ fix: 'export const envSchema = { … } satisfies EnvSchema; export const env = defineEnv(envSchema); // in app.config.ts: move the record defineEnv was handed into envSchema, then: x env example',
178
+ at: 'app.config.ts',
179
+ }));
180
+ };
181
+
156
182
  const isFramework = (name: string): boolean =>
157
183
  FRAMEWORK.has(name) || FRAMEWORK_PREFIXES.some((head) => name.startsWith(head));
158
184
 
185
+ /** Where the record a \`defineEnv(\` call is handed opens: inline, or a same-file \`const\`. */
186
+ const recordOpen = (text: string, call: RegExpMatchArray): number | undefined => {
187
+ if (call[1] !== undefined) return (call.index ?? 0) + call[0].length - 1;
188
+ const named = new RegExp(\`\\\\bconst\\\\s+\${call[2] ?? ''}\\\\b[^=]*=\\\\s*\\\\{\`).exec(text);
189
+ return named === null ? undefined : named.index + named[0].length - 1;
190
+ };
191
+
192
+ /** A \`defineEnv(\` record in app source naming a key \`envSchema\` does not: invisible to \`x env\`. */
193
+ const recordFindings = (file: SourceFile, declared: ReadonlySet<string>): readonly Finding[] => {
194
+ const text = blank(file.source);
195
+ const code = codeOnly(text);
196
+ const findings: Finding[] = [];
197
+ for (const call of text.matchAll(CALL)) {
198
+ const open = code.charAt(call.index) === ' ' ? undefined : recordOpen(code, call);
199
+ if (open === undefined) continue;
200
+ for (const name of topLevelKeys(code, open)) {
201
+ if (declared.has(name) || isFramework(name) || AMBIENT.has(name)) continue;
202
+ findings.push({
203
+ code: CODE,
204
+ cause: \`\${file.path}:\${lineOf(text, call.index)} hands defineEnv a record declaring \${name}, which envSchema in app.config.ts does not — x env check, x env example, x secrets and x deploy never ask for it\`,
205
+ fix: \`add \${name}: { type: 'string', description: '…' } to envSchema in app.config.ts, read it as envSchema.\${name} in \${file.path}, then: x env example\`,
206
+ at: file.path,
207
+ });
208
+ }
209
+ }
210
+ return findings;
211
+ };
212
+
159
213
  /** Pure — the caller does the I/O — so the rule is testable without a filesystem. */
160
214
  export function undeclaredEnv(files: readonly SourceFile[], config: string): readonly Finding[] {
161
215
  const declared = declaredNames(config);
162
- const findings: Finding[] = [];
216
+ const findings: Finding[] = [...formFindings(config)];
163
217
  for (const file of files) {
218
+ findings.push(...recordFindings(file, declared));
164
219
  const text = blank(file.source);
165
220
  const code = codeOnly(text);
166
221
  for (const match of text.matchAll(READ)) {
@@ -218,12 +273,15 @@ unitTest('a declared name, a framework name and a computed key are not reported'
218
273
  expect(undeclaredEnv(file('Bun.env[name];'), CONFIG)).toEqual([]);
219
274
  });
220
275
 
221
- // A declaration's own keys (\\\`type\\\`, \\\`values\\\`) are not names it declares.
222
- unitTest('only the top-level keys of the declaration are declared', () => {
276
+ // A declaration's own keys (\\\`type\\\`, \\\`values\\\`) are not names it declares, and an inline
277
+ // \\\`defineEnv({ … })\\\` declares nothing: it is refused, with the conversion as its fix.
278
+ unitTest('only the top-level keys of the envSchema export are declared', () => {
223
279
  expect([...declaredNames(CONFIG)]).toEqual(['STRIPE_KEY']);
224
- expect([...declaredNames("export const env = defineEnv({ PORT: { type: 'port' } });")]).toEqual([
225
- 'PORT',
226
- ]);
280
+ const inline = "export const env = defineEnv({ PORT: { type: 'port' } });";
281
+ expect([...declaredNames(inline)]).toEqual([]);
282
+ const [refused] = undeclaredEnv([], inline);
283
+ expect(refused?.at).toBe('app.config.ts');
284
+ expect(refused?.fix).toContain('defineEnv(envSchema)');
227
285
  });
228
286
  `;
229
287
 
@@ -102,7 +102,7 @@ export function untranslatedStrings(files: readonly SourceFile[]): readonly Find
102
102
  findings.push({
103
103
  code: CODE,
104
104
  cause: \`\${file.path}:\${lineOf(text, match.index)} renders the typed string "\${typed}" inside <\${match[1] ?? 'element'}> — it is in no catalog, so every locale but the one it was typed in reads it verbatim\`,
105
- fix: \`add a key for "\${typed}" to packages/i18n/catalogs/en.json, render it as {t('…')} in \${file.path}, then: x i18n check\`,
105
+ fix: \`add a key for "\${typed}" to packages/i18n/catalogs/en.json, render it as {t('…')} in \${file.path}, then: x verify --only boundaries\`,
106
106
  at: file.path,
107
107
  });
108
108
  }
@@ -113,7 +113,7 @@ export function untranslatedStrings(files: readonly SourceFile[]): readonly Find
113
113
  findings.push({
114
114
  code: CODE,
115
115
  cause: \`\${file.path}:\${lineOf(text, match.index)} renders the typed string "\${typed}" as its \${name} — it is in no catalog, so every locale but the one it was typed in reads it verbatim\`,
116
- fix: \`add a key for "\${typed}" to packages/i18n/catalogs/en.json, write it as \${name}={t('…')} in \${file.path}, then: x i18n check\`,
116
+ fix: \`add a key for "\${typed}" to packages/i18n/catalogs/en.json, write it as \${name}={t('…')} in \${file.path}, then: x verify --only boundaries\`,
117
117
  at: file.path,
118
118
  });
119
119
  }
@@ -8,6 +8,7 @@ import { ASSISTANT_DIR } from './agent-model';
8
8
 
9
9
  const DIR = `${ASSISTANT_DIR}/prompts`;
10
10
  const EVAL = 'assistant.suggest-title';
11
+ const PROMPT_FILE = `${DIR}/suggest-title.ts`;
11
12
 
12
13
  const TEMPLATE = `You title posts for a team. Someone wants a new post about the topic below.
13
14
 
@@ -64,7 +65,8 @@ const templateLiteral = (text: string): string =>
64
65
  const prompt = (): string => `/**
65
66
  * The prompt behind \`suggestTitle\` (\`../actions/suggest-title.ts\`). No \`model\`: the environment
66
67
  * names it (\`../model.ts\`), so the gateway's \`defaultModel\` answers. Editing the template requires
67
- * bumping \`version\` and re-recording the baseline — the hash keys the traces and the eval.
68
+ * bumping \`version\` and re-recording the baseline — the hash keys the traces and the eval, and
69
+ * the eval test refuses a baseline re-recorded under the old version (\`X_EVAL_BASELINE_MISSING\`).
68
70
  */
69
71
 
70
72
  import { definePrompt } from '@ultimat3/ai';
@@ -89,9 +91,15 @@ import type { Scorer } from '@ultimat3/ai';
89
91
  import { calledTool, defineEval, jsonSchemaValid } from '@ultimat3/ai';
90
92
  import { userActor } from '@ultimat3/core';
91
93
  import { suggestTitle } from '../actions/suggest-title';
94
+ import { suggestTitlePrompt } from './suggest-title';
92
95
 
93
96
  const ORG = '00000000-0000-4000-8000-0000000000a1';
94
97
 
98
+ /** One baseline per prompt version: an edited template is a new version, recorded afresh. */
99
+ export const BASELINE = import.meta.resolve(
100
+ \`./suggest-title.v\${suggestTitlePrompt.version}.baseline.json\`,
101
+ );
102
+
95
103
  /** What \`postTitles\` answers in every case: the titles the team already has. */
96
104
  export const EXISTING = ['Money is minor units and a currency', 'Every date names its time zone'];
97
105
 
@@ -136,7 +144,7 @@ export const suggestTitleEval = defineEval({
136
144
  name: '${EVAL}',
137
145
  agent: suggestTitle,
138
146
  actor: writer,
139
- baseline: import.meta.resolve('./suggest-title.v1.baseline.json'),
147
+ baseline: BASELINE,
140
148
  tolerance: 0.05,
141
149
  tools: { postTitles: () => ({ titles: EXISTING }) },
142
150
  scorers: [jsonSchemaValid(['title']), notExisting, titleShaped, calledTool('postTitles')],
@@ -150,13 +158,18 @@ const evalTest =
150
158
  // one regression that is caught.
151
159
 
152
160
  import type { ScriptedTurn } from '@ultimat3/ai';
153
- import { baselinePath, readBaseline } from '@ultimat3/ai';
161
+ import {
162
+ baselinePath,
163
+ EvalBaselineMissingError,
164
+ readBaseline,
165
+ recordingBaselines,
166
+ } from '@ultimat3/ai';
154
167
  import { expect, test } from '@ultimat3/testing';
155
168
  // The registration: the agent's tool is offered under the name \`defineApi\` gives it.
156
169
  import '../../../api/index';
157
170
  import { scriptedGateway } from '../scripted-model';
158
171
  import { suggestTitlePrompt } from './suggest-title';
159
- import { EXISTING, suggestTitleCases, suggestTitleEval } from './suggest-title.evals';
172
+ import { BASELINE, EXISTING, suggestTitleCases, suggestTitleEval } from './suggest-title.evals';
160
173
 
161
174
  /** What the model answered when the baseline was recorded, keyed by case name. */
162
175
  const RECORDED: Readonly<Record<string, string>> = {
@@ -171,7 +184,29 @@ const turns = (title: (name: string) => string, look: boolean): readonly Scripte
171
184
  { answer: { title: title(testCase.name) } },
172
185
  ]);
173
186
 
187
+ /**
188
+ * This version's baseline was recorded against THIS template. Called before \`assert\`, which
189
+ * re-records under ULTIMATE_EVAL_RECORD=1: an edit that kept \`version\` is refused there too.
190
+ */
191
+ async function refuseAnEditUnderItsVersion(): Promise<void> {
192
+ const path = baselinePath(BASELINE, '${EVAL}');
193
+ const recorded = await readBaseline(path);
194
+ // A bumped version has no baseline yet: the record run writes it, the gate refuses its absence.
195
+ if (recorded === undefined && recordingBaselines()) return;
196
+ if (recorded?.promptHash === suggestTitlePrompt.hash) return;
197
+ throw new EvalBaselineMissingError({
198
+ eval: '${EVAL}',
199
+ path,
200
+ reason:
201
+ recorded === undefined
202
+ ? 'has never been recorded'
203
+ : \`was recorded against another template of version \${suggestTitlePrompt.version}\`,
204
+ fix: 'ULTIMATE_EVAL_RECORD=1 x test eval # after bumping version in ${PROMPT_FILE}: an edited template is a new version',
205
+ });
206
+ }
207
+
174
208
  test('suggest-title holds its recorded scores, reading the titles first', async () => {
209
+ await refuseAnEditUnderItsVersion();
175
210
  const { gateway } = scriptedGateway(turns((name) => RECORDED[name] ?? '', true));
176
211
  const run = await suggestTitleEval.assert(gateway);
177
212
  expect(run.passed).toBe(true);
@@ -181,14 +216,6 @@ test('suggest-title holds its recorded scores, reading the titles first', async
181
216
  );
182
217
  });
183
218
 
184
- test('the baseline was recorded against this template: an edit re-records it', async () => {
185
- const path = baselinePath(
186
- import.meta.resolve('./suggest-title.v1.baseline.json'),
187
- '${EVAL}',
188
- );
189
- expect((await readBaseline(path))?.promptHash).toBe(suggestTitlePrompt.hash);
190
- });
191
-
192
219
  // Through \`run\`, never \`assert\`: \`assert\` re-records under ULTIMATE_EVAL_RECORD=1.
193
220
  test('a model that repeats a taken title without looking is caught', async () => {
194
221
  const { gateway } = scriptedGateway(turns(() => EXISTING[0] ?? '', false));
@@ -245,10 +272,13 @@ const baseline = (): string =>
245
272
 
246
273
  export function promptFiles(): readonly GeneratedFile[] {
247
274
  return [
248
- { path: `${DIR}/suggest-title.ts`, contents: prompt() },
275
+ { path: PROMPT_FILE, contents: prompt() },
249
276
  { path: `${DIR}/suggest-title.evals.ts`, contents: evals() },
250
277
  { path: `${DIR}/suggest-title.eval.test.ts`, contents: evalTest() },
251
278
  { path: `${DIR}/suggest-title.evals.test.ts`, contents: scorerTest() },
252
- { path: `${DIR}/suggest-title.v1.baseline.json`, contents: baseline() },
279
+ {
280
+ path: `${DIR}/suggest-title.v${SUGGEST_TITLE_PROMPT.version}.baseline.json`,
281
+ contents: baseline(),
282
+ },
253
283
  ];
254
284
  }
@@ -27,7 +27,10 @@ const OFFLINE_BUDGET = ` // measured: 158,171 B (\`bunx x verify --only budgets
27
27
  // IndexedDB outbox that replays a write made offline) beside the form; the default form's
28
28
  // transport-only island was 64,167 B. A raise states its own measured bytes and why here, in the
29
29
  // same diff (\`X_BUDGET_EXCEEDED\`).
30
- budget: { js: '155kb' },`;
30
+ // raised 155kb → 156kb, measured: 158,737 B (2026-11-17) — the page boot 84,889 + the island
31
+ // 72,576 + inline 1,272. why: +12 B in each chunk, \`uuidV7\` minting at timestamp 0 for a clock
32
+ // before 1970 (it used to throw), in core's ids, which both chunks carry.
33
+ budget: { js: '156kb' },`;
31
34
 
32
35
  const lan = (): string => `## 📶 Offline, and on your LAN
33
36
 
@@ -74,7 +77,7 @@ const edits = (): readonly ShapeEdit[] => [
74
77
  {
75
78
  path: 'apps/web/app/posts/page.test.ts',
76
79
  find: " expect(page.config.budget.js).toBe('66kb');",
77
- replace: " expect(page.config.budget.js).toBe('155kb');",
80
+ replace: " expect(page.config.budget.js).toBe('156kb');",
78
81
  },
79
82
  // A write replayed from the outbox may already have landed: the key answers it, never twice.
80
83
  {
@@ -1,6 +1,7 @@
1
- // One `x upgrade` per app at a time: `.x/upgrade.lock`, claimed the way `dev-lock.ts` claims
2
- // `dev.lock` — written whole to a staging file, then hard-linked into place, so the create and the
3
- // exclusivity are one syscall. Two hops over one tree would each write pins and install under the other.
1
+ // One `x upgrade` per app at a time: `.x/upgrade.lock`, claimed as `dev-lock.ts` claims `dev.lock`
2
+ // (staged, then hard-linked: create and exclusivity are one syscall), its holder named by pid AND
3
+ // OS start time (`dev-lock-identity.ts`), so a pid reused after a kill -9 never holds it. Two hops
4
+ // over one tree would each write pins and install under the other.
4
5
 
5
6
  // why: the claim is synchronous link/write/unlink syscalls with no Bun equivalent, kept in one turn.
6
7
  import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -8,6 +9,7 @@ import { linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'no
8
9
  import { join } from 'node:path';
9
10
  import { renderFixShellArg, stringField, UltimateError } from '@ultimat3/core';
10
11
  import { isProcessAlive } from './dev-lock';
12
+ import { reusedPid, startedOf } from './dev-lock-identity';
11
13
  import { stealStale } from './dev-lock-steal';
12
14
 
13
15
  /** App-root relative, beside the hop's record in the `.x/` every scaffold ignores. */
@@ -16,16 +18,19 @@ export const UPGRADE_LOCK_FILE = join('.x', 'upgrade.lock');
16
18
  interface Holder {
17
19
  readonly pid: number;
18
20
  readonly startedAt: string;
21
+ /** The holder's OS start time, where the OS reports one; absent in an older CLI's lock. */
22
+ readonly started?: string;
19
23
  }
20
24
 
21
25
  const parseHolder = (raw: string | undefined): Holder | undefined => {
22
26
  if (raw === undefined) return undefined;
23
27
  try {
24
- const value = JSON.parse(raw) as { pid?: unknown; startedAt?: unknown };
28
+ const value = JSON.parse(raw) as { pid?: unknown; startedAt?: unknown; started?: unknown };
25
29
  if (typeof value.pid !== 'number') return undefined;
26
30
  return {
27
31
  pid: value.pid,
28
32
  startedAt: typeof value.startedAt === 'string' ? value.startedAt : '',
33
+ ...(typeof value.started === 'string' ? { started: value.started } : {}),
29
34
  };
30
35
  } catch {
31
36
  return undefined;
@@ -69,16 +74,20 @@ function claim(path: string, text: string): boolean {
69
74
  export interface LockDeps {
70
75
  /** Whether a pid is a live process. */
71
76
  readonly alive?: (pid: number) => boolean;
72
- /** The pid this run records; a test claims as another process. */
77
+ /**
78
+ * The pid this run records; a test claims as another process. Recorded with no start time, since
79
+ * only this process's own is known: such a lock is judged by its pid alone.
80
+ */
73
81
  readonly pid?: number;
74
82
  }
75
83
 
76
84
  /**
77
85
  * Take the app's upgrade lock, or refuse with `X_UPGRADE_LOCKED` naming the live holder. A lock
78
- * whose holder is gone — a hop killed hard — is taken over under `stealStale`'s guard. Returns the
79
- * release, which removes the lock only while it still holds this run's bytes.
86
+ * whose holder is gone — a hop killed hard, its pid dead or reused — is taken over under
87
+ * `stealStale`'s guard. Returns the release, which removes the lock only while it still holds this
88
+ * run's bytes.
80
89
  */
81
- export function acquireUpgradeLock(root: string, deps: LockDeps = {}): () => void {
90
+ export async function acquireUpgradeLock(root: string, deps: LockDeps = {}): Promise<() => void> {
82
91
  const alive = deps.alive ?? isProcessAlive;
83
92
  const path = join(root, UPGRADE_LOCK_FILE);
84
93
  try {
@@ -86,7 +95,9 @@ export function acquireUpgradeLock(root: string, deps: LockDeps = {}): () => voi
86
95
  } catch (error) {
87
96
  throw unwritable(path, error);
88
97
  }
89
- const mine = `${JSON.stringify({ pid: deps.pid ?? process.pid, startedAt: new Date().toISOString() })}\n`;
98
+ const pid = deps.pid ?? process.pid;
99
+ const identity = deps.pid === undefined ? await startedOf(process.pid) : {};
100
+ const mine = `${JSON.stringify({ pid, startedAt: new Date().toISOString(), ...identity })}\n`;
90
101
  for (let attempt = 0; attempt < 3; attempt += 1) {
91
102
  if (claim(path, mine)) {
92
103
  return () => {
@@ -95,7 +106,7 @@ export function acquireUpgradeLock(root: string, deps: LockDeps = {}): () => voi
95
106
  }
96
107
  const raw = readText(path);
97
108
  const holder = parseHolder(raw);
98
- if (holder !== undefined && alive(holder.pid)) {
109
+ if (holder !== undefined && alive(holder.pid) && !(await reusedPid(holder))) {
99
110
  throw new UltimateError({
100
111
  code: 'X_UPGRADE_LOCKED',
101
112
  cause: `another x upgrade (pid ${String(holder.pid)}, since ${holder.startedAt || 'an unknown time'}) holds ${path}, and two hops in one app would write pins and install under each other`,
package/wiki/Auth.md CHANGED
@@ -270,7 +270,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
270
270
  | Piece | What it does |
271
271
  |---|---|
272
272
  | `routes` | `GET /.well-known/oauth-authorization-server` (RFC 8414), `POST /oauth/token`, `/oauth/revoke` (RFC 7009), `/oauth/introspect` (RFC 7662), plus `/oauth/register` (RFC 7591, `registration: 'dynamic'`) and `/oauth/device` (RFC 8628). Plain `Route`s for `runtime.routes`, public, no cookie authenticates them. Every answer is `no-store` RFC 6749 JSON |
273
- | consent | the page calls `readRequest(url)` → `{ client, scopes, resource, redirectUri }` or a refusal; an unknown client or unregistered redirect has `redirectTo: null` — render it, never redirect. Its action calls `approve({ subject, request, scopes? })` / `deny({ request })` for the redirect URL (`code`, `state`, `iss`). A forged request is `X_AUTH_CONSENT_INVALID` (422) |
273
+ | consent | the page calls `readRequest(url, { callerKey })` (`callerKey`: the request's address) → `{ client, scopes, resource, redirectUri }` or a refusal; an unknown client or unregistered redirect has `redirectTo: null` — render it, never redirect. Its action calls `approve({ subject, request, scopes? })` / `deny({ request })` for the redirect URL (`code`, `state`, `iss`). A forged request is `X_AUTH_CONSENT_INVALID` (422) |
274
274
  | device | the verification page calls `readDevice({ userCode, key })`, `approveDevice` / `denyDevice`; `key` is the caller's bucket — 10 misses lock it (`X_ACCOUNT_LOCKED`) |
275
275
  | `registerClient(...)` | a client the app creates itself — a partner's `client_credentials` client; the secret is shown once and stored hashed. A redirect URI, grant, scope or resource that is empty or holds whitespace is `X_AUTH_CLIENT_INVALID` (422, `meta.field`): the store keeps each list space-joined, so it would read back as a different list |
276
276
  | `resolve(token)` | `{ subject, scopes, clientId, resource } \| null`. `oauthBearerResolver(server, { actor, resource? })` is the `resolveToken` a bearer mount and `defineAppMcp` take; `actor` runs per call, so a removed member loses access at once |
@@ -289,6 +289,7 @@ const resolveToken = oauthBearerResolver(oauth, { actor: (grant) => actorFor(gra
289
289
  | `resource` (RFC 8707) binds the grant; one not in `resources` is `invalid_target` | `authorization-server-request.test.ts`, `oauth-bearer-resolver.test.ts` |
290
290
  | tokens are opaque and stored hashed, never a JWT, so `revoke` holds on the next lookup | `token-endpoints.test.ts` |
291
291
  | an `https://` `client_id` is a metadata document, fetched through `outbound({ dial: 'public' })`, 5 KiB, cached 5 minutes, public clients only | `authorization-server-clients.test.ts` |
292
+ | every metadata-document fetch is metered (`X_ACCOUNT_LOCKED` past 10 a minute): per `callerKey`, or — when the consent page names none — on ONE shared bucket, so an unkeyed page is throttled as one caller | `authorization-server-clients.test.ts` |
292
293
  | `client_credentials`: confidential only, no refresh token, subject is the client | `grant-client-credentials.test.ts` |
293
294
  | dynamic registration never hands out `client_credentials` and is counted per address | `authorization-server-clients.test.ts` |
294
295
 
@@ -5,15 +5,18 @@ One file: `app.config.ts` at the repo root. There is no per-environment config d
5
5
  `As of 2026-08-22`. Stable API — semver from here ([Upgrading](Upgrading)). Field names are covered by semver: renaming or removing one needs a major, and the entry in [Upgrading](Upgrading) names the edit. **There is no codemod** — `x upgrade` is a `PLANNED_COMMANDS` entry ([`packages/cli/src/cmd-planned.ts`](https://github.com/developerz-ai/ultimate/blob/main/packages/cli/src/cmd-planned.ts)), so every migration below is a hand edit.
6
6
 
7
7
  ```ts
8
+ import type { EnvSchema } from '@ultimat3/core';
8
9
  import { defineConfig, defineEnv } from '@ultimat3/core';
9
10
 
10
11
  // Module scope, in `app.config.ts` itself: the file is imported at boot, so the env gate runs
11
- // before any listener binds. There is no separate `env.ts` — one config file means one.
12
- export const env = defineEnv({
12
+ // before any listener binds. There is no separate `env.ts` — one config file means one. The
13
+ // declaration is the `envSchema` export, the one form `x env`, `x secrets` and `x deploy` read.
14
+ export const envSchema = {
13
15
  APP_URL: { type: 'url' },
14
16
  DATABASE_URL: { type: 'url' },
15
17
  SESSION_SECRET: { type: 'string', secret: true },
16
- });
18
+ } satisfies EnvSchema;
19
+ export const env = defineEnv(envSchema);
17
20
 
18
21
  export const config = defineConfig({
19
22
  name: 'postly',
@@ -95,17 +95,21 @@ What `x new` writes, and who owns it afterwards:
95
95
 
96
96
  Declared at module scope in `app.config.ts`, next to `defineConfig`. There is no `env.ts` — `app.config.ts` is the one file the CLI and the runtime both load, so it is the one place the env gate can run before anything binds.
97
97
 
98
+ One form: the `envSchema` export, handed to `defineEnv`. `defineEnv` returns the parsed VALUES, so a record written inline in the call is unreachable afterwards — `x env check`, `x env example`, `x secrets` and `x deploy` read `envSchema` and nothing else. The shipped `undeclared-env` guard refuses a `defineEnv(` handed anything else (`X_UNDECLARED_ENV` at `app.config.ts`), its fix the conversion.
99
+
98
100
  ```ts
99
101
  // app.config.ts
102
+ import type { EnvSchema } from '@ultimat3/core';
100
103
  import { defineConfig, defineEnv } from '@ultimat3/core';
101
104
 
102
- export const env = defineEnv({
105
+ export const envSchema = {
103
106
  DATABASE_URL: { type: 'url' },
104
107
  NATS_URL: { type: 'url', required: false },
105
108
  S3_BUCKET: { type: 'string' },
106
109
  VAPID: { type: 'string', required: false },
107
110
  STRIPE_KEY: { type: 'string', pattern: /^sk_/, secret: true },
108
- });
111
+ } satisfies EnvSchema;
112
+ export const env = defineEnv(envSchema);
109
113
 
110
114
  export const config = defineConfig({ name: 'myapp' /* … */ });
111
115
  ```
@@ -118,7 +122,7 @@ X_ENV_MISSING: required environment variables are missing or invalid
118
122
  fix: add STRIPE_KEY, NATS_URL to .env (copy .env.example), then run: x env check
119
123
  ```
120
124
 
121
- The `fix:` is per-key and built from your own declarations ([`packages/core/src/env.ts:237`](https://github.com/developerz-ai/ultimate/blob/main/packages/core/src/env.ts)); `defineEnv({ KEY: { fix } })` overrides it for one key.
125
+ The `fix:` is per-key and built from your own declarations ([`packages/core/src/env.ts:237`](https://github.com/developerz-ai/ultimate/blob/main/packages/core/src/env.ts)); a `fix` on one `envSchema` entry overrides it for that key.
122
126
 
123
127
  | Property | Behavior |
124
128
  |---|---|
@@ -11,7 +11,7 @@ One engine per concern. A **migration** changes the shape of a table — schema,
11
11
  | Add, rename, retype, drop a column or table; add an index or constraint | a **migration** — `x db gen "<name>"` |
12
12
  | Add an index to a big, hot table, or drop one from it | a **migration** too — `indexes: [{ on }]`: on an existing table the build is concurrent by default, and every drop is concurrent already. [Indexes built concurrently](#indexes-built-concurrently--expand--contract) |
13
13
  | Rewrite, normalize, re-derive or backfill values in rows that already exist | a **backfill** — `backfill({ … })` |
14
- | Add a nullable column, then populate every existing row before making it required | both: the migration adds the column, the backfill sweeps the rows, a second migration adds the `not null` once the sweep is done (expand → migrate → contract) |
14
+ | Add a nullable column, then populate every existing row before making it required | both: the migration adds the column, the backfill sweeps the rows, a second migration adds the `not null` once the sweep is done (expand → migrate → contract). Declaring it required at once writes both halves in one `x db gen` — [Foreign keys and CHECKs on a live table](#foreign-keys-and-checks-on-a-live-table) |
15
15
 
16
16
  ## Migrations: one engine, one ledger
17
17
 
@@ -271,10 +271,15 @@ An embedded scratch boot restores a post-`initdb` snapshot instead of running `i
271
271
  | A key on a table this migration creates | the plain `add constraint` in the transaction, byte-identical to before — unless the unique index it needs is built by the deferred step, which would otherwise be `42830`. Then it defers too |
272
272
  | A key re-added after a retype | the transaction: the rewrite holds ACCESS EXCLUSIVE already |
273
273
  | A CHECK on a live table | `add constraint … not valid` in the transaction (it needs no index), `validate constraint` in the deferred step. New writes are held to it at once. A new table's stays in `create table` |
274
- | `down` | restore the old key, drop the new key, drop the index |
274
+ | A column becoming NOT NULL (`As of 2026-11-17`) | a new NOT NULL column with no default: `add column` NULLABLE in the transaction, whose snapshot records it nullable. Then — for it, or for an existing column turned NOT NULL — the `_concurrently` step: `add constraint "<t>_<c>_not_null_check" check ("c" is not null) not valid`, `validate constraint`, `set not null` (Postgres proves it from the validated check, no scan), the check dropped. A key column owes none: `add primary key` makes it NOT NULL |
275
+ | `down` | restore the old key, drop the new key, drop the index; a contracted column `drop not null` |
275
276
 
276
277
  `x db migrate` re-runs a failed step from the top. `validate` finding a bad row is `X_DB_FOREIGN_KEY_VIOLATION` (or the CHECK's own failure) with the constraint in place holding new writes and the old release still serving: repair the row, re-run. A declared constraint left `NOT VALID` in a database whose ledger says the step ran is `X_DB_DRIFT`, kind `not-valid-constraint`, and its fix is the validate statement.
277
278
 
279
+ A NOT NULL contract is the same story. On an empty table — a fresh or `x db reset` database — both steps apply and drift is clean: one `x db gen`, one `x db migrate`. On a table holding NULL there, the validate fails (`X_DB_STATEMENT_FAILED`, the cause naming `<t>_<c>_not_null_check`), the expand step stays applied and recorded nullable, and the database is not drift: backfill the rows, then `x db migrate` finishes the step. On a populated production table that means two releases — declare the column `.nullable()` and ship it with its `backfill()`, then declare it required and `x db gen` writes the contract alone.
280
+
281
+ **Before 2026-11-17** `x db gen` left a comment, `-- backfill "c", then: alter table … set not null;`, and recorded the column NOT NULL in that file's snapshot. Every database that ran it — a fresh one included — failed `x db migrate` with `X_DB_DRIFT` (`changed-column`), and a second `x db gen` wrote nothing. An app holding such a file, with the comment never carried out: declare the column `.nullable()`, `x db gen "relax c"` (a `drop not null`, a no-op on a database already repaired, and a snapshot that tells the truth), then declare it required again and `x db gen "contract c"`.
282
+
278
283
  ## A column drop takes two releases
279
284
 
280
285
  `As of 2026-11-02`. Old and new pods serve one schema during a roll, and the old release names every column it declares in every read and insert, so a drop in the release that stops declaring it answers `X_DB_SCHEMA_STALE` from every old pod.
package/wiki/Realtime.md CHANGED
@@ -670,7 +670,7 @@ No channel kind carries an ordered, two-way byte stream to a browser — a termi
670
670
 
671
671
  ## Wire protocol version
672
672
 
673
- `PROTOCOL_VERSION` is **3** `As of 2026-09-22` (21.0.0; it was 2 from 2026-08-24) ([`packages/realtime/src/sync-protocol.ts`](https://github.com/developerz-ai/ultimate/blob/main/packages/realtime/src/sync-protocol.ts)). A mismatch is `X_PROTOCOL_VERSION` on the frame, with one instruction, rather than a per-field decode error nobody can act on.
673
+ `PROTOCOL_VERSION` is **3** `As of 2026-09-22` (21.0.0; it was 2 from 2026-08-24) ([`packages/realtime/src/sync-protocol.ts`](https://github.com/developerz-ai/ultimate/blob/main/packages/realtime/src/sync-protocol.ts)). A mismatch is `X_PROTOCOL_VERSION` on the frame, with one instruction, rather than a per-field decode error nobody can act on. A throw with no code (a live query's `TypeError`) is `X_INTERNAL` on the ack, its cause withheld as HTTP withholds an unclassified 5xx's — never `X_PROTOCOL_VERSION`, whose rebuild cannot repair a server bug. `As of 2026-11`.
674
674
 
675
675
  **Clients and `sync` nodes must be redeployed together across this bump.** A cursor rides in BOTH directions — the client's `subscribe` and the node's `snapshot` — so a skew breaks resume from either side.
676
676
 
package/wiki/Scraping.md CHANGED
@@ -212,7 +212,8 @@ The `/robots.txt` read is deadlined (10s), capped (500 KiB) and dialled through
212
212
  | The read | Means | The gate |
213
213
  |---|---|---|
214
214
  | `2xx` | the file | its rules, cached for the run |
215
- | `4xx` (not `429`), a body past the cap, a redirect off the list or past the hop cap | **unavailable** | no restrictions, cached for the run |
215
+ | `2xx` with a body past the cap (500 KiB) | the file's head | the whole lines inside the cap are parsed (RFC 9309 §2.5), cached for the run; a head with no line end is **unreachable** |
216
+ | `4xx` (not `429`), a redirect off the list or past the hop cap | **unavailable** | no restrictions, cached for the run |
216
217
  | `5xx`, `429`, a refused connection, the deadline, the run cancelled, a `fetchText` that rejects | **unreachable** | complete disallow — every path on the origin is `X_SCRAPE_ROBOTS_DISALLOWED` — and **not** cached: the next navigation asks again, so the run recovers when the file answers |
217
218
 
218
219
  `429` is the one row that is **our policy, not the RFC's**: RFC 9309 calls every `4xx` unavailable, `429` included. Ultimate refuses on it because a server rate-limiting the crawler has not said "no rules" — stricter than the RFC requires, never looser.
@@ -270,7 +271,8 @@ Reuse is both the fast path and the safe path — logging in on every run is slo
270
271
  |---|---|
271
272
  | this store's sealed record, saved under this key | the session |
272
273
  | nothing | `undefined` — the run logs in |
273
- | an unsealed object, a corrupt one, one sealed under a key this process does not declare, one copied from another key's path | **burned**, then `undefined` — a session is a cache, so nothing is migrated |
274
+ | an unsealed object, a corrupt one, one whose tag fails under a key this process holds, one copied from another key's path | **burned**, then `undefined` — a session is a cache, so nothing is migrated |
275
+ | one sealed under a key this process does not hold yet (`X_SEAL_KEY_UNKNOWN`, mid-rotation) | `undefined`, the object **kept**: a pod that already holds the new key still restores it |
274
276
  | no master key at all | `X_SEAL_KEY_MISSING`, before the browser opens — run `x secrets init` |
275
277
 
276
278
  **Upgrading into sealed sessions discards what was stored before**, refusal markers included. A
package/wiki/Upgrading.md CHANGED
@@ -303,6 +303,15 @@ A setter still on a package's `.` barrel is `X_ADAPTER_PORT_INCOMPLETE` on the `
303
303
  | two shipped guards report more (**31.40.0**), built in: `raw-colour` (`X_RAW_COLOUR`) also reads a component's inline `style` (`style={{ color: '#f00' }}`, a quoted CSS string), and `untranslated-string` (`X_UNTRANSLATED_STRING`) also reads typed user-facing attributes (`aria-label`, `title`, `placeholder`, `alt`, …). A third, `undeclared-env` (`X_UNDECLARED_ENV`), is new: a raw `process.env.X` / `Bun.env.X` that `app.config.ts` does not declare. Every app runs them on its next install; a copy still in `guards/` keeps the old rule until `x upgrade` migrates it to the release after 31.39.0 | each finding names its edit: a semantic token, a `t('…')` key, or the `envSchema` entry to add; `"<name>": "off"` in `guards/shipped.json` opts out |
304
304
  | the shipped `undeclared-env` guard reports less (**31.41.0**), built in: a name quoted inside a string (a generated docs file holding `process.env.X` as text) and a read of the OS's own `PATH`, `HOME`, `TMPDIR`, `USER`, `SHELL`, `PWD`, `LANG` or `HOSTNAME` are no longer `X_UNDECLARED_ENV`. A read inside a template's `${…}` still is | nothing, for the built-in guard. A vendored `guards/undeclared-env.ts` you never edited: `x upgrade` migrates it. An edited one keeps your rule; compare it with `x g guard undeclared-env --force`'s diff |
305
305
  | `live` under a strict floor holds its skips at **0** in CI (**31.42.0**) when `x.verify.json` writes no `skipCeiling.live` and the run reached its database: `X_VERIFY_SKIPS_OVER_CEILING` names the step and the count. A run with no database (no services on the runner) is unchanged: `X_TEST_SERVICES_UNAVAILABLE`, a warning | make each skipped `live` test run — it needs a service the stack does not start, or skips on a condition it should not — or write the ceiling you accept, with its reason: `"skipCeiling": { "live": <n> }` in `x.verify.json`. Then `x verify --only live` |
306
+ | `undeclared-env` refuses an inline `defineEnv({ … })` in `app.config.ts` (**31.43.0**): `defineEnv` returns values, so `x env check`, `x env example`, `x secrets` and `x deploy` read no declaration from it — `X_UNDECLARED_ENV` at `app.config.ts:<line>`. Built in; a copy still in `guards/` keeps the old rule until `x upgrade` migrates it to the release after 31.42.1 | `export const envSchema = { … } satisfies EnvSchema; export const env = defineEnv(envSchema);`, the record moved as is, then `x env example` |
307
+ | shapes that changed in **31.30–31.42** with no changelog line (found by the public API lock in **31.43.0**): `@ultimat3/cache` `assertFiniteDurationMs` lost its 4th parameter; `@ultimat3/core` `INSTRUMENT_EVENTS` changed and `mapBounded` is overloaded; `@ultimat3/entity` `ColumnMeta.countedIn` and `@ultimat3/realtime/server` `QueryEntry.shape` changed type; `@ultimat3/policy` `PolicyScope`/`policyScope` return `ScopeNode[]`; `@ultimat3/render/server` `IsrController` requires `forgetAll`; `@ultimat3/testing` `ExerciseEffect` changed and `TempTree` requires `spawn` | an `IsrController` or `TempTree` you implement adds the new member; the rest is a type error at the call site, if any |
308
+ | `x new`'s CI files pin every `actions/*` step by commit SHA and check out with `persist-credentials: false` (**31.43.0**) | nothing: `x upgrade` applies codemod `ci-pinned-actions`; a hand-edited workflow is listed with its diff to apply by hand |
309
+ | `adminActorFrom()` answers a `kind` key on every actor (**31.44.0**), and an admin decision sees the caller's real kind, scopes and `onBehalfOf`: an MCP caller is an agent, a queued batch chunk runs as the actor that queued it | a test asserting `adminActorFrom(...)` with `toEqual` adds `kind: 'user'` (or the actor's kind); a policy that treated every admin caller as a user now sees agents — check rules that read `actor.kind`. A chunk queued before the upgrade runs as a `user`, as it did |
310
+ | a `sensitive` admin field is no list filter and no sort key by default (**31.44.0**) | nothing; `filterable: true` / `sortable: true` on the field override, on purpose |
311
+ | a `robots.txt` over 500 KiB is obeyed by its first 500 KiB, or refuses the origin when no line ends inside the cap (**31.44.0**) | nothing, unless a scrape relied on an oversized file reading as "no rules": check the target's file, or declare `robots: { ignore: '<reason>' }` |
312
+ | a `timestamp()` filter given zoneless ISO text reads it as UTC in both drivers (**31.44.0**); a Postgres whose session `TimeZone` was not UTC read it in that zone | to mean another zone, pass a `Date` or ISO text with its offset (`'2026-01-01T00:00:00+02:00'`) |
313
+ | a required column with no default is added nullable and contracted to NOT NULL in the migration's non-transactional step (**31.44.0**), so a fresh or reset database migrates clean | a committed migration that still holds the old `-- backfill "c", then: … set not null;` comment: declare the column `.nullable()`, `x db gen "relax c"`, declare it required again, `x db gen "contract c"`, then `x db migrate`. A populated production table: ship `.nullable()` plus its `backfill()` first, then required |
314
+ | two shipped guards change (**31.44.0**), built in: `undeclared-env` (`X_UNDECLARED_ENV`) also refuses a `defineEnv(` record anywhere in app source whose keys `envSchema` in `app.config.ts` does not declare; `untranslated-string` (`X_UNTRANSLATED_STRING`) ends its fix with `x verify --only boundaries`. A copy still in `guards/` keeps the old rule until `x upgrade` migrates it to the release after 31.43.0 | each `undeclared-env` finding names the keys to move into `envSchema`; then `x env example` |
306
315
 
307
316
  ## 29.x → 30.0.0, entry by entry
308
317