@ultimat3/cli 31.52.0 → 31.53.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 (111) hide show
  1. package/CLAUDE.md +1 -1
  2. package/package.json +29 -29
  3. package/src/app-kit-disk.ts +39 -0
  4. package/src/app-kit-forms.ts +27 -0
  5. package/src/app-kit.ts +146 -0
  6. package/src/budgets.ts +3 -1
  7. package/src/cdp-shot-driver-screen.ts +72 -0
  8. package/src/cdp-shot-driver.ts +17 -1
  9. package/src/cmd-design-capture.ts +210 -0
  10. package/src/cmd-design-errors.ts +50 -0
  11. package/src/cmd-design-paths.ts +47 -0
  12. package/src/cmd-design-publish.ts +64 -0
  13. package/src/cmd-design-run.ts +229 -0
  14. package/src/cmd-design-spec.ts +47 -0
  15. package/src/cmd-design-theme.ts +107 -0
  16. package/src/cmd-design-url.ts +201 -0
  17. package/src/cmd-design.ts +188 -0
  18. package/src/cmd-doctor.ts +3 -0
  19. package/src/cmd-generate-spec.ts +5 -0
  20. package/src/cmd-generate.ts +3 -1
  21. package/src/cmd-kit-spec.ts +13 -0
  22. package/src/cmd-kit.ts +133 -0
  23. package/src/cmd-shot-against.ts +275 -0
  24. package/src/cmd-shot-spec.ts +9 -1
  25. package/src/cmd-shot.ts +19 -0
  26. package/src/cmd-upgrade.ts +11 -0
  27. package/src/codemods/agent-kit.ts +130 -0
  28. package/src/codemods/agents-md-budget.ts +47 -0
  29. package/src/codemods/docs-visual-quality.ts +198 -0
  30. package/src/codemods/index.ts +8 -0
  31. package/src/codemods/settings-kit-allow.ts +49 -0
  32. package/src/design-extract-script.ts +187 -0
  33. package/src/design-extract.ts +311 -0
  34. package/src/design-map-colors.ts +180 -0
  35. package/src/design-map.ts +288 -0
  36. package/src/doctor-kit.ts +25 -0
  37. package/src/error-catalog.ts +4 -2
  38. package/src/error-codes-kit.ts +24 -0
  39. package/src/error-codes.ts +12 -10
  40. package/src/generate-files.ts +31 -1
  41. package/src/guards-shipped-names.ts +5 -0
  42. package/src/kit/agent-audit.ts +49 -0
  43. package/src/kit/agent-data.ts +32 -0
  44. package/src/kit/agent-server.ts +34 -0
  45. package/src/kit/agent-shape.ts +61 -0
  46. package/src/kit/agent-web.ts +49 -0
  47. package/src/kit/design-map.ts +106 -0
  48. package/src/kit/managed.ts +12 -0
  49. package/src/kit/registry.ts +89 -0
  50. package/src/kit/skill-design-research.ts +119 -0
  51. package/src/kit/skill-feature.ts +159 -0
  52. package/src/kit/skill-planx.ts +139 -0
  53. package/src/kit/skill-upgrade.ts +94 -0
  54. package/src/kit/skill-verify.ts +80 -0
  55. package/src/mcp-errors.ts +5 -0
  56. package/src/mcp-ui-diff.ts +13 -38
  57. package/src/mcp-ui.ts +30 -1
  58. package/src/messages-design.ts +104 -0
  59. package/src/messages-upgrade.ts +9 -0
  60. package/src/messages.ts +2 -0
  61. package/src/registry.ts +4 -0
  62. package/src/shot-diff.ts +96 -0
  63. package/src/shot-gpu.ts +17 -5
  64. package/src/templates/guard-animated-layout-script.ts +173 -0
  65. package/src/templates/guard-effect-without-fallback.ts +117 -0
  66. package/src/templates/guard-motion-adapter.ts +161 -0
  67. package/src/templates/guard-raw-frame-loop.ts +134 -0
  68. package/src/templates/guard-raw-motion-script.ts +132 -0
  69. package/src/templates/guard-raw-motion-ts-scan.ts +95 -0
  70. package/src/templates/guard-released-forms.ts +10 -0
  71. package/src/templates/index.ts +1 -2
  72. package/src/templates/island.ts +55 -8
  73. package/src/templates/kit-released-forms.ts +63 -0
  74. package/src/templates/motion-scale.ts +115 -0
  75. package/src/templates/scaffold-claude.ts +39 -26
  76. package/src/templates/scaffold-design.ts +41 -0
  77. package/src/templates/scaffold-docs.ts +31 -7
  78. package/src/templates/scaffold-guards.ts +31 -2
  79. package/src/templates/scaffold-verify-floor.ts +3 -0
  80. package/src/templates/shapes/blog-site.ts +15 -0
  81. package/src/templates/shapes/blog.ts +2 -0
  82. package/src/templates/shapes/content-site.ts +13 -0
  83. package/src/templates/shapes/content.ts +2 -0
  84. package/src/templates/shapes/dashboard-detail.ts +2 -0
  85. package/src/templates/shapes/dashboard-motion.ts +284 -0
  86. package/src/templates/shapes/dashboard.ts +19 -1
  87. package/src/templates/shapes/landing-motion.ts +67 -0
  88. package/src/templates/shapes/saas.ts +4 -0
  89. package/src/upgrade-gate.ts +14 -2
  90. package/src/upgrade-kit.ts +65 -0
  91. package/src/upgrade-report-kit.ts +28 -0
  92. package/src/upgrade-report.ts +3 -0
  93. package/src/verify-checks.ts +9 -1
  94. package/src/workspace-checks.ts +3 -3
  95. package/wiki/Agents.md +33 -1
  96. package/wiki/CLI-Reference-Tools.md +24 -3
  97. package/wiki/CLI-Reference.md +4 -2
  98. package/wiki/Design-Research.md +96 -0
  99. package/wiki/Effects.md +83 -0
  100. package/wiki/FAQ.md +1 -1
  101. package/wiki/Getting-Started.md +1 -1
  102. package/wiki/Home.md +2 -2
  103. package/wiki/Known-Gaps.md +3 -2
  104. package/wiki/MCP-And-AI.md +4 -0
  105. package/wiki/Motion.md +85 -0
  106. package/wiki/Project-Layout.md +1 -1
  107. package/wiki/Tutorial-02-First-Feature.md +1 -1
  108. package/wiki/UI-Components.md +2 -0
  109. package/wiki/Upgrading.md +4 -2
  110. package/src/templates/scaffold-claude-agents.ts +0 -161
  111. package/src/templates/scaffold-claude-commands.ts +0 -239
