All files / src resolve-meridian-projects.ts

90.9% Statements 290/319
83.33% Branches 95/114
85.36% Functions 35/41
90.9% Lines 290/319

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 3201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 5x 5x 12x 4x 4x 12x 12x 1x 1x 12x 7x 5x 1x 27x 27x 27x 14x 27x 27x 1x 1x 1x 13x 13x 27x 27x 13x 13x 27x 26x     26x 14x 13x 1x 1x 26x 26x 5x 5x 26x 26x 1x 1x 13x 1x 1x 13x 6x 6x 13x 13x     6x 13x 1x 2x 2x 2x 1x 1x 12x 12x 4x 4x 12x 12x 1x 1x 12x 12x 4x 4x 12x 12x 12x 1x 30x 30x 30x 1x 1x 12x 12x 11x 11x 12x 1x 1x 1x     12x 1x 1x 11x 11x 11x 29x     29x 29x 29x 29x     29x 29x 55x 14x 14x 55x 11x 11x 55x 55x 30x 55x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 55x 55x 18x 29x 11x 11x 11x 11x 1x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 10x 10x 10x 10x 8x 8x 10x 2x 10x 1x 1x 9x 9x 9x 9x 9x 9x 9x 2x 2x 2x 2x 2x 9x 9x 9x 7x 7x 9x 9x 9x 3x 9x 9x 9x 1x 1x 9x 9x 9x 9x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 1x 1x 3x     3x 3x 3x 3x                       3x 3x 3x 1x 1x 3x 3x 3x 3x 3x     3x 2x 2x 3x     3x 1x 1x 3x 3x 1x 1x 7x 7x 7x 7x 7x  
import * as fs from "node:fs"
import * as path from "node:path"
 
const KIT_REL = path.join(".agent", "MERIDIAN.md")
const MANIFEST_REL = path.join(".meridian", "projects.json")
const US_FILENAME = /^US-\d{4}\.md$/i
 
const IGNORED_DIR_NAMES = new Set([
  "node_modules",
  ".git",
  "dist",
  "build",
  "bundled",
  ".agent",
  "coverage",
  ".next",
  ".turbo",
  "out",
  ".cache",
  "vendor",
])
 
const MAX_SCAN_DEPTH = 12
 
export type MeridianProject = {
  id: string
  name: string
  /** Relative to kit root, always ends with `/docs` or `docs` */
  docs: string
  /** Parent folder of docs (`.` = kit root) */
  packageRoot: string
  source: "manifest" | "discovered"
}
 
export type ProjectsManifest = {
  version?: number
  default?: string
  projects?: Array<{ id: string; name: string; docs: string }>
  exclude?: string[]
}
 
export function kitFileAt(root: string): string {
  return path.join(root, KIT_REL)
}
 
export function findKitRoot(startPath: string): string | null {
  let current = path.resolve(startPath)
  for (;;) {
    if (fs.existsSync(kitFileAt(current))) {
      return current
    }
    const parent = path.dirname(current)
    if (parent === current) {
      return null
    }
    current = parent
  }
}
 
function agentScriptsDirHasKit(scriptsDir: string): boolean {
  return (
    fs.existsSync(path.join(scriptsDir, "meridian_db_export.py")) ||
    fs.existsSync(path.join(scriptsDir, "meridian_import_graph.py"))
  )
}
 
/** Walk ancestors until `.agent/scripts` has Meridian kit CLIs (shared kit in monorepos). */
export function findKitScriptsRoot(startPath: string): string | null {
  let current = path.resolve(startPath)
  for (;;) {
    const scriptsDir = path.join(current, ".agent", "scripts")
    if (agentScriptsDirHasKit(scriptsDir)) {
      return current
    }
    const parent = path.dirname(current)
    if (parent === current) {
      return null
    }
    current = parent
  }
}
 
export function toPosixRel(kitRoot: string, absPath: string): string {
  const rel = path.relative(kitRoot, absPath)
  if (rel === "") {
    return "."
  }
  return rel.split(path.sep).join("/")
}
 
export function isMeridianDocs(docsDir: string): boolean {
  if (!fs.existsSync(docsDir) || !fs.statSync(docsDir).isDirectory()) {
    return false
  }
  if (fs.existsSync(path.join(docsDir, "00_scope.md"))) {
    return true
  }
  const usDir = path.join(docsDir, "us")
  if (!fs.existsSync(usDir) || !fs.statSync(usDir).isDirectory()) {
    return false
  }
  return fs.readdirSync(usDir).some((name) => US_FILENAME.test(name))
}
 
function docsDirExists(docsDir: string): boolean {
  return fs.existsSync(docsDir) && fs.statSync(docsDir).isDirectory()
}
 
