⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v0.2.0

claudemap-runtime

quinnaho@quinnaho⭐ 295 stars· last commit 7mo ago· 2 open issues

Internal ClaudeMap runtime for turning a repository into a live architecture map and driving that map during walkthroughs. Prefer the public commands in .claude/commands for normal use.

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐⭐ 295 on GitHubGitHub ↗

Popular

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Welcome to...

ClaudeMap

Version License: MIT npm downloads GitHub stars

Google Maps for vibecoders.

AI lets you build faster than ever, but the very tools that help our productivity are leaving us behind - you don't understand what you're building anymore. You can vibecode a full app in a weekend and not even start to explain how it works. ClaudeMap fixes that.

Unlike traditional visualization tools, ClaudeMap organizes your code by what it actually does. Claude reads your project and groups it into concepts in a way you actually think about your project. Zoom out to see the big picture. Zoom in to see the details. Colors show what's healthy and what's broken. Use /explain and ask any question about your code, Claude will present directly on the map and explain step by step. Use /show to tell Claude what you want to find or see, and it moves the map for you.

All powered by the same AI you vibecode with.

See It In Action

ClaudeMap Demo

Try the map (standalone preview, Claude features require Claude Code or Codex)

Longer YouTube walkthrough

Install

npx @quinnaho/claudemap install
claude
/setup-claudemap

Codex support is here!npx @quinnaho/claudemap install --assistant codex - see Codex guide.

In Codex, run /skills, choose codexmap-runtime, or prefix natural-language requests with $codexmap-runtime, for example:

$codexmap-runtime build the initial map for this repo

Commands

CommandDescription
/setup-claudemapAnalyze your repo and generate the map
/refreshUpdate map after code changes
/explainAI-guided walkthroughs with visual highlighting
/showNavigate the map with natural language

What's New in v0.2.0

  • Sub-map support - create scoped maps for larger codebases
  • Codex support - works with Claude Code and OpenAI Codex
  • Stable map generation - consistent layouts across rebuilds
  • Iterative refinement - tweak your map without starting over
  • Better refresh UX - smoother updates after code changes

Learn More

License

MIT

// HOW IT'S BUILT

// FILES

