@stagepass/cli 2.4.0 → 2.5.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.
@@ -4,18 +4,35 @@
4
4
  *
5
5
  * Writes only:
6
6
  * - stagepass.json `modules` (and `origin` when passed via --site)
7
- * - AGENTS.md managed block (created when missing)
8
- * - .cursor/rules/stagepass.mdc (created when missing, managed block refreshed)
9
- * - tsconfig.json / jsconfig.json `compilerOptions.types` (plain JSON only)
7
+ * - AGENTS.stagepass.md (CLI-owned guide; hand edits need --yes or a TTY)
8
+ * - AGENTS.md short pointer (created when missing)
9
+ * - .cursor/rules/stagepass.mdc only when .cursor/ or the file exists, or --cursor-rule
10
+ * - CLAUDE.md short pointer, only when that file already exists
11
+ * - tsconfig.json / jsconfig.json `compilerOptions.types` (plain JSON with a types array)
12
+ * - stagepass.d.ts triple-slash references when that array cannot be edited
10
13
  */
11
14
 
12
15
  import path from 'node:path';
13
16
  import fs from 'fs-extra';
14
17
  import {
15
18
  BLOCK_BEGIN,
19
+ BLOCK_END,
16
20
  CURSOR_RULE_PATH,
21
+ shouldWriteCursorRule,
22
+ LEGACY_AGENTS_NOTE,
23
+ PHP_LIB_MISSING_NOTE,
24
+ STAGEPASS_AGENTS_CONFIRM,
25
+ STAGEPASS_AGENTS_DECLINED,
26
+ STAGEPASS_AGENTS_HINT,
27
+ STAGEPASS_AGENTS_REL,
28
+ buildAgentsPointerBlock,
29
+ buildCursorPointerBlock,
17
30
  buildCursorRule,
18
- buildManagedBlock,
31
+ buildStagepassGuide,
32
+ decideStagepassAgentsUpdate,
33
+ hasLegacyAgentsProse,
34
+ migrateCursorRuleContent,
35
+ renderStagepassAgentsFile,
19
36
  upsertManagedBlock,
20
37
  } from './ai-guide.js';