export function defaultIdFromDocsRel(docsRel: string): string {
  const parent = path.posix.dirname(docsRel.replace(/\\/g, "/"))
  if (parent === "." || parent === "") {
    return "main"
  }
  return parent.replace(/\//g, "-")
}
 
export function defaultNameFromDocsRel(docsRel: string): string {
  const parent = path.posix.dirname(docsRel.replace(/\\/g, "/"))
  if (parent === "." || parent === "") {
    return "Main"
  }
  const base = parent.split("/").pop() ?? parent
  return base
}
 
function normalizeDocsRel(docsRel: string): string {
  return docsRel.replace(/\\/g, "/").replace(/\/+$/, "")
}
 
export function readProjectsManifest(kitRoot: string): ProjectsManifest | null {
  const manifestPath = path.join(kitRoot, MANIFEST_REL)
  if (!fs.existsSync(manifestPath)) {
    return null
  }
  try {
    const raw = fs.readFileSync(manifestPath, "utf8")
    return JSON.parse(raw) as ProjectsManifest
  } catch {
    return null
  }
}
 
export function discoverMeridianProjects(kitRoot: string): MeridianProject[] {
  const found: MeridianProject[] = []
 
  function walk(dir: string, depth: number): void {
    if (depth > MAX_SCAN_DEPTH) {
      return
    }
    let entries: fs.Dirent[]
    try {
      entries = fs.readdirSync(dir, { withFileTypes: true })
    } catch {
      return
    }
 
    for (const entry of entries) {
      if (!entry.isDirectory()) {
        continue
      }
      if (IGNORED_DIR_NAMES.has(entry.name)) {
        continue
      }
 
      const full = path.join(dir, entry.name)
 
      if (entry.name === "docs") {
        if (isMeridianDocs(full)) {
          const docsRel = normalizeDocsRel(toPosixRel(kitRoot, full))
          const packageRoot = normalizeDocsRel(
            toPosixRel(kitRoot, path.dirname(full)),
          )
          found.push({
            id: defaultIdFromDocsRel(docsRel),
            name: defaultNameFromDocsRel(docsRel),
            docs: docsRel,
            packageRoot: packageRoot === "" ? "." : packageRoot,
            source: "discovered",
          })
        }
        continue
      }
 
      walk(full, depth + 1)
    }
  }
 
  walk(kitRoot, 0)
  return found
}
 
function manifestToProject(
  kitRoot: string,
  entry: { id: string; name: string; docs: string },
): MeridianProject | null {
  const docsRel = normalizeDocsRel(entry.docs)
  const docsAbs = path.join(kitRoot, ...docsRel.split("/"))
  if (!docsDirExists(docsAbs)) {
    return null
  }
  const packageRoot = normalizeDocsRel(toPosixRel(kitRoot, path.dirname(docsAbs)))
  return {
    id: entry.id,
    name: entry.name,
    docs: docsRel,
    packageRoot: packageRoot === "" ? "." : packageRoot,
    source: "manifest",
  }
}
 
export function applyExclude(
  projects: MeridianProject[],
  exclude: string[] | undefined,
): MeridianProject[] {
  if (!exclude?.length) {
    return projects
  }
  const excluded = new Set(exclude.map((e) => normalizeDocsRel(e)))
  return projects.filter((p) => !excluded.has(p.docs))
}
 
export function mergeMeridianProjects(
  kitRoot: string,
  manifest: ProjectsManifest | null,
  discovered: MeridianProject[],
): MeridianProject[] {
  const byDocs = new Map<string, MeridianProject>()
 
  for (const entry of manifest?.projects ?? []) {
    const project = manifestToProject(kitRoot, entry)
    if (project) {
      byDocs.set(project.docs, project)
    }
  }
 
  for (const project of discovered) {
    if (!byDocs.has(project.docs)) {
      byDocs.set(project.docs, project)
    }
  }
 
  const merged = [...byDocs.values()].sort((a, b) =>
    a.docs.localeCompare(b.docs),
  )
  return applyExclude(merged, manifest?.exclude)
}
 
export function resolveMeridianProjects(kitRoot: string): MeridianProject[] {
  const manifest = readProjectsManifest(kitRoot)
  const discovered = discoverMeridianProjects(kitRoot)
  return mergeMeridianProjects(kitRoot, manifest, discovered)
}
 
/** Prefer project whose package or docs matches the opened workspace folder. */
export function matchProjectForWorkspacePath(
  projects: MeridianProject[],
  kitRoot: string,
  workspacePath: string,
): MeridianProject | null {
  const normalized = path.resolve(workspacePath)
  const kit = path.resolve(kitRoot)
 
  for (const project of projects) {
    const packageAbs = path.join(kit, ...project.packageRoot.split("/"))
    const docsAbs = path.join(kit, ...project.docs.split("/"))
    if (normalized === packageAbs || normalized === docsAbs) {
      return project
    }
    if (
      normalized.startsWith(packageAbs + path.sep) ||
      normalized.startsWith(docsAbs + path.sep)
    ) {
      return project
    }
  }
 
  const localDocs = path.join(normalized, "docs")
  if (isMeridianDocs(localDocs)) {
    const docsRel = normalizeDocsRel(toPosixRel(kit, localDocs))
    return (
      projects.find((p) => p.docs === docsRel) ?? {
        id: defaultIdFromDocsRel(docsRel),
        name: defaultNameFromDocsRel(docsRel),
        docs: docsRel,
        packageRoot: normalizeDocsRel(toPosixRel(kit, normalized)),
        source: "discovered",
      }
    )
  }
 
  return null
}
 
export function pickDefaultProjectId(
  projects: MeridianProject[],
  manifest: ProjectsManifest | null,
  preferredId: string | undefined,
): string | undefined {
  if (projects.length === 0) {
    return undefined
  }
  if (preferredId && projects.some((p) => p.id === preferredId)) {
    return preferredId
  }
  if (manifest?.default && projects.some((p) => p.id === manifest.default)) {
    return manifest.default
  }
  if (projects.length === 1) {
    return projects[0].id
  }
  return undefined
}
 
export function projectById(
  projects: MeridianProject[],
  id: string,
): MeridianProject | undefined {
  return projects.find((p) => p.id === id)
}