65 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skill/SKILL.md7.4 KB5412e386f340upstream ↗
    ---
    name: claudemap-runtime
    description: Internal ClaudeMap runtime for turning a repository into a live architecture map and driving that map during walkthroughs. Prefer the public commands in .claude/commands for normal use.
    ---
    
    ClaudeMap is a repo-to-architecture-map workflow.
    
    High-level model:
    
    - snapshot the repository
    - ask `@claudemap-architect` to turn that snapshot into a detailed, human-legible graph
    - render the graph in the bundled ClaudeMap UI
    - keep the graph and presentation state updated as the user explores the codebase
    
    Public commands:
    
    - `/setup-claudemap`: build or rebuild the map for the current repository
    - `/open-claudemap`: reopen the existing UI without rebuilding
    - `/create-map`: create or refresh a scoped subsystem map from the current root graph
    - `/refresh`: update the graph after code changes
    - `/explain`: run a guided walkthrough through the live map
    - `/show`: direct the live map for highlights, focus, presentation, and flows
    
    If this skill is invoked directly, default to the setup workflow.
    
    Target repository:
    
    - If the user passed an argument to the invoked skill command, use `$ARGUMENTS` as the project root.
    - If no argument was passed, use the current working directory.
    
    Execution rules:
    
    1. Resolve the bundled ClaudeMap workspace from `${CLAUDE_SKILL_DIR}`.
    2. Generate a raw repo snapshot by running `${CLAUDE_SKILL_DIR}/skill/commands/snapshot.js` for the target project root.
    3. Read `${CLAUDE_SKILL_DIR}/skill/prompts/enrichment.txt`.
    4. Use the `@claudemap-architect` subagent explicitly. Give it:
       - the raw snapshot JSON
       - the graph schema contract from the enrichment prompt
       - instructions to return only valid graph JSON
       - instructions to optimize for a detailed graph with intuitive human grouping
    5. **Wait for the subagent Task call to fully return**, then save the returned JSON to `${CLAUDE_SKILL_DIR}/tmp/claudemap-enrichment.json`. Do not run the setup JS command until after this file has been written with non-empty valid graph JSON. Do not run setup in parallel with the subagent call.
    6. Run `${CLAUDE_SKILL_DIR}/skill/commands/setup-claudemap.js` for the target project root with `--enrichment-file ${CLAUDE_SKILL_DIR}/tmp/claudemap-enrichment.json`. The setup command is strict: if the file is missing, empty, or unparseable it will exit non-zero and refuse to render a heuristic graph. Do not retry setup without fixing the enrichment file first.
    7. Add `--force-refresh` only when the user explicitly asks for a fresh rebuild.
    8. If the subagent fails to return valid JSON after two attempts, tell the user the architect pass failed and stop. Do not silently rerun setup without `--enrichment-file` — that would render a heuristic graph and pollute the cache. The user should rerun `/setup-claudemap` once the architect issue is resolved.
    9. Let the bundled launcher start the app unless the user explicitly asks not to.
    10. Summarize the analyzed file count, system count, graph source, render transport, and app readiness. Runtime graph outputs land in `${CLAUDE_SKILL_DIR}/app/public/graph/` (served by the bundled Vite app as `/graph/*`).
    11. End the graph-generation flow with a short feedback prompt such as: `Does this map look right, or should I refine it?`
    12. If the user says the map is good, stop there.
    13. If the user asks for refinement, reuse the current target project's `claudemap-cache.json` graph and file snapshot as context when available instead of starting from a blank prompt again.
    14. For refinement passes, send the existing graph plus the user's requested changes back through `@claudemap-architect`, save the refined JSON to `${CLAUDE_SKILL_DIR}/tmp/claudemap-enrichment.json`, and run `${CLAUDE_SKILL_DIR}/skill/commands/refresh.js` with `--enrichment-file` so the graph iterates in place.
    15. After the refined graph renders, ask the same short feedback prompt again.
    
    `/create-map` runs an architect-first scoped pipeline:
    
    1. Resolve the target scope from the user's request (either a scope JSON payload copied from the UI, or a natural language description of a subsystem the architect should locate in the root graph).
    2. Read `${CLAUDE_SKILL_DIR}/skill/prompts/scoped-enrichment.txt`. This is a dedicated scoped prompt — do not reuse the root enrichment prompt.
    3. Build a scoped snapshot by filtering the root graph's file list to the files inside the target subsystem. Include any prior scoped graph from the target map's `cachePath` when one exists so the architect can refine rather than rebuild.
    4. Call the `@claudemap-architect` subagent with the scoped snapshot, the scoped prompt, and any user instructions. Instruct it to emit a richer internal breakdown (2-6 internal subsystems, tighter edges, function nodes welcome) and to decide between edit-in-place and rebuild based on the intent of the request.
    5. Save the returned JSON to `${CLAUDE_SKILL_DIR}/tmp/claudemap-enrichment.json` and run `${CLAUDE_SKILL_DIR}/skill/commands/create-map.js` with `--enrichment-file` (plus `--scope-json` and optional `--instructions`). The command deletes the tmp file after it reads it.
    6. If the architect pass fails, the command can still fall back to `buildScopedGraphFromRoot` by running without `--enrichment-file`, but warn the user the scoped map will be a plain filter view and suggest rerunning with architect enrichment for richer grouping.
    7. After the scoped map renders, ask the same short feedback prompt (`Does this map look right, or should I refine it?`).
    8. If the user asks for refinement, reuse the scoped map's own cache as prior graph context (via `buildScopedSnapshot`'s `priorGraph` option) and rerun the architect. Save the refined JSON to the tmp file and rerun `create-map.js` with the same `--scope-json` payload plus `--enrichment-file`.
    9. After the refined scoped graph renders, ask the same short feedback prompt again.
    
    `/refresh` is change-aware for scoped maps:
    
    - The root graph is always diffed against the cached snapshot.
    - For each scoped map, if none of its files were in the diff and its cached graph was produced by the architect (`meta.source === 'claude-scoped'`), the scoped map is preserved untouched — no rebuild, no filter fallback.
    - If the scoped map's files were touched, it is rebuilt from the updated root graph filter and marked `needsRebuild: true` so the next `/create-map` pass knows to rerun the architect for that scope.
    - If a scope can no longer be resolved in the new root graph, it is marked `stale: true` and `needsRebuild: true` and left for the user to confirm.
    
    Important details:
    
    - The bundled runtime lives inside this skill directory, so keep all paths anchored to `${CLAUDE_SKILL_DIR}`.
    - `/setup-claudemap` should treat the `@claudemap-architect` path as the primary path, not an optional extra.
    - The packaged project includes a `claudemap-architect` subagent in `.claude/agents/` for system identification, graph refinement, and human-first graph restructuring.
    - If a cached Claude-authored graph already exists, do not replace it with a heuristic regeneration unless the user explicitly asks for `--force-refresh`.
    - If the user only wants to reopen the existing map UI, use `/open-claudemap` instead of rerunning setup.
    - Follow-up refreshes should use the `/refresh` command shipped in `.claude/commands/refresh.md`.
    - Graph refinements should prefer `${CLAUDE_SKILL_DIR}/skill/commands/refresh.js --enrichment-file ...` over rerunning setup so the current graph context is reused.
    - `/show` should be treated as a presentation-direction command, not just a low-level transport wrapper.
    
  • skill/commands/create-map.js11 KBf882e3e11656upstream ↗
    #!/usr/bin/env node
    import path from 'path'
    import { fileURLToPath } from 'url'
    import { resolveMapPaths } from '../lib/active-map.js'
    import { readCache, writeCache } from '../lib/cache.js'
    import { enrichScopedGraph } from '../lib/enrichment.js'
    import {
      DEFAULT_MAP_ID,
      createScopeDescriptor,
      findMapById,
      readManifest,
      resolveScopeAgainstGraph,
      setActiveMapId,
      upsertMapEntry,
      writeManifest,
    } from '../lib/map-manifest.js'
    import { readRuntimeGraph, renderGraph } from '../lib/mcp-client.js'
    import { GRAPH_SOURCES } from '../lib/contracts/graph-sources.js'
    import {
      allocateMapId,
      buildScopedGraphFromRoot,
      buildScopedSnapshot,
      createScopedMapFileSet,
      slugifyMapId,
    } from '../lib/scoped-map.js'
    import { runCommand, exitOnError } from '../lib/command-harness/run-command.js'
    import { success, failure, ERROR_CODES } from '../lib/contracts/errors.js'
    import { loadEnrichmentFileStrict, cleanupEnrichmentFile } from '../lib/command-harness/enrichment-io.js'
    
    function parseScopeInput(scopeJson) {
      if (scopeJson) {
        const parsedValue = JSON.parse(scopeJson)
        return {
          scope: parsedValue.scope || parsedValue,
          label: parsedValue.label || parsedValue.scope?.label || null,
          summary: parsedValue.summary || parsedValue.scope?.summary || null,
          mapId: parsedValue.mapId || null,
          instructions: parsedValue.instructions || null,
        }
      }
    
      return null
    }
    
    function readRootGraph(projectRoot, rootMapEntry) {
      const rootMapPaths = resolveMapPaths(projectRoot, rootMapEntry)
      const runtimeGraph = readRuntimeGraph(rootMapPaths.graphPath)
    
      if (Array.isArray(runtimeGraph.nodes) && runtimeGraph.nodes.length > 0) {
        return runtimeGraph
      }
    
      const rootCache = readCache(projectRoot, { relativePath: rootMapEntry.cachePath })
    
      if (Array.isArray(rootCache?.graph?.nodes) && rootCache.graph.nodes.length > 0) {
        return rootCache.graph
      }
    
      throw new Error('No root ClaudeMap graph found. Run /setup-claudemap first.')
    }
    
    function findExistingMapForSystem(manifest, rootGraph, systemId) {
      return (
        manifest.maps.find((mapEntry) => {
          if (mapEntry.id === DEFAULT_MAP_ID || !mapEntry.scope) {
            return false
          }
    
          const resolvedScope = resolveScopeAgainstGraph(mapEntry.scope, rootGraph)
          return resolvedScope?.system?.id === systemId
        }) || null
      )
    }
    
    async function handleCreateMap({ ctx, args }) {
      const projectRoot = ctx.projectRoot
      const scopePayload = parseScopeInput(args.scopeJson)
    
      if (!scopePayload) {
        return failure(ERROR_CODES.INVALID_ARGUMENT, 'Missing scoped map target. Pass --scope-json.')
      }
    
      const { scope, label, summary, mapId, instructions } = scopePayload
      const shouldActivate = !args.noActivate
      const enrichmentFile = args.enrichmentFile
      const enrichmentResponseText = enrichmentFile ? loadEnrichmentFileStrict(enrichmentFile) : null
    
      if (!scope?.rootSystemId && !scope?.rootSystemLabel && !scope?.filePathHint) {
        return failure(ERROR_CODES.INVALID_ARGUMENT, 'Invalid scope payload. Missing rootSystemId or rootSystemLabel.')
      }
    
      let manifest = readManifest(projectRoot)
      const rootMapEntry = findMapById(manifest, DEFAULT_MAP_ID)
      const rootGraph = readRootGraph(projectRoot, rootMapEntry)
      const resolvedScope = resolveScopeAgainstGraph(scope, rootGraph)
    
      if (!resolvedScope) {
        return failure(
          ERROR_CODES.INVALID_ARGUMENT,
          `Could not resolve scoped map target: ${scope.rootSystemLabel || scope.rootSystemId}`,
        )
      }
    
      const resolvedSystemNode = rootGraph.nodes.find((node) => node.id === resolvedScope.system.id)
      const existingMapEntry = findExistingMapForSystem(manifest, rootGraph, resolvedScope.system.id)
      const priorGraph = existingMapEntry
        ? readCache(projectRoot, { relativePath: existingMapEntry.cachePath })?.graph || null
        : null
    
      let scopedGraph
      let graphSource
    
      if (enrichmentResponseText) {
        const scopedSnapshot = buildScopedSnapshot(rootGraph, resolvedScope.system.id, {
          label: label || resolvedSystemNode?.label,
          ancestorPath: scope.ancestorPath || [],
          priorGraph,
          instructions,
        })
        scopedGraph = await enrichScopedGraph(scopedSnapshot, {
          responseText: enrichmentResponseText,
          strict: true,
        })
    
        if (!Array.isArray(scopedGraph?.nodes) || scopedGraph.nodes.length === 0) {
          return failure(
            ERROR_CODES.INVALID_ARGUMENT,
            'Scoped enrichment parsed to an empty graph. Refusing to overwrite the scoped map with an empty result.',
          )
        }
    
        graphSource = GRAPH_SOURCES.CLAUDE_SCOPED
      } else {
        scopedGraph = buildScopedGraphFromRoot(rootGraph, resolvedScope.system.id)
        graphSource = scopedGraph.meta?.source || GRAPH_SOURCES.SCOPED_MAP
      }
    
      const nextScope = createScopeDescriptor(rootGraph, resolvedScope.system.id)
      const requestedMapId = mapId ? slugifyMapId(mapId) : null
      const requestedMapEntry = requestedMapId ? findMapById(manifest, requestedMapId) : null
    
      if (requestedMapEntry && requestedMapEntry.id !== existingMapEntry?.id) {
        return failure(ERROR_CODES.INVALID_ARGUMENT, `ClaudeMap id already exists: ${requestedMapId}`)
      }
    
      const nextMapId = existingMapEntry
        ? existingMapEntry.id
        : requestedMapId
          ? requestedMapId
          : allocateMapId(manifest, label || resolvedSystemNode?.label || resolvedScope.system.id)
      const nextMapEntry = {
        ...(existingMapEntry || createScopedMapFileSet(nextMapId)),
        id: nextMapId,
        label: label || existingMapEntry?.label || resolvedSystemNode?.label || nextMapId,
        summary:
          summary || existingMapEntry?.summary || resolvedSystemNode?.summary || 'Scoped subsystem map',
        scope: nextScope,
      }
      const nextMapPaths = resolveMapPaths(projectRoot, nextMapEntry)
    
      writeCache(projectRoot, scopedGraph, scopedGraph.files, { relativePath: nextMapEntry.cachePath })
    
      ctx.mcp.graphPath = nextMapPaths.graphPath
      ctx.mcp.statePath = nextMapPaths.statePath
      await renderGraph(ctx.mcp, scopedGraph)
    
      upsertMapEntry(manifest, nextMapEntry)
    
      if (shouldActivate) {
        setActiveMapId(manifest, nextMapEntry.id)
      }
    
      manifest = writeManifest(projectRoot, manifest)
    
      if (enrichmentFile) {
        cleanupEnrichmentFile(enrichmentFile)
      }
    
      console.log(
        `${existingMapEntry ? 'Updated' : 'Created'} map ${nextMapEntry.id} (${nextMapEntry.label})`,
      )
      console.log(`Project root: ${projectRoot}`)
      console.log(`Scope: ${nextScope.rootSystemLabel}`)
      console.log(`Active map: ${manifest.activeMapId}`)
      console.log(`Graph source: ${graphSource}`)
    
      if (graphSource !== GRAPH_SOURCES.CLAUDE_SCOPED) {
        console.log(
          'Note: graph built from root filter. For richer subsystem grouping, rerun with --enrichment-file after an @claudemap-architect pass.',
        )
      }
    
      return success()
    }
    
    export const CREATE_MAP_COMMAND = {
      name: 'create-map',
      summary: 'Create or refresh a scoped ClaudeMap for a major subsystem and switch to it.',
      argumentHint: '{"scope":{"rootSystemId":"...","rootSystemLabel":"...","ancestorPath":["..."]},"label":"...","summary":"..."} | <natural language scope description>',
      body: `Use the bundled ClaudeMap scoped-map command. Scoped maps are first-class architect views, not raw filters of the root graph.
    
    Workflow:
    1. Treat the current working directory as the target project root unless the user gave a different path.
    2. Resolve the scope from the user's argument. If it is the JSON payload copied from ClaudeMap's "Create map?" affordance, use it as-is. If it is a natural language request (e.g. "map the auth system"), inspect the current root runtime graph at \`.claude/skills/claudemap-runtime/app/public/graph/claudemap-runtime.json\` and pick the best matching system node, then synthesize a scope payload with \`rootSystemId\`, \`rootSystemLabel\`, and \`ancestorPath\`.
    3. Read \`.claude/skills/claudemap-runtime/skill/prompts/scoped-enrichment.txt\`. This is the dedicated scoped prompt - do not reuse the root enrichment prompt.
    4. Build a scoped snapshot payload for \`@claudemap-architect\` containing: the repo/branch meta, the scope block, the filtered file list for that subsystem (pulled from the root graph), and - if the target map already has a cached scoped graph - include its graph as \`priorGraph\` so the architect can refine rather than rebuild. Include any user-provided refinement instructions under \`instructions\`.
    5. Call \`@claudemap-architect\` with the scoped prompt + payload. Tell it to return valid graph JSON only, to emit richer internal subsystems (2-6) and edges than the root graph, and to decide on its own whether to edit the prior graph in place or rebuild based on the intent of the request.
    6. **Wait for the \`@claudemap-architect\` Task call to fully return**, then save the returned JSON to \`.claude/skills/claudemap-runtime/tmp/claudemap-enrichment.json\`. Do not run create-map until that file contains valid graph JSON.
    7. Run \`.claude/skills/claudemap-runtime/skill/commands/create-map.js\` with Node and pass the scope payload through \`--scope-json\`, the refinement instructions (if any) through \`--instructions\`, and the enrichment file through \`--enrichment-file\`. The command deletes the tmp file after it reads it.
    8. Report the created or updated map id, label, scope root, graph source, and resulting active map id. If the graph source is not \`claude-scoped\`, warn the user that the scoped map is a filtered fallback view and suggest rerunning with architect enrichment.
    9. If the payload is missing or invalid, ask the user to click "Create map?" in ClaudeMap again and paste the copied command, or describe the subsystem they want scoped.
    10. End with a short feedback prompt after the scoped map renders, for example: \`Does this map look right, or should I refine it?\`
    11. If the user says the map is good, stop there.
    12. If the user asks for refinement, reuse the scoped map's cache graph (the \`cachePath\` for that map in the target project's repo-root \`claudemap-maps.json\`) as \`priorGraph\` in the architect payload, pass the refinement instructions through \`instructions\`, save the architect's response to \`.claude/skills/claudemap-runtime/tmp/claudemap-enrichment.json\`, and rerun \`create-map.js\` with the same \`--scope-json\` payload plus \`--enrichment-file\` and \`--instructions\` so the scoped graph iterates in place for the same map entry.
    13. After the refined graph renders, ask the same short feedback prompt again.`,
      positional: {
        name: 'projectRoot',
        required: false,
      },
      flags: [
        { name: 'scope-json', type: 'string' },
        { name: 'map-id', type: 'string' },
        { name: 'no-activate', type: 'boolean' },
        { name: 'stdio-mcp', type: 'boolean' },
        { name: 'enrichment-file', type: 'string' },
        { name: 'instructions', type: 'string' },
      ],
      withMcp: true,
      handler: handleCreateMap,
    }
    
    export async function main(argv = process.argv.slice(2)) {
      return runCommand(CREATE_MAP_COMMAND, argv)
    }
    
    function isDirectExecution(fileUrl) {
      return process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(fileUrl)
    }
    
    if (isDirectExecution(import.meta.url)) {
      main().catch(exitOnError)
    }
    
  • skill/commands/open-claudemap.js3.8 KB5e1a1a1bd1edupstream ↗
    #!/usr/bin/env node
    import path from 'path'
    import { fileURLToPath } from 'url'
    import { launchClaudeMapWindow } from '../lib/launcher.js'
    import { readRuntimeGraph } from '../lib/mcp-client.js'
    import { GRAPH_SOURCES } from '../lib/contracts/graph-sources.js'
    import { runCommand, exitOnError } from '../lib/command-harness/run-command.js'
    import { success } from '../lib/contracts/errors.js'
    
    const DEFAULT_URL = 'http://127.0.0.1:5173'
    
    function getGraphStats(graphPath) {
      try {
        const runtimeGraph = readRuntimeGraph(graphPath)
        const nodes = Array.isArray(runtimeGraph?.nodes) ? runtimeGraph.nodes : []
        const systems = nodes.filter((node) => node.type === 'system').length
        const files = Array.isArray(runtimeGraph?.files) ? runtimeGraph.files.length : 0
    
        return {
          exists: nodes.length > 0,
          nodeCount: nodes.length,
          systemCount: systems,
          fileCount: files,
          source: runtimeGraph?.meta?.source || GRAPH_SOURCES.UNKNOWN,
          repoName: runtimeGraph?.meta?.repoName || 'unknown',
        }
      } catch {
        return {
          exists: false,
          nodeCount: 0,
          systemCount: 0,
          fileCount: 0,
          source: GRAPH_SOURCES.UNKNOWN,
          repoName: 'unknown',
        }
      }
    }
    
    async function handleOpenClaudemap({ ctx, args }) {
      const openBrowser = args.openBrowser || false
      const startApp = args.startApp !== false
      const activeMap = ctx.activeMap
      const graphStats = getGraphStats(activeMap.graphPath)
      const launchState = await launchClaudeMapWindow({
        startIfNeeded: startApp,
        openBrowser,
        url: DEFAULT_URL,
      })
    
      if (graphStats.exists) {
        console.log(
          `ClaudeMap open - loaded existing ${activeMap.mapId} graph for ${graphStats.repoName} with ${graphStats.systemCount} systems across ${graphStats.fileCount} files`,
        )
        console.log(`Graph source: ${graphStats.source}`)
      } else {
        console.log('ClaudeMap open - app runtime is available, but no graph is loaded yet')
        console.log('Run /setup-claudemap first to analyze a project and render a graph')
      }
    
      if (!launchState.running && !launchState.started) {
        console.log(`App server not detected at ${launchState.url}. Run \`npm run dev\` to view the graph.`)
      } else if (launchState.started && launchState.ready) {
        console.log(`Started app dev server at ${launchState.url}`)
      } else if (launchState.started) {
        console.log(`Started app dev server process, but it is not reachable yet at ${launchState.url}`)
      } else if (launchState.running) {
        console.log(`App server ready at ${launchState.url}`)
      }
    
      if (launchState.openedBrowser) {
        console.log('Opened ClaudeMap in the browser')
      }
    
      return success()
    }
    
    export const OPEN_CLAUDEMAP_COMMAND = {
      name: 'open-claudemap',
      summary: 'Open the bundled ClaudeMap app for the current project without rebuilding the graph.',
      disableModelInvocation: true,
      body: `Use the bundled ClaudeMap open command to bring up the existing map runtime.
    
    Steps:
    1. Resolve the bundled command script at \`.claude/skills/claudemap-runtime/skill/commands/open-claudemap.js\`.
    2. Run the open command with Node.
    3. If a graph is already loaded, report the repo name, graph source, system count, and file count.
    4. If no graph is loaded yet, tell the user to run \`/setup-claudemap\` first.
    5. Report whether the app server was reused, started, or still unavailable.`,
      positional: {
        name: 'projectRoot',
        required: false,
      },
      flags: [
        { name: 'open-browser', type: 'boolean' },
        { name: 'start-app', type: 'boolean' },
      ],
      handler: handleOpenClaudemap,
    }
    
    export async function main(argv = process.argv.slice(2)) {
      return runCommand(OPEN_CLAUDEMAP_COMMAND, argv)
    }
    
    function isDirectExecution(fileUrl) {
      return process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(fileUrl)
    }
    
    if (isDirectExecution(import.meta.url)) {
      main().catch(exitOnError)
    }
    
  • skill/commands/refresh.js11 KB953efcf5fc0dupstream ↗
    #!/usr/bin/env node
    import path from 'path'
    import { fileURLToPath } from 'url'
    import { resolveMapPaths } from '../lib/active-map.js'
    import { readCache, writeCache } from '../lib/cache.js'
    import { diffFiles } from '../lib/differ.js'
    import {
      enrichGraph,
      hasEnrichmentResponseOverride,
      selectPreferredGraph,
    } from '../lib/enrichment.js'
    import { collectProjectSnapshot } from '../lib/file-walker.js'
    import {
      DEFAULT_MAP_ID,
      createScopeDescriptor,
      findMapById,
      readManifest,
      resolveScopeAgainstGraph,
      writeManifest,
    } from '../lib/map-manifest.js'
    import { renderGraph } from '../lib/mcp-client.js'
    import { buildScopedGraphFromRoot } from '../lib/scoped-map.js'
    import { GRAPH_SOURCES } from '../lib/contracts/graph-sources.js'
    import { runCommand, exitOnError } from '../lib/command-harness/run-command.js'
    import { success } from '../lib/contracts/errors.js'
    import { loadEnrichmentFileStrict, cleanupEnrichmentFile, readEnrichmentArg } from '../lib/command-harness/enrichment-io.js'
    
    function formatRenderMode(skipRender, mcpClient, graphSource) {
      if (skipRender) {
        return 'skipped'
      }
    
      if (mcpClient?.fallbackReason) {
        return `full-render (stdio fallback:file-shim) (${graphSource})`
      }
    
      return `full-render (${graphSource})`
    }
    
    async function renderMapGraph(mcpClient, mapPaths, graphData) {
      if (!mcpClient) {
        return
      }
    
      mcpClient.graphPath = mapPaths.graphPath
      mcpClient.statePath = mapPaths.statePath
      await renderGraph(mcpClient, graphData)
    }
    
    function scopeTouchedByChanges(priorScopedCache, changedPaths) {
      if (!priorScopedCache || !changedPaths || changedPaths.size === 0) {
        return false
      }
    
      const priorFiles = priorScopedCache.files || priorScopedCache.graph?.files || []
    
      for (const file of priorFiles) {
        const filePath = file.relativePath || file.path
        if (filePath && changedPaths.has(filePath)) {
          return true
        }
      }
    
      return false
    }
    
    async function refreshScopedMaps(projectRoot, manifest, rootGraph, mcpClient, options = {}) {
      const changedPaths = options.changedPaths || new Set()
      const rootRestructured = options.rootRestructured === true
      let refreshedCount = 0
      let staleCount = 0
      let needsRebuildCount = 0
      let skippedCount = 0
    
      for (const mapEntry of manifest.maps) {
        if (mapEntry.id === DEFAULT_MAP_ID || !mapEntry.scope) {
          continue
        }
    
        const resolvedScope = resolveScopeAgainstGraph(mapEntry.scope, rootGraph)
    
        if (!resolvedScope) {
          mapEntry.scope = {
            ...mapEntry.scope,
            stale: true,
            needsRebuild: true,
          }
          staleCount += 1
          continue
        }
    
        const priorCache = readCache(projectRoot, { relativePath: mapEntry.cachePath })
        const scopeTouched = rootRestructured || scopeTouchedByChanges(priorCache, changedPaths)
    
        if (!scopeTouched && priorCache?.graph?.meta?.source === GRAPH_SOURCES.CLAUDE_SCOPED) {
          // Scope untouched and we previously had an architect-enriched graph.
          // Preserve it. Just clear any stale flag and update the scope descriptor.
          mapEntry.scope = {
            ...createScopeDescriptor(rootGraph, resolvedScope.system.id),
            stale: false,
            needsRebuild: false,
          }
          skippedCount += 1
          continue
        }
    
        const nextScope = createScopeDescriptor(rootGraph, resolvedScope.system.id)
        const scopedGraph = buildScopedGraphFromRoot(rootGraph, resolvedScope.system.id)
    
        mapEntry.scope = {
          ...nextScope,
          stale: false,
          // Mark for architect rebuild on next open because we just rebuilt
          // this scoped map from the root filter, which loses scoped-specific grouping.
          needsRebuild: priorCache?.graph?.meta?.source === GRAPH_SOURCES.CLAUDE_SCOPED,
        }
        writeCache(projectRoot, scopedGraph, scopedGraph.files, { relativePath: mapEntry.cachePath })
    
        if (mcpClient) {
          await renderMapGraph(mcpClient, resolveMapPaths(projectRoot, mapEntry), scopedGraph)
        }
    
        if (mapEntry.scope.needsRebuild) {
          needsRebuildCount += 1
        }
    
        refreshedCount += 1
      }
    
      return { refreshedCount, staleCount, needsRebuildCount, skippedCount }
    }
    
    async function buildRootGraph(snapshot, cache, options) {
      const nextGraph = await enrichGraph(snapshot, options)
    
      if (!cache) {
        return {
          graph: nextGraph,
          preservedExisting: false,
          existingSource: null,
          candidateSource: nextGraph.meta?.source || 'generated',
        }
      }
    
      return selectPreferredGraph(cache.graph, nextGraph, {
        forceRefresh: options.forceRefresh,
        allowLowerPriorityOverwrite: options.allowLowerPriorityOverwrite,
      })
    }
    
    async function handleUpdate({ ctx, args }) {
      const projectRoot = ctx.projectRoot
      const forceRefresh = args.forceRefresh || false
      const skipRender = args.noRender || false
      const enrichmentFile = args.enrichmentFile
      const responseText = enrichmentFile ? loadEnrichmentFileStrict(enrichmentFile) : null
      const enrichmentStrict = Boolean(enrichmentFile)
      let manifest = writeManifest(projectRoot, readManifest(projectRoot))
      const rootMapEntry = findMapById(manifest, DEFAULT_MAP_ID)
      const rootMapPaths = resolveMapPaths(projectRoot, rootMapEntry)
      const snapshot = collectProjectSnapshot(projectRoot)
      const cache = readCache(projectRoot, { relativePath: rootMapEntry.cachePath })
      const hasExplicitEnrichmentInput = Boolean(responseText) || hasEnrichmentResponseOverride()
      const mcpClient = ctx.mcp
    
      try {
        if (!cache || forceRefresh) {
          const rootGraphSelection = await buildRootGraph(snapshot, null, {
            responseText,
            forceRefresh,
            allowLowerPriorityOverwrite: hasExplicitEnrichmentInput,
            strict: enrichmentStrict,
          })
    
          writeCache(projectRoot, rootGraphSelection.graph, snapshot.files, {
            relativePath: rootMapEntry.cachePath,
          })
    
          if (mcpClient) {
            await renderMapGraph(mcpClient, rootMapPaths, rootGraphSelection.graph)
          }
    
          const scopedRefresh = await refreshScopedMaps(
            projectRoot,
            manifest,
            rootGraphSelection.graph,
            mcpClient,
            { rootRestructured: true },
          )
          manifest = writeManifest(projectRoot, manifest)
    
          if (enrichmentFile) {
            cleanupEnrichmentFile(enrichmentFile)
          }
    
          console.log(
            forceRefresh
              ? 'Forced refresh requested. Ran a full ClaudeMap analysis.'
              : 'No existing cache found. Ran a full ClaudeMap analysis instead.',
          )
          console.log(`Updated - ${snapshot.totalFiles} files added, 0 removed, 0 changed`)
          console.log(`Project root: ${projectRoot}`)
          console.log(`Active map: ${manifest.activeMapId}`)
          console.log(`Refresh mode: ${formatRenderMode(skipRender, mcpClient, rootGraphSelection.graph.meta?.source || 'generated')}`)
          console.log(
            `Maps refreshed: root + ${scopedRefresh.refreshedCount} scoped (${scopedRefresh.staleCount} stale)`,
          )
          return success()
        }
    
        const diff = diffFiles(snapshot.files, cache)
        const hasChanges = diff.added.length || diff.removed.length || diff.changed.length
        const hasRefinementRequest = hasExplicitEnrichmentInput
    
        if (!hasChanges && !hasRefinementRequest) {
          console.log('No changes detected')
          console.log(`Project root: ${projectRoot}`)
          console.log(`Active map: ${manifest.activeMapId}`)
          return success()
        }
    
        const changedPaths = new Set()
        for (const fileRecord of diff.added || []) {
          const changedPath = fileRecord.relativePath || fileRecord.path
          if (changedPath) changedPaths.add(changedPath)
        }
        for (const fileRecord of diff.removed || []) {
          const changedPath = fileRecord.relativePath || fileRecord.path
          if (changedPath) changedPaths.add(changedPath)
        }
        for (const fileRecord of diff.changed || []) {
          const changedPath = fileRecord.relativePath || fileRecord.path
          if (changedPath) changedPaths.add(changedPath)
        }
    
        const preferredGraphSelection = await buildRootGraph(snapshot, cache, {
          responseText,
          forceRefresh,
          allowLowerPriorityOverwrite: hasExplicitEnrichmentInput,
          strict: enrichmentStrict,
        })
        const nextRootGraph = preferredGraphSelection.graph
    
        if (mcpClient) {
          await renderMapGraph(mcpClient, rootMapPaths, nextRootGraph)
        }
    
        if (!preferredGraphSelection.preservedExisting) {
          writeCache(projectRoot, nextRootGraph, snapshot.files, {
            relativePath: rootMapEntry.cachePath,
          })
        }
    
        const scopedRefresh = await refreshScopedMaps(projectRoot, manifest, nextRootGraph, mcpClient, {
          changedPaths,
          rootRestructured: hasRefinementRequest && !preferredGraphSelection.preservedExisting,
        })
        manifest = writeManifest(projectRoot, manifest)
    
        if (enrichmentFile) {
          cleanupEnrichmentFile(enrichmentFile)
        }
    
        if (hasChanges) {
          console.log(
            `Updated - ${diff.added.length} files added, ${diff.removed.length} removed, ${diff.changed.length} changed`,
          )
        } else {
          console.log('No file changes detected. Applied graph refinement feedback.')
        }
        console.log(`Project root: ${projectRoot}`)
        console.log(`Active map: ${manifest.activeMapId}`)
    
        if (preferredGraphSelection.preservedExisting) {
          console.log(
            `Refresh mode: preserved existing ${preferredGraphSelection.existingSource} graph over ${preferredGraphSelection.candidateSource}`,
          )
          console.log('Graph cache was not replaced. Use --force-refresh to allow a lower-priority regeneration.')
        } else {
          console.log(
            `Refresh mode: ${formatRenderMode(skipRender, mcpClient, nextRootGraph.meta?.source || 'generated')}`,
          )
        }
    
        console.log(
          `Maps refreshed: root + ${scopedRefresh.refreshedCount} scoped (${scopedRefresh.staleCount} stale)`,
        )
        return success()
      } catch (error) {
        throw error
      }
    }
    
    export const UPDATE_COMMAND = {
      name: 'update',
      slashName: 'refresh',
      summary: 'Refresh the bundled ClaudeMap graph for the current project after local code changes.',
      argumentHint: '[project-root]',
      disableModelInvocation: true,
      body: `Use the bundled ClaudeMap refresh command to update the graph for the current working directory.
    
    Steps:
    1. Treat the current working directory as the target project root unless the user gave a different path.
    2. Resolve the bundled command script at \`.claude/skills/claudemap-runtime/skill/commands/refresh.js\`.
    3. Run the refresh command with Node for the target project root.
    4. Report added, removed, and changed file counts plus the refresh mode and scoped map refresh summary.
    5. Preserve any cached Claude-authored graph unless the user explicitly asks for a force refresh.
    6. Scoped maps are refreshed change-aware: maps whose files did not change keep their architect-authored graph, maps whose files did change are rebuilt from the root graph filter and flagged \`needsRebuild\` so the next \`/create-map\` pass can rerun the architect for them.`,
      positional: {
        name: 'projectRoot',
        required: false,
      },
      flags: [
        { name: 'force-refresh', type: 'boolean' },
        { name: 'no-render', type: 'boolean' },
        { name: 'stdio-mcp', type: 'boolean' },
        { name: 'enrichment-file', type: 'string' },
      ],
      withMcp: {
        mode: 'auto',
        required: false,
      },
      handler: handleUpdate,
    }
    
    export async function main(argv = process.argv.slice(2)) {
      return runCommand(UPDATE_COMMAND, argv)
    }
    
    function isDirectExecution(fileUrl) {
      return process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(fileUrl)
    }
    
    if (isDirectExecution(import.meta.url)) {
      main().catch(exitOnError)
    }
    
  • skill/commands/setup-claudemap.js8.8 KB0ff1f0ba0d4eupstream ↗
    #!/usr/bin/env node
    import path from 'path'
    import { fileURLToPath } from 'url'
    import { collectProjectSnapshot } from '../lib/file-walker.js'
    import {
      enrichGraph,
      hasEnrichmentResponseOverride,
      selectPreferredGraph,
    } from '../lib/enrichment.js'
    import { isCacheStale, readCache, writeCache } from '../lib/cache.js'
    import { launchClaudeMapWindow } from '../lib/launcher.js'
    import { resolveMapPaths } from '../lib/active-map.js'
    import {
      DEFAULT_MAP_ID,
      ensureManifestForSetup,
      findMapById,
      setActiveMapId,
      writeManifest,
    } from '../lib/map-manifest.js'
    import { renderGraph } from '../lib/mcp-client.js'
    import { GRAPH_SOURCES } from '../lib/contracts/graph-sources.js'
    import { runCommand, exitOnError } from '../lib/command-harness/run-command.js'
    import { success } from '../lib/contracts/errors.js'
    import { loadEnrichmentFileStrict, cleanupEnrichmentFile } from '../lib/command-harness/enrichment-io.js'
    
    function countSystems(graphData) {
      return graphData.nodes.filter((node) => node.type === 'system').length
    }
    
    function mcpClientModeLabel(renderResult, preferredLabel) {
      if (renderResult?.transport === GRAPH_SOURCES.FILE_SHIM && preferredLabel === 'stdio-mcp') {
        return 'stdio-mcp fallback:file-shim'
      }
    
      return preferredLabel
    }
    
    async function handleSetupClaudemap({ ctx, args }) {
      const projectRoot = ctx.projectRoot
      const forceRefresh = args.forceRefresh || false
      const skipRender = args.noRender || false
      const startApp = args.startApp !== false
      const openBrowser = args.openBrowser || false
      const useStdioMcp = args.stdioMcp || false
      const enrichmentFile = args.enrichmentFile
    
      const responseText = enrichmentFile ? loadEnrichmentFileStrict(enrichmentFile) : null
      let manifest = ensureManifestForSetup(projectRoot)
      setActiveMapId(manifest, DEFAULT_MAP_ID)
      manifest = writeManifest(projectRoot, manifest)
      const rootMapEntry = findMapById(manifest, DEFAULT_MAP_ID)
      const rootMapPaths = resolveMapPaths(projectRoot, rootMapEntry)
      const snapshot = collectProjectSnapshot(projectRoot)
      const existingCache = readCache(projectRoot, { relativePath: rootMapEntry.cachePath })
      const hasExplicitEnrichmentInput = Boolean(responseText) || hasEnrichmentResponseOverride()
      const useCache =
        !forceRefresh &&
        !hasExplicitEnrichmentInput &&
        existingCache &&
        !isCacheStale(projectRoot, snapshot.files, existingCache)
    
      let graphData
      let cacheMode = 'reused'
      let preservedGraphSelection = null
    
      if (useCache) {
        graphData = existingCache.graph
      } else {
        const nextGraph = await enrichGraph(snapshot, {
          responseText,
          strict: Boolean(enrichmentFile),
        })
        preservedGraphSelection = selectPreferredGraph(existingCache?.graph, nextGraph, {
          forceRefresh,
          allowLowerPriorityOverwrite: hasExplicitEnrichmentInput,
        })
        graphData = preservedGraphSelection.graph
    
        if (!preservedGraphSelection.preservedExisting) {
          writeCache(projectRoot, graphData, snapshot.files, { relativePath: rootMapEntry.cachePath })
          cacheMode = forceRefresh ? 'forced refresh' : 'regenerated'
        } else {
          cacheMode = `preserved existing ${preservedGraphSelection.existingSource} graph`
        }
      }
    
      let renderResult = null
    
      if (!skipRender) {
        renderResult = await renderGraph(ctx.mcp, graphData)
      }
    
      if (enrichmentFile) {
        cleanupEnrichmentFile(enrichmentFile)
      }
    
      const launchState = await launchClaudeMapWindow({
        startIfNeeded: startApp,
        openBrowser,
      })
    
      console.log(
        `ClaudeMap ready - analyzed ${snapshot.totalFiles} files across ${countSystems(graphData)} systems`,
      )
      console.log(`Project root: ${projectRoot}`)
      console.log(`Active map: ${DEFAULT_MAP_ID}`)
      console.log(`Graph source: ${graphData.meta?.source || (useCache ? 'cache' : 'generated')}`)
      console.log(`Cache mode: ${useCache ? 'reused' : cacheMode}`)
    
      if (preservedGraphSelection?.preservedExisting) {
        console.log(
          `Preserved cached ${preservedGraphSelection.existingSource} graph instead of replacing it with ${preservedGraphSelection.candidateSource}. Use --force-refresh to replace it.`,
        )
      }
    
      if (renderResult) {
        console.log(
          `Render transport: ${useStdioMcp ? `${mcpClientModeLabel(renderResult, 'stdio-mcp')}` : renderResult.transport} (${renderResult.graphPath || 'mcp'})`,
        )
      }
    
      if (!launchState.running && !launchState.started) {
        console.log('App server not detected at http://127.0.0.1:5173. Run `npm run dev` to view the graph.')
      } else if (launchState.started && launchState.ready) {
        console.log(`Started app dev server at ${launchState.url}`)
      } else if (launchState.started) {
        console.log(`Started app dev server process, but it is not reachable yet at ${launchState.url}`)
      } else if (launchState.running) {
        console.log(`App server ready at ${launchState.url}`)
      }
    
      if (launchState.openedBrowser) {
        console.log('Opened ClaudeMap in the browser')
      }
    
      return success()
    }
    
    export const SETUP_CLAUDEMAP_COMMAND = {
      name: 'setup-claudemap',
      summary: 'Build a detailed architecture map for the current repository and open it in ClaudeMap.',
      argumentHint: '[project-root]',
      body: `Set up ClaudeMap for the target repository.
    
    High-level goal:
    
    - snapshot the repository
    - ask the bundled \`@claudemap-architect\` subagent to build a detailed graph with intuitive human grouping
    - render that graph in the ClaudeMap UI
    
    Generated runtime graphs are written into \`.claude/skills/claudemap-runtime/app/public/graph/\` (served by the bundled app as \`/graph/*\`). Do not drop graph files anywhere else under \`claudemap-runtime/\` - the \`graph/\` subdirectory is the one canonical home for runtime graph outputs.
    
    Steps:
    1. Treat the current working directory as the target project root unless the user gave a different path.
    2. Resolve the bundled snapshot script at \`.claude/skills/claudemap-runtime/skill/commands/snapshot.js\`.
    3. Run the snapshot script and capture the repo snapshot JSON.
    4. Read \`.claude/skills/claudemap-runtime/skill/prompts/enrichment.txt\`.
    5. Use the \`@claudemap-architect\` subagent explicitly and provide:
       - the snapshot JSON
       - the enrichment contract
       - instructions to return only valid graph JSON
       - instructions to optimize for detailed systems, useful file/function depth, and human-intuitive grouping
    6. **Wait for the \`@claudemap-architect\` Task call to fully return**, then save the returned JSON to \`.claude/skills/claudemap-runtime/tmp/claudemap-enrichment.json\`. **Do not run the setup JS command until after this file exists with non-empty valid graph JSON.** Do not launch setup in parallel with the subagent call.
    7. Run \`.claude/skills/claudemap-runtime/skill/commands/setup-claudemap.js\` with \`--enrichment-file\` pointing to that JSON file. The setup command is strict: it will exit non-zero if the file is missing, empty, or unparseable, and it will not fall back to a heuristic graph. If that happens, fix the architect output first and rerun - do not rerun setup without \`--enrichment-file\`.
    8. Add \`--force-refresh\` only when the user explicitly asks for a full rebuild.
    9. If the subagent cannot produce valid JSON after two attempts, stop and tell the user the architect pass failed. Do not silently retry setup without the enrichment file - that would render a heuristic graph and pollute the cache.
    10. Report the analyzed file count, system count, graph source, render transport, and app readiness.
    11. End with a short feedback prompt after the graph opens, for example: \`Does this map look right, or should I refine it?\`
    12. If the user says the map is good, stop there.
    13. If the user asks for refinement, reuse the current root cache graph from \`claudemap-cache.json\` as context, send that graph plus the requested changes back through \`@claudemap-architect\`, **wait for that Task call to fully return**, save the refined JSON to the same \`tmp/claudemap-enrichment.json\` path, and only then run \`.claude/skills/claudemap-runtime/skill/commands/refresh.js\` with \`--enrichment-file\` instead of telling the user to rerun setup from scratch. The refresh command applies the same strict enrichment validation as setup.
    14. After the refined graph renders, ask the same short feedback prompt again.`,
      positional: {
        name: 'projectRoot',
        required: false,
      },
      flags: [
        { name: 'force-refresh', type: 'boolean' },
        { name: 'no-render', type: 'boolean' },
        { name: 'start-app', type: 'boolean' },
        { name: 'open-browser', type: 'boolean' },
        { name: 'stdio-mcp', type: 'boolean' },
        { name: 'enrichment-file', type: 'string' },
      ],
      withMcp: {
        mode: 'auto',
        required: false,
      },
      handler: handleSetupClaudemap,
    }
    
    export async function main(argv = process.argv.slice(2)) {
      return runCommand(SETUP_CLAUDEMAP_COMMAND, argv)
    }
    
    function isDirectExecution(fileUrl) {
      return process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(fileUrl)
    }
    
    if (isDirectExecution(import.meta.url)) {
      main().catch(exitOnError)
    }
    
  • skill/commands/show.js19 KB7a9b390d3a02upstream ↗
    #!/usr/bin/env node
    import {
      clearHighlight,
      clearCaption,
      guidedFlow,
      highlightNodes,
      navigateTo,
      presentStep,
      readRuntimeGraph,
      setPresentationMode,
      setHealthOverlay,
      showCaption,
    } from '../lib/mcp-client.js'
    import { PRESENTATION_MODES, PRESENTATION_MODE_LIST } from '../lib/contracts/presentation.js'
    import { runCommand, exitOnError } from '../lib/command-harness/run-command.js'
    import { success, failure, ERROR_CODES } from '../lib/contracts/errors.js'
    import { fileURLToPath } from 'url'
    import path from 'path'
    
    const CURRENT_FILE_PATH = fileURLToPath(import.meta.url)
    
    function scoreNode(node, query) {
      const normalizedQuery = query.toLowerCase()
      const label = String(node.label || '').toLowerCase()
      const filePath = String(node.filePath || '').toLowerCase()
      const id = String(node.id || '').toLowerCase()
    
      if (id === normalizedQuery) return 100
      if (label === normalizedQuery) return 95
      if (filePath === normalizedQuery) return 90
      if (label.includes(normalizedQuery)) return 70
      if (filePath.includes(normalizedQuery)) return 65
      if (id.includes(normalizedQuery)) return 60
      return -1
    }
    
    function resolveNode(graph, query) {
      const rankedNodes = graph.nodes
        .map((node) => ({ node, score: scoreNode(node, query) }))
        .filter((entry) => entry.score >= 0)
        .sort((left, right) => right.score - left.score || left.node.label.localeCompare(right.node.label))
    
      return rankedNodes[0]?.node || null
    }
    
    function parseQueryList(query) {
      return uniqueArray(
        query
          .split(',')
          .map((value) => value.trim())
          .filter(Boolean),
      )
    }
    
    function resolveNodes(graph, query) {
      return uniqueArray(parseQueryList(query)).map((queryPart) => {
        const node = resolveNode(graph, queryPart)
    
        if (!node) {
          throw new Error(`No node matched "${queryPart}"`)
        }
    
        return node
      })
    }
    
    function collectDescendantIds(nodes, parentId) {
      const descendants = []
      const queue = [parentId]
    
      while (queue.length) {
        const currentParentId = queue.shift()
        const children = nodes.filter((node) => node.parentId === currentParentId)
    
        for (const child of children) {
          descendants.push(child.id)
          queue.push(child.id)
        }
      }
    
      return descendants
    }
    
    function collectBranchIds(nodes, nodeId) {
      return [nodeId, ...collectDescendantIds(nodes, nodeId)]
    }
    
    function collectAncestorIds(nodes, nodeId) {
      const nodeById = new Map(nodes.map((node) => [node.id, node]))
      const ancestors = []
      let walker = nodeById.get(nodeId)
    
      while (walker?.parentId) {
        const parentNode = nodeById.get(walker.parentId)
    
        if (!parentNode) {
          break
        }
    
        ancestors.unshift(parentNode.id)
        walker = parentNode
      }
    
      return ancestors
    }
    
    function buildHighlightNodeIds(graph, node) {
      const ancestorIds = collectAncestorIds(graph.nodes, node.id)
    
      if (node.type === 'system') {
        return uniqueArray(collectBranchIds(graph.nodes, node.id))
      }
    
      if (node.type === 'file') {
        return uniqueArray([
          ...ancestorIds,
          node.id,
          ...collectDescendantIds(graph.nodes, node.id),
        ])
      }
    
      return uniqueArray([...ancestorIds, node.id])
    }
    
    function getDefaultZoomForNode(node) {
      if (node.type === 'function') {
        return 1.18
      }
    
      if (node.type === 'file') {
        return 1.04
      }
    
      return node.parentId ? 0.94 : 0.82
    }
    
    function findWorstNode(graph) {
      const severity = { red: 3, yellow: 2, green: 1 }
    
      return [...graph.nodes]
        .filter((node) => node.type === 'system' || node.type === 'file')
        .sort((left, right) => {
          const severityDelta = (severity[right.health] || 0) - (severity[left.health] || 0)
    
          if (severityDelta !== 0) {
            return severityDelta
          }
    
          return (right.lineCount || 0) - (left.lineCount || 0)
        })[0]
    }
    
    function parseIntentTarget(phrase, prefixes, suffixes = []) {
      let value = phrase
    
      for (const prefix of prefixes) {
        if (value.startsWith(prefix)) {
          value = value.slice(prefix.length)
          break
        }
      }
    
      for (const suffix of suffixes) {
        if (value.endsWith(suffix)) {
          value = value.slice(0, -suffix.length)
          break
        }
      }
    
      return value.trim()
    }
    
    function findDependentSystemIds(graph, targetSystemId) {
      return graph.edges
        .filter((edge) => edge.target === targetSystemId)
        .map((edge) => edge.source)
    }
    
    function buildGuidedSteps(graph, node) {
      if (node.type === 'system') {
        return collectBranchIds(graph.nodes, node.id).slice(0, 5)
      }
    
      if (node.type === 'file') {
        return [node.parentId, node.id, ...collectDescendantIds(graph.nodes, node.id).slice(0, 3)].filter(Boolean)
      }
    
      return [node.parentId, node.id].filter(Boolean)
    }
    
    async function revertToFreeMode(client) {
      await setPresentationMode(client, PRESENTATION_MODES.FREE, { resetScene: false })
    }
    
    function readGraphOrExit(graphPath) {
      const graph = readRuntimeGraph(graphPath)
    
      if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {
        throw new Error('No runtime graph found. Run /setup-claudemap first.')
      }
    
      return graph
    }
    
    function uniqueArray(values) {
      return [...new Set(values.filter(Boolean))]
    }
    
    async function handleClearHighlight({ ctx }) {
      await clearHighlight(ctx.mcp)
      console.log(`[${ctx.activeMap.mapId}] Cleared highlights`)
      return success()
    }
    
    async function handleClearCaption({ ctx }) {
      await clearCaption(ctx.mcp)
      console.log(`[${ctx.activeMap.mapId}] Cleared presentation caption`)
      return success()
    }
    
    async function handleHealth({ ctx, args }) {
      const value = args._positional?.[0]?.toLowerCase()
    
      if (!['on', 'off'].includes(value)) {
        return failure(ERROR_CODES.INVALID_ARGUMENT, 'Usage: health <on|off>')
      }
    
      await setHealthOverlay(ctx.mcp, value === 'on')
      console.log(`[${ctx.activeMap.mapId}] Health overlay ${value}`)
      return success()
    }
    
    async function handleMode({ ctx, args }) {
      const requestedMode = args._positional?.[0]?.toLowerCase()
      const mode = requestedMode === 'locked-demo' ? PRESENTATION_MODES.LOCKED : requestedMode
    
      if (![PRESENTATION_MODES.FREE, PRESENTATION_MODES.GUIDED, PRESENTATION_MODES.LOCKED].includes(mode)) {
        return failure(ERROR_CODES.INVALID_ARGUMENT, 'Usage: mode <free|guided|locked>')
      }
    
      await setPresentationMode(ctx.mcp, mode, {
        lockInput: mode === PRESENTATION_MODES.LOCKED,
      })
      console.log(`[${ctx.activeMap.mapId}] Presentation mode ${mode}`)
      return success()
    }
    
    async function handleCaption({ ctx, args }) {
      const body = args.body
    
      if (!body) {
        return failure(ERROR_CODES.MISSING_ARGUMENT, 'Usage: caption [--title <title>] [--step <step>] <body>')
      }
    
      await showCaption(ctx.mcp, body, {
        title: args.title || null,
        stepLabel: args.step || null,
      })
      console.log(`[${ctx.activeMap.mapId}] Caption updated${args.title ? `: ${args.title}` : ''}`)
      return success()
    }
    
    async function handleHighlight({ ctx, args }) {
      const query = args.query
    
      if (!query) {
        return failure(ERROR_CODES.MISSING_ARGUMENT, 'Usage: highlight <query[, query2 ...]> [--zoom <value>] [--explain "..."]')
      }
    
      const graph = readGraphOrExit(ctx.activeMap.graphPath)
      const resolvedNodes = resolveNodes(graph, query)
      const primaryNode = resolvedNodes[0]
      const nodeIds = uniqueArray(
        resolvedNodes.flatMap((node) => buildHighlightNodeIds(graph, node)),
      )
      const zoom = args.zoom ?? getDefaultZoomForNode(primaryNode)
    
      if (
        args.explain ||
        args.title ||
        args.step ||
        args.mode ||
        typeof args.lockInput === 'boolean'
      ) {
        await presentStep(ctx.mcp, {
          nodeId: primaryNode.id,
          nodeIds,
          zoom,
          mode: args.mode || PRESENTATION_MODES.GUIDED,
          lockInput: args.lockInput,
          title: args.title || null,
          stepLabel: args.step || null,
          explanation: args.explain || null,
        })
        if (!args.keepMode) {
          await revertToFreeMode(ctx.mcp)
        }
        console.log(`[${ctx.activeMap.mapId}] Presented ${resolvedNodes.map((node) => node.label).join(', ')}`)
        return success()
      }
    
      await highlightNodes(ctx.mcp, nodeIds)
      await navigateTo(ctx.mcp, primaryNode.id, zoom)
      console.log(
        `[${ctx.activeMap.mapId}] Highlighted ${resolvedNodes.map((node) => node.label).join(', ')} (${nodeIds.length} nodes)`,
      )
      return success()
    }
    
    async function handlePresent({ ctx, args }) {
      const query = args.query
    
      if (!query) {
        return failure(
          ERROR_CODES.MISSING_ARGUMENT,
          'Usage: present <query[, query2 ...]> [--title "..."] [--step "..."] [--explain "..."]',
        )
      }
    
      const graph = readGraphOrExit(ctx.activeMap.graphPath)
      const resolvedNodes = resolveNodes(graph, query)
      const primaryNode = resolvedNodes[0]
      const nodeIds = uniqueArray(
        resolvedNodes.flatMap((node) => buildHighlightNodeIds(graph, node)),
      )
      await presentStep(ctx.mcp, {
        nodeId: primaryNode.id,
        nodeIds,
        zoom: args.zoom ?? getDefaultZoomForNode(primaryNode),
        mode: args.mode || PRESENTATION_MODES.GUIDED,
        lockInput: args.lockInput,
        title: args.title || null,
        stepLabel: args.step || null,
        explanation: args.explain || null,
      })
      if (!args.keepMode) {
        await revertToFreeMode(ctx.mcp)
      }
      console.log(`[${ctx.activeMap.mapId}] Presented ${resolvedNodes.map((node) => node.label).join(', ')}`)
      return success()
    }
    
    async function handleNavigate({ ctx, args }) {
      const query = args.query
    
      if (!query) {
        return failure(ERROR_CODES.MISSING_ARGUMENT, 'Usage: navigate <query> [--zoom <value>]')
      }
    
      const graph = readGraphOrExit(ctx.activeMap.graphPath)
      const node = resolveNode(graph, query)
    
      if (!node) {
        return failure(ERROR_CODES.NO_NODE_MATCHED, `No node matched "${query}"`)
      }
    
      await navigateTo(ctx.mcp, node.id, args.zoom ?? getDefaultZoomForNode(node))
      console.log(`[${ctx.activeMap.mapId}] Navigating to ${node.label}`)
      return success()
    }
    
    async function handleFlow({ ctx, args }) {
      const queries = args._positional
    
      if (!queries || queries.length < 2) {
        return failure(ERROR_CODES.MISSING_ARGUMENT, 'Usage: flow <query1> <query2> [query3 ...]')
      }
    
      const graph = readGraphOrExit(ctx.activeMap.graphPath)
      const resolvedNodes = queries.map((query) => {
        const node = resolveNode(graph, query)
    
        if (!node) {
          throw new Error(`No node matched "${query}"`)
        }
    
        return node
      })
    
      await guidedFlow(
        ctx.mcp,
        resolvedNodes.map((node) => node.id),
        1200,
      )
      console.log(`[${ctx.activeMap.mapId}] Started guided flow across ${resolvedNodes.length} nodes`)
      return success()
    }
    
    async function handleAsk({ ctx, args }) {
      const phrase = args.query?.toLowerCase()
    
      if (!phrase) {
        return failure(ERROR_CODES.MISSING_ARGUMENT, 'Usage: ask "<phrase>"')
      }
    
      const graph = readGraphOrExit(ctx.activeMap.graphPath)
    
      if (phrase.includes("what's wrong") || phrase.includes('what is wrong')) {
        const worstNode = findWorstNode(graph)
    
        if (!worstNode) {
          return failure(ERROR_CODES.NO_NODE_MATCHED, 'Could not determine a worst node from the runtime graph')
        }
    
        await setHealthOverlay(ctx.mcp, true)
        await navigateTo(ctx.mcp, worstNode.id, 1.05)
        console.log(
          `[${ctx.activeMap.mapId}] ${worstNode.label}: ${worstNode.healthReason || 'This node has the highest current health severity.'}`,
        )
        return success()
      }
    
      if (phrase.startsWith('highlight ')) {
        const query = parseIntentTarget(phrase, ['highlight the ', 'highlight '], [' system'])
        const node = resolveNode(graph, query)
    
        if (!node) {
          return failure(ERROR_CODES.NO_NODE_MATCHED, `No node matched "${query}"`)
        }
    
        const nodeIds = buildHighlightNodeIds(graph, node)
        await highlightNodes(ctx.mcp, nodeIds)
        await navigateTo(ctx.mcp, node.id, getDefaultZoomForNode(node))
        console.log(`[${ctx.activeMap.mapId}] Highlighted ${node.label}`)
        return success()
      }
    
      if (phrase.startsWith('what depends on ')) {
        const query = parseIntentTarget(phrase, ['what depends on the ', 'what depends on '])
        const node = resolveNode(graph, query)
        const targetSystemId = node?.type === 'system' ? node.id : node?.parentId
    
        if (!node || !targetSystemId) {
          return failure(ERROR_CODES.NO_NODE_MATCHED, `No system matched "${query}"`)
        }
    
        const dependentSystemIds = findDependentSystemIds(graph, targetSystemId)
        const nodeIds = uniqueArray(
          dependentSystemIds.flatMap((systemId) => collectBranchIds(graph.nodes, systemId)),
        )
    
        await highlightNodes(ctx.mcp, nodeIds)
        console.log(
          nodeIds.length
            ? `[${ctx.activeMap.mapId}] Highlighted ${dependentSystemIds.length} dependent systems for ${node.label}`
            : `[${ctx.activeMap.mapId}] No systems currently depend on ${node.label}`,
        )
        return success()
      }
    
      if (phrase.startsWith('show me how ') && phrase.endsWith(' works')) {
        const query = parseIntentTarget(phrase, ['show me how '], [' works'])
        const node = resolveNode(graph, query)
    
        if (!node) {
          return failure(ERROR_CODES.NO_NODE_MATCHED, `No node matched "${query}"`)
        }
    
        const steps = buildGuidedSteps(graph, node)
        await guidedFlow(ctx.mcp, steps, 1200)
        console.log(`[${ctx.activeMap.mapId}] Started guided flow for ${node.label}`)
        return success()
      }
    
      return failure(ERROR_CODES.NO_INTENT_MATCH, `No built-in intent matched "${phrase}"`)
    }
    
    export const SHOW_COMMAND = {
      name: 'show',
      summary: 'Direct the live ClaudeMap session. Use it to focus the map, highlight architecture, present a step, compare regions, or show flow.',
      argumentHint: '[intent]',
      body: `Use ClaudeMap as a live presentation and navigation surface.
    
    Principles:
    
    - optimize for the fewest actions that make the user's intent visually obvious
    - prefer \`present\` when the user wants explanation plus focus
    - prefer \`highlight\` or \`navigate\` when the user wants quick emphasis without narration
    - prefer \`flow\` when the user wants sequence or dependency motion
    - keep the map legible and avoid noisy multi-step show-command spam
    
    Workflow:
    1. Resolve the bundled command script at \`.claude/skills/claudemap-runtime/skill/commands/show.js\`.
    2. Read the user request as presentation intent, not just a literal command request.
    3. If needed, inspect the currently active ClaudeMap runtime graph rather than assuming the root map. Prefer the bundled command's own active-map resolution over hardcoded runtime file paths.
    4. Translate the request into the smallest useful set of show commands.
    5. Run the show command or short command sequence with Node.
    6. Briefly report what changed in the UI.
    
    Built-in show actions include:
    - \`highlight <query> [--zoom <value>] [--explain "..."] [--keep-mode]\`
    - \`clear-highlight\`
    - \`present <query> [--title "..."] [--step "..."] [--explain "..."] [--keep-mode]\`
    - \`navigate <query> [--zoom <value>]\`
    - \`health <on|off>\`
    - \`mode <free|guided|locked>\`
    - \`caption [--title <title>] [--step <step>] <body>\`
    - \`clear-caption\`
    - \`flow <query1> <query2> [query3 ...]\`
    - \`ask "<phrase>"\`
    
    Mode handling:
    - \`present\` and \`highlight\` (with explain/title/step/mode/lock options) automatically revert the UI to free mode after the command runs, so one-shot \`/show\` requests never leave the user trapped in guided or locked mode.
    - Pass \`--keep-mode\` when you are running multiple presentation steps in sequence (for example inside \`/explain\`) and want the UI to remain in guided or locked mode between steps.
    - \`mode <x>\` still sets the mode explicitly and is not auto-reverted.
    
    Examples of intent translation:
    
    - "focus the auth system" -> \`navigate\` or \`highlight\`
    - "walk me through request handling" -> a short \`present\` or \`flow\` sequence
    - "show the riskiest area" -> \`ask "what's wrong"\`
    - "put the UI in guided mode and caption this step" -> \`mode\` plus \`caption\``,
      globalFlags: [
        { name: 'stdio-mcp', type: 'boolean' },
      ],
      actions: [
        {
          name: 'highlight',
          summary: 'Highlight one or more nodes and navigate to the primary node.',
          positional: {
            name: 'query',
            rest: true,
            required: true,
          },
          flags: [
            { name: 'zoom', type: 'number' },
            { name: 'explain', type: 'string' },
            { name: 'title', type: 'string' },
            { name: 'step', type: 'string' },
            { name: 'keep-mode', type: 'boolean' },
            { name: 'mode', type: 'enum', values: PRESENTATION_MODE_LIST },
            { name: 'lock', type: 'boolean' },
            { name: 'lockInput', type: 'boolean' },
          ],
          withMcp: true,
          handler: handleHighlight,
        },
        {
          name: 'clear-highlight',
          summary: 'Clear all node highlights.',
          withMcp: true,
          handler: handleClearHighlight,
        },
        {
          name: 'present',
          summary: 'Present one or more nodes with a caption and guidance.',
          positional: {
            name: 'query',
            rest: true,
            required: true,
          },
          flags: [
            { name: 'zoom', type: 'number' },
            { name: 'title', type: 'string' },
            { name: 'step', type: 'string' },
            { name: 'explain', type: 'string' },
            { name: 'keep-mode', type: 'boolean' },
            { name: 'mode', type: 'enum', values: PRESENTATION_MODE_LIST },
            { name: 'lockInput', type: 'boolean' },
          ],
          withMcp: true,
          handler: handlePresent,
        },
        {
          name: 'navigate',
          summary: 'Navigate to a node without highlighting.',
          positional: {
            name: 'query',
            rest: true,
            required: true,
          },
          flags: [
            { name: 'zoom', type: 'number' },
          ],
          withMcp: true,
          handler: handleNavigate,
        },
        {
          name: 'health',
          summary: 'Toggle health overlay.',
          positional: {
            name: 'value',
            required: true,
          },
          withMcp: true,
          handler: handleHealth,
        },
        {
          name: 'mode',
          summary: 'Set presentation mode.',
          positional: {
            name: 'mode',
            required: true,
          },
          withMcp: true,
          handler: handleMode,
        },
        {
          name: 'caption',
          summary: 'Show a caption on the graph.',
          positional: {
            name: 'body',
            rest: true,
            required: true,
          },
          flags: [
            { name: 'title', type: 'string' },
            { name: 'step', type: 'string' },
          ],
          withMcp: true,
          handler: handleCaption,
        },
        {
          name: 'clear-caption',
          summary: 'Clear the presentation caption.',
          withMcp: true,
          handler: handleClearCaption,
        },
        {
          name: 'flow',
          summary: 'Show a guided flow across multiple nodes.',
          positional: {
            name: 'queries',
            rest: true,
            required: true,
          },
          withMcp: true,
          handler: handleFlow,
        },
        {
          name: 'ask',
          summary: 'Ask an intent-driven question about the graph.',
          positional: {
            name: 'query',
            rest: true,
            required: true,
          },
          withMcp: true,
          handler: handleAsk,
        },
      ],
    }
    
    export async function main(argv = process.argv.slice(2)) {
      return runCommand(SHOW_COMMAND, argv)
    }
    
    function isDirectExecution(fileUrl) {
      return process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(fileUrl)
    }
    
    if (isDirectExecution(import.meta.url)) {
      main().catch(exitOnError)
    }
    
  • skill/commands/snapshot.js1.5 KB300aba6a9540upstream ↗
    #!/usr/bin/env node
    import fs from 'fs'
    import path from 'path'
    import { fileURLToPath } from 'url'
    import { collectProjectSnapshot } from '../lib/file-walker.js'
    import { runCommand, exitOnError } from '../lib/command-harness/run-command.js'
    import { success } from '../lib/contracts/errors.js'
    
    async function handleSnapshot({ ctx, args }) {
      const projectRoot = ctx.projectRoot
      const outputPath = args.output
      const snapshot = collectProjectSnapshot(projectRoot)
      const payload = JSON.stringify(snapshot, null, 2)
    
      if (outputPath) {
        const resolvedOutputPath = path.resolve(outputPath)
        fs.mkdirSync(path.dirname(resolvedOutputPath), { recursive: true })
        fs.writeFileSync(resolvedOutputPath, payload)
        console.log(`ClaudeMap snapshot ready at ${resolvedOutputPath}`)
        return success()
      }
    
      console.log(payload)
      return success()
    }
    
    export const SNAPSHOT_COMMAND = {
      name: 'snapshot',
      summary: 'Collect a project snapshot and output it as JSON.',
      argumentHint: '[project-root]',
      noSlashTemplate: true,
      positional: {
        name: 'projectRoot',
        required: false,
      },
      flags: [
        { name: 'output', type: 'string' },
      ],
      handler: handleSnapshot,
    }
    
    export async function main(argv = process.argv.slice(2)) {
      return runCommand(SNAPSHOT_COMMAND, argv)
    }
    
    function isDirectExecution(fileUrl) {
      return process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(fileUrl)
    }
    
    if (isDirectExecution(import.meta.url)) {
      main().catch(exitOnError)
    }
    
  • skill/lib/active-map.js1.4 KB48b286ceda87upstream ↗
    import { CACHE_FILENAME, RUNTIME_GRAPH_REL, RUNTIME_STATE_REL } from './contracts/paths.js'
    import { DEFAULT_MAP_ID, findMapById, getActiveMap, readManifest } from './map-manifest.js'
    import { resolveProjectPath, resolveRuntimePublicPath } from './runtime-paths.js'
    
    export function resolveMapRuntimePaths(mapEntry) {
      return {
        graphPath: resolveRuntimePublicPath(mapEntry?.graphPath, RUNTIME_GRAPH_REL),
        statePath: resolveRuntimePublicPath(mapEntry?.statePath, RUNTIME_STATE_REL),
      }
    }
    
    export function resolveMapCachePath(projectRoot, mapEntry) {
      return resolveProjectPath(projectRoot, mapEntry?.cachePath, CACHE_FILENAME)
    }
    
    export function resolveMapPaths(projectRoot, mapEntry) {
      return {
        cachePath: resolveMapCachePath(projectRoot, mapEntry),
        ...resolveMapRuntimePaths(mapEntry),
      }
    }
    
    export function resolveMapById(projectRoot, mapId) {
      const manifest = readManifest(projectRoot)
      const mapEntry = findMapById(manifest, mapId)
    
      if (!mapEntry) {
        throw new Error(`Unknown ClaudeMap id: ${mapId}`)
      }
    
      return {
        ...resolveMapPaths(projectRoot, mapEntry),
        mapId: mapEntry.id,
        manifest,
        mapEntry,
      }
    }
    
    export function resolveActiveMap(projectRoot) {
      const manifest = readManifest(projectRoot)
      const mapEntry = getActiveMap(manifest)
    
      return {
        ...resolveMapPaths(projectRoot, mapEntry),
        mapId: mapEntry?.id || DEFAULT_MAP_ID,
        manifest,
        mapEntry,
      }
    }
    
  • skill/lib/cache.js2.1 KBf48732b09ab1upstream ↗
    import { CACHE_FILENAME } from './contracts/paths.js'
    import { SCHEMA_NAMES } from './contracts/schemas/index.js'
    import { readJsonFile, resolveProjectPath, writeJsonFileAtomic } from './runtime-paths.js'
    
    const CACHE_SCHEMA_VERSION = 1
    
    function normalizeFileList(files) {
      return files.map((file) => ({
        path: file.path,
        relativePath: file.relativePath,
        name: file.name,
        directory: file.directory,
        lineCount: file.lineCount,
        language: file.language,
        mtimeMs: file.mtimeMs,
        imports: file.imports,
        exports: file.exports,
      }))
    }
    
    export function getCachePath(projectRoot, relativePath = CACHE_FILENAME) {
      return resolveProjectPath(projectRoot, relativePath, CACHE_FILENAME)
    }
    
    export function writeCache(projectRoot, graphData, currentFiles = [], options = {}) {
      const cachePath = getCachePath(projectRoot, options.relativePath)
      const cachePayload = {
        schemaVersion: CACHE_SCHEMA_VERSION,
        generatedAt: new Date().toISOString(),
        fileCount: currentFiles.length || graphData.nodes.filter((node) => node.type === 'file').length,
        files: normalizeFileList(currentFiles),
        graph: graphData,
      }
    
      writeJsonFileAtomic(cachePath, cachePayload)
      return cachePayload
    }
    
    export function readCache(projectRoot, options = {}) {
      const cachePath = getCachePath(projectRoot, options.relativePath)
      return readJsonFile(cachePath, () => null, { schema: SCHEMA_NAMES.CACHE })
    }
    
    export function isCacheStale(projectRoot, currentFileList, cache = readCache(projectRoot)) {
      if (!cache) {
        return true
      }
    
      const cachedFiles = Array.isArray(cache.files) ? cache.files : []
    
      if (cachedFiles.length !== currentFileList.length) {
        return true
      }
    
      const cachedFileMap = new Map(cachedFiles.map((file) => [file.path, file]))
    
      for (const file of currentFileList) {
        const cachedFile = cachedFileMap.get(file.path)
    
        if (!cachedFile) {
          return true
        }
    
        if (
          typeof file.mtimeMs === 'number' &&
          typeof cachedFile.mtimeMs === 'number' &&
          file.mtimeMs !== cachedFile.mtimeMs
        ) {
          return true
        }
    
        if (file.lineCount !== cachedFile.lineCount) {
          return true
        }
      }
    
      return false
    }
    
  • skill/lib/command-harness/enrichment-io.js1.1 KB24843265f797upstream ↗
    import fs from 'fs'
    import { ClaudeMapError, ERROR_CODES } from '../contracts/errors.js'
    
    export function loadEnrichmentFileStrict(filePath) {
      if (!fs.existsSync(filePath)) {
        throw new ClaudeMapError(
          ERROR_CODES.INVALID_ARGUMENT,
          `Enrichment file not found: ${filePath}`,
          'Ensure the @claudemap-architect subagent wrote the file before running this command.',
        )
      }
    
      const content = fs.readFileSync(filePath, 'utf8').trim()
    
      if (!content) {
        throw new ClaudeMapError(
          ERROR_CODES.INVALID_ARGUMENT,
          'Enrichment file is empty',
          'The architect subagent may have failed. Check its output and retry.',
        )
      }
    
      return content
    }
    
    export function cleanupEnrichmentFile(filePath) {
      try {
        if (fs.existsSync(filePath)) {
          fs.unlinkSync(filePath)
        }
      } catch {
        // Best-effort cleanup; swallow ENOENT and permission errors
      }
    }
    
    export function readEnrichmentArg(args) {
      // Convenience helper for commands that accept --enrichment-file
      if (!args.enrichmentFile) {
        return null
      }
    
      return loadEnrichmentFileStrict(args.enrichmentFile)
    }
    
  • skill/lib/command-harness/log.js1014 B8fd979b673c4upstream ↗
    // Structured logging for command handlers.
    // Every log entry has a stable code and optional fields.
    
    export function createLogger({ command, action }) {
      const context = action ? `${command}:${action}` : command
    
      return {
        info(code, fields = {}) {
          logEntry('info', context, code, fields)
        },
    
        warn(code, fields = {}) {
          logEntry('warn', context, code, fields)
        },
    
        error(code, fields = {}) {
          logEntry('error', context, code, fields)
        },
      }
    }
    
    function logEntry(level, context, code, fields) {
      const entry = {
        level,
        context,
        code,
        ...fields,
        timestamp: new Date().toISOString(),
      }
    
      const logFormat = process.env.CLAUDEMAP_LOG_FORMAT || 'human'
    
      if (logFormat === 'json') {
        console.log(JSON.stringify(entry))
      } else {
        // Human-readable format
        const fieldsSummary = Object.keys(fields).length > 0
          ? ` ${JSON.stringify(fields)}`
          : ''
        console.log(`[${level.toUpperCase()}] ${context} ${code}${fieldsSummary}`)
      }
    }
    
  • skill/lib/command-harness/parse-args.js4.8 KB7e590efed0f0upstream ↗
    // Small, explicit argv parser for command descriptors.
    //
    // It supports exactly what Phase 2 descriptors need: booleans, strings,
    // numbers, enums, a single rest-positional, and --help. Unknown flags or
    // missing required values produce ClaudeMapError('ARG_VALIDATION_FAILED')
    // rather than leaking process.argv past the harness.
    //
    // The output is a plain object with camelCased keys ('--keep-mode' becomes
    // 'keepMode', '--stdio-mcp' becomes 'stdioMcp'). Boolean flags default to
    // false when omitted, so handlers can read args.keepMode without a ternary.
    
    import { ClaudeMapError } from '../contracts/errors.js'
    
    export function parseArgs(argv, spec) {
      const normalizedSpec = normalizeSpec(spec)
      const result = initializeDefaults(normalizedSpec)
      const positionalValues = []
    
      let cursor = 0
    
      while (cursor < argv.length) {
        const token = argv[cursor]
    
        if (token === '--help' || token === '-h') {
          result.help = true
          cursor += 1
          continue
        }
    
        if (token === '--') {
          positionalValues.push(...argv.slice(cursor + 1))
          break
        }
    
        if (token.startsWith('--no-')) {
          const flagName = token.slice('--no-'.length)
          const flagSpec = normalizedSpec.flagsByName.get(flagName)
    
          if (!flagSpec || flagSpec.type !== 'boolean') {
            throw argError(`Unknown flag: ${token}`)
          }
    
          result[flagSpec.camelName] = false
          cursor += 1
          continue
        }
    
        if (token.startsWith('--')) {
          const flagName = token.slice(2)
          const flagSpec = normalizedSpec.flagsByName.get(flagName)
    
          if (!flagSpec) {
            throw argError(`Unknown flag: ${token}`)
          }
    
          if (flagSpec.type === 'boolean') {
            result[flagSpec.camelName] = true
            cursor += 1
            continue
          }
    
          const rawValue = argv[cursor + 1]
    
          if (rawValue === undefined || rawValue.startsWith('--')) {
            throw argError(`Missing value for ${token}`)
          }
    
          result[flagSpec.camelName] = coerceValue(flagSpec, rawValue, token)
          cursor += 2
          continue
        }
    
        positionalValues.push(token)
        cursor += 1
      }
    
      assignPositional(result, normalizedSpec, positionalValues)
    
      if (result.help) {
        return { parsed: result, help: true }
      }
    
      return { parsed: result, help: false }
    }
    
    function normalizeSpec(spec) {
      const flags = Array.isArray(spec?.flags) ? spec.flags : []
      const flagsByName = new Map()
      const flagsByCamel = new Map()
    
      for (const flagSpec of flags) {
        const camelName = toCamel(flagSpec.name)
        const normalized = { ...flagSpec, camelName }
        flagsByName.set(flagSpec.name, normalized)
        flagsByCamel.set(camelName, normalized)
      }
    
      return {
        flags,
        flagsByName,
        flagsByCamel,
        positional: spec?.positional || null,
      }
    }
    
    function initializeDefaults(normalizedSpec) {
      const defaults = { help: false }
    
      for (const flagSpec of normalizedSpec.flags) {
        if (flagSpec.type === 'boolean') {
          defaults[flagSpec.camelName] = false
        } else {
          defaults[flagSpec.camelName] = undefined
        }
      }
    
      if (normalizedSpec.positional) {
        defaults[toCamel(normalizedSpec.positional.name)] = normalizedSpec.positional.rest ? '' : undefined
      }
    
      return defaults
    }
    
    function coerceValue(flagSpec, rawValue, token) {
      if (flagSpec.type === 'number') {
        const parsed = Number(rawValue)
    
        if (!Number.isFinite(parsed)) {
          throw argError(`Invalid number for ${token}: ${rawValue}`)
        }
    
        return parsed
      }
    
      if (flagSpec.type === 'enum') {
        const allowed = Array.isArray(flagSpec.values) ? flagSpec.values : []
    
        if (!allowed.includes(rawValue)) {
          throw argError(`Invalid value for ${token}: ${rawValue}. Allowed: ${allowed.join(', ')}`)
        }
    
        return rawValue
      }
    
      return rawValue
    }
    
    function assignPositional(result, normalizedSpec, positionalValues) {
      const positionalSpec = normalizedSpec.positional
    
      if (!positionalSpec) {
        if (positionalValues.length > 0) {
          // Extra positionals without a spec usually means the descriptor owner
          // expects to read them off result._positional. Expose for that case.
          result._positional = positionalValues
        }
    
        return
      }
    
      const camelName = toCamel(positionalSpec.name)
    
      if (positionalSpec.rest) {
        result[camelName] = positionalValues.join(' ').trim()
        result._positional = positionalValues
        return
      }
    
      if (positionalValues.length === 0) {
        if (positionalSpec.required) {
          throw argError(`Missing positional argument: <${positionalSpec.name}>`)
        }
    
        result[camelName] = undefined
        return
      }
    
      result[camelName] = positionalValues[0]
      result._positional = positionalValues
    }
    
    function toCamel(value) {
      return String(value).replace(/-([a-z0-9])/g, (_, char) => char.toUpperCase())
    }
    
    function argError(message) {
      return new ClaudeMapError('ARG_VALIDATION_FAILED', message)
    }
    
  • skill/lib/command-harness/project-root.js640 B0852f6645b80upstream ↗
    import path from 'path'
    
    export function resolveProjectRoot(argv, positionalName = null) {
      const optionsWithValues = new Set([
        '--enrichment-file',
        '--scope-json',
        '--instructions',
        '--zoom',
        '--explain',
        '--title',
        '--step',
        '--mode',
      ])
    
      const projectRootArg = argv.find((argument, index) => {
        if (argument.startsWith('--')) {
          return false
        }
    
        const previousArgument = argv[index - 1]
        return !optionsWithValues.has(previousArgument)
      })
    
      return path.resolve(
        projectRootArg ||
        process.env.CLAUDEMAP_PROJECT_ROOT ||
        process.env.INIT_CWD ||
        process.cwd(),
      )
    }
    
  • skill/lib/command-harness/render-slash-template.js2.5 KB6350eee3bfb4upstream ↗
    // Renders slash-command markdown templates from command descriptors.
    // Replaces hand-authored markdown blobs in package-claudemap-skill.js.
    
    export function slashFileName(descriptor) {
      const base = descriptor.slashName || descriptor.name
      return `${base}.md`
    }
    
    export function renderSlashTemplate(descriptor) {
      const lines = []
    
      lines.push('---')
      lines.push(`description: ${descriptor.summary}`)
    
      if (descriptor.argumentHint) {
        lines.push(`argument-hint: '${descriptor.argumentHint}'`)
      }
    
      if (descriptor.disableModelInvocation) {
        lines.push('disable-model-invocation: true')
      }
    
      lines.push('---')
      lines.push('')
    
      if (descriptor.body) {
        lines.push(descriptor.body)
        lines.push('')
      } else {
        lines.push('## Usage')
        lines.push('')
    
        if (descriptor.actions) {
          for (const action of descriptor.actions) {
            const flagsSummary = renderFlagsSummary(action.flags || [])
            const positionalHint = action.positional?.name || ''
            lines.push(`${descriptor.name} ${action.name} ${positionalHint} ${flagsSummary}`.trim())
          }
        } else {
          const flagsSummary = renderFlagsSummary(descriptor.flags || [])
          const positionalHint = descriptor.positional?.name
            ? `[${descriptor.positional.name}]`
            : ''
          lines.push(`${descriptor.name} ${positionalHint} ${flagsSummary}`.trim())
        }
    
        lines.push('')
      }
    
      const flags = collectFlags(descriptor)
      if (flags.length > 0) {
        lines.push('## Flags')
        lines.push('')
        for (const flag of flags) {
          lines.push(renderFlagLine(flag))
        }
        lines.push('')
      }
    
      return lines.join('\n')
    }
    
    function collectFlags(descriptor) {
      if (descriptor.actions) {
        const seen = new Map()
        for (const action of descriptor.actions) {
          for (const flag of action.flags || []) {
            if (!seen.has(flag.name)) seen.set(flag.name, flag)
          }
        }
        return Array.from(seen.values())
      }
      return descriptor.flags || []
    }
    
    function renderFlagsSummary(flags) {
      if (flags.length === 0) return ''
      return flags.map(flag => `[--${flag.name}${flag.type !== 'boolean' ? ' <value>' : ''}]`).join(' ')
    }
    
    function renderFlagLine(flag) {
      const typeHint = flag.type === 'enum'
        ? ` (one of: ${flag.values.join(', ')})`
        : flag.type === 'number'
          ? ' (number)'
          : flag.type === 'boolean'
            ? ''
            : ' (string)'
      const description = flag.description || ''
      return `- \`--${flag.name}\`${typeHint}${description ? ': ' + description : ''}`
    }
    
  • skill/lib/command-harness/run-command.js5.0 KB970b5f3e015aupstream ↗
    import { resolveProjectRoot } from './project-root.js'
    import { parseArgs } from './parse-args.js'
    import { withMcp } from './with-mcp.js'
    import { createLogger } from './log.js'
    import { resolveActiveMap } from '../active-map.js'
    import { ClaudeMapError, success, ERROR_CODES } from '../contracts/errors.js'
    
    export async function runCommand(descriptor, argv) {
      try {
        const isDispatcher = Boolean(descriptor.actions)
        let parseResult
        let action = null
        let handler
        let actionSpec
    
        if (isDispatcher) {
          const actionName = argv.find(arg => !arg.startsWith('--'))
    
          if (!actionName) {
            printUsage(descriptor)
            return success()
          }
    
          action = descriptor.actions.find(a => a.name === actionName)
    
          if (!action) {
            const available = descriptor.actions.map(a => a.name).join(', ')
            throw new ClaudeMapError(ERROR_CODES.UNKNOWN_ACTION, `Unknown action "${actionName}". Available: ${available}`)
          }
    
          const actionIndex = argv.indexOf(actionName)
          const actionArgv = [...argv.slice(0, actionIndex), ...argv.slice(actionIndex + 1)]
    
          actionSpec = {
            flags: [...(descriptor.globalFlags || []), ...(action.flags || [])],
            positional: action.positional,
          }
    
          parseResult = parseArgs(actionArgv, actionSpec)
          handler = action.handler
        } else {
          actionSpec = {
            flags: descriptor.flags || [],
            positional: descriptor.positional,
          }
    
          parseResult = parseArgs(argv, actionSpec)
          handler = descriptor.handler
        }
    
        if (parseResult.help) {
          printUsage(descriptor, action)
          return success()
        }
    
        const args = parseResult.parsed
        const projectRoot = resolveProjectRoot(argv)
        const activeMap = resolveActiveMap(projectRoot)
        const log = createLogger({
          command: descriptor.name,
          action: isDispatcher ? action.name : null,
        })
    
        const ctx = {
          projectRoot,
          activeMap,
          log,
        }
    
        let mcpMode = null
        let requireStdio = false
    
        if (descriptor.withMcp || (action && action.withMcp)) {
          const withMcpConfig = descriptor.withMcp || action.withMcp
    
          if (typeof withMcpConfig === 'boolean') {
            mcpMode = 'auto'
          } else {
            mcpMode = withMcpConfig.mode || 'auto'
            requireStdio = withMcpConfig.requireStdio || false
          }
    
          if (args.stdioMcp) {
            mcpMode = 'stdio'
          }
        }
    
        const result = await withMcp(
          { mode: mcpMode, requireStdio, activeMap, log },
          async (mcpClient) => {
            ctx.mcp = mcpClient
            return handler({ ctx, args })
          },
        )
    
        if (result && result.ok === false) {
          console.error(`${result.code}: ${result.message}`)
          if (result.hint) {
            console.error(result.hint)
          }
          process.exitCode = 1
          return result
        }
    
        log.info(ERROR_CODES.COMMAND_OK, result?.data || {})
        return result || success()
      } catch (error) {
        if (error instanceof ClaudeMapError) {
          console.error(`${error.code}: ${error.message}`)
          if (error.hint) {
            console.error(error.hint)
          }
        } else {
          console.error(error.message || error)
          if (error.stack && process.env.DEBUG) {
            console.error(error.stack)
          }
        }
    
        process.exitCode = 1
        throw error
      }
    }
    
    function printUsage(descriptor, action = null) {
      if (action) {
        console.log(`${descriptor.name} ${action.name} - ${action.summary || ''}`)
        console.log('')
    
        const positionalHint = action.positional?.name
          ? `[${action.positional.name}]`
          : ''
        console.log(`Usage: ${descriptor.name} ${action.name} ${positionalHint}`)
    
        if (action.flags && action.flags.length > 0) {
          console.log('')
          console.log('Flags:')
          for (const flag of action.flags) {
            const typeHint = flag.type === 'boolean' ? '' : ` <${flag.type || 'value'}>`
            console.log(`  --${flag.name}${typeHint}${flag.description ? ': ' + flag.description : ''}`)
          }
        }
      } else if (descriptor.actions) {
        console.log(`${descriptor.name} - ${descriptor.summary}`)
        console.log('')
        console.log('Actions:')
        for (const a of descriptor.actions) {
          console.log(`  ${a.name} - ${a.summary || ''}`)
        }
        console.log('')
        console.log('Use --help with an action for detailed usage.')
      } else {
        console.log(`${descriptor.name} - ${descriptor.summary}`)
        console.log('')
    
        const positionalHint = descriptor.positional?.name
          ? `[${descriptor.positional.name}]`
          : ''
        console.log(`Usage: ${descriptor.name} ${positionalHint}`)
    
        if (descriptor.flags && descriptor.flags.length > 0) {
          console.log('')
          console.log('Flags:')
          for (const flag of descriptor.flags) {
            const typeHint = flag.type === 'boolean' ? '' : ` <${flag.type || 'value'}>`
            console.log(`  --${flag.name}${typeHint}${flag.description ? ': ' + flag.description : ''}`)
          }
        }
      }
    }
    
    export function exitOnError(error) {
      console.error(error.message || error)
      process.exit(1)
    }
    
  • skill/lib/command-harness/slash-only-descriptors.js2.4 KB6481f8235917upstream ↗
    // Slash-command descriptors that have no underlying runtime command.
    // They exist purely so renderSlashTemplate can produce their .md files
    // from the same descriptor shape as the real commands.
    
    export const EXPLAIN_SLASH_COMMAND = {
      name: 'explain',
      summary: 'Explain part of the codebase by turning the live map into a guided walkthrough.',
      argumentHint: '[topic-or-click-context]',
      body: `Use ClaudeMap as a guided presentation tool.
    
    Workflow:
    1. If the user provided ClaudeMap click context, extract the label, path, and type from it.
    2. If the user provided a plain topic or node name, use that as the walkthrough anchor.
    3. If no usable topic is available, ask the user to click a node in ClaudeMap and paste the copied context, or provide a topic directly.
    4. Read the currently active ClaudeMap runtime graph rather than assuming the root map.
    5. For broad or ambiguous requests, use the \`@claudemap-architect\` subagent to turn the request into a short walkthrough plan of 2-6 steps that follows intuitive architectural groupings.
    6. Start presentation mode by running \`node .claude/skills/claudemap-runtime/skill/commands/show.js mode guided\`.
    7. Drive the map in discrete steps. Prefer one present command per explanation beat so the highlight, navigation, and narration update atomically. Pass \`--keep-mode\` on every \`present\` and \`highlight\` step so the guided mode set in step 6 persists across steps instead of auto-reverting to free:
       - \`node .claude/skills/claudemap-runtime/skill/commands/show.js present <query> --title "..." --step "Step 1" --explain "..." --keep-mode\`
       - \`node .claude/skills/claudemap-runtime/skill/commands/show.js highlight <query> --keep-mode\`
       - \`node .claude/skills/claudemap-runtime/skill/commands/show.js health on\`
       - \`node .claude/skills/claudemap-runtime/skill/commands/show.js flow <query1> <query2> ...\`
    8. Treat each show command as the visual step boundary. Do not rely on plain chat text streaming alone for transitions.
    9. When the explanation is complete, always release the map by running:
       - \`node .claude/skills/claudemap-runtime/skill/commands/show.js clear-caption\`
       - \`node .claude/skills/claudemap-runtime/skill/commands/show.js mode free\`
    10. Use high-level, intuitive language first. Prefer plain-English descriptions of purpose, flow, and impact before lower-level implementation details.
    11. Keep narration concise and synchronized to the step you just triggered.`,
    }
    
  • skill/lib/command-harness/with-mcp.js960 Bbbc263e70601upstream ↗
    import { connectMcpClient, closeMcpClient } from '../mcp-client.js'
    import { GRAPH_SOURCES } from '../contracts/graph-sources.js'
    import { ClaudeMapError, ERROR_CODES } from '../contracts/errors.js'
    
    export async function withMcp({ mode, requireStdio, activeMap, log }, handler) {
      if (!mode) {
        return handler(null)
      }
    
      const client = await connectMcpClient({
        mode: mode === 'stdio' ? 'stdio' : GRAPH_SOURCES.FILE_SHIM,
        graphPath: activeMap.graphPath,
        statePath: activeMap.statePath,
      })
    
      try {
        if (requireStdio && client.fallbackReason) {
          throw new ClaudeMapError(
            ERROR_CODES.MCP_FALLBACK_FORBIDDEN,
            'stdio MCP transport is required but unavailable',
            client.fallbackReason,
          )
        }
    
        if (client.fallbackReason) {
          log.warn(ERROR_CODES.MCP_FALLBACK_FILE_SHIM, { reason: client.fallbackReason })
        }
    
        return await handler(client)
      } finally {
        await closeMcpClient(client)
      }
    }
    
  • skill/lib/contracts/errors.js2.8 KB47c2aeb90d2aupstream ↗
    // Stable error codes. Callers match on these, not on message substrings.
    // Messages may improve; codes do not change.
    
    export const ERROR_CODES = Object.freeze({
      // Expected failures (user-actionable).
      NO_ACTIVE_MAP: 'NO_ACTIVE_MAP',
      NO_RUNTIME_GRAPH: 'NO_RUNTIME_GRAPH',
      NO_NODE_MATCHED: 'NO_NODE_MATCHED',
      INVALID_ARGUMENT: 'INVALID_ARGUMENT',
      MISSING_ARGUMENT: 'MISSING_ARGUMENT',
      UNKNOWN_ACTION: 'UNKNOWN_ACTION',
      NO_INTENT_MATCH: 'NO_INTENT_MATCH',
      MANIFEST_MISSING: 'MANIFEST_MISSING',
      SCOPE_UNRESOLVED: 'SCOPE_UNRESOLVED',
      ARG_VALIDATION_FAILED: 'ARG_VALIDATION_FAILED',
    
      // Degraded modes (ops may care, users usually do not).
      MCP_FALLBACK_FILE_SHIM: 'MCP_FALLBACK_FILE_SHIM',
      MCP_FALLBACK_FORBIDDEN: 'MCP_FALLBACK_FORBIDDEN',
      SEED_MAP_MISSING: 'SEED_MAP_MISSING',
      ENRICHMENT_PROMPT_MISSING: 'ENRICHMENT_PROMPT_MISSING',
    
      // Schema drift (Phase 6 warn+best-effort semantics).
      SCHEMA_VALIDATION_FAILED: 'SCHEMA_VALIDATION_FAILED',
      SCHEMA_MIGRATION_APPLIED: 'SCHEMA_MIGRATION_APPLIED',
    
      // Success codes.
      COMMAND_OK: 'COMMAND_OK',
    
      // Packaging / install.
      ARTIFACT_MANIFEST_MISSING: 'ARTIFACT_MANIFEST_MISSING',
      INSTALL_PARTIAL: 'INSTALL_PARTIAL',
      BUNDLE_BUILD_FAILED: 'BUNDLE_BUILD_FAILED',
    })
    
    // Constructor for structured expected-failure results. Commands return these
    // instead of throwing when the failure is the user's concern, not a bug.
    export function failure(code, message, hint) {
      return { ok: false, code, message, hint }
    }
    
    export function success(data = null) {
      return { ok: true, data }
    }
    
    // Throwable error that carries a code for programmatic handling.
    export class ClaudeMapError extends Error {
      constructor(code, message, hint) {
        super(message)
        this.name = 'ClaudeMapError'
        this.code = code
        this.hint = hint
      }
    }
    
    // Structured warning, reported when a read tolerates drift rather than
    // throwing. Callers attach it to log output; consumers may pattern-match
    // on the code. Shape mirrors failure() so sinks can treat the two alike.
    export function warning(code, message, context) {
      return { level: 'warn', code, message, context: context || null }
    }
    
    // Default warning sink. Writes a single tagged line to stderr so that
    // structured log scrapers can find it without parsing free-form text.
    // Tests may replace this sink via setWarningSink().
    function defaultWarningSink(warn) {
      const context = warn.context ? ` ${JSON.stringify(warn.context)}` : ''
      // eslint-disable-next-line no-console
      console.warn(`[claudemap:${warn.code}] ${warn.message}${context}`)
    }
    
    let activeWarningSink = defaultWarningSink
    
    export function setWarningSink(sink) {
      activeWarningSink = typeof sink === 'function' ? sink : defaultWarningSink
    }
    
    export function reportWarning(warn) {
      if (!warn || !warn.code) {
        return
      }
      activeWarningSink(warn)
    }
    
  • skill/lib/contracts/graph-sources.js1.3 KB7614aef403e0upstream ↗
    // Graph source tags shared by enrichment, scoped-map, mcp-client, and commands.
    //
    // Every string that can appear in a graph's `source` field is declared here.
    // The priority table determines which graph wins when multiple are candidates.
    // Higher priority wins.
    
    export const GRAPH_SOURCES = Object.freeze({
      SAMPLE: 'sample',
      SEED: 'seed',
      FILE_SHIM: 'file-shim',
      HEURISTIC: 'heuristic',
      CLAUDE: 'claude',
      CLAUDE_SCOPED: 'claude-scoped',
      SCOPED_MAP: 'scoped-map',
      IMPORTED: 'imported',
      MANUAL: 'manual',
      RUNTIME: 'runtime',
      ARCHITECT: 'architect',
      UNKNOWN: 'unknown',
    })
    
    export const GRAPH_SOURCE_PRIORITY = Object.freeze({
      [GRAPH_SOURCES.SAMPLE]: 0,
      [GRAPH_SOURCES.SEED]: 0,
      [GRAPH_SOURCES.FILE_SHIM]: 0,
      [GRAPH_SOURCES.UNKNOWN]: 0,
      [GRAPH_SOURCES.HEURISTIC]: 10,
      [GRAPH_SOURCES.RUNTIME]: 20,
      [GRAPH_SOURCES.CLAUDE]: 30,
      [GRAPH_SOURCES.CLAUDE_SCOPED]: 30,
      [GRAPH_SOURCES.SCOPED_MAP]: 30,
      [GRAPH_SOURCES.ARCHITECT]: 35,
      [GRAPH_SOURCES.IMPORTED]: 40,
      [GRAPH_SOURCES.MANUAL]: 50,
    })
    
    export const DEFAULT_GRAPH_SOURCE_PRIORITY = 5
    
    export function isKnownGraphSource(value) {
      return Object.prototype.hasOwnProperty.call(GRAPH_SOURCE_PRIORITY, value)
    }
    
    export function getGraphSourcePriority(value) {
      if (isKnownGraphSource(value)) {
        return GRAPH_SOURCE_PRIORITY[value]
      }
      return DEFAULT_GRAPH_SOURCE_PRIORITY
    }
    
  • skill/lib/contracts/index.js307 B7147ad4a54e2upstream ↗
    // Barrel export. Prefer importing from the specific module for traceability;
    // this exists for call sites that need multiple contract groups at once.
    
    export * from './paths.js'
    export * from './presentation.js'
    export * from './graph-sources.js'
    export * from './versions.js'
    export * from './errors.js'
    
  • skill/lib/contracts/paths.js11 KB78a6f6626a10upstream ↗
    // Canonical path constants for every ClaudeMap surface.
    //
    // Every file path that appears in more than one place lives here. Scripts,
    // skill commands, skill lib, and the installer all import from this module.
    // Do not re-declare these strings anywhere else.
    //
    // Names ending in *_REL are POSIX-relative (forward slashes, no leading slash);
    // callers compose them with path.join against whichever root applies.
    
    // ---------------------------------------------------------------------------
    // Assistant Types
    // ---------------------------------------------------------------------------
    // ClaudeMap supports multiple AI coding assistants. Each has different
    // conventions for where skills, agents, and config live.
    
    export const ASSISTANT_TYPES = Object.freeze({
      CLAUDE: 'claude',
      CODEX: 'codex',
    })
    
    // Brand identifiers used by the app to pick palette + display name.
    // The packaged index.html carries <html data-brand="..."> so the right
    // brand is active before first paint. Kept here (not in the app's
    // branding.js) because the packager must resolve a brand id from an
    // assistant type at build time and both tiers need to agree.
    export const BRAND_IDS = Object.freeze({
      CLAUDEMAP: 'claudemap',
      CODEXMAP: 'codexmap',
    })
    
    // Configuration for each assistant type.
    // - rootDir: primary config/install record directory
    // - skillsPath: where skills are discovered (may differ from rootDir!)
    // - agentsPath: where agent definitions live
    // - commandsPath: where repo-defined slash-command docs live
    //   (null when the assistant has no repo-defined slash-command directory)
    // - agentExt: file extension for agent definitions
    export const ASSISTANT_CONFIGS = Object.freeze({
      [ASSISTANT_TYPES.CLAUDE]: {
        rootDir: '.claude',
        skillsPath: '.claude/skills',
        agentsPath: '.claude/agents',
        commandsPath: '.claude/commands',
        agentExt: '.md',
      },
      [ASSISTANT_TYPES.CODEX]: {
        // Codex uses TWO roots by design:
        // - .agents/skills/ is the hardcoded discovery path for skills
        // - .codex/ is for config, agents, and install records
        rootDir: '.codex',
        skillsPath: '.agents/skills',
        agentsPath: '.codex/agents',
        commandsPath: null, // Codex has no repo-defined slash-command directory
        agentExt: '.toml',
      },
    })
    
    // ---------------------------------------------------------------------------
    // Legacy Constants (backwards compatibility)
    // ---------------------------------------------------------------------------
    // These exports are maintained for backwards compatibility. New code should
    // use resolveAssistantPaths() for assistant-aware path resolution.
    
    // Root directory Claude Code writes into, at the top of a target repo.
    export const CLAUDE_ROOT_DIR = '.claude'
    
    // Subdirectories of .claude/
    export const SKILLS_SUBDIR = 'skills'
    export const COMMANDS_SUBDIR = 'commands'
    export const AGENTS_SUBDIR = 'agents'
    
    // Assistant-visible skill directory names. Claude keeps the original name
    // for backwards compatibility; Codex gets the CodexMap-branded skill name.
    export const RUNTIME_SKILL_NAMES = Object.freeze({
      [ASSISTANT_TYPES.CLAUDE]: 'claudemap-runtime',
      [ASSISTANT_TYPES.CODEX]: 'codexmap-runtime',
    })
    
    // Migration-only assistant-visible names. New artifacts use
    // RUNTIME_SKILL_NAMES; installers use these to clean up managed old roots.
    export const LEGACY_RUNTIME_SKILL_NAMES = Object.freeze({
      [ASSISTANT_TYPES.CODEX]: Object.freeze(['claudemap-runtime']),
    })
    
    // Backwards-compatible default for older imports. This intentionally remains
    // the Claude skill name; assistant-aware code should use resolveAssistantPaths().
    export const RUNTIME_SKILL_NAME = RUNTIME_SKILL_NAMES[ASSISTANT_TYPES.CLAUDE]
    
    // Composed paths relative to a target repo root.
    export const SKILL_ROOT_REL = `${CLAUDE_ROOT_DIR}/${SKILLS_SUBDIR}/${RUNTIME_SKILL_NAME}`
    export const COMMANDS_ROOT_REL = `${CLAUDE_ROOT_DIR}/${COMMANDS_SUBDIR}`
    export const AGENTS_ROOT_REL = `${CLAUDE_ROOT_DIR}/${AGENTS_SUBDIR}`
    
    // Runtime-detection suffix. isInstalledRuntimeRoot compares against this.
    export const RUNTIME_INSTALLED_PATH_SUFFIX = `/${SKILL_ROOT_REL}`
    
    // Graph directory and graph/state filenames.
    export const GRAPH_DIR_NAME = 'graph'
    export const RUNTIME_GRAPH_FILENAME = 'claudemap-runtime.json'
    export const RUNTIME_STATE_FILENAME = 'claudemap-runtime-state.json'
    export const RUNTIME_GRAPH_REL = `${GRAPH_DIR_NAME}/${RUNTIME_GRAPH_FILENAME}`
    export const RUNTIME_STATE_REL = `${GRAPH_DIR_NAME}/${RUNTIME_STATE_FILENAME}`
    
    // Root-level files in a target repo.
    export const CACHE_FILENAME = 'claudemap-cache.json'
    export const MAPS_MANIFEST_FILENAME = 'claudemap-maps.json'
    
    // Installer artifact metadata (lives at .claude/ root after install).
    export const ARTIFACT_MANIFEST_FILENAME = 'claudemap-artifact.json'
    export const INSTALL_RECORD_FILENAME = 'claudemap-install.json'
    
    // Agent definitions that ship with the skill.
    export const ARCHITECT_AGENT_FILENAME = 'claudemap-architect.md'
    export const ARCHITECT_AGENT_REL = `${AGENTS_ROOT_REL}/${ARCHITECT_AGENT_FILENAME}`
    
    // Seed map shipped with the package. Relative to the repo root.
    export const SEED_MAP_REL = 'contracts/claudemap-seed-map.json'
    
    // Packaging artifact locations. Relative to the repo root.
    export const PACKAGE_ARTIFACT_DIR_REL = 'artifacts/claudemap-skill'
    export const NPM_BUNDLE_DIR_REL = '.npm-bundle'
    export const NPM_BUNDLE_SUBDIR = 'claudemap'
    
    // Identity for the packaged artifact on disk and in install records.
    export const ARTIFACT_NAME = 'claudemap'
    
    // Published CLI entry point. Relative to the repo root. bin/claudemap.js
    // delegates to scripts/install-claudemap.js at runtime.
    export const CLI_BIN_REL = 'bin/claudemap.js'
    
    // Transactional install marker. Written under CLAUDE_ROOT_DIR when an
    // install begins and removed on success. Its presence indicates a
    // partial install; a subsequent install refuses to proceed until it is
    // cleared (by completing, or manual deletion after the user verifies).
    export const PARTIAL_INSTALL_MARKER_FILENAME = '.partial-install'
    
    // Static-site output directory at the repo root.
    export const DOCS_DIR_REL = 'docs'
    
    // App public-graph location (inside the skill bundle).
    export const APP_PUBLIC_GRAPH_REL = 'app/public/graph'
    export const APP_PUBLIC_GRAPH_RUNTIME_REL = `${APP_PUBLIC_GRAPH_REL}/${RUNTIME_GRAPH_FILENAME}`
    export const APP_PUBLIC_GRAPH_STATE_REL = `${APP_PUBLIC_GRAPH_REL}/${RUNTIME_STATE_FILENAME}`
    
    // Prompts that the skill ships.
    export const PROMPTS_DIR_REL = 'skill/prompts'
    export const ENRICHMENT_PROMPT_FILENAME = 'enrichment.txt'
    export const SCOPED_ENRICHMENT_PROMPT_FILENAME = 'scoped-enrichment.txt'
    
    // ---------------------------------------------------------------------------
    // Assistant-Aware Path Resolution
    // ---------------------------------------------------------------------------
    
    /**
     * Resolve all paths for a specific assistant type.
     *
     * @param {string} assistantType - One of ASSISTANT_TYPES values ('claude' | 'codex')
     * @returns {Object} Object containing all resolved paths for the assistant
     * @throws {Error} If assistantType is not recognized
     */
    export function resolveAssistantPaths(assistantType) {
      const config = ASSISTANT_CONFIGS[assistantType]
      if (!config) {
        const validTypes = Object.values(ASSISTANT_TYPES).join(', ')
        throw new Error(`Unknown assistant type: ${assistantType}. Valid types: ${validTypes}`)
      }
    
      const skillName = RUNTIME_SKILL_NAMES[assistantType] || RUNTIME_SKILL_NAME
      const legacySkillNames = LEGACY_RUNTIME_SKILL_NAMES[assistantType] || Object.freeze([])
      const skillRootRel = `${config.skillsPath}/${skillName}`
      const legacySkillRootRels = legacySkillNames.map((legacySkillName) => (
        `${config.skillsPath}/${legacySkillName}`
      ))
      const agentBasename = assistantType === ASSISTANT_TYPES.CODEX
        ? ARCHITECT_AGENT_FILENAME.replace('.md', config.agentExt)
        : ARCHITECT_AGENT_FILENAME
    
      const brandId = assistantType === ASSISTANT_TYPES.CODEX
        ? BRAND_IDS.CODEXMAP
        : BRAND_IDS.CLAUDEMAP
    
      return {
        // Base config
        assistantType,
        brandId,
        rootDir: config.rootDir,
        skillsPath: config.skillsPath,
        agentsPath: config.agentsPath,
        commandsPath: config.commandsPath,
        agentExt: config.agentExt,
    
        // Composed skill paths
        skillName,
        skillMention: `$${skillName}`,
        skillRootRel,
        legacySkillRootRels,
        runtimeGraphRel: `${skillRootRel}/${APP_PUBLIC_GRAPH_REL}/${RUNTIME_GRAPH_FILENAME}`,
        runtimeStateRel: `${skillRootRel}/${APP_PUBLIC_GRAPH_REL}/${RUNTIME_STATE_FILENAME}`,
    
        // Agent paths
        architectAgentFilename: agentBasename,
        architectAgentRel: `${config.agentsPath}/${agentBasename}`,
    
        // Commands (Claude only)
        commandsRootRel: config.commandsPath,
    
        // Install/artifact metadata paths (always in rootDir)
        installRecordRel: `${config.rootDir}/${INSTALL_RECORD_FILENAME}`,
        artifactManifestRel: `${config.rootDir}/${ARTIFACT_MANIFEST_FILENAME}`,
        partialInstallMarkerRel: `${config.rootDir}/${PARTIAL_INSTALL_MARKER_FILENAME}`,
    
        // Self-location config (Codex only, written at install time)
        skillConfigRel: assistantType === ASSISTANT_TYPES.CODEX
          ? `${skillRootRel}/.claudemap-config.json`
          : null,
    
        // All managed paths for this assistant (for install record)
        getManagedPaths() {
          const paths = [
            skillRootRel,
            `${config.agentsPath}/${agentBasename}`,
            `${config.rootDir}/${INSTALL_RECORD_FILENAME}`,
            `${config.rootDir}/${ARTIFACT_MANIFEST_FILENAME}`,
          ]
          if (config.commandsPath) {
            paths.push(config.commandsPath)
          }
          return paths
        },
      }
    }
    
    /**
     * Auto-detect assistant type from environment or target directory.
     *
     * Detection order:
     * 1. CLAUDE_SKILL_DIR env var present → Claude
     * 2. Existing .codex/ dir without .claude/ → Codex
     * 3. Existing .claude/ dir → Claude
     * 4. Default → Claude (backwards compatibility)
     *
     * @param {string} targetRoot - Path to the target repository
     * @param {Object} deps - Optional dependencies for testing
     * @param {Object} deps.fs - fs module (defaults to Node's fs)
     * @param {Object} deps.path - path module (defaults to Node's path)
     * @param {Object} deps.env - environment variables (defaults to process.env)
     * @returns {string} One of ASSISTANT_TYPES values
     */
    export function detectAssistant(targetRoot, deps = {}) {
      const env = deps.env || process.env
    
      // 1. Check for CLAUDE_SKILL_DIR env var (Claude is running)
      if (env.CLAUDE_SKILL_DIR) {
        return ASSISTANT_TYPES.CLAUDE
      }
    
      // 2. Check for existing installations
      let fs, pathMod
      try {
        fs = deps.fs || require('fs')
        pathMod = deps.path || require('path')
      } catch {
        // If we can't import fs (e.g., browser), default to Claude
        return ASSISTANT_TYPES.CLAUDE
      }
    
      const codexConfig = ASSISTANT_CONFIGS[ASSISTANT_TYPES.CODEX]
      const claudeConfig = ASSISTANT_CONFIGS[ASSISTANT_TYPES.CLAUDE]
    
      const hasCodex = fs.existsSync(pathMod.join(targetRoot, codexConfig.rootDir))
      const hasClaude = fs.existsSync(pathMod.join(targetRoot, claudeConfig.rootDir))
    
      // If only Codex exists, return Codex
      if (hasCodex && !hasClaude) {
        return ASSISTANT_TYPES.CODEX
      }
    
      // 3. Default to Claude for backwards compatibility
      return ASSISTANT_TYPES.CLAUDE
    }
    
  • skill/lib/contracts/paths.test.js11 KB520e8d76018cupstream ↗
    import { describe, expect, it } from 'vitest'
    import {
      // Assistant types and configs
      ASSISTANT_TYPES,
      ASSISTANT_CONFIGS,
      resolveAssistantPaths,
      detectAssistant,
    
      // Legacy exports (backwards compatibility)
      CLAUDE_ROOT_DIR,
      SKILLS_SUBDIR,
      COMMANDS_SUBDIR,
      AGENTS_SUBDIR,
      RUNTIME_SKILL_NAMES,
      LEGACY_RUNTIME_SKILL_NAMES,
      RUNTIME_SKILL_NAME,
      SKILL_ROOT_REL,
      COMMANDS_ROOT_REL,
      AGENTS_ROOT_REL,
      ARCHITECT_AGENT_FILENAME,
      INSTALL_RECORD_FILENAME,
      ARTIFACT_MANIFEST_FILENAME,
      PARTIAL_INSTALL_MARKER_FILENAME,
    } from './paths.js'
    
    // -----------------------------------------------------------------------------
    // Assistant Types and Configs
    // -----------------------------------------------------------------------------
    
    describe('ASSISTANT_TYPES', () => {
      it('exports claude and codex types', () => {
        expect(ASSISTANT_TYPES.CLAUDE).toBe('claude')
        expect(ASSISTANT_TYPES.CODEX).toBe('codex')
      })
    
      it('is frozen', () => {
        expect(Object.isFrozen(ASSISTANT_TYPES)).toBe(true)
      })
    })
    
    describe('ASSISTANT_CONFIGS', () => {
      it('has config for every assistant type', () => {
        for (const type of Object.values(ASSISTANT_TYPES)) {
          expect(ASSISTANT_CONFIGS[type]).toBeDefined()
          expect(ASSISTANT_CONFIGS[type].rootDir).toBeDefined()
          expect(ASSISTANT_CONFIGS[type].skillsPath).toBeDefined()
          expect(ASSISTANT_CONFIGS[type].agentsPath).toBeDefined()
          expect(ASSISTANT_CONFIGS[type].agentExt).toBeDefined()
        }
      })
    
      it('Claude config uses .claude root for everything', () => {
        const config = ASSISTANT_CONFIGS[ASSISTANT_TYPES.CLAUDE]
        expect(config.rootDir).toBe('.claude')
        expect(config.skillsPath).toBe('.claude/skills')
        expect(config.agentsPath).toBe('.claude/agents')
        expect(config.commandsPath).toBe('.claude/commands')
        expect(config.agentExt).toBe('.md')
      })
    
      it('Codex config uses separate discovery roots', () => {
        const config = ASSISTANT_CONFIGS[ASSISTANT_TYPES.CODEX]
        // .codex is the config root
        expect(config.rootDir).toBe('.codex')
        // .agents/skills is the hardcoded discovery path
        expect(config.skillsPath).toBe('.agents/skills')
        expect(config.agentsPath).toBe('.codex/agents')
        // No repo-defined slash-command directory for Codex
        expect(config.commandsPath).toBe(null)
        expect(config.agentExt).toBe('.toml')
      })
    
      it('is frozen', () => {
        expect(Object.isFrozen(ASSISTANT_CONFIGS)).toBe(true)
      })
    })
    
    // -----------------------------------------------------------------------------
    // resolveAssistantPaths
    // -----------------------------------------------------------------------------
    
    describe('resolveAssistantPaths', () => {
      describe('for Claude', () => {
        const paths = resolveAssistantPaths(ASSISTANT_TYPES.CLAUDE)
    
        it('returns correct base config', () => {
          expect(paths.assistantType).toBe('claude')
          expect(paths.rootDir).toBe('.claude')
          expect(paths.skillsPath).toBe('.claude/skills')
          expect(paths.agentsPath).toBe('.claude/agents')
          expect(paths.commandsPath).toBe('.claude/commands')
          expect(paths.agentExt).toBe('.md')
        })
    
        it('returns correct skill paths', () => {
          expect(paths.skillName).toBe('claudemap-runtime')
          expect(paths.skillMention).toBe('$claudemap-runtime')
          expect(paths.skillRootRel).toBe('.claude/skills/claudemap-runtime')
          expect(paths.runtimeGraphRel).toContain('.claude/skills/claudemap-runtime')
          expect(paths.runtimeStateRel).toContain('.claude/skills/claudemap-runtime')
          expect(paths.legacySkillRootRels).toEqual([])
        })
    
        it('returns correct agent paths', () => {
          expect(paths.architectAgentFilename).toBe('claudemap-architect.md')
          expect(paths.architectAgentRel).toBe('.claude/agents/claudemap-architect.md')
        })
    
        it('returns correct commands path', () => {
          expect(paths.commandsRootRel).toBe('.claude/commands')
        })
    
        it('returns correct install/artifact paths in rootDir', () => {
          expect(paths.installRecordRel).toBe('.claude/claudemap-install.json')
          expect(paths.artifactManifestRel).toBe('.claude/claudemap-artifact.json')
          expect(paths.partialInstallMarkerRel).toBe('.claude/.partial-install')
        })
    
        it('returns null for skillConfigRel (Claude uses env var)', () => {
          expect(paths.skillConfigRel).toBe(null)
        })
    
        it('getManagedPaths includes skill, agent, commands, and metadata', () => {
          const managed = paths.getManagedPaths()
          expect(managed).toContain('.claude/skills/claudemap-runtime')
          expect(managed).toContain('.claude/agents/claudemap-architect.md')
          expect(managed).toContain('.claude/claudemap-install.json')
          expect(managed).toContain('.claude/claudemap-artifact.json')
          expect(managed).toContain('.claude/commands')
        })
      })
    
      describe('for Codex', () => {
        const paths = resolveAssistantPaths(ASSISTANT_TYPES.CODEX)
    
        it('returns correct base config', () => {
          expect(paths.assistantType).toBe('codex')
          expect(paths.rootDir).toBe('.codex')
          expect(paths.skillsPath).toBe('.agents/skills')
          expect(paths.agentsPath).toBe('.codex/agents')
          expect(paths.commandsPath).toBe(null)
          expect(paths.agentExt).toBe('.toml')
        })
    
        it('returns correct skill paths under .agents/skills', () => {
          expect(paths.skillName).toBe('codexmap-runtime')
          expect(paths.skillMention).toBe('$codexmap-runtime')
          expect(paths.skillRootRel).toBe('.agents/skills/codexmap-runtime')
          expect(paths.runtimeGraphRel).toContain('.agents/skills/codexmap-runtime')
          expect(paths.runtimeStateRel).toContain('.agents/skills/codexmap-runtime')
          expect(paths.legacySkillRootRels).toEqual(['.agents/skills/claudemap-runtime'])
        })
    
        it('returns correct agent paths with .toml extension', () => {
          expect(paths.architectAgentFilename).toBe('claudemap-architect.toml')
          expect(paths.architectAgentRel).toBe('.codex/agents/claudemap-architect.toml')
        })
    
        it('returns null for commandsRootRel (Codex has no repo-defined slash-command directory)', () => {
          expect(paths.commandsRootRel).toBe(null)
        })
    
        it('returns correct install/artifact paths in .codex', () => {
          expect(paths.installRecordRel).toBe('.codex/claudemap-install.json')
          expect(paths.artifactManifestRel).toBe('.codex/claudemap-artifact.json')
          expect(paths.partialInstallMarkerRel).toBe('.codex/.partial-install')
        })
    
        it('returns skillConfigRel for self-location', () => {
          expect(paths.skillConfigRel).toBe('.agents/skills/codexmap-runtime/.claudemap-config.json')
        })
    
        it('getManagedPaths spans both roots and excludes commands', () => {
          const managed = paths.getManagedPaths()
          // Skill in .agents/skills
          expect(managed).toContain('.agents/skills/codexmap-runtime')
          // Agent in .codex
          expect(managed).toContain('.codex/agents/claudemap-architect.toml')
          // Metadata in .codex
          expect(managed).toContain('.codex/claudemap-install.json')
          expect(managed).toContain('.codex/claudemap-artifact.json')
          // No repo-defined slash-command files
          expect(managed.some((p) => p.includes('commands'))).toBe(false)
        })
      })
    
      it('throws for unknown assistant type', () => {
        expect(() => resolveAssistantPaths('unknown')).toThrow('Unknown assistant type')
        expect(() => resolveAssistantPaths('unknown')).toThrow('Valid types: claude, codex')
      })
    })
    
    // -----------------------------------------------------------------------------
    // detectAssistant
    // -----------------------------------------------------------------------------
    
    describe('detectAssistant', () => {
      it('returns Claude when CLAUDE_SKILL_DIR env var is set', () => {
        const result = detectAssistant('/some/path', {
          env: { CLAUDE_SKILL_DIR: '/path/to/skill' },
          fs: { existsSync: () => false },
          path: { join: (...args) => args.join('/') },
        })
        expect(result).toBe(ASSISTANT_TYPES.CLAUDE)
      })
    
      it('returns Codex when only .codex/ exists', () => {
        const result = detectAssistant('/repo', {
          env: {},
          fs: {
            existsSync: (p) => p.includes('.codex'),
          },
          path: { join: (...args) => args.join('/') },
        })
        expect(result).toBe(ASSISTANT_TYPES.CODEX)
      })
    
      it('returns Claude when only .claude/ exists', () => {
        const result = detectAssistant('/repo', {
          env: {},
          fs: {
            existsSync: (p) => p.includes('.claude'),
          },
          path: { join: (...args) => args.join('/') },
        })
        expect(result).toBe(ASSISTANT_TYPES.CLAUDE)
      })
    
      it('returns Claude when both .claude/ and .codex/ exist', () => {
        const result = detectAssistant('/repo', {
          env: {},
          fs: {
            existsSync: () => true, // both exist
          },
          path: { join: (...args) => args.join('/') },
        })
        expect(result).toBe(ASSISTANT_TYPES.CLAUDE)
      })
    
      it('returns Claude when neither directory exists (default)', () => {
        const result = detectAssistant('/repo', {
          env: {},
          fs: {
            existsSync: () => false,
          },
          path: { join: (...args) => args.join('/') },
        })
        expect(result).toBe(ASSISTANT_TYPES.CLAUDE)
      })
    
      it('returns Claude when fs is unavailable', () => {
        const result = detectAssistant('/repo', {
          env: {},
          // No fs provided, and require would fail in test env
        })
        // Should default to Claude without throwing
        expect(result).toBe(ASSISTANT_TYPES.CLAUDE)
      })
    })
    
    // -----------------------------------------------------------------------------
    // Legacy Exports (Backwards Compatibility)
    // -----------------------------------------------------------------------------
    
    describe('legacy exports', () => {
      it('CLAUDE_ROOT_DIR matches Claude config', () => {
        expect(CLAUDE_ROOT_DIR).toBe('.claude')
        expect(CLAUDE_ROOT_DIR).toBe(ASSISTANT_CONFIGS[ASSISTANT_TYPES.CLAUDE].rootDir)
      })
    
      it('subdirectory constants are defined', () => {
        expect(SKILLS_SUBDIR).toBe('skills')
        expect(COMMANDS_SUBDIR).toBe('commands')
        expect(AGENTS_SUBDIR).toBe('agents')
      })
    
      it('RUNTIME_SKILL_NAME is defined', () => {
        expect(RUNTIME_SKILL_NAMES[ASSISTANT_TYPES.CLAUDE]).toBe('claudemap-runtime')
        expect(RUNTIME_SKILL_NAMES[ASSISTANT_TYPES.CODEX]).toBe('codexmap-runtime')
        expect(LEGACY_RUNTIME_SKILL_NAMES[ASSISTANT_TYPES.CODEX]).toEqual(['claudemap-runtime'])
        expect(RUNTIME_SKILL_NAME).toBe('claudemap-runtime')
      })
    
      it('composed paths match Claude assistant paths', () => {
        const claudePaths = resolveAssistantPaths(ASSISTANT_TYPES.CLAUDE)
        expect(SKILL_ROOT_REL).toBe(claudePaths.skillRootRel)
        expect(COMMANDS_ROOT_REL).toBe(claudePaths.commandsRootRel)
        expect(AGENTS_ROOT_REL).toBe(claudePaths.agentsPath)
      })
    
      it('filename constants are defined', () => {
        expect(ARCHITECT_AGENT_FILENAME).toBe('claudemap-architect.md')
        expect(INSTALL_RECORD_FILENAME).toBe('claudemap-install.json')
        expect(ARTIFACT_MANIFEST_FILENAME).toBe('claudemap-artifact.json')
        expect(PARTIAL_INSTALL_MARKER_FILENAME).toBe('.partial-install')
      })
    })
    
  • skill/lib/contracts/presentation.js716 B495ad2b3a9f3upstream ↗
    // Presentation-mode enum shared by skill commands and the MCP client.
    //
    // The app (browser) mirrors these values in app/src/contracts/presentation.js.
    // A smoke-test assertion enforces that the two files stay identical.
    
    export const PRESENTATION_MODES = Object.freeze({
      FREE: 'free',
      GUIDED: 'guided',
      LOCKED: 'locked',
    })
    
    export const PRESENTATION_MODE_LIST = Object.freeze([
      PRESENTATION_MODES.FREE,
      PRESENTATION_MODES.GUIDED,
      PRESENTATION_MODES.LOCKED,
    ])
    
    export function isPresentationMode(value) {
      return PRESENTATION_MODE_LIST.includes(value)
    }
    
    export function normalizePresentationMode(value, fallback = PRESENTATION_MODES.FREE) {
      return isPresentationMode(value) ? value : fallback
    }
    
  • skill/lib/contracts/schemas/cache.js750 B2e908aede329upstream ↗
    // Cache file validator (claudemap-cache.json and scoped variants).
    //
    // The cache has had a schemaVersion field from day one, so this validator
    // is the most aligned of the five. The files array is intentionally
    // loose: per-file shape is derived from a file walker that evolves
    // more frequently than the top-level structure.
    
    import { fail, isPlainObject, ok, validateShape } from './shared.js'
    
    const CACHE_ROOT_SHAPE = {
      schemaVersion: 'number',
      generatedAt: 'string',
      fileCount: 'number',
      files: 'array',
      graph: 'object',
    }
    
    export function validateCache(value) {
      const errors = validateShape(value, CACHE_ROOT_SHAPE)
    
      if (errors.length > 0 || !isPlainObject(value)) {
        return fail(errors, value)
      }
    
      return ok(value)
    }
    
  • skill/lib/contracts/schemas/graph.js1.2 KB3029da4858c5upstream ↗
    // Graph JSON validator. Graph payloads are the most-read persisted shape
    // (ClaudeMap, scoped maps, runtime graph). The schema pins the fields that
    // the skill and the app actually depend on; extra fields are tolerated.
    
    import { fail, isPlainObject, ok, pushTypeError, validateShape } from './shared.js'
    
    const GRAPH_ROOT_SHAPE = {
      meta: 'object',
      nodes: 'array',
      edges: 'array',
    }
    
    const NODE_ROOT_SHAPE = {
      id: 'string',
      type: 'string',
    }
    
    const EDGE_ROOT_SHAPE = {
      source: 'string',
      target: 'string',
    }
    
    export function validateGraph(value) {
      const errors = validateShape(value, GRAPH_ROOT_SHAPE)
    
      if (errors.length > 0 || !isPlainObject(value)) {
        return fail(errors, value)
      }
    
      value.nodes.forEach((node, index) => {
        const nodeErrors = validateShape(node, NODE_ROOT_SHAPE, `nodes[${index}]`)
        errors.push(...nodeErrors)
      })
    
      value.edges.forEach((edge, index) => {
        const edgeErrors = validateShape(edge, EDGE_ROOT_SHAPE, `edges[${index}]`)
        errors.push(...edgeErrors)
      })
    
      if (value.files !== undefined && !Array.isArray(value.files)) {
        pushTypeError(errors, 'files', 'array', value.files)
      }
    
      return errors.length === 0 ? ok(value) : fail(errors, value)
    }
    
  • skill/lib/contracts/schemas/index.js3.2 KB3bfcd771430aupstream ↗
    // Entry point for hand-rolled persisted-shape validators.
    //
    // Each reader in the skill / scripts passes its just-parsed JSON through
    // `validateWithWarning(schemaName, value, context)`. If the value is
    // valid, the raw value comes back. If it isn't, a structured warning
    // fires via reportWarning and the raw value still comes back so that
    // the reader can continue with its existing normalize/fallback logic.
    // No validator throws.
    
    import { ERROR_CODES, reportWarning, warning } from '../errors.js'
    import { validateCache } from './cache.js'
    import { validateGraph } from './graph.js'
    import { validateInstallRecord } from './install-record.js'
    import { validateManifest } from './manifest.js'
    import { validateRuntimeEnvelope } from './runtime-envelope.js'
    
    export const SCHEMA_NAMES = Object.freeze({
      GRAPH: 'graph',
      MANIFEST: 'manifest',
      RUNTIME_ENVELOPE: 'runtime-envelope',
      INSTALL_RECORD: 'install-record',
      CACHE: 'cache',
    })
    
    const VALIDATORS = {
      [SCHEMA_NAMES.GRAPH]: validateGraph,
      [SCHEMA_NAMES.MANIFEST]: validateManifest,
      [SCHEMA_NAMES.RUNTIME_ENVELOPE]: validateRuntimeEnvelope,
      [SCHEMA_NAMES.INSTALL_RECORD]: validateInstallRecord,
      [SCHEMA_NAMES.CACHE]: validateCache,
    }
    
    export function validate(schemaName, value) {
      const validator = VALIDATORS[schemaName]
    
      if (!validator) {
        throw new Error(`Unknown schema: ${schemaName}`)
      }
    
      return validator(value)
    }
    
    // Validate and, on failure, fire a warning to the configured sink.
    // Always returns the original value so readers with their own
    // normalize/fallback logic can continue untouched.
    export function validateWithWarning(schemaName, value, context) {
      const result = validate(schemaName, value)
    
      if (!result.ok) {
        reportWarning(
          warning(
            ERROR_CODES.SCHEMA_VALIDATION_FAILED,
            `Schema validation failed for ${schemaName}`,
            {
              ...(context || {}),
              schema: schemaName,
              errors: result.errors.slice(0, 8),
            },
          ),
        )
      }
    
      return value
    }
    
    export { validateCache, validateGraph, validateInstallRecord, validateManifest, validateRuntimeEnvelope }
    
    // Loose predicates for runtime filtering. These match the app's original
    // behavior: they check minimal structural requirements without enforcing
    // the full schema. Use these in contexts where graceful degradation is
    // preferred over strict validation (e.g., fetch response filtering).
    //
    // For strict validation, use validate() or the individual validate*()
    // functions which return { ok, errors, value }.
    
    export function isGraphPayload(value) {
      return Boolean(value && Array.isArray(value.nodes) && Array.isArray(value.edges))
    }
    
    export function isRuntimeEnvelope(value) {
      return Boolean(value && typeof value.graphRevision === 'number' && value.runtime)
    }
    
    export function isMapsManifest(value) {
      return Boolean(value && Array.isArray(value.maps))
    }
    
    // Strict predicates that wrap the full validators. Use these when you want
    // a boolean result but also want to enforce the complete schema.
    
    export function isValidGraph(value) {
      return validateGraph(value).ok
    }
    
    export function isValidRuntimeEnvelope(value) {
      return validateRuntimeEnvelope(value).ok
    }
    
    export function isValidManifest(value) {
      return validateManifest(value).ok
    }
    
  • skill/lib/contracts/schemas/install-record.js1.7 KB2641908ea82cupstream ↗
    // Install record validator (.claude/claudemap-install.json or .codex/claudemap-install.json).
    //
    // Written by scripts/install-claudemap.js at the end of a successful
    // install; read by the same script on the next install to identify
    // managed paths for cleanup. A drifted install record silently causes
    // stale files to survive upgrades, so the validator flags missing keys
    // loudly while still tolerating extra fields.
    //
    // Version history:
    // - v1: Original schema (artifact, artifactVersion, installedAt, managedPaths, mode)
    // - v2: Added `assistant` field to track which assistant type was installed
    
    import { fail, isPlainObject, ok, validateShape } from './shared.js'
    import { ASSISTANT_TYPES } from '../paths.js'
    
    // Required fields for all versions
    const INSTALL_RECORD_SHAPE = {
      artifact: 'string',
      artifactVersion: 'string',
      installedAt: 'string',
      managedPaths: 'array',
      mode: 'string',
    }
    
    // Valid assistant type values
    const VALID_ASSISTANTS = Object.values(ASSISTANT_TYPES)
    
    export function validateInstallRecord(value) {
      const errors = validateShape(value, INSTALL_RECORD_SHAPE)
    
      if (errors.length > 0 || !isPlainObject(value)) {
        return fail(errors, value)
      }
    
      // Validate assistant field if present (optional for backwards compat with v1)
      if (value.assistant !== undefined) {
        if (typeof value.assistant !== 'string') {
          errors.push({
            path: 'assistant',
            message: 'assistant must be a string',
          })
        } else if (!VALID_ASSISTANTS.includes(value.assistant)) {
          errors.push({
            path: 'assistant',
            message: `assistant must be one of: ${VALID_ASSISTANTS.join(', ')}`,
          })
        }
      }
    
      if (errors.length > 0) {
        return fail(errors, value)
      }
    
      return ok(value)
    }
    
  • skill/lib/contracts/schemas/manifest.js1.2 KB2ef8ec2b70fcupstream ↗
    // Map manifest validator (claudemap-maps.json).
    //
    // The manifest is already normalized via normalizeManifest() at every
    // read site. This validator is the pre-normalization shape check: it
    // flags drift loud enough that a future malformed manifest is caught
    // before normalize quietly reshapes it into silence.
    
    import { fail, isPlainObject, ok, pushTypeError, validateShape } from './shared.js'
    
    const MANIFEST_ROOT_SHAPE = {
      version: 'number',
      activeMapId: 'string',
      maps: 'array',
    }
    
    const MAP_ENTRY_SHAPE = {
      id: 'string',
      label: 'string',
      graphPath: 'string',
      statePath: 'string',
      cachePath: 'string',
    }
    
    export function validateManifest(value) {
      const errors = validateShape(value, MANIFEST_ROOT_SHAPE)
    
      if (errors.length > 0 || !isPlainObject(value)) {
        return fail(errors, value)
      }
    
      value.maps.forEach((entry, index) => {
        const entryPath = `maps[${index}]`
        const entryErrors = validateShape(entry, MAP_ENTRY_SHAPE, entryPath)
        errors.push(...entryErrors)
    
        if (entry && entry.scope !== undefined && entry.scope !== null && !isPlainObject(entry.scope)) {
          pushTypeError(errors, `${entryPath}.scope`, 'object|null', entry.scope)
        }
      })
    
      return errors.length === 0 ? ok(value) : fail(errors, value)
    }
    
  • skill/lib/contracts/schemas/runtime-envelope.js1.3 KBcfbd158b5ca4upstream ↗
    // Runtime envelope validator (claudemap-runtime-state.json).
    //
    // Writers are normalizeRuntimeState / buildNextRuntimeEnvelope in
    // mcp-client.js. The schema below is deliberately tight on the top-level
    // keys and loose on the nested runtime/presentation object, because
    // presentation is still evolving and normalizeRuntimeState already coerces
    // drift into canonical shape on every read.
    
    import { fail, isPlainObject, ok, pushTypeError, validateShape } from './shared.js'
    
    const ENVELOPE_ROOT_SHAPE = {
      graphRevision: 'number',
      updatedAt: 'string',
      graphMeta: 'object',
      runtime: 'object',
    }
    
    export function validateRuntimeEnvelope(value) {
      const errors = validateShape(value, ENVELOPE_ROOT_SHAPE)
    
      if (errors.length > 0 || !isPlainObject(value)) {
        return fail(errors, value)
      }
    
      const runtime = value.runtime
    
      if (runtime.presentation !== undefined && !isPlainObject(runtime.presentation)) {
        pushTypeError(errors, 'runtime.presentation', 'object', runtime.presentation)
      }
    
      if (
        runtime.highlightedNodeIds !== undefined &&
        !Array.isArray(runtime.highlightedNodeIds)
      ) {
        pushTypeError(errors, 'runtime.highlightedNodeIds', 'array', runtime.highlightedNodeIds)
      }
    
      return errors.length === 0 ? ok(value) : fail(errors, value)
    }
    
  • skill/lib/contracts/schemas/schemas.test.js11 KB87e1626e8e32upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/contracts/schemas/shared.js2.5 KB19633f2f4052upstream ↗
    // Shared primitives for hand-rolled validators. Each validator returns
    // { ok, errors, value }: ok=true means the value passed, errors is always
    // an array (empty on success), and value is the input (possibly coerced
    // by the validator, though validators here prefer not to mutate).
    //
    // The model is intentionally small: type checks, required-keys checks,
    // array-item checks. Anything more bespoke is written inline per shape.
    //
    // Warn+best-effort semantics: a validator with errors does NOT throw.
    // The reader that calls it is responsible for reporting the warning
    // (via reportWarning from ../errors.js) and deciding how to degrade.
    
    export function isPlainObject(value) {
      return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
    }
    
    export function pushTypeError(errors, path, expected, actual) {
      errors.push({
        path,
        message: `expected ${expected}, got ${typeOf(actual)}`,
      })
    }
    
    export function pushRequiredError(errors, path) {
      errors.push({ path, message: 'required property missing' })
    }
    
    export function pushEnumError(errors, path, allowed, actual) {
      errors.push({
        path,
        message: `expected one of [${allowed.join(', ')}], got ${JSON.stringify(actual)}`,
      })
    }
    
    export function typeOf(value) {
      if (value === null) return 'null'
      if (Array.isArray(value)) return 'array'
      return typeof value
    }
    
    export function ok(value) {
      return { ok: true, errors: [], value }
    }
    
    export function fail(errors, value) {
      return { ok: false, errors, value }
    }
    
    // Require keys on an object; record missing or wrong-type entries.
    // descriptor: { keyName: 'string' | 'number' | 'boolean' | 'object' | 'array' }
    export function validateShape(value, descriptor, pathPrefix = '') {
      const errors = []
    
      if (!isPlainObject(value)) {
        pushTypeError(errors, pathPrefix || '(root)', 'object', value)
        return errors
      }
    
      for (const [key, expected] of Object.entries(descriptor)) {
        const keyPath = pathPrefix ? `${pathPrefix}.${key}` : key
        const field = value[key]
    
        if (field === undefined) {
          pushRequiredError(errors, keyPath)
          continue
        }
    
        if (expected === 'array') {
          if (!Array.isArray(field)) {
            pushTypeError(errors, keyPath, 'array', field)
          }
          continue
        }
    
        if (expected === 'object') {
          if (!isPlainObject(field)) {
            pushTypeError(errors, keyPath, 'object', field)
          }
          continue
        }
    
        if (typeof field !== expected) {
          pushTypeError(errors, keyPath, expected, field)
        }
      }
    
      return errors
    }
    
  • skill/lib/contracts/versions.js4.4 KB1f549bfbd13fupstream ↗
    // Schema versions for persisted shapes.
    //
    // Every version bump ships with a migration function registered in
    // MIGRATIONS below. runMigrations is the single entry point readers
    // use to bring an older payload forward. Today every shape is at
    // version 1; future bumps add entries to the per-shape arrays.
    
    import { SCHEMA_NAMES } from './schemas/index.js'
    
    export const MANIFEST_VERSION = 1
    export const GRAPH_VERSION = 1
    export const RUNTIME_STATE_VERSION = 1
    export const INSTALL_RECORD_VERSION = 2 // v2: added assistant field
    export const CACHE_VERSION = 1
    
    // Sentinel used when a graph has never been assigned a revision.
    export const GRAPH_REVISION_UNSET = 0
    
    export const CURRENT_VERSIONS = Object.freeze({
      [SCHEMA_NAMES.MANIFEST]: MANIFEST_VERSION,
      [SCHEMA_NAMES.GRAPH]: GRAPH_VERSION,
      [SCHEMA_NAMES.RUNTIME_ENVELOPE]: RUNTIME_STATE_VERSION,
      [SCHEMA_NAMES.INSTALL_RECORD]: INSTALL_RECORD_VERSION,
      [SCHEMA_NAMES.CACHE]: CACHE_VERSION,
    })
    
    // Read the on-disk version of a value. Falls back to 1 so pre-versioned
    // files produced before Phase 6 are treated as "current minus zero" and
    // pass through migrations as no-ops.
    function detectVersion(schemaName, value) {
      if (!value || typeof value !== 'object') {
        return 1
      }
    
      if (schemaName === SCHEMA_NAMES.CACHE) {
        return Number.isFinite(value.schemaVersion) ? value.schemaVersion : 1
      }
    
      return Number.isFinite(value.version) ? value.version : 1
    }
    
    // Per-shape migration ladder. Each entry is { from, to, migrate(value) }.
    // Migrations run sequentially; the first entry whose `from` matches the
    // detected version is applied, then `to` becomes the new detected version,
    // and the loop continues. A schema bump that lands without a ladder entry
    // is a failing PR (ARCHITECTURE-REVIEW Phase 6 rule 4).
    const MIGRATIONS = {
      [SCHEMA_NAMES.MANIFEST]: [],
      [SCHEMA_NAMES.GRAPH]: [],
      [SCHEMA_NAMES.RUNTIME_ENVELOPE]: [],
      [SCHEMA_NAMES.INSTALL_RECORD]: [
        {
          // v1 → v2: Add assistant field, inferred from managedPaths prefixes.
          // If managedPaths contain .codex/ paths but not .claude/, infer Codex;
          // otherwise default to Claude for backwards compatibility.
          from: 1,
          to: 2,
          migrate(value) {
            const paths = value.managedPaths || []
            const hasCodexPaths = paths.some((p) => p.startsWith('.codex/') || p.startsWith('.agents/'))
            const hasClaudePaths = paths.some((p) => p.startsWith('.claude/'))
    
            // If only Codex paths exist, infer Codex; otherwise Claude
            const assistant = hasCodexPaths && !hasClaudePaths ? 'codex' : 'claude'
    
            return {
              ...value,
              assistant,
              version: 2,
            }
          },
        },
      ],
      [SCHEMA_NAMES.CACHE]: [],
    }
    
    export function runMigrations(schemaName, value) {
      const ladder = MIGRATIONS[schemaName]
    
      if (!ladder) {
        throw new Error(`Unknown schema: ${schemaName}`)
      }
    
      let current = value
      let currentVersion = detectVersion(schemaName, current)
      const target = CURRENT_VERSIONS[schemaName]
    
      // Linear walk. Ladder is small; branching is forbidden by contract.
      let safety = ladder.length + 1
      while (currentVersion < target && safety > 0) {
        safety -= 1
        const step = ladder.find((entry) => entry.from === currentVersion)
    
        if (!step) {
          // No registered step. A version gap means a prior bump landed
          // without a migration. Return the payload unchanged and let the
          // caller surface the validator warning.
          return current
        }
    
        current = step.migrate(current)
        currentVersion = step.to
      }
    
      return current
    }
    
    // Test-only: run migrations against a custom ladder and target version.
    // Used by versions.test.js to pin the ladder-walking behavior without
    // polluting the production MIGRATIONS registry.
    export function runMigrationsWithLadder(ladder, targetVersion, value, schemaName) {
      let current = value
      let currentVersion
    
      if (!value || typeof value !== 'object') {
        currentVersion = 1
      } else if (schemaName === 'cache') {
        currentVersion = Number.isFinite(value.schemaVersion) ? value.schemaVersion : 1
      } else {
        currentVersion = Number.isFinite(value.version) ? value.version : 1
      }
    
      let safety = ladder.length + 1
      while (currentVersion < targetVersion && safety > 0) {
        safety -= 1
        const step = ladder.find((entry) => entry.from === currentVersion)
    
        if (!step) {
          return current
        }
    
        current = step.migrate(current)
        currentVersion = step.to
      }
    
      return current
    }
    
  • skill/lib/contracts/versions.test.js8.8 KB5462e6d539a0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/differ.js2.6 KBdd8193a60617upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/differ.test.js12 KBf127a9ab1c62upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment.js949 B24967faac535upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/enrichment.test.js11 KBc98157f7cbd0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/graph-validation.js2.4 KB3b4265d189c1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/health.js1.8 KB3e53d5a1f33fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/icons.js1.4 KB27c5c2909a07upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/index.js8.4 KB8aaea3c343b2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/prompts.js2.1 KBfec03cfa278aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/enrichment/source-priority.js2.3 KB7b953b877d8bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/file-walker.js7.1 KBf71415e42c01upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/import-resolution.js3.6 KBfa02ad08360cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/launcher.js2.4 KBde10c887e591upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/fingerprint.js3.4 KBdf6d3063f20cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/index.js1.6 KBdbaaf91a100eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/io.js1.8 KB101b6e5a23a8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/migrations.js2.2 KB304f918c0721upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/normalize.js3.3 KB92784c46b327upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/scope-resolution.js3.3 KB462bfde9f1d1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/manifest/scope-resolution.test.js11 KB750e665718c2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/map-manifest.js1.6 KB264655dcf840upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/mcp-client.js24 KBc86b19c44cf6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/runtime-location.js4.4 KBd8e55858f98bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/runtime-location.test.js3.9 KBcb927f814127upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/runtime-paths.js2.8 KB93cb3f863511upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/scoped-map.js6.7 KB6fda4e8824faupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/lib/show-helpers.test.js7.9 KB62e635f9a88bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/package.json768 Bce00f07571c8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/prompts/enrichment.txt5.3 KBe47699cb1038upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/prompts/scoped-enrichment.txt4.7 KBb3bc7606925eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skill/vitest.config.js154 B7e4d1609ec9bupstream ↗
    import { defineConfig } from 'vitest/config'
    
    export default defineConfig({
      test: {
        include: ['lib/**/*.test.js'],
        environment: 'node',
      },
    })
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/quinnaho-claudemap-skill.md

// REPO STATS

295 stars
2 open issues
Last commit: 7mo ago