@@ -0,0 +1,275 @@
1
+ // `x shot <route> --against <png | .x/design/<slug>>`: the route photographed at each viewport and
2
+ // scheme the reference holds, each picture compared with the reference shot of the same pair, the
3
+ // diff written beside it and the similarity recorded in its verdict.json. Recorded, never gating:
4
+ // "how close to the reference" is a judgement for the reader, not a verdict for the gate.
5
+
6
+ // why: Bun has no synchronous directory listing or existence check, and the plan is decided
7
+ // before anything boots.
8
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
9
+ // why: Bun exposes no path primitives.
10
+ import { join, sep } from 'node:path';
11
+ import { renderCauseValue, UltimateError } from '@ultimat3/core';
12
+ import {
13
+ DESIGN_SCHEMES,
14
+ DESIGN_VIEWPORTS,
15
+ type DesignScheme,
16
+ REFERENCE_SHOT_PATTERN,
17
+ referenceShotName,
18
+ } from './cmd-design-paths';
19
+ import type { ShotRun } from './cmd-shot';
20
+ import { BadFlagError } from './errors';
21
+ import { msg } from './messages';
22
+ import type { CommandResult } from './output';
23
+ import { compareCaptures } from './shot-diff';
24
+ import type { ShotServer } from './shot-server';
25
+ import type { ShotTheme } from './shot-theme';
26
+ import type { ShotArtifacts } from './shot-verdict';
27
+ import { shotSummary, verdictJson } from './shot-verdict';
28
+ import type { ShotViewport } from './shot-viewport';
29
+
30
+ /** `ui.diff`'s default threshold: a tenth of a channel's range absorbs a one-level wobble. */
31
+ export const AGAINST_THRESHOLD = 0.1;
32
+
33
+ /** The size a lone PNG reference is compared at when no `--viewport` names one. */
34
+ const LONE_VIEWPORT: ShotViewport = { width: 1440, height: 900 };
35
+
36
+ export class ShotAgainstMissingError extends UltimateError {
37
+ constructor(input: { readonly reference: string; readonly wanted: string }) {
38
+ super({
39
+ code: 'X_SHOT_AGAINST_MISSING',
40
+ cause: `${renderCauseValue(input.reference)} holds no ${input.wanted} to compare against`,
41
+ fix: 'x design research <url> --viewport 390x844,1440x900 # writes .x/design/<slug>/shot-<width>-<light|dark>.png; then: x shot <route> --against .x/design/<slug>',
42
+ meta: { reference: input.reference, wanted: input.wanted },
43
+ });
44
+ }
45
+ }
46
+
47
+ /** One route shot and the reference picture it is compared with. */
48
+ export interface AgainstPair {
49
+ readonly viewport: ShotViewport;
50
+ readonly scheme: DesignScheme;
51
+ /** Absolute path of the reference PNG. */
52
+ readonly reference: string;
53
+ }
54
+
55
+ export interface AgainstPlanInput {
56
+ /** Absolute: a PNG, or a `x design research` slug directory. */
57
+ readonly reference: string;
58
+ /** The directories a reference must lie under (the app root, the cwd) — through any link too. */
59
+ readonly within: readonly string[];
60
+ readonly viewports?: readonly ShotViewport[] | undefined;
61
+ readonly theme?: ShotTheme | undefined;
62
+ }
63
+
64
+ /** `true` when `path` is `dir` or under it, on whole segments. */
65
+ const under = (path: string, dir: string): boolean => path === dir || path.startsWith(dir + sep);
66
+
67
+ /**
68
+ * Through every link, the reference lies under one of `within` — `ui.diff`'s rule
69
+ * (`mcp-ui-diff.ts`). `--against` reads and decodes the file, and a flag that reads any path on
70
+ * the box is a read primitive for whoever composes the command line.
71
+ */
72
+ function assertWithin(reference: string, within: readonly string[]): void {
73
+ const real = realpathSync(reference);
74
+ const roots = within.flatMap((dir) => (existsSync(dir) ? [realpathSync(dir)] : []));
75
+ // The real path is what is read: a link inside the app pointing out of it is outside.
76
+ if (roots.some((root) => under(real, root))) return;
77
+ throw new BadFlagError({
78
+ flag: 'against',
79
+ command: 'shot',
80
+ reason: `${renderCauseValue(reference)} is not inside the app or the current directory`,
81
+ fix: 'x shot / --against .x/design/<slug> --json # a reference under the app root, e.g. what x design research wrote',
82
+ });
83
+ }
84
+
85
+ /** The height a width is laid out at: the design viewport of that width, else the desktop's. */
86
+ const heightFor = (width: number): number =>
87
+ DESIGN_VIEWPORTS.find((viewport) => viewport.width === width)?.height ?? LONE_VIEWPORT.height;
88
+
89
+ /**
90
+ * Decided before anything boots. A directory pairs every shot it holds, narrowed by `--viewport`
91
+ * and `--theme`; a pair asked for and not held is refused, never skipped — a comparison that
92
+ * quietly covered half of what was asked reads as a whole one.
93
+ */
94
+ export function planAgainst(input: AgainstPlanInput): readonly AgainstPair[] {
95
+ const { reference } = input;
96
+ if (!existsSync(reference)) {
97
+ throw new ShotAgainstMissingError({ reference, wanted: 'file or directory' });
98
+ }
99
+ assertWithin(reference, input.within);
100
+ if (!statSync(reference).isDirectory()) {
101
+ if ((input.viewports?.length ?? 0) > 1) {
102
+ throw new BadFlagError({
103
+ flag: 'viewport',
104
+ command: 'shot',
105
+ reason:
106
+ 'a lone PNG reference is one picture of one size; compare one --viewport against it, or a design research directory against several',
107
+ fix: 'x shot / --against .x/design/<slug> --viewport 390x844,1440x900 --json',
108
+ });
109
+ }
110
+ const viewport = input.viewports?.[0] ?? LONE_VIEWPORT;
111
+ return [{ viewport, scheme: input.theme ?? 'light', reference }];
112
+ }
113
+ const held = readdirSync(reference)
114
+ .map((name) => REFERENCE_SHOT_PATTERN.exec(name))
115
+ .filter((match) => match !== null)
116
+ .map((match) => ({ width: Number(match[1]), scheme: match[2] as DesignScheme }))
117
+ .sort((a, b) => a.width - b.width || a.scheme.localeCompare(b.scheme));
118
+ const schemes = input.theme === undefined ? DESIGN_SCHEMES : [input.theme];
119
+ if (input.viewports === undefined) {
120
+ const pairs = held.filter((shot) => schemes.includes(shot.scheme));
121
+ if (pairs.length === 0) {
122
+ throw new ShotAgainstMissingError({
123
+ reference,
124
+ wanted: `shot-<width>-${input.theme ?? '<light|dark>'}.png`,
125
+ });
126
+ }
127
+ return pairs.map((shot) => ({
128
+ viewport: { width: shot.width, height: heightFor(shot.width) },
129
+ scheme: shot.scheme,
130
+ reference: join(reference, referenceShotName(shot.width, shot.scheme)),
131
+ }));
132
+ }
133
+ return input.viewports.flatMap((viewport) =>
134
+ schemes.map((scheme) => {
135
+ const name = referenceShotName(viewport.width, scheme);
136
+ if (!held.some((shot) => shot.width === viewport.width && shot.scheme === scheme)) {
137
+ throw new ShotAgainstMissingError({ reference, wanted: name });
138
+ }
139
+ return { viewport, scheme, reference: join(reference, name) };
140
+ }),
141
+ );
142
+ }
143
+
144
+ /** `--against` photographs ONE route at the reference's pairs; another subject beside it is two. */
145
+ export function refuseAgainstWith(flag: 'matrix' | 'island' | 'all-islands'): never {
146
+ throw new BadFlagError({
147
+ flag: 'against',
148
+ command: 'shot',
149
+ reason: `compares one route with a reference; --${flag} is another subject`,
150
+ fix: 'x shot / --against .x/design/<slug> --json',
151
+ });
152
+ }
153
+
154
+ export interface AgainstShot {
155
+ readonly width: number;
156
+ readonly height: number;
157
+ readonly scheme: DesignScheme;
158
+ readonly image: string;
159
+ readonly verdictFile: string;
160
+ readonly reference: string;
161
+ readonly diff: string;
162
+ readonly similarity: number;
163
+ readonly changedPercent: number;
164
+ readonly artifacts: ShotArtifacts;
165
+ }
166
+
167
+ export interface AgainstRun {
168
+ readonly pairs: readonly AgainstPair[];
169
+ /** Absolute; each pair lands in `<outDir>/<width>-<scheme>/`. */
170
+ readonly outDir: string;
171
+ readonly boot: () => Promise<ShotServer>;
172
+ /** `runShot`, handed in so this module never imports the command that imports it. */
173
+ readonly shoot: (run: ShotRun) => Promise<ShotArtifacts>;
174
+ readonly base: Omit<ShotRun, 'outDir' | 'boot' | 'viewport' | 'colorScheme'>;
175
+ }
176
+
177
+ /** One server for every pair, `runShotViewports`' rule; each capture is an ordinary `runShot`. */
178
+ export async function runAgainst(
179
+ run: AgainstRun,
180
+ ): Promise<{ readonly ok: boolean; readonly shots: readonly AgainstShot[] }> {
181
+ const server = await run.boot();
182
+ const shared: ShotServer = { ...server, stop: () => Promise.resolve() };
183
+ const shots: AgainstShot[] = [];
184
+ try {
185
+ for (const pair of run.pairs) {
186
+ const key = `${String(pair.viewport.width)}-${pair.scheme}`;
187
+ const outDir = join(run.outDir, key);
188
+ const artifacts = await run.shoot({
189
+ ...run.base,
190
+ viewport: pair.viewport,
191
+ colorScheme: pair.scheme,
192
+ outDir,
193
+ boot: () => Promise.resolve(shared),
194
+ });
195
+ const compared = await compareCaptures(
196
+ await Bun.file(pair.reference).bytes(),
197
+ await Bun.file(artifacts.image).bytes(),
198
+ AGAINST_THRESHOLD,
199
+ );
200
+ const diff = join(outDir, `diff-${key}.png`);
201
+ await Bun.write(diff, compared.diffPng);
202
+ const against = {
203
+ reference: pair.reference,
204
+ diff,
205
+ similarity: compared.similarity,
206
+ changedPercent: compared.changedPercent,
207
+ changedBox: compared.changedBox,
208
+ threshold: AGAINST_THRESHOLD,
209
+ };
210
+ // Merged into the verdict `runShot` wrote, never replacing its `ok`: recorded, not gating.
211
+ const written: unknown = await Bun.file(artifacts.verdictFile).json();
212
+ const verdict = typeof written === 'object' && written !== null ? written : {};
213
+ await Bun.write(
214
+ artifacts.verdictFile,
215
+ `${JSON.stringify({ ...verdict, against }, null, 2)}\n`,
216
+ );
217
+ shots.push({
218
+ width: pair.viewport.width,
219
+ height: pair.viewport.height,
220
+ scheme: pair.scheme,
221
+ image: artifacts.image,
222
+ verdictFile: artifacts.verdictFile,
223
+ reference: pair.reference,
224
+ diff,
225
+ similarity: compared.similarity,
226
+ changedPercent: compared.changedPercent,
227
+ artifacts,
228
+ });
229
+ }
230
+ } finally {
231
+ await server.stop().catch(() => undefined);
232
+ }
233
+ return { ok: shots.every((shot) => shot.artifacts.verdict.ok), shots };
234
+ }
235
+
236
+ export function againstResult(run: {
237
+ readonly ok: boolean;
238
+ readonly shots: readonly AgainstShot[];
239
+ }): CommandResult {
240
+ const lowest = [...run.shots].sort((a, b) => a.similarity - b.similarity)[0];
241
+ return {
242
+ ok: run.ok,
243
+ command: 'shot',
244
+ summary:
245
+ lowest === undefined
246
+ ? msg('cli.shot.against.none')
247
+ : msg('cli.shot.against.summary', {
248
+ pairs: run.shots.length,
249
+ similarity: lowest.similarity,
250
+ pair: `${String(lowest.width)}-${lowest.scheme}`,
251
+ }),
252
+ lines: run.shots.map((shot) =>
253
+ msg('cli.shot.against.line', {
254
+ pair: `${String(shot.width)}-${shot.scheme}`,
255
+ similarity: shot.similarity,
256
+ diff: shot.diff,
257
+ summary: shotSummary(shot.artifacts.verdict),
258
+ }),
259
+ ),
260
+ data: {
261
+ shots: run.shots.map((shot) => ({
262
+ width: shot.width,
263
+ height: shot.height,
264
+ scheme: shot.scheme,
265
+ image: shot.image,
266
+ verdictFile: shot.verdictFile,
267
+ reference: shot.reference,
268
+ diff: shot.diff,
269
+ similarity: shot.similarity,
270
+ changedPercent: shot.changedPercent,
271
+ verdict: verdictJson(shot.artifacts.verdict),
272
+ })),
273
+ },
274
+ };
275
+ }
@@ -7,7 +7,7 @@ export const shotSpec: CommandSpec = {
7
7
  name: 'shot',
8
8
  summary: 'photograph one route, one island in a state it declares, or every island in the app',
9
9
  usage:
10
- 'x shot <route> [--locale <l>] [--theme light|dark] [--viewport 390x844,1440x900] | --matrix [<route>] | --island <name> [--state <id>] | --all-islands [--cookie <name=value>] [--expect-status 404] [--port 0] [--out <dir>] [--settle 2000] [--json]',
10
+ 'x shot <route> [--locale <l>] [--theme light|dark] [--viewport 390x844,1440x900] [--against <png|.x/design/<slug>>] | --matrix [<route>] | --island <name> [--state <id>] | --all-islands [--cookie <name=value>] [--expect-status 404] [--port 0] [--out <dir>] [--settle 2000] [--json]',
11
11
  requiresApp: true,
12
12
  flags: [
13
13
  { name: 'port', type: 'string', summary: 'dev port (0 lets the kernel pick a free one)' },
@@ -83,5 +83,13 @@ export const shotSpec: CommandSpec = {
83
83
  type: 'boolean',
84
84
  summary: 'every island in the app, in every state it declares, plus an index.md',
85
85
  },
86
+ // A flag on `x shot`, not a second command: comparing a route with a reference is photographing
87
+ // that route, plus one diff per picture.
88
+ {
89
+ name: 'against',
90
+ type: 'string',
91
+ summary:
92
+ 'a PNG, or a `x design research` directory: each picture compared with the reference shot of its width and scheme — diff-<w>-<scheme>.png and a similarity in verdict.json, never gating',
93
+ },
86
94
  ],
87
95
  };
