kerfjs 5.0.0-beta.13 → 5.0.0-beta.130

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 (94) hide show
  1. package/CHANGELOG.md +3370 -108
  2. package/README.md +101 -37
  3. package/ai/cursorrules +127 -68
  4. package/ai/manifest.json +36 -7
  5. package/ai/skill.md +167 -86
  6. package/ai/ui-skill.md +18 -0
  7. package/dist/actions.d.ts +1 -1
  8. package/dist/actions.js +10 -6
  9. package/dist/actions.js.map +1 -1
  10. package/dist/array-signal.js +1 -1
  11. package/dist/async.d.ts +7 -3
  12. package/dist/async.js +39 -22
  13. package/dist/async.js.map +1 -1
  14. package/dist/attach.js +1 -66
  15. package/dist/attach.js.map +1 -1
  16. package/dist/{chunk-GY4XV2UV.js → chunk-4TX6YJDM.js} +10 -3
  17. package/dist/chunk-4TX6YJDM.js.map +1 -0
  18. package/dist/{chunk-SVATPF5R.js → chunk-5QDM6HPD.js} +637 -277
  19. package/dist/chunk-5QDM6HPD.js.map +1 -0
  20. package/dist/{chunk-QIP723L4.js → chunk-5WRGJZV6.js} +3 -2
  21. package/dist/chunk-5WRGJZV6.js.map +1 -0
  22. package/dist/chunk-AP2FT33F.js +87 -0
  23. package/dist/chunk-AP2FT33F.js.map +1 -0
  24. package/dist/chunk-BTOKH5FA.js +70 -0
  25. package/dist/chunk-BTOKH5FA.js.map +1 -0
  26. package/dist/{chunk-ZDCJZCNO.js → chunk-GGADRIQO.js} +168 -97
  27. package/dist/chunk-GGADRIQO.js.map +1 -0
  28. package/dist/chunk-KOEGJCIS.js +65 -0
  29. package/dist/chunk-KOEGJCIS.js.map +1 -0
  30. package/dist/{chunk-HW7KSM2Y.js → chunk-KUHXPPJ4.js} +1 -1
  31. package/dist/chunk-KUHXPPJ4.js.map +1 -0
  32. package/dist/{chunk-UZJ6I4T6.js → chunk-MK42GLPV.js} +1 -1
  33. package/dist/chunk-MK42GLPV.js.map +1 -0
  34. package/dist/chunk-N4VHHOCM.js +27 -0
  35. package/dist/chunk-N4VHHOCM.js.map +1 -0
  36. package/dist/{chunk-V46JKE44.js → chunk-NRPLVJVR.js} +43 -14
  37. package/dist/chunk-NRPLVJVR.js.map +1 -0
  38. package/dist/{chunk-LVH3GC6B.js → chunk-QOAB2ESQ.js} +3 -3
  39. package/dist/chunk-QOAB2ESQ.js.map +1 -0
  40. package/dist/{chunk-KZJXHFIB.js → chunk-V322Z7FX.js} +5 -5
  41. package/dist/chunk-V322Z7FX.js.map +1 -0
  42. package/dist/{delegate-CL9VTZFb.d.ts → delegate--CrfgYtC.d.ts} +0 -34
  43. package/dist/dev.d.ts +46 -15
  44. package/dist/dev.js +185 -40
  45. package/dist/dev.js.map +1 -1
  46. package/dist/html.js +20 -8
  47. package/dist/html.js.map +1 -1
  48. package/dist/index.d.ts +98 -13
  49. package/dist/index.js +49 -21
  50. package/dist/index.js.map +1 -1
  51. package/dist/jsx-runtime.d.ts +25 -10
  52. package/dist/jsx-runtime.js +1 -1
  53. package/dist/list.d.ts +7 -3
  54. package/dist/list.js +236 -78
  55. package/dist/list.js.map +1 -1
  56. package/dist/overlay.d.ts +287 -142
  57. package/dist/overlay.js +1039 -369
  58. package/dist/overlay.js.map +1 -1
  59. package/dist/remount.js +2 -2
  60. package/dist/remount.js.map +1 -1
  61. package/dist/router.d.ts +22 -6
  62. package/dist/router.js +58 -19
  63. package/dist/router.js.map +1 -1
  64. package/dist/scope.d.ts +45 -8
  65. package/dist/scope.js +69 -30
  66. package/dist/scope.js.map +1 -1
  67. package/dist/testing.js +1 -1
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +8 -3
  70. package/dist/timing.js.map +1 -1
  71. package/llms.txt +17 -6
  72. package/package.json +48 -12
  73. package/setup/apply.mjs +202 -0
  74. package/setup/cli.mjs +95 -0
  75. package/setup/common.mjs +77 -0
  76. package/setup/detect.mjs +274 -0
  77. package/setup/index.d.mts +39 -0
  78. package/setup/index.mjs +1226 -0
  79. package/setup/jsonc.mjs +201 -0
  80. package/setup/state.schema.json +57 -0
  81. package/setup/ui-baseline.mjs +210 -0
  82. package/dist/chunk-GY4XV2UV.js.map +0 -1
  83. package/dist/chunk-HW7KSM2Y.js.map +0 -1
  84. package/dist/chunk-KPXIOG2C.js +0 -54
  85. package/dist/chunk-KPXIOG2C.js.map +0 -1
  86. package/dist/chunk-KZJXHFIB.js.map +0 -1
  87. package/dist/chunk-LVH3GC6B.js.map +0 -1
  88. package/dist/chunk-QIP723L4.js.map +0 -1
  89. package/dist/chunk-SVATPF5R.js.map +0 -1
  90. package/dist/chunk-U6FK33SG.js +0 -20
  91. package/dist/chunk-U6FK33SG.js.map +0 -1
  92. package/dist/chunk-UZJ6I4T6.js.map +0 -1
  93. package/dist/chunk-V46JKE44.js.map +0 -1
  94. package/dist/chunk-ZDCJZCNO.js.map +0 -1
