@venizia/vulcan 0.3.4 → 0.3.6

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 (56) hide show
  1. package/README.md +2 -2
  2. package/base/agents.json +232 -0
  3. package/base/claude/settings.json +12 -0
  4. package/base/hooks/guard-package.ts +29 -0
  5. package/base/rules.md +2 -0
  6. package/base/templates/AGENTS.md +4 -3
  7. package/package.json +3 -3
  8. package/src/agents/atlas-block.ts +54 -0
  9. package/src/agents/common/constants.ts +38 -0
  10. package/src/agents/common/index.ts +3 -0
  11. package/src/agents/common/schema.ts +42 -0
  12. package/src/agents/common/types.ts +30 -0
  13. package/src/agents/detect.ts +36 -0
  14. package/src/agents/exclude.ts +87 -0
  15. package/src/agents/index.ts +9 -0
  16. package/src/agents/local.ts +65 -0
  17. package/src/agents/prompt.ts +22 -0
  18. package/src/agents/render.ts +229 -0
  19. package/src/agents/resolve.ts +145 -0
  20. package/src/agents/table.ts +35 -0
  21. package/src/commands/agents.command.ts +154 -0
  22. package/src/commands/doctor.command.ts +5 -1
  23. package/src/commands/help.command.ts +5 -1
  24. package/src/commands/index.ts +2 -0
  25. package/src/commands/sync.command.ts +112 -3
  26. package/src/common/constants.ts +9 -1
  27. package/src/config/common/constants.ts +12 -1
  28. package/src/config/packages.ts +2 -0
  29. package/src/config/schema.ts +16 -1
  30. package/src/create/add-app.ts +110 -4
  31. package/src/create/add-lib.ts +317 -0
  32. package/src/create/common/constants.ts +3 -0
  33. package/src/create/common/types.ts +18 -2
  34. package/src/create/dockerignore.ts +36 -0
  35. package/src/create/init-monorepo.ts +22 -4
  36. package/src/create/lib-preset.ts +154 -0
  37. package/src/create/preset.ts +22 -3
  38. package/src/create/workspace.ts +94 -3
  39. package/src/doctor/checks.ts +183 -12
  40. package/src/doctor/common/constants.ts +26 -0
  41. package/src/doctor/runner.ts +22 -0
  42. package/src/hooks/guard-package.ts +211 -0
  43. package/src/hooks/index.ts +1 -0
  44. package/src/hooks/session-digest.ts +27 -1
  45. package/src/init/scaffold.ts +8 -5
  46. package/src/manifest/render.ts +4 -0
  47. package/src/router.ts +10 -1
  48. package/src/sync/agent-files.ts +112 -0
  49. package/src/sync/agent-removal.ts +241 -0
  50. package/src/sync/atlas-block.ts +55 -0
  51. package/src/sync/common/constants.ts +2 -0
  52. package/src/sync/exclude.ts +89 -0
  53. package/src/sync/index.ts +5 -0
  54. package/src/sync/local-choice.ts +55 -0
  55. package/src/sync/planner.ts +55 -19
  56. package/src/sync/settings.ts +26 -0
@@ -1,6 +1,7 @@
1
+ import { relative, resolve } from 'node:path';
1
2
  import { coversFolder } from '../init/index.ts';
2
3
  import { CreateConstants } from './common/index.ts';
3
- import type { IApp, IAppsBlock, IPreset, IPresetSpec } from './common/index.ts';
4
+ import type { IApp, IAppsBlock, IPreset, IPresetSpec, IRecordedPreset } from './common/index.ts';
4
5
 
5
6
  const ENV_PORT = /^[A-Z0-9_]*PORT=(\d+)\s*$/m;
6
7
 
@@ -20,7 +21,7 @@ export const renderRootManifest = (opts: {
20
21
  name: opts.project,
21
22
  private: true,
22
23
  workspaces: { packages: opts.workspaces, catalog: opts.catalog },
23
- scripts: { dev: "bun run --filter '*' dev" },
24
+ scripts: { dev: "bun run --filter '*' server:dev" },
24
25
  devDependencies: { '@venizia/vulcan': opts.vulcanVersion },
25
26
  },
26
27
  });