21
38
  import {
@@ -321,6 +338,380 @@ export function updateConfigTypes(raw, modules, opts) {
321
338
  return { status: 'updated', content: `${JSON.stringify(json, null, 2)}${trailing}`, types: nextTypes };
322
339
  }
323
340
 
341
+ /** First-line marker. Upgrade rewrites the file only when this is present. */
342
+ export const STAGEPASS_TYPES_MARKER = '@stagepass-types';
343
+
344
+ export function renderStagepassTypesFile(types) {
345
+ const refs = types.map((entry) => `/// <reference types="${entry}" />`);
346
+ return `// ${STAGEPASS_TYPES_MARKER}\n${refs.join('\n')}\n`;
347
+ }
348
+
349
+ /** True when `dtsRel` is a root file. A directory include (`src`) expands to everything under it. */
350
+ export function configCoversTypesFile(json, dtsRel) {
351
+ const rel = normalizeConfigRel(dtsRel);
352
+ if (!rel || !json || typeof json !== 'object') return false;
353
+ const files = Array.isArray(json.files) ? json.files : [];
354
+ for (const entry of files) {
355
+ if (normalizeConfigRel(entry) === rel) return true;
356
+ }
357
+ const include = Array.isArray(json.include) ? json.include : [];
358
+ if (files.length === 0 && include.length === 0) return !isConfigExcluded(rel, json);
359
+ if (include.some((pattern) => includePatternMatches(rel, pattern)) && !isConfigExcluded(rel, json)) {
360
+ return true;
361
+ }
362
+ return false;
363
+ }
364
+
365
+ function normalizeConfigRel(value) {
366
+ let rel = String(value ?? '').trim().replace(/\\/g, '/');
367
+ if (rel.startsWith('./')) rel = rel.slice(2);
368
+ if (!rel || rel.startsWith('/') || rel.split('/').includes('..')) return '';
369
+ return rel.replace(/\/+/g, '/');
370
+ }
371
+
372
+ function expandIncludePattern(pattern) {
373
+ const rel = normalizeConfigRel(pattern);
374
+ if (!rel) return '';
375
+ const last = rel.split('/').pop() || '';
376
+ if (!/[?*]/.test(last) && !last.includes('.')) return `${rel}/**/*`;
377
+ return rel;
378
+ }
379
+
380
+ function includePatternMatches(rel, pattern) {
381
+ const expanded = expandIncludePattern(pattern);
382
+ if (!expanded) return false;
383
+ return globToRegExp(expanded).test(rel);
384
+ }
385
+
386
+ function includeDirPrefix(pattern) {
387
+ const expanded = expandIncludePattern(pattern);
388
+ if (!expanded) return null;
389
+ const idx = expanded.search(/[*?]/);
390
+ if (idx === -1) return null;
391
+ const head = expanded.slice(0, idx).replace(/\/$/, '');
392
+ if (/[*?]/.test(head)) return null;
393
+ return head;
394
+ }
395
+
396
+ function globToRegExp(pattern) {
397
+ let re = '';
398
+ let i = 0;
399
+ while (i < pattern.length) {
400
+ if (pattern.startsWith('**/', i)) {
401
+ re += '(?:.*/)?';
402
+ i += 3;
403
+ continue;
404
+ }
405
+ if (pattern.startsWith('**', i)) {
406
+ re += '.*';
407
+ i += 2;
408
+ continue;
409
+ }
410
+ const ch = pattern[i];
411
+ if (ch === '*') {
412
+ re += '[^/]*';
413
+ i += 1;
414
+ continue;
415
+ }
416
+ if (ch === '?') {
417
+ re += '[^/]';
418
+ i += 1;
419
+ continue;
420
+ }
421
+ re += /[\\^$+()|[\]{}.]/.test(ch) ? `\\${ch}` : ch;
422
+ i += 1;
423
+ }
424
+ return new RegExp(`^${re}$`);
425
+ }
426
+
427
+ function isConfigExcluded(rel, json) {
428
+ /** @type {unknown[]} */
429
+ const patterns = ['node_modules', 'bower_components', 'jspm_packages'];
430
+ const outDir = /** @type {{ outDir?: unknown }} */ (json.compilerOptions || {}).outDir;
431
+ if (typeof outDir === 'string' && normalizeConfigRel(outDir)) patterns.push(normalizeConfigRel(outDir));
432
+ if (Array.isArray(json.exclude)) patterns.push(...json.exclude);
433
+ for (const pattern of patterns) {
434
+ const normalized = normalizeConfigRel(pattern);
435
+ if (!normalized) continue;
436
+ if (rel === normalized || rel.startsWith(`${normalized}/`)) return true;
437
+ if (/[*?]/.test(normalized) && globToRegExp(normalized).test(rel)) return true;
438
+ }
439
+ return false;
440
+ }
441
+
442
+ function parseConfigSource(raw) {
443
+ const asObject = (/** @type {unknown} */ value, kind) => {
444
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { kind: 'invalid', json: null };
445
+ return { kind, json: /** @type {Record<string, unknown>} */ (value) };
446
+ };
447
+ try {
448
+ return asObject(JSON.parse(raw), 'json');
449
+ } catch {
450
+ try {
451
+ return asObject(JSON.parse(stripJsonComments(raw)), 'jsonc');
452
+ } catch {
453
+ return { kind: 'invalid', json: null };
454
+ }
455
+ }
456
+ }
457
+
458
+ function stripJsonComments(raw) {
459
+ let out = '';
460
+ let i = 0;
461
+ let inString = false;
462
+ while (i < raw.length) {
463
+ const ch = raw[i];
464
+ const next = raw[i + 1];
465
+ if (inString) {
466
+ out += ch;
467
+ if (ch === '\\') {
468
+ out += next || '';
469
+ i += 2;
470
+ continue;
471
+ }
472
+ if (ch === '"') inString = false;
473
+ i += 1;
474
+ continue;
475
+ }
476
+ if (ch === '"') {
477
+ inString = true;
478
+ out += ch;
479
+ i += 1;
480
+ continue;
481
+ }
482
+ if (ch === '/' && next === '/') {
483
+ i += 2;
484
+ while (i < raw.length && raw[i] !== '\n') i += 1;
485
+ continue;
486
+ }
487
+ if (ch === '/' && next === '*') {
488
+ i += 2;
489
+ while (i < raw.length && !(raw[i] === '*' && raw[i + 1] === '/')) i += 1;
490
+ i += 2;
491
+ continue;
492
+ }
493
+ out += ch;
494
+ i += 1;
495
+ }
496
+ return out.replace(/,\s*([}\]])/g, '$1');
497
+ }
498
+
499
+ function hasTypesArray(json) {
500
+ const co = json && /** @type {{ types?: unknown }} */ (json.compilerOptions);
501
+ return !!(co && typeof co === 'object' && Array.isArray(co.types));
502
+ }
503
+
504
+ function hasTypesMarker(raw) {
505
+ return String(raw)
506
+ .split(/\r?\n/)
507
+ .slice(0, 8)
508
+ .some((line) => line.includes(STAGEPASS_TYPES_MARKER));
509
+ }
510
+
511
+ /** Printed when neither tsconfig.json nor jsconfig.json exists. The root file stays. */
512
+ const NO_CONFIG_TYPES_NOTE =
513
+ 'No tsconfig.json or jsconfig.json: editors only load stagepass.d.ts as part of a project. Add a jsconfig.json (or tsconfig.json) that includes your sources, for example {"include": ["src", "stagepass.d.ts"]}, then run stagepass upgrade again.';
514
+
515
+ async function planEditorTypes(input) {
516
+ const { cwd, modules, modulesDependency, perModuleTypes, skipSymlink, fse } = input;
517
+ /** @type {{ file: string, content: string, action: string }[]} */
518
+ const writes = [];
519
+ /** @type {string[]} */
520
+ const notes = [];
521
+ const wanted = typesForModules(modules, { modulesDependency, perModuleTypes });
522
+ const content = renderStagepassTypesFile(wanted);
523
+
524
+ /** @type {{ name: string, symlink?: boolean, needsDts?: boolean, kind?: string, json?: Record<string, unknown> | null }[]} */
525
+ const configs = [];
526
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
527
+ const file = path.join(cwd, name);
528
+ if (!(await fse.pathExists(file))) continue;
529
+ if (await skipSymlink(name)) {
530
+ configs.push({ name, symlink: true });
531
+ continue;
532
+ }
533
+ const raw = await fse.readFile(file, 'utf8');
534
+ const parsed = parseConfigSource(raw);
535
+ if (parsed.kind === 'json' && hasTypesArray(parsed.json)) {
536
+ const result = updateConfigTypes(raw, modules, { modulesDependency, perModuleTypes });
537
+ if (result.status === 'updated' && result.content) {
538
+ writes.push({ file: name, content: result.content, action: `types: ${(result.types || []).join(', ')}` });
539
+ }
540
+ configs.push({ name, needsDts: false, json: parsed.json });
541
+ continue;
542
+ }
543
+ configs.push({ name, needsDts: true, kind: parsed.kind, json: parsed.json });
544
+ }
545
+
546
+ /**
547
+ * @param {string} rel
548
+ * @returns {Promise<'placed' | 'current' | 'blocked'>}
549
+ */
550
+ const writeTypesFile = async (rel) => {
551
+ if (writes.some((item) => item.file === rel)) return 'placed';
552
+ if (await skipSymlink(rel)) return 'blocked';
553
+ const abs = path.join(cwd, rel);
554
+ if (await fse.pathExists(abs)) {
555
+ const previous = await fse.readFile(abs, 'utf8');
556
+ if (!hasTypesMarker(previous)) {
557
+ notes.push(`${rel} has no ${STAGEPASS_TYPES_MARKER} marker; left unchanged.`);
558
+ return 'blocked';
559
+ }
560
+ if (previous === content) return 'current';
561
+ }
562
+ writes.push({ file: rel, content, action: `references ${wanted.join(', ')}` });
563
+ return 'placed';
564
+ };
565
+
566
+ if (configs.length === 0) {
567
+ await writeTypesFile('stagepass.d.ts');
568
+ notes.push(NO_CONFIG_TYPES_NOTE);
569
+ return { writes, notes };
570
+ }
571
+
572
+ const needing = configs.filter((config) => config.needsDts);
573
+ if (needing.length === 0) {
574
+ const rels = new Set(['stagepass.d.ts']);
575
+ for (const config of configs) {
576
+ const include = config.json && Array.isArray(config.json.include) ? config.json.include : [];
577
+ for (const pattern of include) {
578
+ const dir = includeDirPrefix(pattern);
579
+ if (dir == null) continue;
580
+ rels.add(dir === '' ? 'stagepass.d.ts' : `${dir}/stagepass.d.ts`);
581
+ }
582
+ }
583
+ for (const rel of rels) {
584
+ const abs = path.join(cwd, rel);
585
+ let previous = '';
586
+ try {
587
+ const st = await fse.lstat(abs);
588
+ if (!st.isFile()) continue;
589
+ previous = await fse.readFile(abs, 'utf8');
590
+ } catch {
591
+ continue;
592
+ }
593
+ if (hasTypesMarker(previous)) await writeTypesFile(rel);
594
+ }
595
+ return { writes, notes };
596
+ }
597
+
598
+ /** @type {{ rel: string, score: number }[]} */
599
+ const ranked = [];
600
+ /** @type {string[]} */
601
+ const candidates = ['stagepass.d.ts'];
602
+ for (const config of needing) {
603
+ const include = config.json && Array.isArray(config.json.include) ? config.json.include : [];
604
+ for (const pattern of include) {
605
+ const dir = includeDirPrefix(pattern);
606
+ if (dir == null) continue;
607
+ const rel = dir === '' ? 'stagepass.d.ts' : `${dir}/stagepass.d.ts`;
608
+ if (!candidates.includes(rel)) candidates.push(rel);
609
+ }
610
+ }
611
+ for (const rel of candidates) {
612
+ const score = needing.filter((config) => coversTypesPath(config, rel)).length;
613
+ if (score > 0) ranked.push({ rel, score });
614
+ }
615
+ ranked.sort((a, b) => b.score - a.score || candidates.indexOf(a.rel) - candidates.indexOf(b.rel));
616
+
617
+ /** @type {string | null} */
618
+ let placedRel = null;
619
+ for (const item of ranked) {
620
+ const status = await writeTypesFile(item.rel);
621
+ if (status === 'placed' || status === 'current') {
622
+ placedRel = item.rel;
623
+ break;
624
+ }
625
+ }
626
+
627
+ for (const config of needing) {
628
+ notes.push(typesConfigNote(config, placedRel));
629
+ const ownInclude = Array.isArray(config.json?.include) && config.json.include.length > 0;
630
+ const ownFiles = Array.isArray(config.json?.files) && config.json.files.length > 0;
631
+ if (placedRel && config.json && config.json.extends && !ownInclude && !ownFiles) {
632
+ notes.push(
633
+ `${config.name} extends another config and does not set include or files. Confirm ${placedRel} is part of that project.`
634
+ );
635
+ }
636
+ }
637
+ return { writes, notes };
638
+ }
639
+
640
+ function coversTypesPath(config, rel) {
641
+ if (config.kind === 'invalid') return rel === 'stagepass.d.ts';
642
+ if (!config.json) return false;
643
+ return configCoversTypesFile(config.json, rel);
644
+ }
645
+
646
+ function typesConfigNote(config, placedRel) {
647
+ if (config.kind === 'jsonc') {
648
+ const base = `${config.name} contains comments and was left unchanged.`;
649
+ if (placedRel && coversTypesPath(config, placedRel)) return `${base} Types: ${placedRel}.`;
650
+ return `${base} Its include/files does not cover stagepass.d.ts.`;
651
+ }
652
+ if (config.kind === 'invalid') {
653
+ const base = `${config.name} is not valid JSON and was left unchanged.`;
654
+ return placedRel
655
+ ? `${base} Types: ${placedRel} (include coverage was not checked).`
656
+ : base;
657
+ }
658
+ const base = `${config.name} has no compilerOptions.types array and was left unchanged.`;
659
+ if (placedRel && coversTypesPath(config, placedRel)) return `${base} Types: ${placedRel}.`;
660
+ return `${config.name} include/files does not cover stagepass.d.ts. The config was left unchanged.`;
661
+ }
662
+
663
+ /**
664
+ * @param {Record<string, unknown> | null | undefined} data
665
+ * @param {string} key
666
+ * @returns {string | null}
667
+ */
668
+ function stringField(data, key) {
669
+ if (!data || typeof data[key] !== 'string') return null;
670
+ const value = data[key].trim();
671
+ return value === '' ? null : value;
672
+ }
673
+
674
+ /**
675
+ * @param {string} cwd
676
+ * @param {Record<string, unknown> | null} data
677
+ * @param {typeof fs} fse
678
+ * @returns {Promise<'ts' | 'js' | null>}
679
+ */
680
+ async function detectProjectLang(cwd, data, fse) {
681
+ const lang = stringField(data, 'lang');
682
+ if (lang === 'ts' || lang === 'js') return lang;
683
+ if (await fse.pathExists(path.join(cwd, 'tsconfig.json'))) return 'ts';
684
+ if (await fse.pathExists(path.join(cwd, 'jsconfig.json'))) return 'js';
685
+ return null;
686
+ }
687
+
688
+ /**
689
+ * @param {string} cwd
690
+ * @param {typeof fs} fse
691
+ */
692
+ async function phpLibPresent(cwd, fse) {
693
+ try {
694
+ const st = await fse.stat(path.join(cwd, 'api', 'lib'));
695
+ return st.isDirectory();
696
+ } catch {
697
+ return false;
698
+ }
699
+ }
700
+
701
+ /**
702
+ * True when the project already has a `.cursor` directory or symlink.
703
+ * @param {string} cwd
704
+ * @param {typeof fs} [fse]
705
+ */
706
+ export async function cursorDirPresent(cwd, fse = fs) {
707
+ try {
708
+ const st = await fse.lstat(path.join(cwd, '.cursor'));
709
+ return st.isDirectory() || st.isSymbolicLink();
710
+ } catch {
711
+ return false;
712
+ }
713
+ }
714
+
324
715
  /** @param {string} abs @param {typeof fs} fse */
