@mgamadeus/ddd-web 0.16.1 → 0.17.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.
@@ -292,8 +292,8 @@ function entityInvalidation(endpoint, info, tag) {
292
292
  if (action === "upsert" || action === "delete") {
293
293
  if (identity.startsWith("path:")) {
294
294
  const accessor = endpoint.pathArgs[identity.slice("path:".length)];
295
- const relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
296
- if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
295
+ const relative5 = accessor !== void 0 ? relativeAccessor(accessor) : null;
296
+ if (relative5 !== null) return [argTag(tag, relative5), listTag(tag)];
297
297
  }
298
298
  if (identity.startsWith("body:") && endpoint.bodyArg !== void 0) {
299
299
  const body = relativeAccessor(endpoint.bodyArg);
@@ -306,8 +306,8 @@ function entityInvalidation(endpoint, info, tag) {
306
306
  function heuristicInvalidation(endpoint, info, tag, doc, lookup) {
307
307
  const parameter = identityPathParameter(endpoint.path, tag);
308
308
  const accessor = parameter ? endpoint.pathArgs[parameter] : void 0;
309
- const relative6 = accessor !== void 0 ? relativeAccessor(accessor) : null;
310
- if (relative6 !== null) return [argTag(tag, relative6), listTag(tag)];
309
+ const relative5 = accessor !== void 0 ? relativeAccessor(accessor) : null;
310
+ if (relative5 !== null) return [argTag(tag, relative5), listTag(tag)];
311
311
  if (info && endpoint.bodyArg !== void 0) {
312
312
  const body = relativeAccessor(endpoint.bodyArg);
313
313
  const inner = identityBodyPath(doc, info.operation, tag, lookup);
@@ -418,8 +418,8 @@ function buildEnhancedEndpoints(input) {
418
418
  sideEffects: info?.sideEffects ?? true,
419
419
  pathArgs: Object.fromEntries(
420
420
  Object.entries(endpoint.pathArgs).flatMap(([name, accessor]) => {
421
- const relative6 = relativeAccessor(accessor);
422
- return relative6 === null ? [] : [[name, relative6]];
421
+ const relative5 = relativeAccessor(accessor);
422
+ return relative5 === null ? [] : [[name, relative5]];
423
423
  })
424
424
  ),
425
425
  ...endpoint.bodyArg !== void 0 && relativeAccessor(endpoint.bodyArg) !== null ? { bodyArg: relativeAccessor(endpoint.bodyArg) } : {},
@@ -1425,9 +1425,9 @@ function registryMatch(name, registry) {
1425
1425
  return null;
1426
1426
  }
1427
1427
  function importSpecifier(fromFile, toFile, esm) {
1428
- let relative6 = path4.relative(path4.dirname(fromFile), toFile.replace(/\.ts$/, "")).replace(/\\/g, "/");
1429
- if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
1430
- return esm ? `${relative6}.js` : relative6;
1428
+ let relative5 = path4.relative(path4.dirname(fromFile), toFile.replace(/\.ts$/, "")).replace(/\\/g, "/");
1429
+ if (!relative5.startsWith(".")) relative5 = `./${relative5}`;
1430
+ return esm ? `${relative5}.js` : relative5;
1431
1431
  }
1432
1432
  var EXPORTED_NAME = /^export (?:type|interface) (\w+)/m;
1433
1433
  function extractModels(input) {
@@ -1437,8 +1437,8 @@ function extractModels(input) {
1437
1437
  const indexPath = path4.join(modelsDir, "index.ts");
1438
1438
  const nameOwners = /* @__PURE__ */ new Map();
1439
1439
  for (const filePath of files.paths()) {
1440
- const relative6 = path4.relative(modelsDir, filePath);
1441
- if (relative6.startsWith("..") || path4.isAbsolute(relative6) || path4.resolve(filePath) === path4.resolve(indexPath)) continue;
1440
+ const relative5 = path4.relative(modelsDir, filePath);
1441
+ if (relative5.startsWith("..") || path4.isAbsolute(relative5) || path4.resolve(filePath) === path4.resolve(indexPath)) continue;
1442
1442
  const name = files.get(filePath)?.match(EXPORTED_NAME)?.[1];
1443
1443
  if (name && !nameOwners.has(name)) nameOwners.set(name, path4.resolve(filePath).toLowerCase());
1444
1444
  }
@@ -1771,9 +1771,9 @@ function commitOutput(files, modelsDir, stagingParent, options = {}) {
1771
1771
  fs5.mkdirSync(stagedModels, { recursive: true });
1772
1772
  for (const filePath of files.paths()) {
1773
1773
  const content = files.get(filePath);
1774
- const relative6 = path5.relative(modelsDir, filePath);
1775
- if (!relative6.startsWith("..") && !path5.isAbsolute(relative6)) {
1776
- const staged = path5.join(stagedModels, relative6);
1774
+ const relative5 = path5.relative(modelsDir, filePath);
1775
+ if (!relative5.startsWith("..") && !path5.isAbsolute(relative5)) {
1776
+ const staged = path5.join(stagedModels, relative5);
1777
1777
  fs5.mkdirSync(path5.dirname(staged), { recursive: true });
1778
1778
  fs5.writeFileSync(staged, content);
1779
1779
  } else {
@@ -1968,9 +1968,9 @@ function mergeEndpointOverrides(userOverrides, typeOverrides) {
1968
1968
  }
1969
1969
  function relativeImport(fromDir, target) {
1970
1970
  if (!isPathLike(target)) return target;
1971
- let relative6 = path7.relative(fromDir, target).replace(/\\/g, "/");
1972
- if (!relative6.startsWith(".")) relative6 = `./${relative6}`;
1973
- return relative6;
1971
+ let relative5 = path7.relative(fromDir, target).replace(/\\/g, "/");
1972
+ if (!relative5.startsWith(".")) relative5 = `./${relative5}`;
1973
+ return relative5;
1974
1974
  }
1975
1975
  async function runRtkCodegen(api, doc, index, specFile, prettierConfigFile, endpointNameOf = (rtkName) => rtkName) {
1976
1976
  fs6.writeFileSync(specFile, JSON.stringify(doc));
@@ -2042,8 +2042,8 @@ function sniffWorkspace(rootDir, options) {
2042
2042
  const vars = parseEnvFile(path8.join(rootDir, file));
2043
2043
  for (const key of options.urlKeys ?? DEFAULT_URL_KEYS) {
2044
2044
  const value = vars[key];
2045
- const label = value ? firstHostLabel(value) : null;
2046
- if (label) return label;
2045
+ const label2 = value ? firstHostLabel(value) : null;
2046
+ if (label2) return label2;
2047
2047
  }
2048
2048
  }
2049
2049
  return null;
@@ -2261,58 +2261,544 @@ ${withHandlers}` : withHandlers;
2261
2261
  }
2262
2262
 
2263
2263
  // src/codegen/link-skills.ts
2264
+ import { spawnSync } from "child_process";
2265
+ import { createHash } from "crypto";
2264
2266
  import * as fs9 from "fs";
2267
+ import * as os2 from "os";
2265
2268
  import * as path10 from "path";
2266
- function packageLabel(packageDir) {
2267
- if (packageDir) {
2268
- try {
2269
- const version = JSON.parse(fs9.readFileSync(path10.join(packageDir, "package.json"), "utf-8")).version;
2270
- if (typeof version === "string") return `@mgamadeus/ddd-web ${version}`;
2271
- } catch {
2269
+ var PRIMARY_SKILLS_DIRECTORY = ".claude/skills";
2270
+ var MIRROR_SKILLS_DIRECTORIES = [".agents/skills", ".codex/skills"];
2271
+ var SKILLS_MANIFEST_FILE_NAME = ".ddd-skills.json";
2272
+ var SKILLS_MANIFEST_FORMAT = 1;
2273
+ var SKILLS_GITIGNORE_BLOCK_START = "# ddd-skills:start";
2274
+ var SKILLS_GITIGNORE_BLOCK_END = "# ddd-skills:end";
2275
+ var GITIGNORE_BLOCK_COMMENT = "# Generated by ddd-link-skills / ddd-web link-skills; rewritten on every install.";
2276
+ var MAXIMUM_INSTALL_FOLDER_DEPTH = 3;
2277
+ var SKILLS_ROOT_ENV = "DDD_SKILLS_ROOT";
2278
+ var SKILLS_OUTPUT_PREFIX = "[ddd-skills]";
2279
+ var OPERATION_LABELS = {
2280
+ link: ["linked", "would link", "missing"],
2281
+ relink: ["relinked", "would relink", "stale"],
2282
+ remove: ["removed", "would remove", "broken"],
2283
+ write: ["updated", "would update", "outdated"]
2284
+ };
2285
+ var prefixedConsoleLogger = {
2286
+ info: (message) => console.log(`${SKILLS_OUTPUT_PREFIX} ${message}`),
2287
+ warn: (message) => console.warn(`${SKILLS_OUTPUT_PREFIX} ${message}`),
2288
+ error: (message) => console.error(`${SKILLS_OUTPUT_PREFIX} ${message}`)
2289
+ };
2290
+ var label = (text) => text.padEnd(13);
2291
+ function findSkillsRepositoryRoot(startDirectory) {
2292
+ const start = realpathOr(path10.resolve(startDirectory));
2293
+ const home = realpathOr(os2.homedir());
2294
+ for (const marker of [".git", ".claude"]) {
2295
+ let directory = start;
2296
+ for (; ; ) {
2297
+ const isHomeClaude = marker === ".claude" && directory === home;
2298
+ if (!isHomeClaude && lstatOrNull(path10.join(directory, marker))) return directory;
2299
+ const parent = path10.dirname(directory);
2300
+ if (parent === directory) break;
2301
+ directory = parent;
2272
2302
  }
2273
2303
  }
2274
- return "@mgamadeus/ddd-web";
2304
+ return start;
2275
2305
  }
2276
- function linkSkills(options = {}) {
2306
+ function runSkillLinks(options = {}) {
2307
+ const logger = options.logger ?? prefixedConsoleLogger;
2277
2308
  const cwd = path10.resolve(options.cwd ?? process.cwd());
2278
- const logger = options.logger ?? consoleLogger;
2279
- const packageDir = path10.join(cwd, "node_modules", "@mgamadeus", "ddd-web");
2280
- const sourceDir = options.sourceDir ? path10.resolve(cwd, options.sourceDir) : path10.join(packageDir, ".claude", "skills");
2281
- if (!options.sourceDir && !fs9.existsSync(packageDir)) {
2282
- logger.warn(`@mgamadeus/ddd-web is not installed in ${cwd} (no ${packageDir}) \u2014 nothing to link.`);
2283
- return [];
2309
+ const envRoot = process.env[SKILLS_ROOT_ENV];
2310
+ const requestedRoot = options.root ? path10.resolve(cwd, options.root) : envRoot ? path10.resolve(cwd, envRoot) : findSkillsRepositoryRoot(cwd);
2311
+ const linker = new SkillLinker(requestedRoot, options, logger);
2312
+ return linker.run();
2313
+ }
2314
+ function linkSkills(options = {}) {
2315
+ return runSkillLinks(options).skills;
2316
+ }
2317
+ var SkillLinker = class {
2318
+ constructor(rootDirectory, options, logger) {
2319
+ this.options = options;
2320
+ this.logger = logger;
2321
+ this.root = realpathOr(rootDirectory);
2322
+ this.modeIndex = options.check ? 2 : options.dryRun ? 1 : 0;
2323
+ }
2324
+ options;
2325
+ logger;
2326
+ root;
2327
+ modeIndex;
2328
+ lines = [];
2329
+ problems = [];
2330
+ results = [];
2331
+ run() {
2332
+ if (!isDirectory(this.root)) {
2333
+ this.warn(`error: the root directory ${this.root} does not exist`);
2334
+ return this.report(1);
2335
+ }
2336
+ let plan;
2337
+ try {
2338
+ plan = this.createPlan();
2339
+ } catch (error) {
2340
+ this.warn(`error: ${error.message}`);
2341
+ return this.report(1);
2342
+ }
2343
+ if (plan.nothingToDo) {
2344
+ this.info(`no DDD package ships agent skills below ${this.root}; nothing to link`);
2345
+ return this.report(0);
2346
+ }
2347
+ this.problems.push(...plan.warnings);
2348
+ if (!this.options.check && !this.options.dryRun) {
2349
+ try {
2350
+ this.applyOperations(plan.operations);
2351
+ } catch (error) {
2352
+ this.warn(`error: ${error.message}`);
2353
+ return this.report(1);
2354
+ }
2355
+ }
2356
+ for (const operation of plan.operations) {
2357
+ const line = label(OPERATION_LABELS[operation.kind][this.modeIndex]) + operation.display;
2358
+ if (this.options.check) {
2359
+ this.problems.push(line);
2360
+ this.warn(line);
2361
+ } else if (!this.options.quiet) {
2362
+ this.print(line, "info");
2363
+ }
2364
+ }
2365
+ for (const warning of plan.warnings) this.warn(warning);
2366
+ const skillCount = plan.managedSkillNames.length;
2367
+ const packageCount = plan.packageNames.length;
2368
+ const changeCount = plan.operations.length;
2369
+ if (this.options.check) {
2370
+ if (this.problems.length > 0) {
2371
+ this.warn(`check failed: ${this.problems.length} problem(s); run ddd-link-skills (or ddd-web link-skills) to fix the links`);
2372
+ return this.report(1);
2373
+ }
2374
+ this.info(`check passed: ${skillCount} skill(s) from ${packageCount} package(s)`);
2375
+ return this.report(0);
2376
+ }
2377
+ if (this.options.dryRun) {
2378
+ this.info(`dry run: ${changeCount} change(s) would be made`);
2379
+ return this.report(0);
2380
+ }
2381
+ this.info(`${skillCount} skill(s) from ${packageCount} package(s), ${changeCount} change(s)`);
2382
+ return this.report(0);
2383
+ }
2384
+ report(exitCode) {
2385
+ return { root: this.root, exitCode, skills: this.results, lines: this.lines, problems: this.problems };
2386
+ }
2387
+ createPlan() {
2388
+ const operations = [];
2389
+ const discovery = this.discoverSkills();
2390
+ const warnings = [...discovery.warnings];
2391
+ const winners = discovery.winners;
2392
+ const primaryLogical = `${this.root}/${PRIMARY_SKILLS_DIRECTORY}`;
2393
+ const primary = this.resolvePrimaryDirectory();
2394
+ const primaryExists = isDirectory(primaryLogical);
2395
+ if (!primaryExists && winners.size === 0) {
2396
+ return { nothingToDo: true, operations: [], warnings: [], managedSkillNames: [], packageNames: [] };
2397
+ }
2398
+ const previousManifestPath = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
2399
+ let previousEntries = readManifestEntries(previousManifestPath);
2400
+ if (previousEntries === null) {
2401
+ warnings.push(`${label("manifest")}${this.displayPath(previousManifestPath)} is not readable; rewritten`);
2402
+ previousEntries = {};
2403
+ }
2404
+ const managed = /* @__PURE__ */ new Map();
2405
+ for (const [skillName, skill] of winners) {
2406
+ const linkPath = `${primary}/${skillName}`;
2407
+ const desiredTarget = relativePath(primary, skill.directory);
2408
+ const display = `${PRIMARY_SKILLS_DIRECTORY}/${skillName}`;
2409
+ const entryType = getEntryType(linkPath);
2410
+ let action = "unchanged";
2411
+ if (entryType === "missing") {
2412
+ operations.push({ kind: "link", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget}` });
2413
+ action = "linked";
2414
+ } else if (entryType === "link") {
2415
+ const currentTarget = fs9.readlinkSync(linkPath);
2416
+ if (currentTarget !== desiredTarget) {
2417
+ if (!isDddVendorPath(resolveLinkTarget(primary, currentTarget))) {
2418
+ warnings.push(`${label("clash")}${display}: a symlink of the app to ${currentTarget} exists; the skill of ${skill.package} is not linked`);
2419
+ this.results.push({ skill: skillName, action: "skipped", target: desiredTarget, package: skill.package });
2420
+ continue;
2421
+ }
2422
+ operations.push({ kind: "relink", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget} (was ${currentTarget})` });
2423
+ action = "relinked";
2424
+ }
2425
+ } else {
2426
+ warnings.push(`${label("clash")}${display}: the app has its own skill of this name; the skill of ${skill.package} is not linked`);
2427
+ this.results.push({ skill: skillName, action: "skipped", target: desiredTarget, package: skill.package });
2428
+ continue;
2429
+ }
2430
+ this.results.push({ skill: skillName, action, target: desiredTarget, package: skill.package });
2431
+ let skillFileHash = createHash("sha256").update(fs9.readFileSync(`${skill.directory}/SKILL.md`)).digest("hex");
2432
+ const previous = previousEntries[skillName];
2433
+ if (previous && previous.package === skill.package && skill.version !== null && previous.version === skill.version && typeof previous.sha256 === "string" && previous.sha256 !== skillFileHash) {
2434
+ warnings.push(
2435
+ `${label("edited")}${skillName}: SKILL.md of ${skill.package} ${skill.version} differs from the installed copy recorded in the manifest`
2436
+ );
2437
+ skillFileHash = previous.sha256;
2438
+ }
2439
+ managed.set(skillName, {
2440
+ package: skill.package,
2441
+ version: skill.version,
2442
+ source: relativePath(this.root, skill.directory),
2443
+ target: desiredTarget,
2444
+ sha256: skillFileHash,
2445
+ mirrors: []
2446
+ });
2447
+ }
2448
+ for (const [skillName, previous] of Object.entries(previousEntries)) {
2449
+ if (managed.has(skillName) || winners.has(skillName) || !previous || typeof previous !== "object") continue;
2450
+ const linkPath = `${primary}/${skillName}`;
2451
+ if (getEntryType(linkPath) !== "link") continue;
2452
+ const currentTarget = fs9.readlinkSync(linkPath);
2453
+ if (!isDddVendorPath(resolveLinkTarget(primary, currentTarget))) continue;
2454
+ if (fs9.existsSync(linkPath)) {
2455
+ managed.set(skillName, {
2456
+ package: previous.package ?? null,
2457
+ version: previous.version ?? null,
2458
+ source: previous.source ?? null,
2459
+ target: currentTarget,
2460
+ sha256: previous.sha256 ?? null,
2461
+ mirrors: []
2462
+ });
2463
+ }
2464
+ }
2465
+ const removedNames = /* @__PURE__ */ new Set();
2466
+ for (const entryName of listDirectoryNames(primary)) {
2467
+ const linkPath = `${primary}/${entryName}`;
2468
+ if (managed.has(entryName) || getEntryType(linkPath) !== "link" || fs9.existsSync(linkPath)) continue;
2469
+ const currentTarget = fs9.readlinkSync(linkPath);
2470
+ if (isDddVendorPath(resolveLinkTarget(primary, currentTarget))) {
2471
+ removedNames.add(entryName);
2472
+ operations.push({ kind: "remove", path: linkPath, display: `${PRIMARY_SKILLS_DIRECTORY}/${entryName} (broken link to ${currentTarget})` });
2473
+ }
2474
+ }
2475
+ const managedNames = [...managed.keys()].sort(compareBytes);
2476
+ const mirrorGitignoreNames = /* @__PURE__ */ new Map();
2477
+ const gitPaths = [];
2478
+ for (const mirrorName of MIRROR_SKILLS_DIRECTORIES) {
2479
+ const mirrorLogical = `${this.root}/${mirrorName}`;
2480
+ if (getEntryType(mirrorLogical) === "missing" || !isDirectory(mirrorLogical)) continue;
2481
+ const mirror = realpathOr(mirrorLogical);
2482
+ const mirrorParent = realpathOr(path10.dirname(mirrorLogical));
2483
+ if (mirror === primary || mirrorParent === primary) continue;
2484
+ mirrorGitignoreNames.set(mirror, []);
2485
+ for (const skillName of managedNames) {
2486
+ const linkPath = `${mirror}/${skillName}`;
2487
+ const primaryEntryPath = `${primaryLogical}/${skillName}`;
2488
+ const desiredTarget = relativePath(mirror, primaryEntryPath);
2489
+ const display = `${mirrorName}/${skillName}`;
2490
+ const entryType = getEntryType(linkPath);
2491
+ if (entryType === "missing") {
2492
+ operations.push({ kind: "link", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget}` });
2493
+ } else if (entryType === "link") {
2494
+ const currentTarget = fs9.readlinkSync(linkPath);
2495
+ if (currentTarget !== desiredTarget) {
2496
+ const resolvedTarget = resolveLinkTarget(mirror, currentTarget);
2497
+ const pointsToPrimary = resolvedTarget === primaryEntryPath || resolvedTarget === `${primary}/${skillName}`;
2498
+ if (!pointsToPrimary && !isDddVendorPath(resolvedTarget)) {
2499
+ warnings.push(`${label("clash")}${display}: a symlink of the app to ${currentTarget} exists; not mirrored`);
2500
+ continue;
2501
+ }
2502
+ operations.push({ kind: "relink", path: linkPath, target: desiredTarget, display: `${display} -> ${desiredTarget} (was ${currentTarget})` });
2503
+ }
2504
+ } else {
2505
+ warnings.push(`${label("clash")}${display}: the app has its own skill of this name; not mirrored`);
2506
+ continue;
2507
+ }
2508
+ managed.get(skillName).mirrors.push(mirrorName);
2509
+ mirrorGitignoreNames.get(mirror).push(skillName);
2510
+ gitPaths.push(linkPath);
2511
+ }
2512
+ for (const entryName of listDirectoryNames(mirror)) {
2513
+ const linkPath = `${mirror}/${entryName}`;
2514
+ if (managed.has(entryName) || getEntryType(linkPath) !== "link") continue;
2515
+ const currentTarget = fs9.readlinkSync(linkPath);
2516
+ const resolvedTarget = resolveLinkTarget(mirror, currentTarget);
2517
+ const pointsToPrimary = resolvedTarget === `${primaryLogical}/${entryName}` || resolvedTarget === `${primary}/${entryName}`;
2518
+ const isBrokenDddLink = !fs9.existsSync(linkPath) && isDddVendorPath(resolvedTarget);
2519
+ const isFormerMirror = pointsToPrimary && (removedNames.has(entryName) || entryName in previousEntries) && (!fs9.existsSync(`${primary}/${entryName}`) || removedNames.has(entryName));
2520
+ if (isBrokenDddLink || isFormerMirror) {
2521
+ operations.push({ kind: "remove", path: linkPath, display: `${mirrorName}/${entryName} (link to removed ${currentTarget})` });
2522
+ }
2523
+ }
2524
+ }
2525
+ const manifestPath = `${primary}/${SKILLS_MANIFEST_FILE_NAME}`;
2526
+ const manifestContent = encodeManifest(managedNames, managed);
2527
+ if ((isFile(manifestPath) ? fs9.readFileSync(manifestPath, "utf-8") : null) !== manifestContent) {
2528
+ operations.push({ kind: "write", path: manifestPath, content: manifestContent, display: `${PRIMARY_SKILLS_DIRECTORY}/${SKILLS_MANIFEST_FILE_NAME}` });
2529
+ }
2530
+ const primaryGitignoreEntries = [`/${SKILLS_MANIFEST_FILE_NAME}`];
2531
+ for (const skillName of managedNames) {
2532
+ primaryGitignoreEntries.push(`/${skillName}`);
2533
+ gitPaths.push(`${primary}/${skillName}`);
2534
+ }
2535
+ gitPaths.push(manifestPath);
2536
+ const gitignoreTargets = /* @__PURE__ */ new Map([[primary, primaryGitignoreEntries]]);
2537
+ for (const [mirror, names] of mirrorGitignoreNames) {
2538
+ gitignoreTargets.set(mirror, [...names].sort(compareBytes).map((name) => `/${name}`));
2539
+ }
2540
+ for (const [directory, entries] of gitignoreTargets) {
2541
+ const gitignorePath = `${directory}/.gitignore`;
2542
+ const currentContent = isFile(gitignorePath) ? fs9.readFileSync(gitignorePath, "utf-8") : null;
2543
+ const newContent = createGitignoreContent(currentContent, entries);
2544
+ if (newContent === null) {
2545
+ warnings.push(
2546
+ `${label("gitignore")}${this.displayPath(gitignorePath)}: ${SKILLS_GITIGNORE_BLOCK_START} without ${SKILLS_GITIGNORE_BLOCK_END}; left as is`
2547
+ );
2548
+ } else if (newContent !== (currentContent ?? "")) {
2549
+ operations.push({ kind: "write", path: gitignorePath, content: newContent, display: this.displayPath(gitignorePath) });
2550
+ }
2551
+ }
2552
+ const trackedPaths = this.findTrackedPaths(gitPaths);
2553
+ if (trackedPaths.length > 0) {
2554
+ warnings.push(
2555
+ `${label("tracked")}${trackedPaths.length} generated path(s) are still tracked by git; run in ${this.root}: git rm --cached -- ${trackedPaths.map(quoteShellArgument).join(" ")} (then commit with the updated .gitignore)`
2556
+ );
2557
+ }
2558
+ const packageNames = /* @__PURE__ */ new Set();
2559
+ for (const entry of managed.values()) if (typeof entry.package === "string") packageNames.add(entry.package);
2560
+ return { nothingToDo: false, operations, warnings, managedSkillNames: managedNames, packageNames: [...packageNames] };
2561
+ }
2562
+ /**
2563
+ * Skills of all DDD packages below the root in deterministic order (skill path, byte order). The first package
2564
+ * shipping a name wins; another package with the same name is a clash; the same package installed twice is not.
2565
+ */
2566
+ discoverSkills() {
2567
+ const candidates = [];
2568
+ const packages = this.options.sourceDir ? [this.legacySourcePackage(this.options.sourceDir)] : this.findPackages(this.root, 0);
2569
+ for (const pkg of packages) {
2570
+ const skillsDirectory = pkg.skillsDirectory;
2571
+ for (const skillName of listDirectoryNames(skillsDirectory)) {
2572
+ const skillDirectory = `${skillsDirectory}/${skillName}`;
2573
+ if (skillName.startsWith(".") || !isDirectory(skillDirectory) || !isFile(`${skillDirectory}/SKILL.md`)) continue;
2574
+ candidates.push({ name: skillName, package: pkg.package, version: pkg.version, directory: skillDirectory });
2575
+ }
2576
+ }
2577
+ candidates.sort((first, second) => compareBytes(first.directory, second.directory));
2578
+ const winners = /* @__PURE__ */ new Map();
2579
+ const warnings = [];
2580
+ for (const candidate of candidates) {
2581
+ const winner = winners.get(candidate.name);
2582
+ if (!winner) {
2583
+ winners.set(candidate.name, candidate);
2584
+ } else if (winner.package !== candidate.package) {
2585
+ warnings.push(
2586
+ `${label("clash")}${candidate.name}: shipped by ${winner.package} (${relativePath(this.root, winner.directory)}) and ${candidate.package} (${relativePath(this.root, candidate.directory)}); ${winner.package} kept`
2587
+ );
2588
+ this.results.push({ skill: candidate.name, action: "skipped", target: relativePath(this.root, candidate.directory), package: candidate.package });
2589
+ }
2590
+ }
2591
+ return { winners, warnings };
2284
2592
  }
2285
- const skills = fs9.existsSync(sourceDir) ? fs9.readdirSync(sourceDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() || entry.isSymbolicLink()) : [];
2286
- if (skills.length === 0) {
2287
- logger.info(`${packageLabel(options.sourceDir ? void 0 : packageDir)} ships no agent skills (${sourceDir}) \u2014 nothing to link.`);
2288
- return [];
2593
+ legacySourcePackage(sourceDir) {
2594
+ const skillsDirectory = path10.resolve(path10.resolve(this.options.cwd ?? process.cwd()), sourceDir);
2595
+ const packageJson = readJson(path10.join(skillsDirectory, "..", "..", "package.json"));
2596
+ return {
2597
+ package: typeof packageJson?.name === "string" ? packageJson.name : "@mgamadeus/ddd-web",
2598
+ version: typeof packageJson?.version === "string" ? packageJson.version : null,
2599
+ skillsDirectory
2600
+ };
2289
2601
  }
2290
- const targetDir = path10.join(cwd, ".claude", "skills");
2291
- fs9.mkdirSync(targetDir, { recursive: true });
2292
- const results = [];
2293
- for (const entry of skills) {
2294
- const linkPath = path10.join(targetDir, entry.name);
2295
- const linkTarget = path10.relative(targetDir, path10.join(sourceDir, entry.name));
2296
- let action;
2297
- const existing = fs9.lstatSync(linkPath, { throwIfNoEntry: false });
2298
- if (!existing) {
2299
- fs9.symlinkSync(linkTarget, linkPath, "dir");
2300
- action = "linked";
2301
- } else if (!existing.isSymbolicLink()) {
2302
- action = "skipped";
2303
- } else if (fs9.readlinkSync(linkPath) === linkTarget) {
2304
- action = "unchanged";
2305
- } else {
2306
- fs9.unlinkSync(linkPath);
2307
- fs9.symlinkSync(linkTarget, linkPath, "dir");
2308
- action = "relinked";
2602
+ findPackages(directory, depth) {
2603
+ const packages = [];
2604
+ const composerScope = `${directory}/vendor/mgamadeus`;
2605
+ if (isDirectory(composerScope)) {
2606
+ const installedVersions = readComposerInstalledVersions(`${directory}/vendor/composer/installed.json`);
2607
+ for (const folderName of listDirectoryNames(composerScope)) {
2608
+ const packageDirectory = `${composerScope}/${folderName}`;
2609
+ if (!isDirectory(packageDirectory)) continue;
2610
+ const packageName = `mgamadeus/${folderName}`;
2611
+ packages.push({
2612
+ package: packageName,
2613
+ version: installedVersions.get(packageName) ?? readJsonVersion(`${packageDirectory}/composer.json`),
2614
+ skillsDirectory: `${packageDirectory}/.claude/skills`
2615
+ });
2616
+ }
2617
+ }
2618
+ const npmScope = `${directory}/node_modules/@mgamadeus`;
2619
+ if (isDirectory(npmScope)) {
2620
+ for (const folderName of listDirectoryNames(npmScope)) {
2621
+ const packageDirectory = `${npmScope}/${folderName}`;
2622
+ if (!isDirectory(packageDirectory)) continue;
2623
+ packages.push({
2624
+ package: `@mgamadeus/${folderName}`,
2625
+ version: readJsonVersion(`${packageDirectory}/package.json`),
2626
+ skillsDirectory: `${packageDirectory}/.claude/skills`
2627
+ });
2628
+ }
2629
+ }
2630
+ if (depth + 1 >= MAXIMUM_INSTALL_FOLDER_DEPTH) return packages;
2631
+ for (const childName of listDirectoryNames(directory)) {
2632
+ const childDirectory = `${directory}/${childName}`;
2633
+ if (childName.startsWith(".") || childName === "vendor" || childName === "node_modules") continue;
2634
+ const childStat = lstatOrNull(childDirectory);
2635
+ if (!childStat || !childStat.isDirectory()) continue;
2636
+ packages.push(...this.findPackages(childDirectory, depth + 1));
2637
+ }
2638
+ return packages;
2639
+ }
2640
+ /** Real location of `<root>/.claude/skills`, also when it does not exist yet (then `.claude` resolved). */
2641
+ resolvePrimaryDirectory() {
2642
+ const claude = `${this.root}/.claude`;
2643
+ const primaryLogical = `${this.root}/${PRIMARY_SKILLS_DIRECTORY}`;
2644
+ if (isDirectory(primaryLogical)) return realpathOr(primaryLogical);
2645
+ if (lstatOrNull(primaryLogical)) throw new Error(`${PRIMARY_SKILLS_DIRECTORY} exists but is not a folder (broken symlink?)`);
2646
+ if (isDirectory(claude)) return `${realpathOr(claude)}/skills`;
2647
+ if (lstatOrNull(claude)) throw new Error(".claude exists but is not a folder (broken symlink?)");
2648
+ return primaryLogical;
2649
+ }
2650
+ findTrackedPaths(absolutePaths) {
2651
+ const relativePaths = absolutePaths.filter((p) => p.startsWith(`${this.root}/`)).map((p) => p.slice(this.root.length + 1));
2652
+ if (relativePaths.length === 0) return [];
2653
+ const result = spawnSync("git", ["-C", this.root, "ls-files", "-z", "--", ...relativePaths], { encoding: "utf-8" });
2654
+ if (result.error || result.status !== 0) return [];
2655
+ return [...new Set(result.stdout.split("\0").filter((p) => p !== ""))].sort(compareBytes);
2656
+ }
2657
+ applyOperations(operations) {
2658
+ const primary = this.resolvePrimaryDirectory();
2659
+ fs9.mkdirSync(primary, { recursive: true });
2660
+ for (const kind of ["remove", "relink", "link", "write"]) {
2661
+ for (const operation of operations) {
2662
+ if (operation.kind !== kind) continue;
2663
+ if (kind === "remove" || kind === "relink") fs9.unlinkSync(operation.path);
2664
+ if (kind === "relink" || kind === "link") fs9.symlinkSync(operation.target, operation.path, "dir");
2665
+ if (kind === "write") fs9.writeFileSync(operation.path, operation.content);
2666
+ }
2309
2667
  }
2310
- const message = `${action.padEnd(9)} .claude/skills/${entry.name} \u2192 ${linkTarget}`;
2311
- if (action === "skipped") logger.warn(`${message} (exists and is not a symlink \u2014 left as is)`);
2312
- else logger.info(message);
2313
- results.push({ skill: entry.name, action, target: linkTarget });
2314
2668
  }
2315
- return results;
2669
+ displayPath(absolutePath) {
2670
+ return absolutePath.startsWith(`${this.root}/`) ? absolutePath.slice(this.root.length + 1) : absolutePath;
2671
+ }
2672
+ info(line) {
2673
+ if (!this.options.quiet) this.print(line, "info");
2674
+ }
2675
+ warn(line) {
2676
+ this.print(line, "warn");
2677
+ }
2678
+ print(line, level) {
2679
+ this.lines.push(line);
2680
+ this.logger[level](line);
2681
+ }
2682
+ };
2683
+ function readManifestEntries(manifestPath) {
2684
+ if (!isFile(manifestPath)) return {};
2685
+ const manifest = readJson(manifestPath);
2686
+ if (!manifest || typeof manifest.skills !== "object" || manifest.skills === null || Array.isArray(manifest.skills)) return null;
2687
+ return manifest.skills;
2688
+ }
2689
+ function encodeManifest(sortedNames, entries) {
2690
+ const skills = {};
2691
+ for (const name of sortedNames) {
2692
+ const entry = entries.get(name);
2693
+ skills[name] = {
2694
+ package: entry.package,
2695
+ version: entry.version,
2696
+ source: entry.source,
2697
+ target: entry.target,
2698
+ sha256: entry.sha256,
2699
+ mirrors: [...entry.mirrors].sort(compareBytes)
2700
+ };
2701
+ }
2702
+ const manifest = { format: SKILLS_MANIFEST_FORMAT, skills };
2703
+ return `${JSON.stringify(manifest, null, 4)}
2704
+ `;
2705
+ }
2706
+ function createGitignoreContent(currentContent, entries) {
2707
+ const lines = currentContent === null || currentContent === "" ? [] : currentContent.replace(/\n+$/, "").split("\n");
2708
+ const startIndex = lines.indexOf(SKILLS_GITIGNORE_BLOCK_START);
2709
+ const block = entries.length > 0 ? [SKILLS_GITIGNORE_BLOCK_START, GITIGNORE_BLOCK_COMMENT, ...entries, SKILLS_GITIGNORE_BLOCK_END] : [];
2710
+ if (startIndex === -1) {
2711
+ if (block.length === 0) return currentContent ?? "";
2712
+ if (lines.length > 0 && lines[lines.length - 1] !== "") lines.push("");
2713
+ return `${[...lines, ...block].join("\n")}
2714
+ `;
2715
+ }
2716
+ const endIndex = lines.indexOf(SKILLS_GITIGNORE_BLOCK_END, startIndex + 1);
2717
+ if (endIndex === -1) return null;
2718
+ const before = lines.slice(0, startIndex);
2719
+ const after = lines.slice(endIndex + 1);
2720
+ if (block.length === 0 && before.length > 0 && before[before.length - 1] === "") before.pop();
2721
+ const newLines = [...before, ...block, ...after];
2722
+ return newLines.length > 0 ? `${newLines.join("\n")}
2723
+ ` : "";
2724
+ }
2725
+ function readComposerInstalledVersions(installedJsonPath) {
2726
+ const versions = /* @__PURE__ */ new Map();
2727
+ const installed2 = readJson(installedJsonPath);
2728
+ const list2 = Array.isArray(installed2) ? installed2 : installed2?.packages;
2729
+ if (!Array.isArray(list2)) return versions;
2730
+ for (const item of list2) {
2731
+ if (item && typeof item.name === "string" && typeof item.version === "string") versions.set(item.name, item.version);
2732
+ }
2733
+ return versions;
2734
+ }
2735
+ function readJsonVersion(jsonPath) {
2736
+ const decoded = readJson(jsonPath);
2737
+ return typeof decoded?.version === "string" ? decoded.version : null;
2738
+ }
2739
+ function readJson(jsonPath) {
2740
+ try {
2741
+ return JSON.parse(fs9.readFileSync(jsonPath, "utf-8"));
2742
+ } catch {
2743
+ return null;
2744
+ }
2745
+ }
2746
+ function getEntryType(entryPath) {
2747
+ const stat = lstatOrNull(entryPath);
2748
+ if (!stat) return "missing";
2749
+ if (stat.isSymbolicLink()) return "link";
2750
+ return stat.isDirectory() ? "directory" : "file";
2751
+ }
2752
+ function lstatOrNull(entryPath) {
2753
+ try {
2754
+ return fs9.lstatSync(entryPath);
2755
+ } catch {
2756
+ return null;
2757
+ }
2758
+ }
2759
+ function isDirectory(entryPath) {
2760
+ try {
2761
+ return fs9.statSync(entryPath).isDirectory();
2762
+ } catch {
2763
+ return false;
2764
+ }
2765
+ }
2766
+ function isFile(entryPath) {
2767
+ try {
2768
+ return fs9.statSync(entryPath).isFile();
2769
+ } catch {
2770
+ return false;
2771
+ }
2772
+ }
2773
+ function realpathOr(entryPath) {
2774
+ try {
2775
+ return fs9.realpathSync(entryPath);
2776
+ } catch {
2777
+ return entryPath;
2778
+ }
2779
+ }
2780
+ function listDirectoryNames(directory) {
2781
+ try {
2782
+ return fs9.readdirSync(directory).sort(compareBytes);
2783
+ } catch {
2784
+ return [];
2785
+ }
2786
+ }
2787
+ function compareBytes(first, second) {
2788
+ return Buffer.compare(Buffer.from(first), Buffer.from(second));
2789
+ }
2790
+ function isDddVendorPath(candidate) {
2791
+ const withSlash = `${candidate}/`;
2792
+ return withSlash.includes("/vendor/mgamadeus/") || withSlash.includes("/node_modules/@mgamadeus/");
2793
+ }
2794
+ function resolveLinkTarget(linkDirectory, target) {
2795
+ return path10.posix.resolve(linkDirectory, target);
2796
+ }
2797
+ function relativePath(fromDirectory, toPath) {
2798
+ return path10.posix.relative(fromDirectory, toPath) || ".";
2799
+ }
2800
+ function quoteShellArgument(argument) {
2801
+ return /^[A-Za-z0-9._/@+=:-]+$/.test(argument) ? argument : `'${argument.replace(/'/g, "'\\''")}'`;
2316
2802
  }
2317
2803
 
2318
2804
  export {
@@ -2327,6 +2813,8 @@ export {
2327
2813
  loadSpec,
2328
2814
  validateSpec,
2329
2815
  generateSdk,
2816
+ findSkillsRepositoryRoot,
2817
+ runSkillLinks,
2330
2818
  linkSkills
2331
2819
  };
2332
- //# sourceMappingURL=chunk-6CQEUZ3B.js.map
2820
+ //# sourceMappingURL=chunk-3V22MYDI.js.map