@@ -168,6 +169,60 @@ export const renderAppManifest = (opts: {
168
169
  },
169
170
  });
170
171
 
172
+ /** A library's package.json: generated fields first, then what the lib preset passes through. */
173
+ export const renderLibManifest = (opts: {
174
+ name: string;
175
+ lib: {
176
+ scripts: Record<string, string>;
177
+ dependencies: Record<string, string>;
178
+ devDependencies: Record<string, string>;
179
+ peerDependencies: Record<string, string>;
180
+ imports: Record<string, string>;
181
+ exports: Record<string, unknown>;
182
+ packageFields: Record<string, unknown>;
183
+ };
184
+ }): string => {
185
+ const { lib } = opts;
186
+ const section = (value: Record<string, unknown>, key: string): Record<string, unknown> =>
187
+ Object.keys(value).length === 0 ? {} : { [key]: value };
188
+
189
+ return json({
190
+ value: {
191
+ name: opts.name,
192
+ version: '0.0.0',
193
+ private: true,
194
+ ...lib.packageFields,
195
+ ...section(lib.exports, 'exports'),
196
+ ...section(lib.imports, 'imports'),
197
+ ...section(lib.scripts, 'scripts'),
198
+ ...section(toCatalog({ dependencies: lib.dependencies }), 'dependencies'),
199
+ ...section(toCatalog({ dependencies: lib.devDependencies }), 'devDependencies'),
200
+ ...section(toCatalog({ dependencies: lib.peerDependencies }), 'peerDependencies'),
201
+ },
202
+ });
203
+ };
204
+
205
+ export const renderLibConcept = (opts: {
206
+ name: string;
207
+ path: string;
208
+ summary: string;
209
+ presetPackage: string;
210
+ }): string =>
211
+ [
212
+ '---',
213
+ 'type: Package',
214
+ `title: ${opts.name}`,
215
+ `description: ${JSON.stringify(opts.summary)}`,
216
+ `resource: ${opts.path}`,
217
+ 'tags: [packages, library]',
218
+ '---',
219
+ '',
220
+ `# ${opts.name}`,
221
+ '',
222
+ `The shared package at \`${opts.path}\`, created from the ${opts.presetPackage} preset (lib kind). ${oneLine({ text: opts.summary })}`,
223
+ '',
224
+ ].join('\n');
225
+
171
226
  export const renderAppsBlock = (opts: { block: IAppsBlock }): string =>
172
227
  [
173
228
  CreateConstants.APPS_BLOCK_START,
@@ -183,15 +238,43 @@ export const renderVulcanConfig = (opts: { project: string; block: IAppsBlock })
183
238
  '',
184
239
  'export default {',
185
240
  ` name: '${opts.project}',`,
186
- " agents: ['claude'],",
187
241
  " rules: { 'V-W-01': 'on-user-word' },",
188
242
  ' layout: apps.layout,',
189
243
  ' packages: apps.packages,',
244
+ ' presets: apps.presets,',
190
245
  ' atlas: { sources: apps.sources },',
191
246
  '} satisfies VulcanConfig;',
192
247
  '',
193
248
  ].join('\n');
194
249
 
250
+ /**
251
+ * What `--preset` was given, kept so it can be typed again from the project root: a package spec as
252
+ * typed, a `file:` path made relative to the project.
253
+ */
254
+ export const presetSpecOf = (opts: { value: string; root: string; cwd: string }): string => {
255
+ const prefix = CreateConstants.PRESET_FILE_PREFIX;
256
+
257
+ if (!opts.value.startsWith(prefix)) {
258
+ return opts.value;
259
+ }
260
+
261
+ const target = resolve(opts.cwd, opts.value.slice(prefix.length));
262
+
263
+ return `${prefix}${relative(opts.root, target) || '.'}`;
264
+ };
265
+
266
+ /** The block with this preset recorded: once per spec, its side and summary refreshed. */
267
+ export const recordPreset = (opts: { block: IAppsBlock; preset: IRecordedPreset }): IAppsBlock => {
268
+ const others = (opts.block.presets ?? []).filter(item => item.spec !== opts.preset.spec);
269
+ const index = (opts.block.presets ?? []).findIndex(item => item.spec === opts.preset.spec);
270
+ const presets =
271
+ index === -1
272
+ ? [...others, opts.preset]
273
+ : (opts.block.presets ?? []).map((item, at) => (at === index ? opts.preset : item));
274
+
275
+ return { ...opts.block, presets };
276
+ };
277
+
195
278
  /** Only the text between the markers is rewritten; undefined when the user edited them away. */
