# claudemap-runtime

Adopt this skill: https://proskills.md/skills/other/quinnaho-claudemap-skill

Page: https://proskills.md/skills/other/quinnaho-claudemap-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skill/SKILL.md
size: 7602
sha: 5412e386f3403d56ae7cf042059a00f0e1ec63ff
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/SKILL.md

```text
---
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.
```

## File: skill/commands/create-map.js
size: 11163
sha: f882e3e116569eb62c16bf8da08c19a7ef072f5b
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/commands/create-map.js

```text
#!/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)
}
```

## File: skill/commands/open-claudemap.js
size: 3887
sha: 5e1a1a1bd1edeb0ea3d48a8eb7fd29055904dd73
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/commands/open-claudemap.js

```text
#!/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)
}
```

## File: skill/commands/refresh.js
size: 11659
sha: 953efcf5fc0d05c373ca1d7ba7e63684a79650bb
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/commands/refresh.js

```text
#!/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)
}
```

## File: skill/commands/setup-claudemap.js
size: 9058
sha: 0ff1f0ba0d4ed4fd74415aaaffd45cae65992a5b
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/commands/setup-claudemap.js

```text
#!/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)
}
```

## File: skill/commands/show.js
size: 19281
sha: 7a9b390d3a021d546a19b8611c9261b9e8130466
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/commands/show.js

```text
#!/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)
}
```

## File: skill/commands/snapshot.js
size: 1495
sha: 300aba6a95404231094b21e4219dd236d713bfca
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/commands/snapshot.js

```text
#!/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)
}
```

## File: skill/lib/active-map.js
size: 1428
sha: 48b286ceda87cbdf4d0f966e23c08151f5849cc3
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/active-map.js

```text
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,
  }
}
```

## File: skill/lib/cache.js
size: 2191
sha: f48732b09ab1a41b2ca715dd4199484c0c4eeade
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/cache.js

```text
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
}
```

## File: skill/lib/command-harness/enrichment-io.js
size: 1112
sha: 24843265f797800d99287bdb9ce9d0d508a43778
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/enrichment-io.js

```text
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)
}
```

## File: skill/lib/command-harness/log.js
size: 1014
sha: 8fd979b673c42219a0eb0afdb04d84c6188c54f5
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/log.js