325
716
  async function isSymlink(abs, fse) {
326
717
  try {
@@ -339,6 +730,10 @@ async function isSymlink(abs, fse) {
339
730
  * @param {string | null} [input.origin] stored in stagepass.json when set
340
731
  * @param {object} input.pkg package.json
341
732
  * @param {boolean} [input.perModuleTypes] false when @stagepass/modules has no per-module types (umbrella entry)
733
+ * @param {boolean} [input.interactive] TTY: ask before replacing a hand-edited AGENTS.stagepass.md
734
+ * @param {boolean} [input.assumeYes] `--yes`: replace that file without asking
735
+ * @param {(question: string, defYes: boolean) => Promise<boolean>} [input.confirm]
736
+ * @param {boolean} [input.cursorRule] `--cursor-rule`: write the Cursor rule even without `.cursor/`
342
737
  * @param {typeof fs} [fse]
343
738
  * @returns {Promise<{ writes: { file: string, content: string, action: string }[], notes: string[] }>}
344
739
  */
@@ -395,13 +790,88 @@ export async function planProjectSync(input, fse = fs) {
395
790
  }
396
791
  }
397
792
 
398
- // AGENTS.md
399
- const block = buildManagedBlock(modules);
793
+ const title = typeof pkg?.name === 'string' && pkg.name ? pkg.name : path.basename(cwd);
794
+ const projectName = stringField(sp.data, 'name') || title;
795
+ const lang = await detectProjectLang(cwd, sp.data, fse);
796
+ const php = phpFromStagepassConfig(sp.data) === true;
797
+ const phpBoilerplate = php ? await phpLibPresent(cwd, fse) : false;
798
+ const guide = renderStagepassAgentsFile(
799
+ buildStagepassGuide({
800
+ name: projectName,
801
+ domain: stringField(sp.data, 'domain'),
802
+ modules,
803
+ php,
804
+ phpBoilerplate,
805
+ lang,
806
+ origin: input.origin || stringField(sp.data, 'origin'),
807
+ production: stringField(sp.data, 'production'),
808
+ configFile: lang === 'ts' ? 'tsconfig.json' : lang === 'js' ? 'jsconfig.json' : null,
809
+ types: typesForModules(modules, {
810
+ modulesDependency,
811
+ perModuleTypes,
812
+ }),
813
+ modulesDependency,
814
+ })
815
+ );
816
+ if (php && !phpBoilerplate) notes.push(PHP_LIB_MISSING_NOTE);
817
+
818
+ // AGENTS.stagepass.md (CLI-owned). Hand edits need --yes or a TTY.
819
+ if (await skipSymlink(STAGEPASS_AGENTS_REL)) {
820
+ // note already added
821
+ } else {
822
+ const agentsGuidePath = path.join(cwd, STAGEPASS_AGENTS_REL);
823
+ /** @type {string | null} */
824
+ let existingGuide = null;
825
+ let guideReadable = true;
826
+ if (await fse.pathExists(agentsGuidePath)) {
827
+ try {
828
+ existingGuide = await fse.readFile(agentsGuidePath, 'utf8');
829
+ } catch (err) {
830
+ guideReadable = false;
831
+ notes.push(
832
+ `AGENTS.stagepass.md could not be read; left unchanged. ${err instanceof Error ? err.message : String(err)}`
833
+ );
834
+ }
835
+ }
836
+ if (guideReadable) {
837
+ const decision = decideStagepassAgentsUpdate({
838
+ existing: existingGuide,
839
+ desired: guide,
840
+ assumeYes: input.assumeYes === true,
841
+ interactive: input.interactive === true,
842
+ });
843
+ if (decision.action === 'create') {
844
+ writes.push({ file: STAGEPASS_AGENTS_REL, content: guide, action: 'created' });
845
+ } else if (decision.action === 'update') {
846
+ writes.push({
847
+ file: STAGEPASS_AGENTS_REL,
848
+ content: guide,
849
+ action: decision.reason ? 'replaced hand-edited file' : 'refreshed',
850
+ });
851
+ } else if (decision.action === 'ask') {
852
+ if (typeof input.confirm !== 'function') {
853
+ throw new Error('confirm is required when upgrade asks about AGENTS.stagepass.md');
854
+ }
855
+ const yes = await input.confirm(STAGEPASS_AGENTS_CONFIRM, true);
856
+ if (yes) {
857
+ writes.push({ file: STAGEPASS_AGENTS_REL, content: guide, action: 'replaced hand-edited file' });
858
+ } else {
859
+ notes.push(STAGEPASS_AGENTS_DECLINED);
860
+ }
861
+ } else if (decision.action === 'hint') {
862
+ notes.push(STAGEPASS_AGENTS_HINT);
863
+ }
864
+ }
865
+ }
866
+
867
+ // AGENTS.md (user-owned). Only the short pointer between the markers.
868
+ const block = buildAgentsPointerBlock();
400
869
  const agentsPath = path.join(cwd, 'AGENTS.md');
401
870
  if (await skipSymlink('AGENTS.md')) {
402
871
  // note already added
403
872
  } else if (await fse.pathExists(agentsPath)) {
404
873
  const raw = await fse.readFile(agentsPath, 'utf8');
874
+ if (hasLegacyAgentsProse(raw)) notes.push(LEGACY_AGENTS_NOTE);
405
875
  const result = upsertManagedBlock(raw, block);
406
876
  if (result.action === 'invalid') {
407
877
  notes.push('AGENTS.md skipped: stagepass markers are incomplete; fix or remove them and rerun.');
@@ -413,7 +883,6 @@ export async function planProjectSync(input, fse = fs) {
413
883
  });
414
884
  }
415
885
  } else {
416
- const title = typeof pkg?.name === 'string' ? pkg.name : path.basename(cwd);
417
886
  writes.push({
418
887
  file: 'AGENTS.md',
419
888
  content: `# ${title} (Stagepass project)\n\n${block}\n`,
@@ -421,45 +890,71 @@ export async function planProjectSync(input, fse = fs) {
421
890
  });
422
891
  }
423
892
 
424
- // Cursor rule
893
+ // Cursor rule: only when .cursor/ exists, the file exists, or --cursor-rule.
894
+ const cursorBlock = buildCursorPointerBlock();
425
895
  const rulePath = path.join(cwd, CURSOR_RULE_PATH);
426
- if (await skipSymlink(CURSOR_RULE_PATH)) {
896
+ const cursorDirExists = await cursorDirPresent(cwd, fse);
897
+ const ruleExists = await fse.pathExists(rulePath);
898
+ if (
899
+ !shouldWriteCursorRule({
900
+ cursorDirExists,
901
+ cursorRule: input.cursorRule === true,
902
+ ruleExists,
903
+ })
904
+ ) {
905
+ // AGENTS.md is the tool-neutral guide. Do not create .cursor/ unasked.
906
+ } else if (await skipSymlink(CURSOR_RULE_PATH)) {
427
907
  // note already added
428
- } else if (await fse.pathExists(rulePath)) {
908
+ } else if (ruleExists) {
429
909
  const raw = await fse.readFile(rulePath, 'utf8');
430
- if (raw.includes(BLOCK_BEGIN)) {
431
- const result = upsertManagedBlock(raw, block);
910
+ if (raw.includes(BLOCK_BEGIN) || raw.includes(BLOCK_END)) {
911
+ const result = upsertManagedBlock(raw, cursorBlock);
432
912
  if (result.action === 'invalid') {
433
913
  notes.push(`${CURSOR_RULE_PATH} skipped: stagepass markers are incomplete.`);
434
- } else if (result.action !== 'unchanged') {
435
- writes.push({ file: CURSOR_RULE_PATH, content: result.content, action: 'managed block refreshed' });
914
+ } else {
915
+ const migrated = migrateCursorRuleContent(result.content);
916
+ if (migrated !== raw) {
917
+ writes.push({ file: CURSOR_RULE_PATH, content: migrated, action: 'managed block refreshed' });
918
+ }
436
919
  }
437
920
  } else {
438
921
  notes.push(`${CURSOR_RULE_PATH} exists without stagepass markers; left unchanged.`);
439
922
  }
440
923
  } else {
441
- writes.push({ file: CURSOR_RULE_PATH, content: buildCursorRule(modules), action: 'created' });
924
+ writes.push({ file: CURSOR_RULE_PATH, content: buildCursorRule(), action: 'created' });
442
925
  }
443
926
 
444
- // tsconfig / jsconfig
445
- let sawConfig = false;
446
- for (const name of ['tsconfig.json', 'jsconfig.json']) {
447
- const file = path.join(cwd, name);
448
- if (!(await fse.pathExists(file))) continue;
449
- sawConfig = true;
450
- if (await skipSymlink(name)) continue;
451
- const raw = await fse.readFile(file, 'utf8');
452
- const result = updateConfigTypes(raw, modules, { modulesDependency, perModuleTypes });
453
- if (result.status === 'skipped') {
454
- const wanted = JSON.stringify(typesForModules(modules, { modulesDependency, perModuleTypes }));
455
- notes.push(`${name} ${result.reason}: "types": ${wanted}`);
456
- } else if (result.status === 'updated') {
457
- writes.push({ file: name, content: result.content, action: `types: ${result.types.join(', ')}` });
927
+ // CLAUDE.md: pointer only when the file already exists. Never create it.
928
+ const claudeRel = 'CLAUDE.md';
929
+ const claudePath = path.join(cwd, claudeRel);
930
+ if (await fse.pathExists(claudePath)) {
931
+ if (await skipSymlink(claudeRel)) {
932
+ // note already added
933
+ } else {
934
+ const raw = await fse.readFile(claudePath, 'utf8');
935
+ const result = upsertManagedBlock(raw, block);
936
+ if (result.action === 'invalid') {
937
+ notes.push('CLAUDE.md skipped: stagepass markers are incomplete; fix or remove them and rerun.');
938
+ } else if (result.action !== 'unchanged') {
939
+ writes.push({
940
+ file: claudeRel,
941
+ content: result.content,
942
+ action: result.action === 'inserted' ? 'managed block added' : 'managed block refreshed',
943
+ });
944
+ }
458
945
  }
459
946
  }
460
- if (!sawConfig) {
461
- notes.push('No tsconfig.json or jsconfig.json found; types not configured.');
462
- }
947
+
948
+ const typesPlan = await planEditorTypes({
949
+ cwd,
950
+ modules,
951
+ modulesDependency,
952
+ perModuleTypes,
953
+ skipSymlink,
954
+ fse,
955
+ });
956
+ writes.push(...typesPlan.writes);
957
+ notes.push(...typesPlan.notes);
463
958
  if (!modulesDependency && modules.length > 0) {
464
959
  notes.push('Module types need @stagepass/modules in devDependencies (npm install -D @stagepass/modules).');
465
960
  }
@@ -11,7 +11,7 @@ import fs from 'fs-extra';
11
11
  import path from 'node:path';
12
12
  import { defaultExec } from './exec.js';
13
13
  import { MODULE_IDS } from './project-modules.js';
14
- import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
14
+ import { SNIPPET_LOADER_VERSION } from './cdn-base.js';
15
15
 
16
16
  /** Major range used for new projects (matches the `@2` CDN embed policy). */
17
17
  export const PACKAGES_MAJOR_RANGE = '^2';
@@ -190,16 +190,18 @@ export async function installedLoaderVersion(cwd, fse = fs) {
190
190
 
191
191
  /**
192
192
  * Loader version for Webflow snippets; never the CLI version.
193
- * Prefers the newest published stable 2.x, then installed, then bundled.
193
+ * Prefers the newest published stable 2.x from the registry, otherwise
194
+ * the explicit bundled fallback or SNIPPET_LOADER_VERSION. Does not use a
195
+ * locally installed loader (it may be unpublished).
194
196
  * @param {object} options
195
197
  * @param {{ distTags: Record<string, string>, versions: string[] } | null} options.published
196
- * @param {string} options.cwd
198
+ * @param {string} [options.cwd] Unused; kept so existing callers stay valid.
197
199
  * @param {string} [options.bundled]
198
- * @param {typeof fs} [options.fse]
200
+ * @param {typeof fs} [options.fse] Unused; kept so existing callers stay valid.
199
201
  * @returns {Promise<string>}
200
202
  */
201
- export async function resolveSnippetLoaderVersion({ published, cwd, bundled, fse = fs }) {
203
+ export async function resolveSnippetLoaderVersion({ published, bundled }) {
202
204
  const best = published ? maxSatisfying(published.versions, PACKAGES_MAJOR_RANGE) : null;
203
205
  if (best) return best;
204
- return (await installedLoaderVersion(cwd, fse)) || bundled || STAGEPASS_PACKAGES_VERSION;
206
+ return bundled || SNIPPET_LOADER_VERSION;
205
207
  }