196
279
  export const replaceAppsBlock = (opts: {
197
280
  source: string;
@@ -216,8 +299,16 @@ const hasStrings = (opts: { value: unknown; keys: string[] }): boolean => {
216
299
  return isRecord(value) && opts.keys.every(key => typeof value[key] === 'string');
217
300
  };
218
301
 
302
+ const isRecordedPreset = (value: unknown): boolean =>
303
+ hasStrings({ value, keys: ['spec', 'side', 'summary'] }) &&
304
+ isRecord(value) &&
305
+ (value.side === 'backend' || value.side === 'frontend') &&
306
+ (value.lib === undefined || typeof value.lib === 'string');
307
+
219
308
  const isAppsBlock = (value: unknown): value is IAppsBlock =>
220
309
  isRecord(value) &&
310
+ (value.presets === undefined ||
311
+ (Array.isArray(value.presets) && value.presets.every(entry => isRecordedPreset(entry)))) &&
221
312
  isRecord(value.layout) &&
222
313
  Object.values(value.layout).every(folder => typeof folder === 'string') &&
223
314
  Array.isArray(value.packages) &&
@@ -1,6 +1,6 @@
1
1
  import { Glob } from 'bun';
2
2
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
3
- import { join, relative } from 'node:path';
3
+ import { dirname, join, relative } from 'node:path';
4
4
  import { BASE_DIRECTORY, ProjectLayout } from '../common/index.ts';
5
5
  import { coversFolder, declaresWorkspaces, readWorkspaceGlobs } from '../init/index.ts';
6
6
  import { resolvePackages } from '../config/index.ts';
@@ -18,8 +18,15 @@ import {
18
18
  projectNameOf,
19
19
  renderManifest,
20
20
  } from '../manifest/index.ts';
21
- import { planManifest, planPrune, planSync, SyncStatuses } from '../sync/index.ts';
22
- import { DoctorChecks, DoctorConstants } from './common/index.ts';
21
+ import { readLocalChoice, resolveAgentsQuietly } from '../agents/index.ts';
22
+ import {
23
+ mergedAtlasBlock,
24
+ planManifest,
25
+ planPrune,
26
+ planSync,
27
+ SyncStatuses,
28
+ } from '../sync/index.ts';
29
+ import { AppScripts, DoctorChecks, DoctorConstants } from './common/index.ts';
23
30
  import type { IViolation, TDoctorCheck } from './common/index.ts';
24
31
  import { parseMakeIncludes, parseMakeTargets } from './makefile.ts';
25
32
 
@@ -221,7 +228,11 @@ export const checkHooks = (opts: ICheckContext): IViolation[] =>
221
228
  );
222
229
 
223
230
  export const checkAdapters = (opts: ICheckContext): IViolation[] => {
224
- const pending = planSync({ root: opts.root, config: opts.config })
231
+ const pending = planSync({
232
+ root: opts.root,
233
+ config: opts.config,
234
+ agents: resolveAgentsQuietly({ root: opts.root, configAgents: opts.config.agents }),
235
+ })
225
236
  .filter(action => action.status !== SyncStatuses.UNCHANGED)
226
237
  .filter(action => action.path !== join(opts.root, ManifestConstants.FILE));
227
238
  const absent = pending.filter(action => action.status === SyncStatuses.CREATED);
@@ -333,12 +344,19 @@ export const checkStyle = (opts: ICheckContext): IViolation[] => {
333
344
  let lintConfigs = 0;
334
345
 
335
346
  for (const owner of owners) {
336
- const directory = join(owner, '.configs');
337
- const names = existsSync(join(opts.root, directory))
338
- ? readdirSync(join(opts.root, directory)).filter(file =>
339
- DoctorConstants.LINT_CONFIG_FILE.test(file),
340
- )
341
- : [];
347
+ const configs = join(owner, '.configs');
348
+ const found = ['.', ...new Set(Object.values(DoctorConstants.LINT_CONFIG_FOLDERS))].flatMap(
349
+ folder => {
350
+ const directory = join(configs, folder);
351
+
352
+ return existsSync(join(opts.root, directory))
353
+ ? readdirSync(join(opts.root, directory))
354
+ .filter(file => DoctorConstants.LINT_CONFIG_FILE.test(file))
355
+ .map(file => ({ file: join(directory, file), name: file, legacy: folder === '.' }))
356
+ : [];
357
+ },
358
+ );
359
+ const names = found.map(item => item.file);
342
360
 
343
361
  lintConfigs += names.length;
344
362
 
@@ -356,8 +374,20 @@ export const checkStyle = (opts: ICheckContext): IViolation[] => {
356
374
  );
357
375
  }
358
376
 
359
- for (const name of names) {
360
- const file = join(directory, name);
377
+ for (const item of found) {
378
+ const { file } = item;
379
+
380
+ if (item.legacy) {
381
+ const tool = item.name.split('.')[0];
382
+
383
+ violations.push(
384
+ createViolation({
385
+ check: DoctorChecks.STYLE,
386
+ file,
387
+ message: `move it to .configs/${DoctorConstants.LINT_CONFIG_FOLDERS[tool]}/${item.name}`,
388
+ }),
389
+ );
390
+ }
361
391
 
362
392
  if (!readText({ file: join(opts.root, file) }).includes(ProjectLayout.STYLE_PACKAGE)) {
363
393
  violations.push(
@@ -445,6 +475,23 @@ export const checkApps = (opts: ICheckContext): IViolation[] => {
445
475
  const names = folders.map(([, folder]) => folder);
446
476
 
447
477
  for (const entry of resolvePackages({ config: opts.config }).filter(item => !item.retired)) {
478
+ if (entry.kind === 'lib') {
479
+ const parent = dirname(entry.path);
480
+
481
+ // A library lives where the project keeps libraries; it only has to be a workspace.
482
+ if (!coversFolder({ globs, folder: parent })) {
483
+ violations.push(
484
+ createViolation({
485
+ check: DoctorChecks.APPS,
486
+ file: opts.configFile,
487
+ message: `package ${entry.dir} lives at ${entry.path}, which no workspace glob covers - add '${parent}/*' to workspaces`,
488
+ }),
489
+ );
490
+ }
491
+
492
+ continue;
493
+ }
494
+
448
495
  if (!names.some(folder => entry.path.startsWith(`${folder}/`))) {
449
496
  violations.push(
450
497
  createViolation({
@@ -458,3 +505,127 @@ export const checkApps = (opts: ICheckContext): IViolation[] => {
458
505
 
459
506
  return violations;
460
507
  };
508
+
509
+ const readScriptNames = (opts: { file: string }): string[] | undefined => {
510
+ if (!existsSync(opts.file)) {
511
+ return undefined;
512
+ }
513
+
514
+ try {
515
+ const parsed: unknown = JSON.parse(readFileSync(opts.file, 'utf8'));
516
+ const scripts =
517
+ typeof parsed === 'object' && parsed !== null && 'scripts' in parsed ? parsed.scripts : {};
518
+
519
+ return typeof scripts === 'object' && scripts !== null ? Object.keys(scripts) : [];
520
+ } catch (error) {
521
+ console.error(
522
+ `[readScriptNames] ${opts.file} | ${error instanceof Error ? error.message : String(error)}`,
523
+ );
524
+
525
+ return undefined;
526
+ }
527
+ };
528
+
529
+ /**
530
+ * Info only, never a failure: an app that lacks a standard script or carries a legacy one gets one
531
+ * line naming them. Apps are the live packages inside the backend and frontend folders.
532
+ */
533
+ export const checkAppScripts = (opts: ICheckContext): IViolation[] => {
534
+ const layout = opts.config.layout;
535
+
536
+ if (layout === undefined) {
537
+ return [];
538
+ }
539
+
540
+ const appFolders = [layout.backend, layout.frontend].filter(
541
+ (folder): folder is string => folder !== undefined,
542
+ );
543
+ const notes: IViolation[] = [];
544
+
545
+ for (const entry of resolvePackages({ config: opts.config }).filter(item => !item.retired)) {
546
+ if (!appFolders.some(folder => entry.path.startsWith(`${folder}/`))) {
547
+ continue;
548
+ }
549
+
550
+ const file = `${entry.path}/package.json`;
551
+ const names = readScriptNames({ file: join(opts.root, file) });
552
+
553
+ if (names === undefined) {
554
+ continue;
555
+ }
556
+
557
+ const missing = AppScripts.STANDARD.filter(name => !names.includes(name));
558
+ const legacy = AppScripts.LEGACY.filter(name => names.includes(name));
559
+ const parts = [
560
+ ...(missing.length === 0 ? [] : [`missing ${missing.join(', ')}`]),
561
+ ...(legacy.length === 0 ? [] : [`legacy ${legacy.join(', ')} (use the standard names)`]),
562
+ ];
563
+
564
+ if (parts.length > 0) {
565
+ notes.push(
566
+ createViolation({
567
+ check: DoctorChecks.SCRIPTS,
568
+ file,
569
+ message: `app ${entry.dir}: ${parts.join('; ')}`,
570
+ }),
571
+ );
572
+ }
573
+ }
574
+
575
+ return notes;
576
+ };
577
+
578
+ /** The developer's stored agents must parse and name known agents; a broken file would otherwise hide as a default. */
579
+ export const checkAgents = (opts: ICheckContext): IViolation[] => {
580
+ const stored = readLocalChoice({ root: opts.root });
581
+
582
+ return stored.ok
583
+ ? []
584
+ : [
585
+ createViolation({
586
+ check: DoctorChecks.AGENTS,
587
+ file: '.agents/vulcan.local.json',
588
+ message: stored.error,
589
+ }),
590
+ ];
591
+ };
592
+
593
+ /** Info only: the Atlas block of AGENTS.md is missing or no longer matches the config. */
594
+ const DOCKERFILE = '.configs/builders/Dockerfile';
595
+
596
+ /** A Dockerfile is built from the project root: without a root `.dockerignore` the context carries node_modules, dist and .git. */
597
+ export const checkDockerignore = (opts: ICheckContext): IViolation[] => {
598
+ if (existsSync(join(opts.root, '.dockerignore'))) {
599
+ return [];
600
+ }
601
+
602
+ const apps = resolvePackages({ config: opts.config })
603
+ .filter(entry => !entry.retired && existsSync(join(opts.root, entry.path, DOCKERFILE)))
604
+ .map(entry => entry.dir);
605
+
606
+ if (apps.length === 0) {
607
+ return [];
608
+ }
609
+
610
+ return [
611
+ createViolation({
612
+ check: DoctorChecks.DOCKERIGNORE,
613
+ file: '.dockerignore',
614
+ message: `${apps.length === 1 ? `app ${apps[0]} has` : `apps ${apps.join(', ')} have`} a Dockerfile and the root has no .dockerignore: the build context would carry node_modules, dist and .git`,
615
+ }),
616
+ ];
617
+ };
618
+
619
+ export const checkAtlasBlock = (opts: ICheckContext): IViolation[] => {
620
+ const merged = mergedAtlasBlock({ root: opts.root, config: opts.config });
621
+
622
+ return merged === undefined || !merged.changed
623
+ ? []
624
+ : [
625
+ createViolation({
626
+ check: DoctorChecks.AGENTS,
627
+ file: 'AGENTS.md',
628
+ message: `the Atlas block is missing or out of date - run '${ProjectLayout.VULCAN_COMMAND} sync'`,
629
+ }),
630
+ ];
631
+ };
@@ -13,6 +13,9 @@ export class DoctorChecks {
13
13
  static readonly PRUNE = 'prune';
14
14
  static readonly SCAFFOLD = 'scaffold';
15
15
  static readonly APPS = 'apps';
16
+ static readonly SCRIPTS = 'scripts';
17
+ static readonly AGENTS = 'agents';
18
+ static readonly DOCKERIGNORE = 'dockerignore';
16
19
  static readonly SCHEME_SET = new Set<string>([
17
20
  this.CONFIG,
18
21
  this.LAYOUT,
@@ -28,15 +31,38 @@ export class DoctorChecks {
28
31
  this.PRUNE,
29
32
  this.SCAFFOLD,
30
33
  this.APPS,
34
+ this.SCRIPTS,
35
+ this.AGENTS,
36
+ this.DOCKERIGNORE,
31
37
  ]);
32
38
  static isValid(value: string): boolean {
33
39
  return this.SCHEME_SET.has(value);
34
40
  }
35
41
  }
36
42
 
43
+ /** The `package.json` scripts every app carries, and the names the standard retired. */
44
+ export class AppScripts {
45
+ static readonly STANDARD = [
46
+ 'server:dev',
47
+ 'compile',
48
+ 'typecheck',
49
+ 'lint',
50
+ 'lint:fix',
51
+ 'test',
52
+ 'clean',
53
+ ];
54
+ static readonly LEGACY = ['dev', 'start', 'build', 'rebuild', 'preview', 'server:prod'];
55
+ }
56
+
37
57
  export class DoctorConstants {
38
58
  static readonly MAKE_INCLUDE_PATTERN =
39
59
  /^-?include\s+\S*@venizia\/vulcan\/base\/make\/vulcan\.mk\s*$/m;
40
60
  static readonly SHIPPED_HOOKS_PATH = '@venizia/vulcan/base/hooks/';
41
61
  static readonly LINT_CONFIG_FILE = /^(oxlint|eslint|oxfmt)\.config\.(mts|ts|mjs|js|cjs)$/;
62
+ /** Where each tool's config lives under `.configs/`; a file left directly in `.configs/` is told where it belongs. */
63
+ static readonly LINT_CONFIG_FOLDERS: Record<string, string> = {
64
+ oxlint: 'lints',
65
+ eslint: 'lints',
66
+ oxfmt: 'formatters',
67
+ };
42
68
  }
@@ -2,6 +2,10 @@ import { relative } from 'node:path';
2
2
  import { loadConfig } from '../config/index.ts';
3
3
  import {
4
4
  checkAdapters,
5
+ checkAgents,
6
+ checkAppScripts,
7
+ checkAtlasBlock,
8
+ checkDockerignore,
5
9
  checkApps,
6
10
  checkManifest,
7
11
  checkPrune,
@@ -47,6 +51,7 @@ export const runDoctorChecks = async (opts: { root: string }): Promise<IViolatio
47
51
  ...checkMake(context),
48
52
  ...checkHooks(context),
49
53
  ...checkAdapters(context),
54
+ ...checkAgents(context),
50
55
  ...checkPrune(context),
51
56
  ...checkManifest(context),
52
57
  ...checkTags(context),
@@ -56,3 +61,20 @@ export const runDoctorChecks = async (opts: { root: string }): Promise<IViolatio
56
61
  ...checkApps(context),
57
62
  ];
58
63
  };
64
+
65
+ /** Notes that never fail the doctor: what a project could change, one line each. */
66
+ export const runDoctorNotes = async (opts: { root: string }): Promise<IViolation[]> => {
67
+ const loaded = await loadConfig({ root: opts.root });
68
+
69
+ if (!loaded.ok) {
70
+ return [];
71
+ }
72
+
73
+ const context = {
74
+ root: opts.root,
75
+ config: loaded.config,
76
+ configFile: relative(opts.root, loaded.file),
77
+ };
78
+
79
+ return [...checkAppScripts(context), ...checkAtlasBlock(context), ...checkDockerignore(context)];
80
+ };
@@ -0,0 +1,211 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, normalize, relative, sep } from 'node:path';
3
+ import { GuardDecisions, HookConstants } from './common/index.ts';
4
+ import type { IManifestHookInput } from './common/index.ts';
5
+
6
+ const MANIFEST_FILE = '.agents/vulcan.manifest.json';
7
+ const PACKAGE_FILE = 'package.json';
8
+ const NODE_MODULES = 'node_modules';
9
+ const ADD = 'bun x --no-install vulcan add';
10
+ const NO_HAND_WRITING = 'do not hand-write package.json, tsconfig or scripts';
11
+
12
+ export interface IPackageVerdict {
13
+ /** `deny` only when a real `vulcan add` command exists for the folder; otherwise `warn`. */
14
+ kind: 'deny' | 'warn';
15
+ message: string;
16
+ }
17
+
18
+ interface IRecordedPreset {
19
+ spec: string;
20
+ side: string;
21
+ lib: boolean;
22
+ }
23
+
24
+ interface IProjectView {
25
+ root: string;
26
+ layout: Record<string, string>;
27
+ presets: IRecordedPreset[];
28
+ }
29
+
30
+ const isRecord = (opts: { value: unknown }): opts is { value: Record<string, unknown> } =>
31
+ typeof opts.value === 'object' && opts.value !== null && !Array.isArray(opts.value);
32
+
33
+ const toFolder = (opts: { value: unknown }): string | undefined =>
34
+ typeof opts.value === 'string' && opts.value !== ''
35
+ ? normalize(opts.value).replace(/\/+$/, '')
36
+ : undefined;
37
+
38
+ /** The nearest project above `start`: the folder holding the generated manifest. */
39
+ const findRoot = (opts: { start: string }): string | undefined => {
40
+ let current = opts.start;
41
+
42
+ for (;;) {
43
+ if (existsSync(join(current, MANIFEST_FILE))) {
44
+ return current;
45
+ }
46
+
47
+ const parent = dirname(current);
48
+
49
+ if (parent === current) {
50
+ return undefined;
51
+ }
52
+
53
+ current = parent;
54
+ }
55
+ };
56
+
57
+ /** What the manifest says of layout and presets; `undefined` when it is missing or not readable. */
58
+ const readProject = (opts: { start: string }): IProjectView | undefined => {
59
+ const root = findRoot({ start: opts.start });
60
+
61
+ if (root === undefined) {
62
+ return undefined;
63
+ }
64
+
65
+ let manifest: unknown;
66
+
67
+ try {
68
+ manifest = JSON.parse(readFileSync(join(root, MANIFEST_FILE), 'utf8'));
69
+ } catch (error) {
70
+ console.error(
71
+ `[readProject] unreadable manifest - letting the call through | ${error instanceof Error ? error.message : String(error)}`,
72
+ );
73
+
74
+ return undefined;
75
+ }
76
+
77
+ const holder = { value: manifest };
78
+
79
+ if (!isRecord(holder)) {
80
+ return undefined;
81
+ }
82
+
83
+ const layoutHolder = { value: holder.value['layout'] };
84
+ const layout: Record<string, string> = {};
85
+
86
+ if (isRecord(layoutHolder)) {
87
+ for (const key of ['backend', 'frontend', 'shared']) {
88
+ const folder = toFolder({ value: layoutHolder.value[key] });
89
+
90
+ if (folder !== undefined) {
91
+ layout[key] = folder;
92
+ }
93
+ }
94
+ }
95
+
96
+ const recorded = Array.isArray(holder.value['presets']) ? holder.value['presets'] : [];
97
+ const presets = recorded.flatMap((item: unknown): IRecordedPreset[] => {
98
+ const entry = { value: item };
99
+
100
+ if (!isRecord(entry)) {
101
+ return [];
102
+ }
103
+
104
+ const { spec, side, lib } = entry.value;
105
+
106
+ return typeof spec === 'string' && typeof side === 'string'
107
+ ? [{ spec, side, lib: typeof lib === 'string' }]
108
+ : [];
109
+ });
110
+
111
+ return { root, layout, presets };
112
+ };
113
+
114
+ /** `services/api3` from `services/api3/package.json`, as the folder it sits in and its name. */
115
+ const newPackageOf = (opts: {
116
+ root: string;
117
+ path: string;
118
+ }): { folder: string; name: string } | undefined => {
119
+ const parts = normalize(relative(opts.root, opts.path)).split(sep);
120
+
121
+ if (parts.length < 3 || parts.includes('..') || parts.includes(NODE_MODULES)) {
122
+ return undefined;
123
+ }
124
+
125
+ const name = parts[parts.length - 2];
126
+ const folder = parts.slice(0, -2).join('/');
127
+
128
+ return { folder, name };
129
+ };
130
+
131
+ const appCommand = (opts: { preset: IRecordedPreset; name: string }): string =>
132
+ `${ADD} --preset ${opts.preset.spec} --app ${opts.name}${opts.preset.side === 'frontend' ? ' --api <backend app> | --no-api' : ''}`;
133
+
134
+ /**
135
+ * Whether this tool call creates the `package.json` of a new app or shared package in one of the
136
+ * project's layout folders. A real `vulcan add` command for that folder makes it a `deny`; with no
137
+ * preset behind the folder it is only a `warn`: the guard never blocks without a command to offer.
138
+ */
139
+ export const inspectPackageWrite = (opts: {
140
+ input: IManifestHookInput;
141
+ }): IPackageVerdict | undefined => {
142
+ const { tool, filePath, cwd } = opts.input;
143
+
144
+ if (tool !== 'Write' || filePath === undefined || basename(filePath) !== PACKAGE_FILE) {
145
+ return undefined;
146
+ }
147
+
148
+ const absolute = normalize(
149
+ isAbsolute(filePath) ? filePath : join(cwd ?? process.cwd(), filePath),
150
+ );
151
+
152
+ if (absolute.split(sep).includes(NODE_MODULES) || existsSync(absolute)) {
153
+ return undefined;
154
+ }
155
+
156
+ const project = readProject({ start: dirname(absolute) });
157
+ const created =
158
+ project === undefined ? undefined : newPackageOf({ root: project.root, path: absolute });
159
+
160
+ if (project === undefined || created === undefined) {
161
+ return undefined;
162
+ }
163
+
164
+ const entry = Object.entries(project.layout).find(([, folder]) => folder === created.folder);
165
+
166
+ if (entry === undefined) {
167
+ return undefined;
168
+ }
169
+
170
+ const [key] = entry;
171
+ const isLib = key === 'shared';
172
+ const what = isLib ? 'lib' : `${key} app`;
173
+ const commands = isLib
174
+ ? project.presets
175
+ .filter(preset => preset.lib)
176
+ .map(preset => `${ADD} --preset ${preset.spec} --lib ${created.name}`)
177
+ : project.presets
178
+ .filter(preset => preset.side === key)
179
+ .map(preset => appCommand({ preset, name: created.name }));
180
+
181
+ if (commands.length > 0) {
182
+ return {
183
+ kind: GuardDecisions.DENY,
184
+ message: `${created.folder}/${created.name} is a new ${what}: create it with a preset, not by hand - run ${commands.join(' or ')} (ask atlas \`presets\` for the choice); ${NO_HAND_WRITING}`,
185
+ };
186
+ }
187
+
188
+ return {
189
+ kind: 'warn',
190
+ message:
191
+ project.presets.length === 0
192
+ ? `${created.folder}/${created.name} looks like a new ${what} and this project recorded no preset: ask the user which preset to use (\`vulcan add --preset <name|file:path> --app <name>\`, --lib <name> for a shared package); ${NO_HAND_WRITING}`
193
+ : `${created.folder}/${created.name} looks like a new ${what} but no recorded preset makes a ${what}: ask the user how it should be made; ${NO_HAND_WRITING}`,
194
+ };
195
+ };
196
+
197
+ export const buildPackageDecision = (opts: { verdict: IPackageVerdict }) =>
198
+ opts.verdict.kind === GuardDecisions.DENY
199
+ ? {
200
+ hookSpecificOutput: {
201
+ hookEventName: HookConstants.PRE_TOOL_USE,
202
+ permissionDecision: GuardDecisions.DENY,
203
+ permissionDecisionReason: opts.verdict.message,
204
+ },
205
+ }
206
+ : {
207
+ hookSpecificOutput: {
208
+ hookEventName: HookConstants.PRE_TOOL_USE,
209
+ additionalContext: opts.verdict.message,
210
+ },
211
+ };
@@ -1,5 +1,6 @@
1
1
  export * from './common/index.ts';
2
2
  export * from './guard-manifest.ts';
3
+ export * from './guard-package.ts';
3
4
  export * from './guard-writes.ts';
4
5
  export * from './session-digest.ts';
5
6
  export * from './remote-hosts.ts';