```text
// 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}`)
  }
}
```

## File: skill/lib/command-harness/parse-args.js
size: 4877
sha: 7e590efed0f074c2fe2e59a36af815f6f188868f
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/parse-args.js

```text
// 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)
}
```

## File: skill/lib/command-harness/project-root.js
size: 640
sha: 0852f6645b80121e435f8b4ffa66e5ed38fa6b28
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/project-root.js

```text
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(),
  )
}
```

## File: skill/lib/command-harness/render-slash-template.js
size: 2517
sha: 6350eee3bfb4a3e07cf870a081d63efc96f175ed
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/render-slash-template.js

```text
// 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 : ''}`
}
```

## File: skill/lib/command-harness/run-command.js
size: 5069
sha: 970b5f3e015ac0535fee9cb76b0e915574cdd1d3
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/run-command.js

```text
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)
}
```

## File: skill/lib/command-harness/slash-only-descriptors.js
size: 2481
sha: 6481f823591703eaaaa2fe1cb952f05537e93188
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/slash-only-descriptors.js

```text
// 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.`,
}
```

## File: skill/lib/command-harness/with-mcp.js
size: 960
sha: bbc263e70601b37a9d9e21ae61802ec9ed452b31
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/command-harness/with-mcp.js

```text
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)
  }
}
```

## File: skill/lib/contracts/errors.js
size: 2849
sha: 47c2aeb90d2a3c4b4753c0dbd191298959ce3b2d
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/errors.js

```text
// 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)
}
```

## File: skill/lib/contracts/graph-sources.js
size: 1375
sha: 7614aef403e0fa78cf5c2bf7200a68f651d00626
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/graph-sources.js

```text
// 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
}
```

## File: skill/lib/contracts/index.js
size: 307
sha: 7147ad4a54e20cc1a0ce0545d660c6347d2af2a3
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/index.js

```text
// 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'
```

## File: skill/lib/contracts/paths.js
size: 11314
sha: 78a6f6626a10f868c9b1097d9c70013881dea9c7
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/paths.js

```text
// 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
}
```

## File: skill/lib/contracts/paths.test.js
size: 11137
sha: 520e8d76018c595618dba012de808aea776e28b0
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/paths.test.js

```text
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')
  })
})
```

## File: skill/lib/contracts/presentation.js
size: 716
sha: 495ad2b3a9f3950ea72eca4575f589b03670fc20
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/presentation.js

```text
// 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
}
```

## File: skill/lib/contracts/schemas/cache.js
size: 750
sha: 2e908aede3291a4fb5dedf714d94bf1532c2d6ff
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/cache.js

```text
// 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)
}
```

## File: skill/lib/contracts/schemas/graph.js
size: 1216
sha: 3029da4858c55845923aa309f6d41fbefb67191f
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/graph.js

```text
// 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)
}
```

## File: skill/lib/contracts/schemas/index.js
size: 3290
sha: 3bfcd771430a98f50327b970ce69eae13feedc0c
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/index.js

```text
// 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
}
```

## File: skill/lib/contracts/schemas/install-record.js
size: 1762
sha: 2641908ea82c92feb3a7fa725faed328bbabc793
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/install-record.js

```text
// 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)
}
```

## File: skill/lib/contracts/schemas/manifest.js
size: 1264
sha: 2ef8ec2b70fc10c6fd4996db66ee45d668c20c50
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/manifest.js

```text
// 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)
}
```

## File: skill/lib/contracts/schemas/runtime-envelope.js
size: 1281
sha: cfbd158b5ca43b265328b234a5dc441628adbbe7
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/runtime-envelope.js

```text
// 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)
}
```

## File: skill/lib/contracts/schemas/schemas.test.js
size: 11521
sha: 87e1626e8e324dc6b0a006603b48c1b182616e11
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/schemas.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/schemas.test.js

## File: skill/lib/contracts/schemas/shared.js
size: 2546
sha: 19633f2f4052b509641d5985142d8d7acafd62fe
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/schemas/shared.js

```text
// 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
}
```

## File: skill/lib/contracts/versions.js
size: 4513
sha: 1f549bfbd13fe2835a7d9d48b666e4daac21b8a8
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/versions.js

```text
// 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
}
```

## File: skill/lib/contracts/versions.test.js
size: 9008
sha: 5462e6d539a0cf18aa0c167b81dfa703caab33ee
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/versions.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/contracts/versions.test.js

## File: skill/lib/differ.js
size: 2701
sha: dd8193a6061751dca800dd877ccaebcced8c7219
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/differ.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/differ.js

## File: skill/lib/differ.test.js
size: 12522
sha: f127a9ab1c62cfa23d386beacba626fda5adab73
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/differ.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/differ.test.js

## File: skill/lib/enrichment.js
size: 949
sha: 24967faac5356ce80e7264482941ce6dca24aae9
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment.js

## File: skill/lib/enrichment/enrichment.test.js
size: 11592
sha: c98157f7cbd08da2129800fea9575eae0ab803a3
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/enrichment.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/enrichment.test.js

## File: skill/lib/enrichment/graph-validation.js
size: 2423
sha: 3b4265d189c121e2b90b178b2439aa748c8026ff
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/graph-validation.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/graph-validation.js

## File: skill/lib/enrichment/health.js
size: 1848
sha: 3e53d5a1f33f353b025efa8ac82478709d0f8613
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/health.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/health.js

## File: skill/lib/enrichment/icons.js
size: 1421
sha: 27c5c2909a074b1b21e47aa5678a192c913e5f73
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/icons.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/icons.js

## File: skill/lib/enrichment/index.js
size: 8574
sha: 8aaea3c343b2ebe6eddbd3ab505d3f209c4560f7
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/index.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/index.js

## File: skill/lib/enrichment/prompts.js
size: 2101
sha: fec03cfa278a24e6ceeea792a3211214639d3a58
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/prompts.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/prompts.js

## File: skill/lib/enrichment/source-priority.js
size: 2351
sha: 7b953b877d8b2b403c7ea25a01a9f3e061fbee52
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/source-priority.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/enrichment/source-priority.js

## File: skill/lib/file-walker.js
size: 7302
sha: f71415e42c0157f1b3a8b73c7719bed3e285e50d
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/file-walker.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/file-walker.js

## File: skill/lib/import-resolution.js
size: 3668
sha: fa02ad08360ca8d38708e387506189f1f20a7a97
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/import-resolution.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/import-resolution.js

## File: skill/lib/launcher.js
size: 2460
sha: de10c887e591a4f0c10a5a09b9736b856cef3ca8
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/launcher.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/launcher.js

## File: skill/lib/manifest/fingerprint.js
size: 3438
sha: df6d3063f20c5bac9570c90d5b5f66828e7eb508
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/fingerprint.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/fingerprint.js

## File: skill/lib/manifest/index.js
size: 1611
sha: dbaaf91a100ea7ba0e9d05a9b716f9d14d0ae500
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/index.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/index.js

## File: skill/lib/manifest/io.js
size: 1854
sha: 101b6e5a23a8bdad6a535d8862f5baf3a0932100
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/io.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/io.js

## File: skill/lib/manifest/migrations.js
size: 2271
sha: 304f918c07218ffd338367e8cd8e32c182b2f430
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/migrations.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/migrations.js

## File: skill/lib/manifest/normalize.js
size: 3395
sha: 92784c46b32771b0ba7e2084b7da566d5b5851d3
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/normalize.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/normalize.js

## File: skill/lib/manifest/scope-resolution.js
size: 3377
sha: 462bfde9f1d18488501b69acc486d6b057f5a459
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/scope-resolution.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/scope-resolution.js

## File: skill/lib/manifest/scope-resolution.test.js
size: 10990
sha: 750e665718c2e5e7d5df6e5e1b53f08386fc1702
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/scope-resolution.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/manifest/scope-resolution.test.js

## File: skill/lib/map-manifest.js
size: 1606
sha: 264655dcf84002f3c49d5cf8da6202fc04b119e9
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/map-manifest.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/map-manifest.js

## File: skill/lib/mcp-client.js
size: 24607
sha: c86b19c44cf6fce40ce9bc32e4ba6d1b2edaa399
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/mcp-client.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/mcp-client.js

## File: skill/lib/runtime-location.js
size: 4476
sha: d8e55858f98b594a40dfedf86bba77f5efe372ef
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/runtime-location.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/runtime-location.js

## File: skill/lib/runtime-location.test.js
size: 3945
sha: cb927f8141274c40729139e2addc228521d6abb5
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/runtime-location.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/runtime-location.test.js

## File: skill/lib/runtime-paths.js
size: 2819
sha: 93cb3f8635112f9897c4c0e74f55ed94c4cf1468
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/runtime-paths.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/runtime-paths.js

## File: skill/lib/scoped-map.js
size: 6836
sha: 6fda4e8824fa700828320e00b136484036e9851f
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/scoped-map.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/scoped-map.js

## File: skill/lib/show-helpers.test.js
size: 8083
sha: 62e635f9a88ba0b408fa33da979ea4c40115c850
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/lib/show-helpers.test.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/lib/show-helpers.test.js

## File: skill/package.json
size: 768
sha: ce00f07571c88597f0f8633b27d4b9d67c32e37f
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/package.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/package.json

## File: skill/prompts/enrichment.txt
size: 5438
sha: e47699cb10386b362a7b7fd8b3a2d25b4f77524e
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/prompts/enrichment.txt

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/prompts/enrichment.txt

## File: skill/prompts/scoped-enrichment.txt
size: 4809
sha: b3bc7606925eb2df447eabd4fb8c0124a7b7c2d0
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/prompts/scoped-enrichment.txt

Content is not inlined in the catalog. Read the upstream file: https://github.com/quinnaho/claudemap/blob/main/skill/prompts/scoped-enrichment.txt

## File: skill/vitest.config.js
size: 154
sha: 7e4d1609ec9bc87a5626067cc2aad0ef8de2f889
upstream: https://github.com/quinnaho/claudemap/blob/main/skill/vitest.config.js

```text
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    include: ['lib/**/*.test.js'],
    environment: 'node',
  },
})
```

## File: README.md
upstream: https://github.com/quinnaho/claudemap/blob/main/README.md

````text
Welcome to...

![ClaudeMap](resources/img/ClaudeMapBranding.png)

[![Version](https://img.shields.io/badge/version-v0.2.0-blue)](CHANGELOG.md) [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE) ![npm downloads](https://img.shields.io/npm/dw/%40quinnaho%2Fclaudemap) ![GitHub stars](https://img.shields.io/github/stars/QuinnAho/claudemap)

**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](resources/img/thumbnail.png)](https://www.loom.com/share/6a2ff0948ae64ae6994fb3817cb3607e)

[Try the map](https://quinnaho.github.io/claudemap/) (standalone preview, Claude features require Claude Code or Codex)

[Longer YouTube walkthrough](https://www.youtube.com/watch?v=mubRRx5mXzA)

## Install

```bash
npx @quinnaho/claudemap install
claude
/setup-claudemap
```

**Codex support is here!**`npx @quinnaho/claudemap install --assistant codex` - see [Codex guide](docs/CODEX.md).

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

```text
$codexmap-runtime build the initial map for this repo
```

## Commands

| Command | Description |
|---------|-------------|
| `/setup-claudemap` | Analyze your repo and generate the map |
| `/refresh` | Update map after code changes |
| `/explain` | AI-guided walkthroughs with visual highlighting |
| `/show` | Navigate 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

- [Full Guide](docs/GUIDE.md) - setup walkthrough, commands, multi-map workflow
- [Codex Guide](docs/CODEX.md) - Codex-specific setup and commands
- [Changelog](CHANGELOG.md) - version history
- [Contributing](CONTRIBUTING.md) - help improve ClaudeMap

## License

MIT
````