@@ -0,0 +1,1226 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, relative, resolve } from 'node:path';
4
+ import process from 'node:process';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ import {
8
+ contained,
9
+ dependencies,
10
+ describeValue,
11
+ exists,
12
+ parseJsonFile,
13
+ portable,
14
+ readJson,
15
+ readText,
16
+ redactText,
17
+ sha256,
18
+ shellArg,
19
+ stableJson,
20
+ } from './common.mjs';
21
+ import { detectMode, packageManagerInfo, selectPackage } from './detect.mjs';
22
+ import {
23
+ applyJsoncEdits,
24
+ jsoncInsertProperties,
25
+ jsoncValueEdit,
26
+ parseJsoncDocument,
27
+ } from './jsonc.mjs';
28
+ import {
29
+ uiAppFiles,
30
+ uiDoctorConfig,
31
+ uiEslintTemplate,
32
+ uiPrettierConfig,
33
+ } from './ui-baseline.mjs';
34
+
35
+ export { applyKerfSetup } from './apply.mjs';
36
+
37
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
38
+ const marker = '<!-- KERF-APP-CANONICAL-END · your customizations below -->';
39
+
40
+ function validateSetupState(state) {
41
+ if (!state || typeof state !== 'object' || Array.isArray(state))
42
+ throw new Error('.kerf-ai-setup.json must be an object.');
43
+ if (![1, 2].includes(state.schemaVersion))
44
+ throw new Error(
45
+ `Unsupported .kerf-ai-setup.json schemaVersion ${state.schemaVersion}.`,
46
+ );
47
+ if (
48
+ typeof state.setupVersion !== 'string' ||
49
+ !['npm', 'pnpm', 'yarn'].includes(state.packageManager) ||
50
+ (state.packageManagerVersion !== undefined &&
51
+ typeof state.packageManagerVersion !== 'string') ||
52
+ (state.packageManagerVariant !== undefined &&
53
+ !['classic', 'berry'].includes(state.packageManagerVariant)) ||
54
+ (state.packageManagerVariant !== undefined &&
55
+ state.packageManager !== 'yarn')
56
+ )
57
+ throw new Error(
58
+ '.kerf-ai-setup.json has invalid version or package-manager metadata.',
59
+ );
60
+ const packageStates =
61
+ state.schemaVersion === 2 ? state.packages : { [state.packagePath]: state };
62
+ if (!packageStates || typeof packageStates !== 'object')
63
+ throw new Error('.kerf-ai-setup.json packages must be an object.');
64
+ for (const [key, value] of Object.entries(packageStates)) {
65
+ if (
66
+ !value ||
67
+ typeof value !== 'object' ||
68
+ value.packagePath !== key ||
69
+ typeof value.package !== 'string' ||
70
+ !['core', 'ui'].includes(value.mode) ||
71
+ !value.managed ||
72
+ typeof value.managed !== 'object' ||
73
+ !value.resolutions ||
74
+ typeof value.resolutions !== 'object'
75
+ )
76
+ throw new Error(`Invalid setup state for package ${key}.`);
77
+ for (const resolution of Object.values(value.resolutions ?? {}))
78
+ if (!['keep', 'kerf', 'skip'].includes(resolution))
79
+ throw new Error(`Invalid persisted resolution for package ${key}.`);
80
+ for (const item of Object.values(value.managed ?? {}))
81
+ if (!item || !/^[a-f0-9]{64}$/.test(item.sha256 ?? ''))
82
+ throw new Error(`Invalid managed-value hash for package ${key}.`);
83
+ }
84
+ }
85
+
86
+ function allowsVersion(range, version) {
87
+ if (typeof range !== 'string') return false;
88
+ if (range === version || range === '*' || range === 'latest') return true;
89
+ const requested = version
90
+ .match(/^(\d+)\.(\d+)\.(\d+)/)
91
+ ?.slice(1)
92
+ .map(Number);
93
+ const declared = range.match(/^(\^|~|>=)\s*(\d+)\.(\d+)\.(\d+)/);
94
+ if (!requested || !declared) return false;
95
+ const base = declared.slice(2).map(Number);
96
+ const compare =
97
+ requested[0] - base[0] || requested[1] - base[1] || requested[2] - base[2];
98
+ if (compare < 0) return false;
99
+ if (declared[1] === '^') return requested[0] === base[0];
100
+ if (declared[1] === '~')
101
+ return requested[0] === base[0] && requested[1] === base[1];
102
+ return true;
103
+ }
104
+
105
+ function splitCanonical(source) {
106
+ const first = source.indexOf(marker);
107
+ if (first < 0) return { error: 'missing canonical marker' };
108
+ if (source.indexOf(marker, first + marker.length) >= 0)
109
+ return { error: 'multiple canonical markers' };
110
+ const end = first + marker.length + (source[first + marker.length] === '\n');
111
+ return { canonical: source.slice(0, end), append: source.slice(end) };
112
+ }
113
+
114
+ function mergeCanonical(current, bundled, history, version) {
115
+ if (current === null) return { value: bundled };
116
+ const local = splitCanonical(current);
117
+ if (local.error) return { conflict: local.error };
118
+ const localVersion = current
119
+ .slice(0, 512)
120
+ .match(/kerf-skill-version:\s*([\w.-]+)/)?.[1];
121
+ if (!localVersion) return { conflict: 'missing kerf-skill-version' };
122
+ const expected =
123
+ localVersion === version ? sha256(bundled) : history[localVersion];
124
+ if (!expected || sha256(local.canonical) !== expected)
125
+ return { conflict: 'canonical content was customized above the marker' };
126
+ return { value: bundled + local.append };
127
+ }
128
+
129
+ const hashValue = (value) => sha256(JSON.stringify(value) ?? 'undefined');
130
+
131
+ function reconcileValue({
132
+ target,
133
+ key,
134
+ value,
135
+ id,
136
+ conflicts,
137
+ managedBefore,
138
+ managedAfter,
139
+ resolutions,
140
+ activeConflictIds,
141
+ activeProposalIds,
142
+ knownResolutionIds,
143
+ }) {
144
+ knownResolutionIds.add(id);
145
+ const current = target[key];
146
+ const previouslyManaged = managedBefore[id]?.sha256 === hashValue(current);
147
+ const divergent = key in target && current !== value && !previouslyManaged;
148
+ if (divergent) activeConflictIds.add(id);
149
+ const resolution =
150
+ resolutions[id] === 'skip' && divergent ? undefined : resolutions[id];
151
+ if (divergent && !resolution) {
152
+ conflicts.push({
153
+ id,
154
+ message: `existing value ${describeValue(id, current)} differs from ${describeValue(id, value)}`,
155
+ });
156
+ return;
157
+ }
158
+ if (divergent && resolution === 'keep') return;
159
+ if (!divergent && hashValue(current) !== hashValue(value)) {
160
+ activeProposalIds.add(id);
161
+ if (resolution === 'skip') {
162
+ if (previouslyManaged) managedAfter[id] = managedBefore[id];
163
+ return;
164
+ }
165
+ }
166
+ target[key] = value;
167
+ managedAfter[id] = { sha256: hashValue(value) };
168
+ }
169
+
170
+ function addMapValues(target, additions, path, context) {
171
+ for (const [key, value] of Object.entries(additions)) {
172
+ reconcileValue({ target, key, value, id: `${path}.${key}`, ...context });
173
+ }
174
+ }
175
+
176
+ function eslintTemplate(mode, format = 'module') {
177
+ if (mode === 'ui') return uiEslintTemplate(format);
178
+ const preset = mode === 'ui' ? 'recommended-ui' : 'recommended';
179
+ if (format === 'commonjs')
180
+ return `module.exports = (async () => {\n const { default: parser } = await import('@typescript-eslint/parser');\n const { default: kerfjs } = await import('eslint-plugin-kerfjs');\n return [\n { files: ['**/*.{ts,tsx}'], languageOptions: { parser } },\n kerfjs.configs['${preset}'],\n ];\n})();\n`;
181
+ return `import parser from '@typescript-eslint/parser';\nimport kerfjs from 'eslint-plugin-kerfjs';\n\nexport default [\n { files: ['**/*.{ts,tsx}'], languageOptions: { parser } },\n kerfjs.configs['${preset}'],\n];\n`;
182
+ }
183
+
184
+ function mergeEslintConfig(source, mode) {
185
+ const imported = source.match(
186
+ /^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]eslint-plugin-kerfjs['"]\s*;?\s*$/m,
187
+ );
188
+ if (imported) {
189
+ const preset = mode === 'ui' ? 'recommended-ui' : 'recommended';
190
+ const configured = new RegExp(
191
+ `^\\s*${imported[1]}\\.configs\\[['"]${preset}['"]\\],?\\s*$`,
192
+ 'm',
193
+ );
194
+ if (configured.test(source)) return { value: source };
195
+ }
196
+ const match = source.match(/^\s*export\s+default\s*\[/m);
197
+ if (!match || (source.includes('`') && !imported))
198
+ return {
199
+ conflict: 'config does not use a provable static export default array',
200
+ };
201
+ const preset = mode === 'ui' ? 'recommended-ui' : 'recommended';
202
+ const importLine = imported
203
+ ? ''
204
+ : "import kerfjs from 'eslint-plugin-kerfjs';\n";
205
+ const binding = imported?.[1] ?? 'kerfjs';
206
+ return {
207
+ value: `${importLine}${source.slice(0, match.index + match[0].length)}\n ${binding}.configs['${preset}'],${source.slice(match.index + match[0].length)}`,
208
+ };
209
+ }
210
+
211
+ function profileTemplate(packageName, catalogPath, selectionPath) {
212
+ return {
213
+ $schema:
214
+ 'https://raw.githubusercontent.com/brianwestphal/kerf/main/ui/ai/application-ui-profile.schema.json',
215
+ schemaVersion: 1,
216
+ scope: 'workspace',
217
+ catalogs: [
218
+ {
219
+ package: packageName,
220
+ ...(selectionPath
221
+ ? { selection: { path: selectionPath, schemaVersion: 1 } }
222
+ : {}),
223
+ composition: { path: catalogPath, schemaVersion: 1 },
224
+ },
225
+ ],
226
+ };
227
+ }
228
+
229
+ function metadataTemplate() {
230
+ return {
231
+ $schema:
232
+ './node_modules/create-kerf-component/component-metadata.schema.json',
233
+ schemaVersion: 1,
234
+ componentCatalog: 'not-applicable',
235
+ components: [],
236
+ };
237
+ }
238
+
239
+ async function installedVersion(directory, name) {
240
+ try {
241
+ const require = createRequire(resolve(directory, 'package.json'));
242
+ let current = dirname(require.resolve(name));
243
+ while (dirname(current) !== current) {
244
+ const manifest = await readJson(resolve(current, 'package.json'));
245
+ if (manifest?.name === name) return manifest.version;
246
+ current = dirname(current);
247
+ }
248
+ } catch {
249
+ return null;
250
+ }
251
+ return null;
252
+ }
253
+
254
+ function mergeProfile(current, recommended, context) {
255
+ if (current === undefined) current = {};
256
+ const idPrefix = '.kerf-ui-profile.json';
257
+ if (!current || typeof current !== 'object' || Array.isArray(current)) {
258
+ context.knownResolutionIds.add(idPrefix);
259
+ context.activeConflictIds.add(idPrefix);
260
+ if (!context.resolutions[idPrefix]) {
261
+ context.conflicts.push({
262
+ id: idPrefix,
263
+ message: 'profile root must be an object',
264
+ });
265
+ return current;
266
+ }
267
+ if (context.resolutions[idPrefix] === 'keep') return current;
268
+ current = {};
269
+ }
270
+ const output = JSON.parse(JSON.stringify(current));
271
+ for (const key of ['$schema', 'schemaVersion', 'scope']) {
272
+ reconcileValue({
273
+ target: output,
274
+ key,
275
+ value: recommended[key],
276
+ id: `.kerf-ui-profile.json#${key}`,
277
+ ...context,
278
+ });
279
+ }
280
+ if (output.catalogs !== undefined && !Array.isArray(output.catalogs)) {
281
+ const id = `${idPrefix}#catalogs`;
282
+ context.knownResolutionIds.add(id);
283
+ context.activeConflictIds.add(id);
284
+ if (!context.resolutions[id]) {
285
+ context.conflicts.push({ id, message: 'catalogs must be an array' });
286
+ return output;
287
+ }
288
+ if (context.resolutions[id] === 'keep') return output;
289
+ output.catalogs = [];
290
+ }
291
+ output.catalogs ??= [];
292
+ const local = recommended.catalogs[0];
293
+ const existing = output.catalogs.find(
294
+ (item) => item.package === local.package,
295
+ );
296
+ const id = `.kerf-ui-profile.json#catalogs.${local.package}`;
297
+ context.knownResolutionIds.add(id);
298
+ if (!existing) {
299
+ context.activeProposalIds.add(id);
300
+ if (context.resolutions[id] !== 'skip') {
301
+ output.catalogs.push(local);
302
+ context.managedAfter[id] = { sha256: hashValue(local) };
303
+ }
304
+ } else {
305
+ const previouslyManaged =
306
+ context.managedBefore[id]?.sha256 === hashValue(existing);
307
+ const divergent =
308
+ JSON.stringify(existing) !== JSON.stringify(local) && !previouslyManaged;
309
+ if (divergent) context.activeConflictIds.add(id);
310
+ if (
311
+ divergent &&
312
+ (!context.resolutions[id] || context.resolutions[id] === 'skip')
313
+ )
314
+ context.conflicts.push({
315
+ id,
316
+ message: 'existing catalog declaration differs',
317
+ });
318
+ else if (!divergent || context.resolutions[id] === 'kerf') {
319
+ if (hashValue(existing) !== hashValue(local)) {
320
+ context.activeProposalIds.add(id);
321
+ if (context.resolutions[id] === 'skip') {
322
+ context.managedAfter[id] = context.managedBefore[id];
323
+ return output;
324
+ }
325
+ }
326
+ output.catalogs[output.catalogs.indexOf(existing)] = local;
327
+ context.managedAfter[id] = { sha256: hashValue(local) };
328
+ }
329
+ }
330
+ return output;
331
+ }
332
+
333
+ /**
334
+ * Validates an explicit or remembered shared-guidance source and returns its
335
+ * workspace-relative path (undefined when there is none).
336
+ */
337
+ async function validatedGuidanceSource(root, guidanceSource) {
338
+ if (!guidanceSource) return guidanceSource;
339
+ const sourcePath = resolve(root, guidanceSource);
340
+ if (!sourcePath.startsWith(`${root}/`))
341
+ throw new Error(
342
+ 'Shared guidance source must be inside the workspace root.',
343
+ );
344
+ const actualSourcePath = await realpath(sourcePath).catch(() => null);
345
+ if (
346
+ actualSourcePath &&
347
+ !actualSourcePath.startsWith(`${await realpath(root)}/`)
348
+ )
349
+ throw new Error(
350
+ 'Shared guidance source must resolve inside the workspace root.',
351
+ );
352
+ const source = await readText(sourcePath);
353
+ if (
354
+ !source ||
355
+ !/\bkerf(?:js)?\b/i.test(source) ||
356
+ !/(?:kerf:check|npm run check)/i.test(source)
357
+ )
358
+ throw new Error(
359
+ 'Shared guidance source must exist and describe Kerf and a project check command.',
360
+ );
361
+ return portable(root, sourcePath);
362
+ }
363
+
364
+ /**
365
+ * The shared accumulator every planning phase writes into: planned file
366
+ * actions, conflicts, managed hashes, and the resolution bookkeeping that
367
+ * `reconcileValue` / `addMapValues` read through `context`.
368
+ */
369
+ function createPlanAccumulator({
370
+ root,
371
+ selected,
372
+ mode,
373
+ setupVersion,
374
+ resolutions,
375
+ requestedResolutions,
376
+ managedBefore,
377
+ }) {
378
+ const plan = {
379
+ root,
380
+ selected,
381
+ mode,
382
+ setupVersion,
383
+ resolutions,
384
+ requestedResolutions,
385
+ managedBefore,
386
+ conflicts: [],
387
+ actions: [],
388
+ generatedPaths: [],
389
+ managedAfter: {},
390
+ knownResolutionIds: new Set(),
391
+ activeConflictIds: new Set(),
392
+ activeProposalIds: new Set(),
393
+ };
394
+ plan.context = {
395
+ conflicts: plan.conflicts,
396
+ managedBefore,
397
+ managedAfter: plan.managedAfter,
398
+ resolutions,
399
+ knownResolutionIds: plan.knownResolutionIds,
400
+ activeConflictIds: plan.activeConflictIds,
401
+ activeProposalIds: plan.activeProposalIds,
402
+ };
403
+ plan.addAction = async (path, value, kind = 'write') => {
404
+ const before = await readText(path);
405
+ if (before !== value)
406
+ plan.actions.push({
407
+ path: portable(root, path),
408
+ absolutePath: path,
409
+ before,
410
+ after: value,
411
+ kind,
412
+ });
413
+ };
414
+ return plan;
415
+ }
416
+
417
+ /** Conflicts when the running setup differs from the project's installed kerfjs. */
418
+ async function planKerfVersion(plan) {
419
+ const { selected, setupVersion, resolutions } = plan;
420
+ const projectKerfVersion = await installedVersion(
421
+ selected.directory,
422
+ 'kerfjs',
423
+ );
424
+ plan.knownResolutionIds.add('kerfjs-version');
425
+ if (projectKerfVersion && projectKerfVersion !== setupVersion) {
426
+ plan.activeConflictIds.add('kerfjs-version');
427
+ if (!resolutions['kerfjs-version'])
428
+ plan.conflicts.push({
429
+ id: 'kerfjs-version',
430
+ message: `running setup ${setupVersion} differs from installed kerfjs ${projectKerfVersion}; rerun with kerfjs@${projectKerfVersion}, or choose keep to retain project declarations or kerf to update them`,
431
+ });
432
+ }
433
+ }
434
+
435
+ /** The canonical AI guidance files (skills, cursorrules) and shared-guidance imports. */
436
+ async function planAiFiles(plan, aiManifest, guidanceSource) {
437
+ const { root, mode, resolutions, managedAfter } = plan;
438
+ for (const file of aiManifest.files) {
439
+ if (file.name === 'ui-skill' && mode !== 'ui') continue;
440
+ if (
441
+ file.name === 'cursorrules' &&
442
+ !(await exists(resolve(root, '.cursor'))) &&
443
+ !(await exists(resolve(root, '.cursorrules')))
444
+ )
445
+ continue;
446
+ const destination = resolve(root, file.dest);
447
+ const bundled = await readFile(resolve(packageRoot, file.bundle), 'utf8');
448
+ if ((file.name === 'skill' || file.name === 'ui-skill') && guidanceSource) {
449
+ const sourcePath = resolve(root, guidanceSource);
450
+ const importPath = relative(dirname(destination), sourcePath).replaceAll(
451
+ '\\',
452
+ '/',
453
+ );
454
+ const shared =
455
+ file.name === 'ui-skill'
456
+ ? `---\nname: kerf-ui\ndescription: Use shared workspace guidance and the installed @kerfjs/ui instructions.\n---\n\n@${importPath}\n\nIn the selected package, read \`node_modules/@kerfjs/ui/llms.txt\` first, then \`node_modules/@kerfjs/ui/ai/skill.md\` and the component references they name.\n`
457
+ : `---\nname: kerf-app\ndescription: Use the shared workspace guidance for Kerf application work.\n---\n\n@${importPath}\n`;
458
+ const current = await readText(destination);
459
+ plan.knownResolutionIds.add(file.dest);
460
+ if (current !== null && current !== shared && !resolutions[file.dest]) {
461
+ plan.activeConflictIds.add(file.dest);
462
+ plan.conflicts.push({
463
+ id: file.dest,
464
+ message: 'shared guidance import differs from existing skill',
465
+ });
466
+ } else if (
467
+ current === null ||
468
+ current === shared ||
469
+ resolutions[file.dest] === 'kerf'
470
+ ) {
471
+ await plan.addAction(destination, shared, 'canonical');
472
+ managedAfter[file.dest] = { sha256: sha256(shared) };
473
+ } else {
474
+ plan.activeConflictIds.add(file.dest);
475
+ }
476
+ continue;
477
+ }
478
+ const merged = mergeCanonical(
479
+ await readText(destination),
480
+ bundled,
481
+ file.history ?? {},
482
+ file.version,
483
+ );
484
+ plan.knownResolutionIds.add(file.dest);
485
+ if (merged.conflict) {
486
+ plan.activeConflictIds.add(file.dest);
487
+ if (!resolutions[file.dest])
488
+ plan.conflicts.push({ id: file.dest, message: merged.conflict });
489
+ else if (resolutions[file.dest] === 'kerf') {
490
+ const local = splitCanonical((await readText(destination)) ?? '');
491
+ const replacement = local.error ? bundled : bundled + local.append;
492
+ await plan.addAction(destination, replacement, 'canonical');
493
+ managedAfter[file.dest] = { sha256: sha256(bundled) };
494
+ }
495
+ } else {
496
+ await plan.addAction(destination, merged.value, 'canonical');
497
+ managedAfter[file.dest] = {
498
+ sha256: sha256(splitCanonical(merged.value).canonical),
499
+ };
500
+ }
501
+ }
502
+ if (mode === 'ui') {
503
+ const content = `---\nname: kerf-ui-design-mock\ndescription: Plan and review rendered Kerf UI screen concepts before implementation, using the installed package's design-mock workflow.\n---\n\nRead the selected project's installed \`node_modules/@kerfjs/ui/ai/design-mock/SKILL.md\` and follow it. Resolve that path from the selected package in a workspace. Read the same installed package's \`llms.txt\` and \`ai/skill.md\` as directed there so the design uses its actual component version.\n`;
504
+ for (const provider of ['.claude', '.agents']) {
505
+ const path = `${provider}/skills/kerf-ui-design-mock/SKILL.md`;
506
+ const destination = resolve(root, path);
507
+ const current = await readText(destination);
508
+ plan.knownResolutionIds.add(path);
509
+ if (current !== null && current !== content && !resolutions[path]) {
510
+ plan.activeConflictIds.add(path);
511
+ plan.conflicts.push({
512
+ id: path,
513
+ message:
514
+ 'design-mock skill entry differs from installed guidance pointer',
515
+ });
516
+ } else if (
517
+ current === null ||
518
+ current === content ||
519
+ resolutions[path] === 'kerf'
520
+ ) {
521
+ await plan.addAction(destination, content, 'canonical');
522
+ managedAfter[path] = { sha256: sha256(content) };
523
+ } else {
524
+ plan.activeConflictIds.add(path);
525
+ }
526
+ }
527
+ }
528
+ }
529
+
530
+ /**
531
+ * The selected package's package.json: scripts, tool devDependencies, the
532
+ * kerfjs / @kerfjs/ui dependency reconciliation, and (UI) the component
533
+ * catalog configuration. Returns the next manifest plus the facts later
534
+ * phases share.
535
+ */
536
+ async function planManifest(plan, priorPackageState, packageKey) {
537
+ const {
538
+ root,
539
+ selected,
540
+ mode,
541
+ setupVersion,
542
+ resolutions,
543
+ requestedResolutions,
544
+ managedBefore,
545
+ context,
546
+ } = plan;
547
+ const packagePath = resolve(selected.directory, 'package.json');
548
+ const nextManifest = JSON.parse(JSON.stringify(selected.manifest));
549
+ const freshUiApp =
550
+ mode === 'ui' &&
551
+ !(await exists(resolve(selected.directory, 'src'))) &&
552
+ !(await exists(resolve(selected.directory, 'index.html'))) &&
553
+ !(await exists(resolve(selected.directory, 'vite.config.mjs'))) &&
554
+ !(await exists(resolve(selected.directory, 'app')));
555
+ const scaffoldUiApp =
556
+ freshUiApp ||
557
+ Boolean(
558
+ priorPackageState.managed?.[
559
+ `${packageKey === '.' ? '' : `${packageKey}/`}src/app/main.tsx`
560
+ ],
561
+ );
562
+ nextManifest.scripts ??= {};
563
+ nextManifest.devDependencies ??= {};
564
+ nextManifest.dependencies ??= {};
565
+ const packageDoctorConfig = resolve(
566
+ selected.directory,
567
+ '.kerf-ui-doctor.json',
568
+ );
569
+ const workspaceDoctorArgs =
570
+ selected.directory === root
571
+ ? ''
572
+ : ` --root ${portable(selected.directory, root)} --package ${nextManifest.name}${
573
+ mode === 'ui' || (await exists(packageDoctorConfig))
574
+ ? ` --config ${shellArg(portable(root, packageDoctorConfig))}`
575
+ : ''
576
+ }`;
577
+ addMapValues(
578
+ nextManifest.scripts,
579
+ mode === 'ui'
580
+ ? {
581
+ lint: 'prettier --check . --ignore-unknown && eslint . --max-warnings 0',
582
+ typecheck: 'tsc --noEmit',
583
+ check: `prettier --check . --ignore-unknown && eslint . --max-warnings 0 && tsc --noEmit && kerf-component-catalog --check && kerf-ui-doctor --full${workspaceDoctorArgs}${scaffoldUiApp ? ' && node --test tests/structure.test.mjs && vite build' : ''}`,
584
+ 'kerf:check': `prettier --check . --ignore-unknown && eslint . --max-warnings 0 && tsc --noEmit && kerf-component-catalog --check && kerf-ui-doctor --full${workspaceDoctorArgs}${scaffoldUiApp ? ' && node --test tests/structure.test.mjs && vite build' : ''}`,
585
+ 'kerf:doctor': `kerf-ui-doctor --full${workspaceDoctorArgs}`,
586
+ 'kerf:doctor:changed': `kerf-ui-doctor --changed${workspaceDoctorArgs}`,
587
+ 'catalog:generate': 'kerf-component-catalog --write',
588
+ 'catalog:check': 'kerf-component-catalog --check',
589
+ ...(scaffoldUiApp
590
+ ? {
591
+ dev: 'vite',
592
+ build: 'vite build',
593
+ 'test:structure': 'node --test tests/structure.test.mjs',
594
+ }
595
+ : {}),
596
+ }
597
+ : { 'kerf:check': 'tsc --noEmit && eslint .' },
598
+ 'package.json#scripts',
599
+ context,
600
+ );
601
+ addMapValues(
602
+ nextManifest.devDependencies,
603
+ {
604
+ 'eslint-plugin-kerfjs': setupVersion,
605
+ '@typescript-eslint/parser': '^8.0.0',
606
+ eslint: '^9.0.0',
607
+ typescript: '^5.0.0 || ^6.0.0',
608
+ ...(mode === 'ui' ? { 'create-kerf-component': setupVersion } : {}),
609
+ ...(mode === 'ui'
610
+ ? {
611
+ '@eslint/js': '^9.0.0',
612
+ '@stylistic/eslint-plugin': '^5.0.0',
613
+ 'eslint-plugin-simple-import-sort': '^12.1.1',
614
+ prettier: '^3.0.0',
615
+ 'typescript-eslint': '^8.65.0',
616
+ ...(scaffoldUiApp ? { vite: '^7.0.0' } : {}),
617
+ }
618
+ : {}),
619
+ },
620
+ 'package.json#devDependencies',
621
+ context,
622
+ );
623
+ const reconcileDependency = (name) => {
624
+ const section =
625
+ ['dependencies', 'devDependencies', 'peerDependencies'].find(
626
+ (candidate) => name in (nextManifest[candidate] ?? {}),
627
+ ) ?? 'dependencies';
628
+ nextManifest[section] ??= {};
629
+ const id = `package.json#${section}.${name}`;
630
+ if (
631
+ allowsVersion(nextManifest[section][name], setupVersion) &&
632
+ managedBefore[id]?.sha256 !== hashValue(nextManifest[section][name])
633
+ ) {
634
+ plan.knownResolutionIds.add(id);
635
+ return;
636
+ }
637
+ const dependencyContext =
638
+ name === 'kerfjs' && resolutions['kerfjs-version']
639
+ ? {
640
+ ...context,
641
+ resolutions: {
642
+ ...resolutions,
643
+ [id]: requestedResolutions[id] ?? resolutions['kerfjs-version'],
644
+ },
645
+ }
646
+ : context;
647
+ reconcileValue({
648
+ target: nextManifest[section],
649
+ key: name,
650
+ value: setupVersion,
651
+ id,
652
+ ...dependencyContext,
653
+ });
654
+ };
655
+ reconcileDependency('kerfjs');
656
+ if (mode === 'ui') reconcileDependency('@kerfjs/ui');
657
+ if (mode === 'ui') {
658
+ reconcileValue({
659
+ target: nextManifest,
660
+ key: 'kerfComponentCatalog',
661
+ value: {
662
+ source: './kerf.components.json',
663
+ output: './component-composition.json',
664
+ },
665
+ id: 'package.json#kerfComponentCatalog',
666
+ ...context,
667
+ });
668
+ for (const [key, configuredPath] of Object.entries(
669
+ nextManifest.kerfComponentCatalog ?? {},
670
+ ))
671
+ if (
672
+ typeof configuredPath !== 'string' ||
673
+ !contained(
674
+ selected.directory,
675
+ resolve(selected.directory, configuredPath),
676
+ )
677
+ )
678
+ throw new Error(
679
+ `kerfComponentCatalog.${key} must stay inside the selected package.`,
680
+ );
681
+ }
682
+ await plan.addAction(packagePath, stableJson(nextManifest), 'json');
683
+ return { nextManifest, scaffoldUiApp, packageDoctorConfig };
684
+ }
685
+
686
+ /** tsconfig.json: create it, or merge the recommended compiler options as JSONC edits. */
687
+ async function planTsconfig(plan) {
688
+ const { selected, mode, resolutions, managedAfter, context } = plan;
689
+ const tsconfigPath = resolve(selected.directory, 'tsconfig.json');
690
+ const tsconfigSource = await readText(tsconfigPath);
691
+ const tsconfigRecommendations = {
692
+ target: 'ES2022',
693
+ module: 'ESNext',
694
+ moduleResolution: 'Bundler',
695
+ strict: true,
696
+ ...(mode === 'ui' ? { noUncheckedIndexedAccess: true } : {}),
697
+ jsx: 'react-jsx',
698
+ jsxImportSource: 'kerfjs',
699
+ };
700
+ if (tsconfigSource === null) {
701
+ const tsconfig = { compilerOptions: {}, include: ['src'] };
702
+ addMapValues(
703
+ tsconfig.compilerOptions,
704
+ tsconfigRecommendations,
705
+ 'tsconfig.json#compilerOptions',
706
+ context,
707
+ );
708
+ await plan.addAction(tsconfigPath, stableJson(tsconfig), 'json');
709
+ return;
710
+ }
711
+ const parsed = parseJsoncDocument(tsconfigSource, 'tsconfig.json');
712
+ const rootId = 'tsconfig.json';
713
+ if (parsed.root.type !== 'object') {
714
+ plan.knownResolutionIds.add(rootId);
715
+ plan.activeConflictIds.add(rootId);
716
+ if (!resolutions[rootId])
717
+ plan.conflicts.push({
718
+ id: rootId,
719
+ message: 'root value must be an object',
720
+ });
721
+ else if (resolutions[rootId] === 'kerf') {
722
+ const replacement = {
723
+ compilerOptions: { ...tsconfigRecommendations },
724
+ include: ['src'],
725
+ };
726
+ for (const [key, value] of Object.entries(tsconfigRecommendations))
727
+ managedAfter[`tsconfig.json#compilerOptions.${key}`] = {
728
+ sha256: hashValue(value),
729
+ };
730
+ await plan.addAction(tsconfigPath, stableJson(replacement), 'json');
731
+ }
732
+ return;
733
+ }
734
+ const edits = [];
735
+ const rootInsertions = [];
736
+ const compilerProperty = parsed.root.properties.get('compilerOptions');
737
+ if (compilerProperty && compilerProperty.valueNode.type !== 'object') {
738
+ const id = 'tsconfig.json#compilerOptions';
739
+ plan.knownResolutionIds.add(id);
740
+ plan.activeConflictIds.add(id);
741
+ if (!resolutions[id])
742
+ plan.conflicts.push({ id, message: 'existing value must be an object' });
743
+ else if (resolutions[id] === 'kerf') {
744
+ edits.push(
745
+ jsoncValueEdit(
746
+ compilerProperty.valueNode,
747
+ tsconfigRecommendations,
748
+ tsconfigSource,
749
+ ),
750
+ );
751
+ for (const [key, value] of Object.entries(tsconfigRecommendations))
752
+ managedAfter[`tsconfig.json#compilerOptions.${key}`] = {
753
+ sha256: hashValue(value),
754
+ };
755
+ }
756
+ } else {
757
+ const compilerOptions = compilerProperty?.valueNode.value ?? {};
758
+ const before = { ...compilerOptions };
759
+ addMapValues(
760
+ compilerOptions,
761
+ tsconfigRecommendations,
762
+ 'tsconfig.json#compilerOptions',
763
+ context,
764
+ );
765
+ if (compilerProperty) {
766
+ const missing = [];
767
+ for (const [key, value] of Object.entries(compilerOptions)) {
768
+ const property = compilerProperty.valueNode.properties.get(key);
769
+ if (!property) missing.push([key, value]);
770
+ else if (before[key] !== value)
771
+ edits.push(jsoncValueEdit(property.valueNode, value, tsconfigSource));
772
+ }
773
+ edits.push(
774
+ ...jsoncInsertProperties(
775
+ tsconfigSource,
776
+ compilerProperty.valueNode,
777
+ missing,
778
+ ),
779
+ );
780
+ } else {
781
+ rootInsertions.push(['compilerOptions', compilerOptions]);
782
+ }
783
+ }
784
+ if (!parsed.root.properties.has('include'))
785
+ rootInsertions.push(['include', ['src']]);
786
+ edits.push(
787
+ ...jsoncInsertProperties(tsconfigSource, parsed.root, rootInsertions),
788
+ );
789
+ await plan.addAction(
790
+ tsconfigPath,
791
+ applyJsoncEdits(tsconfigSource, edits),
792
+ 'jsonc',
793
+ );
794
+ }
795
+
796
+ /** The ESLint flat config: generate one, or merge / conflict on an existing one. */
797
+ async function planEslint(plan, nextManifest) {
798
+ const { root, selected, mode, resolutions, managedBefore, managedAfter } =
799
+ plan;
800
+ const eslintNames = [
801
+ 'eslint.config.js',
802
+ 'eslint.config.mjs',
803
+ 'eslint.config.cjs',
804
+ ];
805
+ let eslintPath;
806
+ for (const name of eslintNames)
807
+ if (await exists(resolve(selected.directory, name))) {
808
+ eslintPath = resolve(selected.directory, name);
809
+ break;
810
+ }
811
+ if (!eslintPath) {
812
+ const generatedPath = resolve(selected.directory, 'eslint.config.mjs');
813
+ const generated = eslintTemplate(mode);
814
+ await plan.addAction(generatedPath, generated);
815
+ managedAfter[portable(root, generatedPath)] = { sha256: sha256(generated) };
816
+ return;
817
+ }
818
+ const source = await readText(eslintPath);
819
+ const id = portable(root, eslintPath);
820
+ plan.knownResolutionIds.add(id);
821
+ const commonjs =
822
+ eslintPath.endsWith('.cjs') ||
823
+ (eslintPath.endsWith('.js') && nextManifest.type !== 'module');
824
+ const template = eslintTemplate(mode, commonjs ? 'commonjs' : 'module');
825
+ const wasManaged = managedBefore[id]?.sha256 === sha256(source);
826
+ const wasEditedManaged = Boolean(managedBefore[id]) && !wasManaged;
827
+ const merged = wasManaged
828
+ ? { value: template }
829
+ : wasEditedManaged
830
+ ? { conflict: 'setup-authored config was customized' }
831
+ : mode === 'ui'
832
+ ? source === template
833
+ ? { value: source }
834
+ : {
835
+ conflict:
836
+ 'existing UI ESLint config needs the full typed Kerf baseline',
837
+ }
838
+ : commonjs
839
+ ? {
840
+ conflict:
841
+ 'CommonJS config requires an explicit Kerf preset merge',
842
+ }
843
+ : mergeEslintConfig(source, mode);
844
+ if (merged.conflict) {
845
+ plan.activeConflictIds.add(id);
846
+ if (!resolutions[id])
847
+ plan.conflicts.push({
848
+ id,
849
+ message: `${merged.conflict}; choose keep or kerf`,
850
+ });
851
+ else if (resolutions[id] === 'kerf') {
852
+ const generated = template;
853
+ await plan.addAction(eslintPath, generated);
854
+ managedAfter[id] = { sha256: sha256(generated) };
855
+ }
856
+ } else {
857
+ await plan.addAction(eslintPath, merged.value);
858
+ if (wasManaged) managedAfter[id] = { sha256: sha256(merged.value) };
859
+ }
860
+ }
861
+
862
+ /** UI mode: Prettier config, doctor config, and the fresh-app scaffold files. */
863
+ async function planUiBaseline(plan, { scaffoldUiApp, packageDoctorConfig }) {
864
+ const { root, selected, resolutions, managedBefore, managedAfter } = plan;
865
+ const prettierFiles = [
866
+ 'prettier.config.mjs',
867
+ 'prettier.config.js',
868
+ '.prettierrc',
869
+ '.prettierrc.json',
870
+ '.prettierrc.js',
871
+ '.prettierrc.mjs',
872
+ ];
873
+ if (
874
+ !(
875
+ await Promise.all(
876
+ prettierFiles.map((name) => exists(resolve(selected.directory, name))),
877
+ )
878
+ ).some(Boolean)
879
+ ) {
880
+ await plan.addAction(
881
+ resolve(selected.directory, 'prettier.config.mjs'),
882
+ uiPrettierConfig,
883
+ );
884
+ }
885
+ if (!(await exists(packageDoctorConfig)))
886
+ await plan.addAction(
887
+ packageDoctorConfig,
888
+ stableJson(uiDoctorConfig),
889
+ 'json',
890
+ );
891
+ if (!scaffoldUiApp) return;
892
+ for (const [path, content] of Object.entries(uiAppFiles())) {
893
+ const destination = resolve(selected.directory, path);
894
+ const id = portable(root, destination);
895
+ const current = await readText(destination);
896
+ plan.knownResolutionIds.add(id);
897
+ if (
898
+ current !== null &&
899
+ current !== content &&
900
+ managedBefore[id]?.sha256 !== sha256(current)
901
+ ) {
902
+ plan.activeConflictIds.add(id);
903
+ if (!resolutions[id]) {
904
+ plan.conflicts.push({
905
+ id,
906
+ message: 'app scaffold file was customized; choose keep or kerf',
907
+ });
908
+ continue;
909
+ }
910
+ if (resolutions[id] === 'keep') continue;
911
+ }
912
+ await plan.addAction(destination, content);
913
+ managedAfter[id] = { sha256: sha256(content) };
914
+ }
915
+ }
916
+
917
+ /**
918
+ * UI mode with a component catalog: the workspace .kerf-ui-profile.json
919
+ * catalog entry, the catalog metadata source, and the generated catalog paths.
920
+ */
921
+ async function planUiCatalog(plan, nextManifest) {
922
+ const { root, selected, context } = plan;
923
+ const profilePath = resolve(root, '.kerf-ui-profile.json');
924
+ const currentProfileSource = await readText(profilePath);
925
+ const currentProfile =
926
+ currentProfileSource === null
927
+ ? undefined
928
+ : parseJsonFile(currentProfileSource, profilePath, root);
929
+ const profileCatalogPath = (configuredPath) => {
930
+ const relative = portable(
931
+ root,
932
+ resolve(selected.directory, configuredPath),
933
+ );
934
+ return relative.startsWith('.') ? relative : `./${relative}`;
935
+ };
936
+ const profile = mergeProfile(
937
+ currentProfile,
938
+ profileTemplate(
939
+ nextManifest.name,
940
+ profileCatalogPath(nextManifest.kerfComponentCatalog.output),
941
+ nextManifest.kerfComponentCatalog.selectionOutput
942
+ ? profileCatalogPath(nextManifest.kerfComponentCatalog.selectionOutput)
943
+ : undefined,
944
+ ),
945
+ context,
946
+ );
947
+ await plan.addAction(profilePath, stableJson(profile), 'json');
948
+ const metadataPath = resolve(
949
+ selected.directory,
950
+ nextManifest.kerfComponentCatalog.source,
951
+ );
952
+ if (nextManifest.kerfComponentCatalog.selectionOutput) {
953
+ const metadata = await readJson(metadataPath, root);
954
+ if (
955
+ !metadata ||
956
+ typeof metadata.description !== 'string' ||
957
+ !metadata.description.trim()
958
+ )
959
+ throw new Error(
960
+ `${portable(root, metadataPath)}: selectionOutput requires an authored metadata source with a nonempty description. Add the source and description before running setup.`,
961
+ );
962
+ } else if (!(await exists(metadataPath)))
963
+ await plan.addAction(metadataPath, stableJson(metadataTemplate()), 'json');
964
+ if (
965
+ nextManifest.scripts['catalog:generate'] &&
966
+ dependencies(nextManifest)['create-kerf-component']
967
+ ) {
968
+ plan.generatedPaths.push(
969
+ resolve(selected.directory, nextManifest.kerfComponentCatalog.output),
970
+ );
971
+ if (nextManifest.kerfComponentCatalog.selectionOutput)
972
+ plan.generatedPaths.push(
973
+ resolve(
974
+ selected.directory,
975
+ nextManifest.kerfComponentCatalog.selectionOutput,
976
+ ),
977
+ );
978
+ }
979
+ }
980
+
981
+ /** Every requested resolution must name a live conflict or proposal. */
982
+ function validateRequestedResolutions(plan) {
983
+ for (const [id, resolution] of Object.entries(plan.requestedResolutions)) {
984
+ if (!['keep', 'kerf', 'skip'].includes(resolution))
985
+ throw new Error(`Resolution ${id} must be keep, kerf, or skip.`);
986
+ if (!plan.knownResolutionIds.has(id))
987
+ throw new Error(`Unknown resolution id ${id}.`);
988
+ if (resolution === 'skip' && plan.activeConflictIds.has(id))
989
+ throw new Error(
990
+ `Resolution ${id} cannot skip a conflict; choose keep or kerf.`,
991
+ );
992
+ if (
993
+ !plan.activeConflictIds.has(id) &&
994
+ !(resolution !== 'keep' && plan.activeProposalIds.has(id))
995
+ )
996
+ throw new Error(
997
+ `Stale resolution id ${id}; there is no applicable conflict or proposal.`,
998
+ );
999
+ }
1000
+ }
1001
+
1002
+ /** The next .kerf-ai-setup.json: prior package states plus this package's. */
1003
+ function nextSetupState(plan, { manager, priorState, packageEntry }) {
1004
+ return {
1005
+ schemaVersion: 2,
1006
+ setupVersion: plan.setupVersion,
1007
+ packageManager: manager.name,
1008
+ ...(manager.version ? { packageManagerVersion: manager.version } : {}),
1009
+ ...(manager.variant ? { packageManagerVariant: manager.variant } : {}),
1010
+ packages: {
1011
+ ...(priorState.packages ??
1012
+ (priorState.packagePath
1013
+ ? {
1014
+ [priorState.packagePath]: {
1015
+ mode: priorState.mode,
1016
+ package: priorState.package,
1017
+ packagePath: priorState.packagePath,
1018
+ ...(priorState.guidanceSource
1019
+ ? { guidanceSource: priorState.guidanceSource }
1020
+ : {}),
1021
+ managed: priorState.managed ?? {},
1022
+ resolutions: priorState.resolutions ?? {},
1023
+ },
1024
+ }
1025
+ : {})),
1026
+ [packageEntry.packagePath]: packageEntry,
1027
+ },
1028
+ };
1029
+ }
1030
+
1031
+ export async function planKerfSetup({
1032
+ root = process.cwd(),
1033
+ package: selector,
1034
+ mode: requestedMode,
1035
+ version,
1036
+ resolutions = {},
1037
+ guidanceSource,
1038
+ } = {}) {
1039
+ root = resolve(root);
1040
+ const selected = await selectPackage(root, selector, requestedMode);
1041
+ const detectedMode = await detectMode(selected);
1042
+ const mode = requestedMode ?? detectedMode;
1043
+ if (!mode) throw new Error('Pass --core or --ui for a new Kerf package.');
1044
+ if (requestedMode && detectedMode && requestedMode !== detectedMode)
1045
+ throw new Error(
1046
+ `Requested ${requestedMode} conflicts with detected ${detectedMode} usage.`,
1047
+ );
1048
+ const ownManifest = await readJson(resolve(packageRoot, 'package.json'));
1049
+ const setupVersion = version ?? ownManifest.version;
1050
+ const statePath = resolve(root, '.kerf-ai-setup.json');
1051
+ const priorState = (await readJson(statePath, root)) ?? {};
1052
+ if (Object.keys(priorState).length) validateSetupState(priorState);
1053
+ const packageKey = portable(root, selected.directory);
1054
+ const legacyPackageState =
1055
+ priorState.packagePath === packageKey ? priorState : {};
1056
+ const priorPackageState =
1057
+ priorState.packages?.[packageKey] ?? legacyPackageState;
1058
+ guidanceSource = await validatedGuidanceSource(
1059
+ root,
1060
+ guidanceSource ?? priorPackageState.guidanceSource,
1061
+ );
1062
+ if (
1063
+ priorPackageState.package &&
1064
+ priorPackageState.package !== (selected.manifest.name ?? packageKey)
1065
+ )
1066
+ throw new Error(`Setup state package identity changed at ${packageKey}.`);
1067
+
1068
+ const plan = createPlanAccumulator({
1069
+ root,
1070
+ selected,
1071
+ mode,
1072
+ setupVersion,
1073
+ requestedResolutions: { ...resolutions },
1074
+ resolutions: { ...(priorPackageState.resolutions ?? {}), ...resolutions },
1075
+ managedBefore: priorPackageState.managed ?? {},
1076
+ });
1077
+ const aiManifest = await readJson(resolve(packageRoot, 'ai/manifest.json'));
1078
+ await planKerfVersion(plan);
1079
+ await planAiFiles(plan, aiManifest, guidanceSource);
1080
+ const manifestPlan = await planManifest(plan, priorPackageState, packageKey);
1081
+ const { nextManifest } = manifestPlan;
1082
+ await planTsconfig(plan);
1083
+ await planEslint(plan, nextManifest);
1084
+ if (mode === 'ui') {
1085
+ await planUiBaseline(plan, manifestPlan);
1086
+ if (!nextManifest.name)
1087
+ throw new Error(
1088
+ 'UI setup requires package.json name for catalog identity.',
1089
+ );
1090
+ if (nextManifest.kerfComponentCatalog !== undefined)
1091
+ await planUiCatalog(plan, nextManifest);
1092
+ }
1093
+ validateRequestedResolutions(plan);
1094
+
1095
+ const {
1096
+ resolutions: effectiveResolutions,
1097
+ activeConflictIds,
1098
+ activeProposalIds,
1099
+ } = plan;
1100
+ const manager = await packageManagerInfo(root);
1101
+ const state = nextSetupState(plan, {
1102
+ manager,
1103
+ priorState,
1104
+ packageEntry: {
1105
+ mode,
1106
+ package: nextManifest.name ?? packageKey,
1107
+ packagePath: packageKey,
1108
+ ...(guidanceSource ? { guidanceSource } : {}),
1109
+ managed: plan.managedAfter,
1110
+ resolutions: Object.fromEntries(
1111
+ [...new Set([...activeConflictIds, ...activeProposalIds])]
1112
+ .filter(
1113
+ (id) =>
1114
+ (activeConflictIds.has(id) &&
1115
+ effectiveResolutions[id] === 'keep') ||
1116
+ (activeProposalIds.has(id) &&
1117
+ effectiveResolutions[id] === 'skip'),
1118
+ )
1119
+ .map((id) => [id, effectiveResolutions[id]]),
1120
+ ),
1121
+ },
1122
+ });
1123
+ await plan.addAction(statePath, stableJson(state), 'state');
1124
+ return {
1125
+ schemaVersion: 1,
1126
+ root,
1127
+ packageRoot: selected.directory,
1128
+ packageName: nextManifest.name ?? packageKey,
1129
+ packageManager: state.packageManager,
1130
+ packageManagerVersion: manager.version,
1131
+ packageManagerVariant: manager.variant,
1132
+ mode,
1133
+ setupVersion,
1134
+ actions: plan.actions,
1135
+ proposalIds: [...activeProposalIds].filter(
1136
+ (id) => effectiveResolutions[id] !== 'skip',
1137
+ ),
1138
+ conflicts: plan.conflicts,
1139
+ generatedPaths: plan.generatedPaths,
1140
+ };
1141
+ }
1142
+
1143
+ export function formatSetupPlan(plan) {
1144
+ const lines = [
1145
+ `Kerf AI setup: ${plan.mode} package ${portable(plan.root, plan.packageRoot)}`,
1146
+ ];
1147
+ let shown = 0;
1148
+ const render = (key, value) =>
1149
+ /token|secret|password|credential/i.test(key)
1150
+ ? '<redacted>'
1151
+ : value === undefined
1152
+ ? '<missing>'
1153
+ : redactText(JSON.stringify(value));
1154
+ const leaves = (value, prefix = '$', output = new Map()) => {
1155
+ if (value && typeof value === 'object') {
1156
+ for (const [key, child] of Object.entries(value))
1157
+ leaves(
1158
+ child,
1159
+ Array.isArray(value) ? `${prefix}[${key}]` : `${prefix}.${key}`,
1160
+ output,
1161
+ );
1162
+ } else output.set(prefix, value);
1163
+ return output;
1164
+ };
1165
+ for (const action of plan.actions) {
1166
+ lines.push(
1167
+ `${action.before === null ? 'CREATE' : 'UPDATE'} ${action.path}`,
1168
+ );
1169
+ if (shown >= 120) continue;
1170
+ if (
1171
+ action.kind === 'json' ||
1172
+ action.kind === 'jsonc' ||
1173
+ action.kind === 'state'
1174
+ ) {
1175
+ const before = leaves(
1176
+ action.before === null
1177
+ ? {}
1178
+ : action.kind === 'jsonc'
1179
+ ? parseJsoncDocument(action.before, action.path).value
1180
+ : JSON.parse(action.before),
1181
+ );
1182
+ const after = leaves(
1183
+ action.kind === 'jsonc'
1184
+ ? parseJsoncDocument(action.after, action.path).value
1185
+ : JSON.parse(action.after),
1186
+ );
1187
+ const keys = new Set([...before.keys(), ...after.keys()]);
1188
+ for (const key of keys) {
1189
+ if (action.kind === 'state' && key.includes('.managed.')) continue;
1190
+ if (JSON.stringify(before.get(key)) === JSON.stringify(after.get(key)))
1191
+ continue;
1192
+ if (shown++ >= 120) break;
1193
+ lines.push(
1194
+ ` ${key}: ${render(key, before.get(key))} -> ${render(key, after.get(key))}`,
1195
+ );
1196
+ }
1197
+ } else {
1198
+ const beforeLines = action.before?.split('\n').length ?? 0;
1199
+ const afterLines = action.after.split('\n').length;
1200
+ lines.push(` content: ${beforeLines} line(s) -> ${afterLines} line(s)`);
1201
+ shown += 1;
1202
+ }
1203
+ }
1204
+ if (shown >= 120) lines.push(' … additional changes omitted');
1205
+ for (const conflict of plan.conflicts)
1206
+ lines.push(
1207
+ `CONFLICT ${conflict.id}: ${conflict.message} (use --resolve ${conflict.id}=keep|kerf)`,
1208
+ );
1209
+ for (const id of plan.proposalIds ?? [])
1210
+ lines.push(`PROPOSAL ${id} (use --resolve ${id}=skip to decline)`);
1211
+ if (!plan.actions.length && !plan.conflicts.length) lines.push('No changes.');
1212
+ lines.push('AI guidance: .claude/skills/kerf-app/SKILL.md');
1213
+ if (plan.mode === 'ui') {
1214
+ lines.push('AI UI guidance: .claude/skills/kerf-ui/SKILL.md');
1215
+ lines.push(
1216
+ 'AI design mocks: .claude/skills/kerf-ui-design-mock/SKILL.md and .agents/skills/kerf-ui-design-mock/SKILL.md',
1217
+ );
1218
+ lines.push(
1219
+ `Read first: ${portable(plan.root, resolve(plan.packageRoot, 'node_modules/@kerfjs/ui/llms.txt'))}`,
1220
+ );
1221
+ lines.push(
1222
+ `Then read: ${portable(plan.root, resolve(plan.packageRoot, 'node_modules/@kerfjs/ui/ai/skill.md'))}`,
1223
+ );
1224
+ }
1225
+ return lines.join('\n');
1226
+ }