package/src/cmd-shot.ts CHANGED
@@ -13,6 +13,7 @@ import { IDLE_HYDRATE_TIMEOUT_MS } from '@ultimat3/render';
13
13
  import { requireAppRoot } from './app-root';
14
14
  import { appBrowser } from './browser-launcher';
15
15
  import { DEFAULT_PAGE_TIMEOUT_MS } from './cdp-shot-clock';
16
+ import { againstResult, planAgainst, refuseAgainstWith, runAgainst } from './cmd-shot-against';
16
17
  import {
17
18
  islandShot,
18
19
  islandShotResult,
@@ -118,6 +119,7 @@ export const shotCommand: CliCommand = {
118
119
  const sweep = flagBool(ctx.args, 'all-islands');
119
120
  const matrix = flagBool(ctx.args, 'matrix');
120
121
  const cookies = readCookieFlag(flagString(ctx.args, 'cookie'));
122
+ const against = flagString(ctx.args, 'against');
121
123
  const viewports = parseViewports(flagString(ctx.args, 'viewport'));
122
124
  const app = await appLocaleSet(root);
123
125
  const locale = readLocaleFlag(flagString(ctx.args, 'locale'), app);
@@ -131,6 +133,11 @@ export const shotCommand: CliCommand = {
131
133
  refuseRouteWithIsland(positional, island);
132
134
  }
133
135
  const component = sweep || (island !== undefined && island !== '');
136
+ if (against !== undefined) {
137
+ if (matrix) refuseAgainstWith('matrix');
138
+ if (sweep) refuseAgainstWith('all-islands');
139
+ if (component) refuseAgainstWith('island');
140
+ }
134
141
  // The matrix photographs ROUTES; a component beside it is two subjects.
135
142
  if (matrix && component) refuseMatrixWithComponent();
136
143
  // An island state declares its own size, so a size asked for beside one is a second answer.
@@ -235,6 +242,18 @@ export const shotCommand: CliCommand = {
235
242
  ...(theme === undefined ? {} : { colorScheme: theme }),
236
243
  };
237
244
  const outDir = shotOutDir(ctx.cwd, out, join(root, SHOT_DIR, shotSlug(path)));
245
+ if (against !== undefined) {
246
+ // Relative to where the caller stands, `--out`'s rule: the path they typed.
247
+ const pairs = planAgainst({
248
+ reference: resolve(ctx.cwd, against),
249
+ within: [root, ctx.cwd],
250
+ viewports,
251
+ theme,
252
+ });
253
+ return againstResult(
254
+ await runAgainst({ pairs, outDir, boot, shoot: runShot, base: { ...single } }),
255
+ );
256
+ }
238
257
  if (viewports !== undefined) {
239
258
  return runShotViewports({ viewports, outDir, boot, shoot: runShot, base: single });
240
259
  }
@@ -373,6 +373,17 @@ export const createUpgradeCommand = (
373
373
  return {
374
374
  spec: upgradeSpec,
375
375
  async run(ctx: CommandContext): Promise<CommandResult> {
376
+ // `--dry-run` is the one read-only form an allowlist may grant (`.claude/settings.json`), and
377
+ // last-wins parsing would let a trailing `--no-dry-run` turn it into a real hop.
378
+ if (ctx.args.flags.get('dry-run') === false) {
379
+ throw new BadFlagError({
380
+ flag: 'dry-run',
381
+ command: 'upgrade',
382
+ reason:
383
+ '--no-dry-run is refused: a hop is what a bare x upgrade is, so there is nothing to negate',
384
+ fix: 'x upgrade --dry-run --json # or, to move the pins: x upgrade --json',
385
+ });
386
+ }
376
387
  if (ctx.args.subcommand === 'codemods') return runUpgradeCodemods(ctx);
377
388
  const { dir: root, app } = await findUpgradeRoot(ctx.cwd);
378
389
  const to = readTarget(ctx);
@@ -0,0 +1,130 @@
1
+ // The agent kit replaces what `x new` once wrote as `.claude/commands/{feature,planx,verify}.md` and
2
+ // `.claude/agents/{shape,data,server,web}.md`: an unedited copy — any text a release shipped — is
3
+ // deleted, because `x kit` writes the managed skill or agent in its place; an edited one is kept as
4
+ // the app's own `app-<name>.md`, with the diff to the managed file, so no edit is ever lost.
5
+
6
+ import { isReleasedKitForm } from '../app-kit-forms';
7
+ import { KIT_MARKER, kitFiles } from '../kit/registry';
8
+ import { RELEASED_KIT_FORMS } from '../templates/kit-released-forms';
9
+ import { names } from '../templates/naming';
10
+ import { claudeFiles } from '../templates/scaffold-claude';
11
+ import { appName } from './agents-dev-mcp';
12
+ import type { Codemod, CodemodApp, CodemodResult } from './codemod';
13
+ import { unifiedDiff } from './engine-diff';
14
+
15
+ /** Each old file, and the managed file that now answers the same question. */
16
+ const sameText = (a: string, b: string): boolean =>
17
+ a.replaceAll('\r\n', '\n') === b.replaceAll('\r\n', '\n');
18
+
19
+ const OLD_FILES: readonly { readonly path: string; readonly now: string }[] = [
20
+ { path: '.claude/commands/feature.md', now: '.claude/skills/feature/SKILL.md' },
21
+ { path: '.claude/commands/planx.md', now: '.claude/skills/planx/SKILL.md' },
22
+ { path: '.claude/commands/verify.md', now: '.claude/skills/verify/SKILL.md' },
23
+ { path: '.claude/agents/shape.md', now: '.claude/agents/shape.md' },
24
+ { path: '.claude/agents/data.md', now: '.claude/agents/data.md' },
25
+ { path: '.claude/agents/server.md', now: '.claude/agents/server.md' },
26
+ { path: '.claude/agents/web.md', now: '.claude/agents/web.md' },
27
+ ];
28
+
29
+ /** `<dir>/app-<name>.md`, or the first `app-<name>-<n>` the app does not already hold. */
30
+ const freePath = async (app: CodemodApp, path: string): Promise<string> => {
31
+ const slash = path.lastIndexOf('/');
32
+ const dir = path.slice(0, slash);
33
+ const name = path.slice(slash + 1, -'.md'.length);
34
+ for (let n = 1; ; n += 1) {
35
+ const candidate = `${dir}/app-${name}${n === 1 ? '' : `-${String(n)}`}.md`;
36
+ if (!(await app.exists(candidate))) return candidate;
37
+ }
38
+ };
39
+
40
+ /** An agent's `name:` is its identity: the copy renamed to `app-<n>` must not still claim `<n>`. */
41
+ const renamedAgent = (text: string, name: string): string =>
42
+ text.replace(
43
+ new RegExp(`^(---\\r?\\n(?:[^\\n]*\\n)*?name:[ \\t]*)${name}([ \\t]*\\r?$)`, 'm'),
44
+ `$1app-${name}$2`,
45
+ );
46
+
47
+ async function run(
48
+ app: CodemodApp,
49
+ forms: Readonly<Record<string, readonly string[]>>,
50
+ ): Promise<CodemodResult> {
51
+ const changed: string[] = [];
52
+ const skipped: CodemodResult['skipped'] = [];
53
+ // Opted in already: the files at these paths are the kit's own, and `x verify` judges them.
54
+ if (await app.exists(KIT_MARKER)) return { changed, skipped };
55
+ const name = appName((await app.read('package.json')) ?? '') ?? '';
56
+ const managed = new Map(
57
+ kitFiles(names(name === '' ? 'app' : name)).map((f) => [f.path, f.contents]),
58
+ );
59
+ for (const { path, now } of OLD_FILES) {
60
+ const held = await app.read(path);
61
+ if (held === undefined) continue;
62
+ // What `x kit` writes today is no old file: an agent already as rendered stays.
63
+ if (managed.get(path)?.replaceAll('\r\n', '\n') === held.replaceAll('\r\n', '\n')) continue;
64
+ const known = Object.hasOwn(forms, path) ? forms[path] : undefined;
65
+ if (isReleasedKitForm(held, [name], known)) {
66
+ await app.remove(path);
67
+ changed.push(path);
68
+ continue;
69
+ }
70
+ const target = await freePath(app, path);
71
+ const stem = path.slice(path.lastIndexOf('/') + 1, -'.md'.length);
72
+ await app.write(target, path.startsWith('.claude/agents/') ? renamedAgent(held, stem) : held);
73
+ await app.remove(path);
74
+ changed.push(path, target);
75
+ skipped.push({
76
+ path: target,
77
+ reason: `${path} was edited, so it is kept as your own ${target}; the managed ${now} (written by x kit) replaces it — carry what you changed into ${target} or drop it`,
78
+ diff: unifiedDiff(target, held, managed.get(now) ?? ''),
79
+ });
80
+ }
81
+ await carryReadme(app, { name, forms, changed, skipped });
82
+ return { changed, skipped };
83
+ }
84
+
85
+ const README = '.claude/README.md';
86
+
87
+ /**
88
+ * `.claude/README.md` said "nothing here is enforced" until the kit made the managed files so. An
89
+ * unedited released copy is replaced by the new one; an edited one is kept and reported with the
90
+ * diff to the new text, because its prose is the author's.
91
+ */
92
+ async function carryReadme(
93
+ app: CodemodApp,
94
+ input: {
95
+ readonly name: string;
96
+ readonly forms: Readonly<Record<string, readonly string[]>>;
97
+ readonly changed: string[];
98
+ readonly skipped: CodemodResult['skipped'];
99
+ },
100
+ ): Promise<void> {
101
+ const held = await app.read(README);
102
+ const next = claudeFiles(names(input.name === '' ? 'app' : input.name)).find(
103
+ (file) => file.path === README,
104
+ )?.contents;
105
+ if (held === undefined || typeof next !== 'string' || sameText(held, next)) return;
106
+ const known = Object.hasOwn(input.forms, README) ? input.forms[README] : undefined;
107
+ if (isReleasedKitForm(held, [input.name], known)) {
108
+ await app.write(README, next);
109
+ input.changed.push(README);
110
+ return;
111
+ }
112
+ input.skipped.push({
113
+ path: README,
114
+ reason: `${README} was edited, so it is kept; it still says nothing here is enforced, which is no longer true of the managed kit — merge what the new one says (the diff) into it`,
115
+ diff: unifiedDiff(README, held, next),
116
+ });
117
+ }
118
+
119
+ /** The migration over a released-forms table: the committed one, or a test's own. */
120
+ export const agentKitCodemod = (
121
+ forms: Readonly<Record<string, readonly string[]>> = RELEASED_KIT_FORMS,
122
+ ): Codemod => ({
123
+ id: 'agent-kit',
124
+ since: '31.53.0',
125
+ summary:
126
+ 'the agent kit is managed (x kit): unedited .claude/commands and .claude/agents deleted, an edited one kept as app-<name>.md',
127
+ run: (app) => run(app, forms),
128
+ });
129
+
130
+ export const codemod: Codemod = agentKitCodemod();
@@ -0,0 +1,47 @@
1
+ // 31.53.0: lifts an app's default `agentsMdMaxBytes` (12,000 B, or none declared) to the scaffold's
2
+ // 13,120 B, so `docs-visual-quality`'s rows fit; a budget the author raised is never touched.
3
+ //
4
+ // The brief `x new` writes grew by the motion, effect and Visual quality rows (plan 101); without
5
+ // this hop an app would get a build error for the framework's own prose.
6
+
7
+ import { AGENTS_MD_MAX_BYTES } from '@ultimat3/manifest';
8
+ import { SCAFFOLD_AGENTS_MD_MAX_BYTES } from '../templates/scaffold-docs';
9
+ import { VERIFY_FLOOR_FILE } from '../verify-floor';
10
+ import type { Codemod } from './codemod';
11
+
12
+ export const codemod: Codemod = {
13
+ id: 'agents-md-budget',
14
+ since: '31.53.0',
15
+ summary: `x.verify.json agentsMdMaxBytes ${String(SCAFFOLD_AGENTS_MD_MAX_BYTES)}, the budget the new brief rows need (was the ${String(AGENTS_MD_MAX_BYTES)} default)`,
16
+ async run(app) {
17
+ const source = await app.read(VERIFY_FLOOR_FILE);
18
+ // No floor file is no floor: the default stands, and a floor is the app's to opt into.
19
+ if (source === undefined) return { changed: [], skipped: [] };
20
+ let floor: unknown;
21
+ try {
22
+ floor = JSON.parse(source);
23
+ } catch {
24
+ return {
25
+ changed: [],
26
+ skipped: [
27
+ {
28
+ path: VERIFY_FLOOR_FILE,
29
+ reason: `${VERIFY_FLOOR_FILE} does not parse: fix it, then add "agentsMdMaxBytes": ${String(SCAFFOLD_AGENTS_MD_MAX_BYTES)} by hand`,
30
+ },
31
+ ],
32
+ };
33
+ }
34
+ if (typeof floor !== 'object' || floor === null || Array.isArray(floor)) {
35
+ return { changed: [], skipped: [] };
36
+ }
37
+ const held = Reflect.get(floor, 'agentsMdMaxBytes');
38
+ if (held !== undefined && held !== AGENTS_MD_MAX_BYTES) {
39
+ return { changed: [], skipped: [] };
40
+ }
41
+ await app.write(
42
+ VERIFY_FLOOR_FILE,
43
+ `${JSON.stringify({ ...floor, agentsMdMaxBytes: SCAFFOLD_AGENTS_MD_MAX_BYTES }, null, 2)}\n`,
44
+ );
45
+ return { changed: [VERIFY_FLOOR_FILE], skipped: [] };
46
+ },
47
+ };