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