{"version":3,"file":"init.cjs","names":["join","existsSync","parseYaml","readFileSync","stringifyYaml","readWorkspaceCatalogFromDisk","findConfigPath","resolve","walkExtendsChain","basename","isAppDescriptorPath","loadAppDescriptorConfig","fetchBosConfigFromFastKv","getExtendsRef","parseBosRef","fetchResponse","createWriteStream","pipeline","tarExtract","lstatSync","dirname","serializeAppDescriptorSource","saveBosConfig","loadManifestNormalizationSpec","buildAuthTypesGenContent","buildAuthExportStub","buildAuthContractStub","relative","normalizePackageManifestsInTree","computeHash","writeSnapshot","mkdtempSync","tmpdir"],"sources":["../../src/cli/init.ts"],"sourcesContent":["import {\n  createWriteStream,\n  existsSync,\n  lstatSync,\n  mkdirSync,\n  mkdtempSync,\n  readFileSync,\n  rmSync,\n  writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { execa } from \"execa\";\nimport { glob } from \"glob\";\nimport { extract as tarExtract } from \"tar\";\nimport { parse as parseYaml, stringify as stringifyYaml } from \"yaml\";\nimport {\n  buildAuthContractStub,\n  buildAuthExportStub,\n  buildAuthTypesGenContent,\n} from \"../auth-types-gen\";\nimport { findConfigPath, isAppDescriptorPath, loadAppDescriptorConfig } from \"../config\";\nimport type { OverrideSection } from \"../contract\";\nimport { serializeAppDescriptorSource } from \"../descriptor/serialize\";\nimport { fetchBosConfigFromFastKv } from \"../fastkv\";\nimport { fetchResponse } from \"../http-client\";\nimport {\n  loadManifestNormalizationSpec,\n  normalizePackageManifestsInTree,\n} from \"../internal/manifest-normalizer\";\nimport { walkExtendsChain } from \"../resolution/session\";\nimport type { BosConfig, BosConfigInput, ParentStarterConfig, StarterLevel } from \"../types\";\nimport { saveBosConfig } from \"../utils/save-config\";\nimport { computeSnapshotHash as computeHash } from \"../utils/snapshot-hash\";\nimport { readWorkspaceCatalog as readWorkspaceCatalogFromDisk } from \"../workspace-catalog\";\nimport { writeSnapshot } from \"./snapshot\";\nimport { getExtendsRef, parseBosRef } from \"./utils/helpers\";\n\nexport const PNPM_PACKAGE_MANAGER = \"pnpm@12.10.1\";\n\n/**\n * Transitive-singleton overrides every workspace in the fleet must agree on\n * (ticket 05's deviation log: isolated resolution splits better-auth\n * peer-context identities across the plugin fleet). Values derive from the\n * catalog so sync keeps them current; keys absent from the catalog are left\n * unpinned.\n */\nconst CHILD_OVERRIDE_KEYS = [\n  \"@better-fetch/fetch\",\n  \"@rspack/core\",\n  \"better-auth\",\n  \"react\",\n  \"react-dom\",\n] as const;\n\n/**\n * The child's workspace manifest: pnpm-workspace.yaml is canonical (v2, ADR\n * 0026) — packages globs synthesized from the child's override sections, the\n * catalog merged over any local entry, plus the fleet-wide linker posture and\n * singleton overrides. Re-running (sync/upgrade) merges instead of clobbering.\n */\nexport function writeChildWorkspaceYaml(\n  projectDir: string,\n  next: { packages: string[]; catalog: Record<string, string> },\n): boolean {\n  const yamlPath = join(projectDir, \"pnpm-workspace.yaml\");\n  let doc: {\n    packages?: string[];\n    catalog?: Record<string, string>;\n    nodeLinker?: string;\n    linkWorkspacePackages?: boolean;\n    ignoreScripts?: boolean;\n    overrides?: Record<string, string>;\n  } = {};\n  if (existsSync(yamlPath)) {\n    try {\n      const parsed = parseYaml(readFileSync(yamlPath, \"utf-8\"));\n      if (parsed && typeof parsed === \"object\") doc = parsed;\n    } catch {\n      doc = {};\n    }\n  }\n\n  let changed = !existsSync(yamlPath);\n  const packages = [...new Set([...(doc.packages ?? []), ...next.packages])].sort();\n  if (JSON.stringify(packages) !== JSON.stringify(doc.packages)) {\n    doc.packages = packages;\n    changed = true;\n  }\n\n  const catalog: Record<string, string> = { ...doc.catalog };\n  for (const [name, version] of Object.entries(next.catalog)) {\n    if (catalog[name] !== version) {\n      catalog[name] = version;\n      changed = true;\n    }\n  }\n  if (\n    Object.keys(catalog).length > 0 &&\n    Object.keys(catalog).length !== Object.keys(doc.catalog ?? {}).length\n  ) {\n    changed = true;\n  }\n  if (changed || !doc.catalog) {\n    doc.catalog = Object.fromEntries(\n      Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b)),\n    );\n  }\n\n  if (doc.nodeLinker !== \"hoisted\") {\n    doc.nodeLinker = \"hoisted\";\n    changed = true;\n  }\n  if (doc.linkWorkspacePackages !== true) {\n    doc.linkWorkspacePackages = true;\n    changed = true;\n  }\n  if (doc.ignoreScripts !== true) {\n    doc.ignoreScripts = true;\n    changed = true;\n  }\n\n  const overrides: Record<string, string> = { ...doc.overrides };\n  for (const key of CHILD_OVERRIDE_KEYS) {\n    if (catalog[key] && overrides[key] !== catalog[key]) {\n      overrides[key] = catalog[key];\n      changed = true;\n    }\n  }\n  if (Object.keys(overrides).length > 0) {\n    doc.overrides = Object.fromEntries(\n      Object.entries(overrides).sort(([a], [b]) => a.localeCompare(b)),\n    );\n  }\n\n  if (changed) {\n    writeFileSync(yamlPath, `${stringifyYaml(doc, { lineWidth: 0 }).trimEnd()}\\n`);\n    return true;\n  }\n  return false;\n}\n\n/**\n * Init must never reuse a lockfile left in the target (copied from a parent\n * checkout or left by a previous run) — stale framework resolutions would\n * survive the fresh install. Bun's bun.lock is deleted on sight (ADR 0026's\n * silent-revert footgun); the child's own pnpm-lock.yaml is re-resolved.\n */\nexport function removeStrayLockfiles(projectDir: string): void {\n  for (const lockfile of [\"pnpm-lock.yaml\", \"bun.lock\"]) {\n    const lockfilePath = join(projectDir, lockfile);\n    if (existsSync(lockfilePath)) {\n      rmSync(lockfilePath, { force: true });\n    }\n  }\n}\n\nexport const INIT_ROOT_PATTERNS = [\n  \"bos.config.json\",\n  \"package.json\",\n  \".env.example\",\n  \".gitignore\",\n  \"biome.json\",\n  \"railway.json\",\n  \"railway.toml\",\n  \"AGENTS.md\",\n  \".agents/skills/**\",\n  \"skills-lock.json\",\n  \"docs/agents/**\",\n  \".changeset/config.json\",\n  \".changeset/README.md\",\n  \"README.md\",\n  \"CONTRIBUTING.md\",\n  \".github/templates/**\",\n] as const;\n\nconst OVERRIDE_WORKSPACE_MAP: Record<OverrideSection, string[]> = {\n  ui: [\"ui\"],\n  api: [\"api\"],\n  host: [\"host\"],\n  plugins: [],\n};\n\ninterface SourceResult {\n  sourceDir: string;\n  parentConfig: BosConfig;\n  cleanup: () => Promise<void>;\n}\n\nexport interface CatalogChainSource {\n  catalog: Record<string, string>;\n  repository?: string;\n  extendsChain: string[];\n}\n\nexport function readWorkspaceCatalog(sourceDir: string): Record<string, string> {\n  return readWorkspaceCatalogFromDisk(sourceDir);\n}\n\nexport async function resolveCatalogChainSource(opts: {\n  extendsAccount: string;\n  extendsGateway: string;\n  sourceDir?: string;\n}): Promise<CatalogChainSource> {\n  const entry = opts.sourceDir\n    ? (findConfigPath(resolve(opts.sourceDir)) ?? join(resolve(opts.sourceDir), \"bos.config.json\"))\n    : `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n  const catalogs: Record<string, string>[] = [];\n  const cleanups: Array<() => Promise<void>> = [];\n  const resolvedRefs: string[] = [];\n  let repository: string | undefined;\n\n  try {\n    await walkExtendsChain(entry, {\n      env: \"production\",\n      collectCatalogs: true,\n      registerCleanup: (fn) => cleanups.push(fn),\n      visit: async (link) => {\n        resolvedRefs.unshift(\n          link.ref.startsWith(\"bos://\") ? link.ref : join(link.baseDir, basename(link.ref)),\n        );\n        catalogs.push(readWorkspaceCatalog(link.sourceDir ?? link.baseDir));\n        const repositoryValue = (link.config as Record<string, unknown>).repository;\n        if (typeof repositoryValue === \"string\" && repository === undefined) {\n          repository = repositoryValue;\n        }\n      },\n    });\n  } finally {\n    for (const cleanup of [...cleanups].reverse()) {\n      await cleanup();\n    }\n  }\n\n  return {\n    catalog: Object.assign({}, ...catalogs),\n    repository,\n    extendsChain: opts.sourceDir\n      ? [`bos://${opts.extendsAccount}/${opts.extendsGateway}`, ...resolvedRefs.slice(1)]\n      : resolvedRefs,\n  };\n}\n\nexport async function resolveSourceDir(opts: {\n  extendsAccount: string;\n  extendsGateway: string;\n  source?: string;\n}): Promise<SourceResult> {\n  if (opts.source) {\n    const sourceDir = resolve(opts.source);\n    const configPath = findConfigPath(sourceDir);\n    if (!configPath) {\n      throw new Error(\n        `No authored config (bos.app.ts or bos.config.json) found in source directory: ${sourceDir}`,\n      );\n    }\n    const parentConfig = isAppDescriptorPath(configPath)\n      ? ((await loadAppDescriptorConfig(configPath)) as BosConfig)\n      : (JSON.parse(readFileSync(configPath, \"utf-8\")) as BosConfig);\n    return { sourceDir, parentConfig, cleanup: async () => {} };\n  }\n\n  const parentConfig = await fetchParentConfig(opts.extendsAccount, opts.extendsGateway);\n\n  if (parentConfig.repository) {\n    const { dir: sourceDir, cleanup } = await downloadTarball(parentConfig.repository);\n    return { sourceDir, parentConfig, cleanup };\n  }\n\n  const chainResult = await resolveRepositoryViaExtendsChain(\n    opts.extendsAccount,\n    opts.extendsGateway,\n  );\n  if (chainResult?.repository) {\n    const { dir: sourceDir, cleanup } = await downloadTarball(chainResult.repository);\n    return { sourceDir, parentConfig: chainResult.config, cleanup };\n  }\n\n  return {\n    sourceDir: \"\",\n    parentConfig,\n    cleanup: async () => {},\n  };\n}\n\nexport function buildInitPatterns(\n  overrides: OverrideSection[],\n  plugins?: string[],\n  pluginDirMap?: Record<string, string>,\n): string[] {\n  const has = (section: OverrideSection) => overrides.includes(section);\n  const patterns: string[] = [...INIT_ROOT_PATTERNS];\n\n  if (has(\"ui\")) patterns.push(\"ui/**\");\n  if (has(\"api\")) patterns.push(API_TEMPLATE_PATTERN);\n  if (has(\"api\") || has(\"host\")) patterns.push(COMPOSE_TEMPLATE_PATTERN);\n  if (has(\"host\")) patterns.push(\"host/**\");\n  if (has(\"plugins\")) {\n    for (const plugin of plugins ?? []) {\n      const dirName = pluginDirMap?.[plugin] ?? plugin;\n      patterns.push(`plugins/${dirName}/**`);\n    }\n  }\n\n  return patterns;\n}\n\n/** api-override children get the slim generic shell, never the parent's domain API. */\nconst API_TEMPLATE_PATTERN = \".github/templates/api/**\";\n\n/** Child-sized compose (api + api-test databases) for local compute overrides. */\nconst COMPOSE_TEMPLATE_PATTERN = \".github/templates/docker-compose.yml\";\n\nexport function isApiTemplatePath(filePath: string): boolean {\n  return filePath.startsWith(\".github/templates/api/\");\n}\n\nexport function isComposeTemplatePath(filePath: string): boolean {\n  return filePath === COMPOSE_TEMPLATE_PATTERN;\n}\n\nexport function buildPluginRouteExclusions(\n  parentConfig: { plugins?: Record<string, unknown> } | null | undefined,\n  selectedPlugins: string[],\n): string[] {\n  if (!parentConfig?.plugins) return [];\n\n  const selected = new Set(selectedPlugins);\n  const claimedBySelected = new Set<string>();\n  const claimedByUnselected: string[] = [];\n\n  for (const [pluginKey, entry] of Object.entries(parentConfig.plugins)) {\n    const routes = extractPluginRoutes(entry);\n    if (!routes) continue;\n\n    if (selected.has(pluginKey)) {\n      for (const route of routes) claimedBySelected.add(route);\n    } else {\n      for (const route of routes) claimedByUnselected.push(route);\n    }\n  }\n\n  return claimedByUnselected.filter((route) => !claimedBySelected.has(route));\n}\n\nconst STARTER_PRODUCT_EXCLUSIONS = [\n  \"_public/explore.tsx\",\n  \"_public/stake.tsx\",\n  \"_public/n/**\",\n  \"_public/$accountId.tsx\",\n  \"_public/$accountId/**\",\n  \"_public/activity/**\",\n  \"_public/-stake-*\",\n  \"_authenticated/_dashboard/dashboard/node/**\",\n  \"_authenticated/_dashboard/nodes/**\",\n  \"_authenticated/_dashboard/tenant.*\",\n  \"_authenticated/_dashboard/discover.tsx\",\n  \"_authenticated/_dashboard/apply.tsx\",\n  \"_authenticated/_dashboard/prototype-staking-poc.tsx\",\n  \"_authenticated/onboarding/**\",\n  \"_admin/_dashboard/_dashboard/admin/nodes/**\",\n  \"_admin/_dashboard/_dashboard/admin/proposals/**\",\n  \"_admin/_dashboard/_dashboard/admin/tenants/**\",\n  \"_admin/_dashboard/_dashboard/admin/relayer.tsx\",\n  \"_admin/_dashboard/_dashboard/admin/organizations.tsx\",\n] as const;\n\nconst STARTER_SIMPLE_EXCLUSIONS = [\n  \"_authenticated.tsx\",\n  \"_authenticated/**\",\n  \"_admin.tsx\",\n  \"_admin/**\",\n] as const;\n\n/**\n * Route-file globs (relative to the child's `ui/src/routes/`) that a starter\n * of the given level must not receive. Parent `starter` config can add\n * exclusions (`exclude`, `levels[level].exclude`) or reclaim routes for a\n * level (`levels[level].include`). Entries are prefixed with\n * `ui/src/routes/` so they compose with `copyFilteredFiles`'s ignore list.\n */\nexport function buildStarterRouteExclusions(\n  level: StarterLevel,\n  parentConfig: { starter?: ParentStarterConfig } | null | undefined,\n): string[] {\n  const excluded = new Set<string>(STARTER_PRODUCT_EXCLUSIONS);\n  if (level === \"simple\") {\n    for (const entry of STARTER_SIMPLE_EXCLUSIONS) excluded.add(entry);\n  }\n\n  const starter = parentConfig?.starter;\n  if (starter) {\n    for (const entry of starter.exclude ?? []) excluded.add(entry);\n    const levelConfig = starter.levels?.[level];\n    if (levelConfig) {\n      for (const entry of levelConfig.exclude ?? []) excluded.add(entry);\n      for (const entry of levelConfig.include ?? []) excluded.delete(entry);\n    }\n  }\n\n  return [...excluded].map((entry) => `ui/src/routes/${entry}`);\n}\n\nfunction extractPluginRoutes(entry: unknown): string[] | undefined {\n  if (typeof entry !== \"object\" || entry === null) return undefined;\n  const routes = (entry as { routes?: unknown }).routes;\n  if (!Array.isArray(routes)) return undefined;\n  return routes.filter((r): r is string => typeof r === \"string\");\n}\n\nexport function sourcePathToDestinationPath(filePath: string): string {\n  if (isApiTemplatePath(filePath)) {\n    return filePath.replace(/^\\.github\\/templates\\/api\\//, \"api/\");\n  }\n  if (isComposeTemplatePath(filePath)) {\n    return \"docker-compose.yml\";\n  }\n  return filePath.startsWith(\".github/templates/\")\n    ? filePath.replace(/^\\.github\\/templates\\//, \".github/\")\n    : filePath;\n}\n\nexport async function fetchParentConfig(\n  extendsAccount: string,\n  extendsGateway: string,\n): Promise<BosConfig> {\n  const bosUrl = `bos://${extendsAccount}/${extendsGateway}`;\n  return fetchBosConfigFromFastKv<BosConfig>(bosUrl);\n}\n\nexport async function resolveRepositoryViaExtendsChain(\n  extendsAccount: string,\n  extendsGateway: string,\n  visited = new Set<string>(),\n): Promise<{ repository: string; config: BosConfig } | null> {\n  const key = `bos://${extendsAccount}/${extendsGateway}`;\n  if (visited.has(key)) return null;\n  visited.add(key);\n\n  try {\n    const config = await fetchParentConfig(extendsAccount, extendsGateway);\n    if (config.repository) {\n      return { repository: config.repository, config };\n    }\n\n    const extendsRef = getExtendsRef(config as Record<string, unknown>);\n    if (extendsRef) {\n      const normalized = extendsRef.startsWith(\"bos://\") ? extendsRef : `bos://${extendsRef}`;\n      const parsed = parseBosRef(normalized);\n      if (parsed) {\n        const result = await resolveRepositoryViaExtendsChain(\n          parsed.account,\n          parsed.gateway,\n          visited,\n        );\n        if (result) return result;\n      }\n    }\n\n    return null;\n  } catch {\n    return null;\n  }\n}\n\nexport async function detectGitRemoteUrl(directory: string): Promise<string | undefined> {\n  try {\n    const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n      cwd: directory,\n      stdio: \"pipe\",\n    });\n    const url = stdout.trim();\n    if (!url) return undefined;\n    return normalizeGitUrl(url);\n  } catch {\n    return undefined;\n  }\n}\n\nfunction normalizeGitUrl(url: string): string | undefined {\n  const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n  if (sshMatch) {\n    return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;\n  }\n  const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n  if (httpsMatch) {\n    return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;\n  }\n  return url.endsWith(\".git\") ? url.slice(0, -4) : url;\n}\n\nexport async function downloadTarball(\n  repoUrl: string,\n): Promise<{ dir: string; cleanup: () => Promise<void> }> {\n  const parsed = parseGitHubUrl(repoUrl);\n  if (!parsed) {\n    throw new Error(`Cannot parse repository URL: ${repoUrl}`);\n  }\n\n  const { owner, repo } = parsed;\n  let response: Response | null = null;\n\n  for (const branch of [\"main\", \"master\"]) {\n    const candidate = await fetchResponse(\n      `https://api.github.com/repos/${owner}/${repo}/tarball/${branch}`,\n      {\n        headers: { \"User-Agent\": \"everything-dev\" },\n        redirect: \"follow\",\n        timeout: \"60 seconds\",\n      },\n    );\n    if (candidate.ok) {\n      response = candidate;\n      break;\n    }\n    if (candidate.status !== 404) {\n      throw new Error(\n        `GitHub tarball download failed: ${candidate.status} ${candidate.statusText}`,\n      );\n    }\n  }\n\n  if (!response) {\n    throw new Error(`GitHub tarball download failed for ${repoUrl}: tried main and master`);\n  }\n\n  if (!response.body) {\n    throw new Error(\"GitHub tarball download returned empty body\");\n  }\n\n  const tmpDir = mkTmpDir(\"bos-init-tarball-\");\n  const tarballPath = join(tmpDir, \"source.tar.gz\");\n\n  const fileStream = createWriteStream(tarballPath);\n  const reader = response.body as unknown as NodeJS.ReadableStream;\n  await pipeline(reader, fileStream);\n\n  const extractDir = mkTmpDir(\"bos-init-extract-\");\n  try {\n    await tarExtract({ cwd: extractDir, file: tarballPath, strip: 1 });\n  } catch {\n    await execCommand(\"tar\", [\"-xzf\", tarballPath, \"--strip-components=1\", \"-C\", extractDir]);\n  }\n\n  rmSync(tmpDir, { recursive: true, force: true });\n\n  return {\n    dir: extractDir,\n    cleanup: async () => {\n      rmSync(extractDir, { recursive: true, force: true });\n    },\n  };\n}\n\nfunction parseGitHubUrl(url: string): { owner: string; repo: string } | null {\n  const httpsMatch = url.match(/^https?:\\/\\/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/.*)?$/);\n  if (httpsMatch?.[1] && httpsMatch[2]) {\n    return { owner: httpsMatch[1], repo: httpsMatch[2] };\n  }\n\n  const sshMatch = url.match(/^git@github\\.com:([^/]+)\\/([^/]+?)(?:\\.git)?$/);\n  if (sshMatch?.[1] && sshMatch[2]) {\n    return { owner: sshMatch[1], repo: sshMatch[2] };\n  }\n\n  return null;\n}\n\nexport async function copyFilteredFiles(\n  sourceDir: string,\n  destination: string,\n  patterns: string[],\n  options: {\n    overrides: OverrideSection[];\n    plugins?: string[];\n    ignore?: string[];\n  },\n): Promise<number> {\n  if (patterns.length === 0) {\n    return 0;\n  }\n\n  const baseIgnore = [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"];\n  const ignore = options.ignore ? [...baseIgnore, ...options.ignore] : baseIgnore;\n\n  const allFiles = new Set<string>();\n  for (const pattern of patterns) {\n    const matches = await glob(pattern, {\n      cwd: sourceDir,\n      nodir: true,\n      dot: true,\n      absolute: false,\n      ignore,\n    });\n    for (const match of matches) {\n      allFiles.add(match);\n    }\n  }\n  if (!options.overrides.includes(\"api\")) {\n    for (const match of allFiles) {\n      if (isApiTemplatePath(match)) allFiles.delete(match);\n    }\n  }\n  if (!options.overrides.includes(\"api\") && !options.overrides.includes(\"host\")) {\n    for (const match of allFiles) {\n      if (isComposeTemplatePath(match)) allFiles.delete(match);\n    }\n  }\n\n  mkdirSync(destination, { recursive: true });\n\n  let count = 0;\n  for (const filePath of allFiles) {\n    const src = join(sourceDir, filePath);\n    const stat = lstatSync(src);\n    if (!stat.isFile()) continue;\n\n    const destPath = sourcePathToDestinationPath(filePath);\n    const dest = join(destination, destPath);\n    mkdirSync(dirname(dest), { recursive: true });\n    const content = readFileSync(src);\n    writeFileSync(dest, content);\n    count++;\n  }\n\n  return count;\n}\n\nfunction stripProductionFields(entry: Record<string, unknown>): void {\n  delete entry.production;\n  delete entry.integrity;\n  delete entry.ssr;\n  delete entry.ssrIntegrity;\n  delete entry.pin;\n}\n\n/**\n * Scaffold the authored config as the TS form: the personalized\n * bos.config.json materializes into an authored `bos.app.ts` descriptor and\n * the JSON copy is removed — publish/sync still canonicalize to JSON for\n * FastKV from the resolved config. Returns the config that was converted, so\n * callers that need it (before the child has node_modules to import the\n * descriptor) can pass it onward.\n */\nexport async function convertChildConfigToAppForm(\n  destination: string,\n): Promise<BosConfigInput | null> {\n  const configPath = join(destination, \"bos.config.json\");\n  if (!existsSync(configPath)) return null;\n  const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as BosConfigInput;\n  writeFileSync(join(destination, \"bos.app.ts\"), serializeAppDescriptorSource(config));\n  rmSync(configPath);\n  return config;\n}\n\n/**\n * Scaffold the root dev-overlay starter (`bos.dev.ts`). Idempotent — never\n * overwrites an existing overlay. Dev overlays are merged child-wins over\n * the resolved config in development and are never published.\n */\nexport function writeDevOverlayTemplate(\n  destination: string,\n  opts: { extendsRef?: string } = {},\n): void {\n  const overlayPath = join(destination, \"bos.dev.ts\");\n  if (existsSync(overlayPath)) return;\n  const extendsLine = opts.extendsRef ? `\\n// Inherited base: ${opts.extendsRef}\\n` : \"\";\n  writeFileSync(\n    overlayPath,\n    `import type { AppDescriptor } from \"everything-dev/descriptor\";\n${extendsLine}\n/**\n * Development-only overlay for bos.app.ts — merged child-wins over the\n * resolved config when the environment is development. Never published.\n * Example: pin the auth attachment to a running dev server instead of\n * letting the dev harness spawn it.\n */\nexport default {\n  // auth: { development: \"http://localhost:3006\" },\n} satisfies Partial<AppDescriptor>;\n`,\n  );\n}\n\nfunction buildRootTypecheckScript(sections: {\n  ui: boolean;\n  api: boolean;\n  host: boolean;\n  plugins: boolean;\n}): string {\n  const commands = [\"pnpm run types:gen\"];\n\n  if (sections.ui) {\n    commands.push(\"if [ -d ui ]; then pnpm --dir ui run typecheck; fi\");\n  }\n  if (sections.api) {\n    commands.push(\"if [ -d api ]; then pnpm --dir api run typecheck; fi\");\n  }\n  if (sections.host) {\n    commands.push(\"if [ -d host ]; then pnpm --dir host run typecheck; fi\");\n  }\n  if (sections.plugins) {\n    commands.push(\n      'if [ -d plugins ]; then for dir in plugins/*; do if [ -f \"$dir/package.json\" ]; then pnpm --dir \"$dir\" run typecheck; fi; done; fi',\n    );\n  }\n\n  return commands.join(\" && \");\n}\n\nexport function getParentOnlyScriptKeys(projectDir: string): string[] {\n  const parentPkgPath = join(projectDir, \"node_modules\", \"everything-dev\", \"package.json\");\n  if (!existsSync(parentPkgPath)) return [];\n\n  try {\n    const parentPkg = JSON.parse(readFileSync(parentPkgPath, \"utf-8\")) as Record<string, unknown>;\n    const parentScripts = (parentPkg.scripts ?? {}) as Record<string, string>;\n\n    const allChildKeys = new Set(\n      Object.keys(buildChildRootScripts({ ui: true, api: true, host: true, plugins: true })),\n    );\n    allChildKeys.add(\"test:integration\");\n\n    return Object.keys(parentScripts).filter((key) => !allChildKeys.has(key));\n  } catch {\n    return [];\n  }\n}\n\nexport function buildChildRootScripts(sections: {\n  ui: boolean;\n  api: boolean;\n  host: boolean;\n  plugins: boolean;\n}): Record<string, string> {\n  const scripts: Record<string, string> = {\n    dev: \"bos dev\",\n    \"dev:proxy\": \"bos dev --proxy\",\n    build: \"bos build\",\n    deploy: \"bos deploy\",\n    publish: \"bos publish\",\n    start: \"bos start\",\n    typecheck: buildRootTypecheckScript(sections),\n    lint: \"biome check .\",\n    \"lint:fix\": \"biome check --write .\",\n    format: \"biome format --write .\",\n    \"format:check\": \"biome format .\",\n    changeset: \"changeset\",\n    version: \"changeset version\",\n    release: \"echo 'Packages versioned - app release handled by workflow'\",\n    \"types:gen\": \"bos types gen\",\n    bos: \"bos\",\n  };\n\n  if (sections.api) {\n    scripts[\"db:push\"] = \"pnpm --dir api exec drizzle-kit push\";\n    scripts[\"db:studio\"] = \"bos db:studio\";\n    scripts[\"db:doctor\"] = \"bos db:doctor\";\n    scripts[\"db:repair\"] = \"bos db:repair\";\n    scripts[\"db:generate\"] = \"pnpm --dir api exec drizzle-kit generate\";\n    scripts[\"db:migrate\"] = \"pnpm --dir api exec drizzle-kit migrate\";\n    scripts[\"test:api\"] = \"pnpm --dir api run test --if-present\";\n    scripts[\"test:integration\"] = \"pnpm --dir api run test tests/integration/ --if-present\";\n  }\n\n  if (sections.host) {\n    scripts[\"test:e2e\"] = \"pnpm --dir host run test --if-present\";\n  }\n\n  const testTargets: string[] = [];\n  if (sections.api) testTargets.push(\"pnpm --dir api run test --if-present\");\n  if (sections.host) testTargets.push(\"pnpm --dir host run test --if-present\");\n  if (sections.ui) testTargets.push(\"pnpm --dir ui run test --if-present\");\n  if (sections.plugins) {\n    testTargets.push(\n      'for d in plugins/*; do [ -f \"$d/package.json\" ] && pnpm --dir \"$d\" run test --if-present; done',\n    );\n  }\n  scripts.test =\n    testTargets.length > 0\n      ? testTargets.join(\" && \")\n      : 'echo \"No workspace directories configured\"';\n\n  // Scripts key off the child's own override selection (what it runs locally),\n  // not off resolved-config secrets — a ui-only child gets none of these.\n  if (sections.api || sections.host) {\n    scripts[\"dev:postgres\"] = \"docker compose up -d --wait && pnpm run dev\";\n    scripts[\"dev:postgres:down\"] = \"docker compose down\";\n    scripts[\"dev:postgres:reset\"] = \"docker compose down -v && docker compose up -d --wait\";\n  }\n\n  if (sections.ui) {\n    scripts[\"dev:ui\"] = \"bos dev --ui local --api remote\";\n  }\n  if (sections.api) {\n    scripts[\"dev:api\"] = \"bos dev --ui remote --api local\";\n  }\n\n  return scripts;\n}\n\nexport async function personalizeConfig(\n  destination: string,\n  opts: {\n    extendsAccount: string;\n    extendsGateway: string;\n    account?: string;\n    domain?: string;\n    plugins?: string[];\n    overrides: OverrideSection[];\n    pluginRoutes?: Record<string, string[]>;\n    workspaceOpts?: { localOverrides?: boolean; sourceDir?: string };\n    mode?: \"init\" | \"sync\";\n    existingConfig?: Record<string, unknown>;\n    repository?: string;\n    title?: string;\n    description?: string;\n    testnet?: string;\n    staging?: unknown;\n    starter?: StarterLevel;\n  },\n): Promise<void> {\n  const has = (section: OverrideSection) => opts.overrides.includes(section);\n  const existingApp =\n    opts.mode === \"sync\" && opts.existingConfig?.app && typeof opts.existingConfig.app === \"object\"\n      ? (opts.existingConfig.app as Record<string, unknown>)\n      : undefined;\n  const preservedAuth = existingApp?.auth;\n  const applyStarter = (config: Record<string, unknown>): void => {\n    if (opts.starter) {\n      config.starter = opts.starter;\n    } else if (opts.mode !== \"sync\") {\n      delete config.starter;\n    }\n  };\n\n  const explicitRootKeys = new Set(\n    Object.entries(opts)\n      .filter(\n        ([key, value]) =>\n          value !== undefined &&\n          ![\n            \"extendsAccount\",\n            \"extendsGateway\",\n            \"plugins\",\n            \"overrides\",\n            \"pluginRoutes\",\n            \"workspaceOpts\",\n            \"mode\",\n            \"existingConfig\",\n          ].includes(key),\n      )\n      .map(([key]) => key),\n  );\n\n  const jsonConfigPath = join(destination, \"bos.config.json\");\n  const appConfigPath = join(destination, \"bos.app.ts\");\n  const tsForm = !existsSync(jsonConfigPath) && existsSync(appConfigPath);\n\n  if (tsForm) {\n    const config = (await loadAppDescriptorConfig(appConfigPath)) as Record<string, unknown>;\n\n    config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n    if (opts.account) {\n      config.account = opts.account;\n    }\n    if (opts.domain) {\n      config.domain = opts.domain;\n    }\n    if (opts.repository) {\n      config.repository = opts.repository;\n    } else {\n      delete config.repository;\n    }\n\n    const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n    for (const field of inheritableFields) {\n      if (!(field in opts)) {\n        delete config[field];\n      }\n    }\n\n    applyStarter(config);\n\n    if (config.app && typeof config.app === \"object\") {\n      const app = config.app as Record<string, unknown>;\n\n      for (const entryKey of Object.keys(app)) {\n        if (\n          !has(entryKey as OverrideSection) &&\n          (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n        ) {\n          delete app[entryKey];\n          continue;\n        }\n        if (entryKey === \"auth\") {\n          delete app[entryKey];\n          continue;\n        }\n        const entry = app[entryKey];\n        if (entry && typeof entry === \"object\") {\n          stripProductionFields(entry as Record<string, unknown>);\n        }\n      }\n\n      if (preservedAuth !== undefined) {\n        app.auth = preservedAuth;\n      }\n\n      if (Object.keys(app).length === 0) {\n        delete config.app;\n      }\n    }\n\n    if (has(\"plugins\")) {\n      if (config.plugins && typeof config.plugins === \"object\") {\n        const plugins = config.plugins as Record<string, unknown>;\n\n        if (opts.plugins !== undefined) {\n          for (const pluginKey of Object.keys(plugins)) {\n            if (!opts.plugins.includes(pluginKey)) {\n              delete plugins[pluginKey];\n            }\n          }\n        }\n\n        for (const pluginKey of Object.keys(plugins)) {\n          const plugin = plugins[pluginKey];\n          let pluginObj: Record<string, unknown>;\n\n          if (typeof plugin === \"string\") {\n            pluginObj = { extends: plugin };\n            plugins[pluginKey] = pluginObj;\n          } else if (plugin && typeof plugin === \"object\") {\n            pluginObj = { ...(plugin as Record<string, unknown>) };\n            plugins[pluginKey] = pluginObj;\n          } else {\n            continue;\n          }\n\n          stripProductionFields(pluginObj);\n        }\n\n        if (Object.keys(plugins).length === 0) {\n          config.plugins = {};\n        }\n      }\n    } else {\n      config.plugins = {};\n    }\n\n    writeFileSync(appConfigPath, serializeAppDescriptorSource(config as BosConfigInput));\n    return;\n  }\n\n  const configPath = join(destination, \"bos.config.json\");\n  if (existsSync(configPath)) {\n    const config = JSON.parse(readFileSync(configPath, \"utf-8\")) as Record<string, unknown>;\n\n    config.extends = `bos://${opts.extendsAccount}/${opts.extendsGateway}`;\n\n    if (opts.account) {\n      config.account = opts.account;\n    }\n    if (opts.domain) {\n      config.domain = opts.domain;\n    }\n    if (opts.repository) {\n      config.repository = opts.repository;\n    } else {\n      delete config.repository;\n    }\n\n    const inheritableFields = [\"title\", \"description\", \"testnet\", \"staging\"] as const;\n    for (const field of inheritableFields) {\n      if (!(field in opts)) {\n        delete config[field];\n      }\n    }\n\n    applyStarter(config);\n\n    if (config.app && typeof config.app === \"object\") {\n      const app = config.app as Record<string, unknown>;\n\n      for (const entryKey of Object.keys(app)) {\n        if (\n          !has(entryKey as OverrideSection) &&\n          (entryKey === \"host\" || entryKey === \"ui\" || entryKey === \"api\")\n        ) {\n          delete app[entryKey];\n          continue;\n        }\n        if (entryKey === \"auth\") {\n          delete app[entryKey];\n          continue;\n        }\n        const entry = app[entryKey];\n        if (entry && typeof entry === \"object\") {\n          stripProductionFields(entry as Record<string, unknown>);\n        }\n      }\n\n      if (preservedAuth !== undefined) {\n        app.auth = preservedAuth;\n      }\n\n      if (Object.keys(app).length === 0) {\n        delete config.app;\n      }\n    }\n\n    if (has(\"plugins\")) {\n      if (config.plugins && typeof config.plugins === \"object\") {\n        const plugins = config.plugins as Record<string, unknown>;\n\n        if (opts.plugins !== undefined) {\n          for (const pluginKey of Object.keys(plugins)) {\n            if (!opts.plugins.includes(pluginKey)) {\n              delete plugins[pluginKey];\n            }\n          }\n        }\n\n        for (const pluginKey of Object.keys(plugins)) {\n          const plugin = plugins[pluginKey];\n          let pluginObj: Record<string, unknown>;\n\n          if (typeof plugin === \"string\") {\n            pluginObj = { extends: plugin };\n            plugins[pluginKey] = pluginObj;\n          } else if (plugin && typeof plugin === \"object\") {\n            pluginObj = { ...(plugin as Record<string, unknown>) };\n            plugins[pluginKey] = pluginObj;\n          } else {\n            continue;\n          }\n\n          stripProductionFields(pluginObj);\n        }\n\n        if (Object.keys(plugins).length === 0) {\n          config.plugins = {};\n        }\n      }\n    } else {\n      config.plugins = {};\n    }\n\n    if (opts.mode === \"sync\" && opts.existingConfig) {\n      const managedRootKeys = new Set([\"extends\", \"account\", \"domain\", \"app\", \"plugins\"]);\n      const preservedRootKeys = new Set([\n        ...managedRootKeys,\n        ...Object.keys(opts.existingConfig),\n        ...explicitRootKeys,\n      ]);\n\n      for (const key of Object.keys(config)) {\n        if (!preservedRootKeys.has(key)) {\n          delete config[key];\n        }\n      }\n\n      for (const [key, value] of Object.entries(opts.existingConfig)) {\n        if (!(key in config) && !managedRootKeys.has(key) && !explicitRootKeys.has(key)) {\n          config[key] = value;\n        }\n      }\n    }\n\n    await saveBosConfig(destination, config);\n  }\n\n  for (const relPath of [\"ui/src/lib/api-types.gen.ts\", \"api/src/lib/plugins-types.gen.ts\"]) {\n    const absolutePath = join(destination, relPath);\n    try {\n      rmSync(absolutePath, { force: true });\n    } catch {}\n  }\n\n  const pkgPath = join(destination, \"package.json\");\n  if (existsSync(pkgPath)) {\n    const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n    const childScripts = buildChildRootScripts({\n      ui: has(\"ui\"),\n      api: has(\"api\"),\n      host: has(\"host\"),\n      plugins: has(\"plugins\"),\n    });\n\n    if (typeof pkg.name !== \"string\" || pkg.name.length === 0) {\n      pkg.name = \"monorepo\";\n    }\n    pkg.private = true;\n    pkg.type = \"module\";\n    pkg.packageManager = PNPM_PACKAGE_MANAGER;\n    delete pkg.module;\n    delete pkg.peerDependencies;\n    delete pkg.patchedDependencies;\n\n    const childWorkspaces: string[] = [];\n    if (has(\"host\")) childWorkspaces.push(\"host\");\n    if (has(\"ui\")) childWorkspaces.push(\"ui\");\n    if (has(\"api\")) childWorkspaces.push(\"api\");\n    if (has(\"plugins\")) childWorkspaces.push(\"plugins/*\");\n    const localCatalog =\n      pkg.workspaces && typeof pkg.workspaces === \"object\"\n        ? ((pkg.workspaces as { catalog?: Record<string, string> }).catalog ?? {})\n        : {};\n    delete pkg.workspaces;\n\n    if (!pkg.scripts || typeof pkg.scripts !== \"object\") {\n      pkg.scripts = {};\n    }\n    const scripts = pkg.scripts as Record<string, string>;\n    for (const [key, value] of Object.entries(childScripts)) {\n      scripts[key] = value;\n    }\n    for (const obsoleteScript of [\n      ...getParentOnlyScriptKeys(destination),\n      \"init\",\n      \"prepare\",\n      \"sync-catalog\",\n      \"db:push\",\n      \"db:studio\",\n      \"db:doctor\",\n      \"db:repair\",\n      \"db:generate\",\n      \"db:migrate\",\n      \"test\",\n      \"test:api\",\n      \"test:integration\",\n      \"test:e2e\",\n      \"dev:postgres\",\n      \"dev:postgres:down\",\n      \"dev:postgres:reset\",\n      \"dev:ui\",\n      \"dev:api\",\n    ]) {\n      if (!(obsoleteScript in childScripts)) {\n        delete scripts[obsoleteScript];\n      }\n    }\n\n    if (pkg.devDependencies && typeof pkg.devDependencies === \"object\") {\n      const deps = pkg.devDependencies as Record<string, string>;\n      delete deps[\"every-plugin\"];\n      delete deps[\"everything-dev\"];\n    }\n\n    const catalog: Record<string, string> = { ...localCatalog };\n\n    // The copied root manifest is the parent's — a monorepo root whose\n    // dependencies (workspace members, vendored links) do not exist in the\n    // child. The child root carries exactly the framework packages.\n    pkg.dependencies = {\n      \"everything-dev\": \"catalog:\",\n      \"every-plugin\": \"catalog:\",\n    };\n    const deps = pkg.dependencies as Record<string, string>;\n    const spec = opts.workspaceOpts?.sourceDir\n      ? loadManifestNormalizationSpec(opts.workspaceOpts.sourceDir)\n      : null;\n    if (spec) {\n      const rootCatalogEverythingDev = spec.rootCatalog[\"everything-dev\"];\n      const rootCatalogEveryPlugin = spec.rootCatalog[\"every-plugin\"];\n      if (rootCatalogEverythingDev) {\n        catalog[\"everything-dev\"] = rootCatalogEverythingDev;\n      }\n      if (rootCatalogEveryPlugin) {\n        catalog[\"every-plugin\"] = rootCatalogEveryPlugin;\n      }\n    }\n    const frameworkCatalog = (\n      await resolveCatalogChainSource({\n        extendsAccount: opts.extendsAccount,\n        extendsGateway: opts.extendsGateway,\n        sourceDir: opts.workspaceOpts?.sourceDir,\n      })\n    ).catalog;\n    for (const [name, version] of Object.entries(frameworkCatalog)) {\n      catalog[name] = version;\n    }\n    if (!deps[\"everything-dev\"]) deps[\"everything-dev\"] = \"catalog:\";\n    if (!deps[\"every-plugin\"]) deps[\"every-plugin\"] = \"catalog:\";\n\n    writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\\n`);\n\n    writeChildWorkspaceYaml(destination, { packages: childWorkspaces, catalog });\n  }\n\n  const apiTsConfigPath = join(destination, \"api\", \"tsconfig.json\");\n  if (existsSync(apiTsConfigPath)) {\n    const apiTsConfig = JSON.parse(readFileSync(apiTsConfigPath, \"utf-8\")) as {\n      files?: string[];\n      [key: string]: unknown;\n    };\n    if (apiTsConfig.files) {\n      const validFiles = apiTsConfig.files.filter((f) => existsSync(join(destination, \"api\", f)));\n      if (validFiles.length !== apiTsConfig.files.length) {\n        if (validFiles.length === 0) {\n          delete apiTsConfig.files;\n        } else {\n          apiTsConfig.files = validFiles;\n        }\n        writeFileSync(apiTsConfigPath, `${JSON.stringify(apiTsConfig, null, 2)}\\n`);\n      }\n    }\n  }\n\n  await resolveWorkspaceRefs(destination, opts.workspaceOpts);\n\n  if (has(\"ui\")) {\n    const genContractPath = join(destination, \"ui\", \"src\", \"lib\", \"api-types.gen.ts\");\n    if (!existsSync(genContractPath)) {\n      mkdirSync(dirname(genContractPath), { recursive: true });\n      writeFileSync(genContractPath, `export type ApiContract = Record<string, never>;\\n`);\n    }\n\n    const publicDir = join(destination, \"ui\", \"public\");\n    if (!existsSync(publicDir)) {\n      mkdirSync(publicDir, { recursive: true });\n    }\n\n    const llmsTxtPath = join(publicDir, \"llms.txt\");\n    if (!existsSync(llmsTxtPath)) {\n      const title = opts.title ?? opts.account ?? \"app\";\n      writeFileSync(llmsTxtPath, buildChildLlmsTxt(title));\n    }\n\n    const skillMdPath = join(publicDir, \"skill.md\");\n    if (!existsSync(skillMdPath)) {\n      const title = opts.title ?? opts.account ?? \"app\";\n      const repository = opts.repository ?? \"\";\n      writeFileSync(skillMdPath, buildChildSkillMd(title, repository));\n    }\n\n    for (const agentFilePath of [llmsTxtPath, skillMdPath]) {\n      const content = readFileSync(agentFilePath, \"utf-8\");\n      if (content.includes(WORKFLOW_SKILLS_MARKER)) continue;\n      writeFileSync(agentFilePath, `${content.replace(/\\n*$/, \"\\n\")}${WORKFLOW_SKILLS_NOTE}`);\n    }\n  }\n\n  if (has(\"api\")) {\n    const pluginsClientGenPath = join(destination, \"api\", \"src\", \"lib\", \"plugins-types.gen.ts\");\n    if (!existsSync(pluginsClientGenPath)) {\n      mkdirSync(dirname(pluginsClientGenPath), { recursive: true });\n      writeFileSync(\n        pluginsClientGenPath,\n        `import type { RouterContractClient, RouterContract } from \"@orpc/contract\";\\ntype ClientFactory<C extends RouterContract> = (context?: Record<string, unknown>) => RouterContractClient<C>;\\nexport type PluginsClient = Record<string, never>;\\n`,\n      );\n    }\n  }\n\n  const authTypesPaths: string[] = [];\n  if (has(\"ui\")) {\n    authTypesPaths.push(join(destination, \"ui\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n  }\n  if (has(\"api\")) {\n    authTypesPaths.push(join(destination, \"api\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n  }\n  if (has(\"host\") && existsSync(join(destination, \"host\", \"src\"))) {\n    authTypesPaths.push(join(destination, \"host\", \"src\", \"lib\", \"auth-types.gen.ts\"));\n  }\n  for (const authTypesGenPath of authTypesPaths) {\n    if (!existsSync(authTypesGenPath)) {\n      mkdirSync(dirname(authTypesGenPath), { recursive: true });\n      const authExportRel = toRelativeImportPath(\n        join(destination, \".bos\", \"generated\", \"auth\", \"auth-export.d.ts\"),\n        authTypesGenPath,\n      );\n      const contractRel = toRelativeImportPath(\n        join(destination, \".bos\", \"generated\", \"auth\", \"contract.d.ts\"),\n        authTypesGenPath,\n      );\n      writeFileSync(authTypesGenPath, buildAuthTypesGenContent(authExportRel, contractRel));\n    }\n  }\n\n  if (authTypesPaths.length > 0) {\n    const authDir = join(destination, \".bos\", \"generated\", \"auth\");\n    if (!existsSync(authDir)) {\n      mkdirSync(authDir, { recursive: true });\n    }\n    const authExportStubPath = join(authDir, \"auth-export.d.ts\");\n    if (!existsSync(authExportStubPath)) {\n      writeFileSync(authExportStubPath, buildAuthExportStub());\n    }\n    const contractStubPath = join(authDir, \"contract.d.ts\");\n    if (!existsSync(contractStubPath)) {\n      writeFileSync(contractStubPath, buildAuthContractStub());\n    }\n  }\n\n  if (has(\"plugins\")) {\n    for (const plugin of opts.plugins ?? []) {\n      const pluginSrcDir = join(destination, \"plugins\", plugin, \"src\");\n      const pluginIndexPath = join(pluginSrcDir, \"index.ts\");\n      const pluginClientGenPath = join(pluginSrcDir, \"lib\", \"plugins-client.gen.ts\");\n      if (!existsSync(pluginIndexPath) || existsSync(pluginClientGenPath)) {\n        continue;\n      }\n      const pluginIndex = readFileSync(pluginIndexPath, \"utf-8\");\n      if (!pluginIndex.includes(\"./lib/plugins-client.gen\")) {\n        continue;\n      }\n      writeFileSync(pluginClientGenPath, \"export type PluginsClient = Record<string, never>;\\n\");\n    }\n  }\n}\n\nfunction toRelativeImportPath(fromPath: string, toPath: string): string {\n  const rel = relative(dirname(toPath), fromPath);\n  return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport async function runPnpmInstall(\n  destination: string,\n  opts?: {\n    spinner?: { message: (msg: string) => void };\n  },\n): Promise<void> {\n  await runWithProgress(\n    \"pnpm\",\n    [\"install\", \"--ignore-scripts\"],\n    destination,\n    opts?.spinner,\n    \"Installing dependencies\",\n  );\n}\n\nexport async function runPnpmInstallForUpgrade(\n  destination: string,\n  opts?: {\n    spinner?: { message: (msg: string) => void };\n  },\n): Promise<void> {\n  await runWithProgress(\n    \"pnpm\",\n    [\"install\", \"--force\"],\n    destination,\n    opts?.spinner,\n    \"Installing dependencies\",\n  );\n}\n\nexport async function runTypesGen(\n  destination: string,\n  opts?: {\n    spinner?: { message: (msg: string) => void };\n    remotePlugins?: string[];\n  },\n): Promise<void> {\n  const bosModule = join(destination, \"node_modules\", \"everything-dev\", \"dist\", \"cli.mjs\");\n  if (existsSync(bosModule)) {\n    const args = [bosModule, \"types\", \"gen\"];\n    if (opts?.remotePlugins && opts.remotePlugins.length > 0) {\n      args.push(\"--remote-plugins\", opts.remotePlugins.join(\",\"));\n    }\n    await runWithProgress(process.execPath, args, destination, opts?.spinner, \"Generating types\");\n    return;\n  }\n\n  throw new Error(\"Unable to locate bos CLI for types generation\");\n}\n\nexport { runDockerComposeUp } from \"../infra/docker\";\n\nasync function runWithProgress(\n  command: string,\n  args: string[],\n  cwd: string,\n  spinner: { message: (msg: string) => void } | undefined,\n  label: string,\n): Promise<void> {\n  const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n  const child = execa(command, args, {\n    cwd,\n    stdio: \"inherit\",\n    timeout,\n    env: { ...process.env, BOS_NO_BANNER: \"1\" },\n  });\n\n  if (spinner) {\n    const start = Date.now();\n    const interval = setInterval(() => {\n      const elapsed = Math.round((Date.now() - start) / 1000);\n      spinner.message(`${label}... (${elapsed}s)`);\n    }, 2000);\n    try {\n      await child;\n    } finally {\n      clearInterval(interval);\n    }\n  } else {\n    await child;\n  }\n}\n\nexport async function scaffoldMinimalProject(\n  destination: string,\n  parentConfig: BosConfigInput,\n  opts: {\n    extendsAccount: string;\n    extendsGateway: string;\n    account?: string;\n    domain?: string;\n    plugins?: string[];\n    overrides: OverrideSection[];\n    repository?: string;\n    title?: string;\n    description?: string;\n    starter?: StarterLevel;\n    /** local parent source dir — resolves the catalog offline (tests, --source) */\n    catalogSourceDir?: string;\n  },\n): Promise<number> {\n  mkdirSync(destination, { recursive: true });\n\n  const has = (section: OverrideSection) => opts.overrides.includes(section);\n\n  const config: Record<string, unknown> = {\n    extends: `bos://${opts.extendsAccount}/${opts.extendsGateway}`,\n    account: opts.account || opts.extendsAccount,\n    ...(opts.domain ? { domain: opts.domain } : {}),\n    ...(opts.repository ? { repository: opts.repository } : {}),\n    ...(opts.title ? { title: opts.title } : {}),\n    ...(opts.description ? { description: opts.description } : {}),\n    ...(opts.starter ? { starter: opts.starter } : {}),\n  };\n\n  if (parentConfig.app && typeof parentConfig.app === \"object\") {\n    const app: Record<string, unknown> = {};\n    const parentApp = parentConfig.app as Record<string, Record<string, unknown>>;\n\n    if (has(\"host\") && parentApp.host) {\n      app.host = { ...parentApp.host };\n      stripProductionFields(app.host as Record<string, unknown>);\n    }\n\n    if (has(\"ui\") && parentApp.ui) {\n      app.ui = { ...parentApp.ui };\n      stripProductionFields(app.ui as Record<string, unknown>);\n    }\n\n    if (has(\"api\") && parentApp.api) {\n      app.api = { ...parentApp.api };\n      stripProductionFields(app.api as Record<string, unknown>);\n    }\n\n    if (Object.keys(app).length > 0) {\n      config.app = app;\n    }\n  }\n\n  if (has(\"plugins\") && opts.plugins && opts.plugins.length > 0 && parentConfig.plugins) {\n    const plugins: Record<string, unknown> = {};\n    for (const key of opts.plugins) {\n      const parentPlugin = (parentConfig.plugins as Record<string, unknown>)?.[key];\n      if (parentPlugin) {\n        if (typeof parentPlugin === \"string\") {\n          plugins[key] = { extends: parentPlugin };\n        } else {\n          const pluginCopy = { ...(parentPlugin as Record<string, unknown>) };\n          stripProductionFields(pluginCopy);\n          plugins[key] = pluginCopy;\n        }\n      }\n    }\n    config.plugins = plugins;\n  } else if (has(\"plugins\")) {\n    config.plugins = {};\n  }\n\n  await saveBosConfig(destination, config);\n\n  const workspacePackages: string[] = [];\n  for (const section of opts.overrides) {\n    workspacePackages.push(...OVERRIDE_WORKSPACE_MAP[section]);\n  }\n  if (has(\"plugins\")) {\n    workspacePackages.push(\"plugins/*\");\n  }\n\n  const catalog = (\n    await resolveCatalogChainSource({\n      extendsAccount: opts.extendsAccount,\n      extendsGateway: opts.extendsGateway,\n      sourceDir: opts.catalogSourceDir,\n    })\n  ).catalog;\n\n  const pkg: Record<string, unknown> = {\n    name: \"monorepo\",\n    private: true,\n    type: \"module\",\n    packageManager: PNPM_PACKAGE_MANAGER,\n    scripts: buildChildRootScripts({\n      ui: has(\"ui\"),\n      api: has(\"api\"),\n      host: has(\"host\"),\n      plugins: has(\"plugins\"),\n    }),\n    dependencies: {\n      \"everything-dev\": \"catalog:\",\n      \"every-plugin\": \"catalog:\",\n    },\n    devDependencies: {},\n  };\n  writeFileSync(join(destination, \"package.json\"), `${JSON.stringify(pkg, null, 2)}\\n`);\n\n  writeChildWorkspaceYaml(destination, { packages: workspacePackages, catalog });\n\n  writeFileSync(join(destination, \".gitignore\"), generateGitignore());\n\n  return 4;\n}\n\nasync function resolveWorkspaceRefs(\n  destination: string,\n  options?: { localOverrides?: boolean; sourceDir?: string },\n): Promise<void> {\n  await normalizePackageManifestsInTree({\n    sourceRootDir: options?.sourceDir ?? destination,\n    targetDir: destination,\n    resolveCatalogRefs: false,\n    preserveCatalogRefs: true,\n    removeWorkspaceDeps: [\"host\"],\n  });\n}\n\nexport async function writeInitSnapshot(\n  destination: string,\n  extendsAccount: string,\n  extendsGateway: string,\n  sourceDir: string,\n  patterns: string[],\n  options: {\n    overrides: OverrideSection[];\n    plugins?: string[];\n    ignore?: string[];\n    starter?: StarterLevel;\n  },\n): Promise<void> {\n  const baseIgnore = [\"**/node_modules/**\", \"**/.git/**\", \"**/dist/**\", \"**/.bos/**\"];\n  const ignore = options.ignore ? [...baseIgnore, ...options.ignore] : baseIgnore;\n\n  const allFiles = new Set<string>();\n  for (const pattern of patterns) {\n    const matches = await glob(pattern, {\n      cwd: sourceDir,\n      nodir: true,\n      dot: true,\n      absolute: false,\n      ignore,\n    });\n    for (const match of matches) {\n      allFiles.add(match);\n    }\n  }\n  if (!options.overrides.includes(\"api\")) {\n    for (const match of allFiles) {\n      if (isApiTemplatePath(match)) allFiles.delete(match);\n    }\n  }\n  if (!options.overrides.includes(\"api\") && !options.overrides.includes(\"host\")) {\n    for (const match of allFiles) {\n      if (isComposeTemplatePath(match)) allFiles.delete(match);\n    }\n  }\n\n  const fileHashes: Record<string, string> = {};\n  for (const filePath of allFiles) {\n    const src = join(sourceDir, filePath);\n    const stat = lstatSync(src);\n    if (!stat.isFile()) continue;\n    const destPath = sourcePathToDestinationPath(filePath);\n    // Only snapshot what the scaffold actually delivered — files pruned\n    // after copy (e.g. unused ui sources) must not come back via bos sync.\n    if (!existsSync(join(destination, destPath))) continue;\n    const content = readFileSync(src);\n    fileHashes[destPath] = computeHash(content);\n  }\n\n  await writeSnapshot(destination, {\n    parentRef: `bos://${extendsAccount}/${extendsGateway}`,\n    files: fileHashes,\n    starter: options.starter,\n  });\n}\n\nfunction mkTmpDir(prefix: string): string {\n  return mkdtempSync(join(tmpdir(), `${prefix}-`));\n}\n\nexport async function generateDatabaseMigrations(destination: string): Promise<void> {\n  const drizzleConfigs = await glob(\"**/drizzle.config.ts\", {\n    cwd: destination,\n    nodir: true,\n    dot: false,\n    absolute: false,\n    ignore: [\"**/node_modules/**\"],\n  });\n\n  for (const configPath of drizzleConfigs) {\n    const workspaceDir = dirname(configPath);\n    const pkgPath = join(destination, workspaceDir, \"package.json\");\n    if (!existsSync(pkgPath)) continue;\n\n    const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as Record<string, unknown>;\n    const scripts = pkg.scripts as Record<string, string> | undefined;\n    if (!scripts?.[\"db:generate\"]) continue;\n\n    const cwd = join(destination, workspaceDir);\n    await execCommand(\"pnpm\", [\"--dir\", \"api\", \"exec\", \"drizzle-kit\", \"generate\"], cwd);\n  }\n}\n\nconst COMMAND_TIMEOUTS: Record<string, number> = {\n  pnpm: 5 * 60_000,\n  docker: 5 * 60_000,\n  node_modules: 2 * 60_000,\n  tar: 60_000,\n};\n\nexport async function execCommand(\n  command: string,\n  args: string[],\n  cwd?: string,\n  options?: { stdio?: \"pipe\" | \"inherit\" },\n): Promise<void> {\n  const timeout = COMMAND_TIMEOUTS[command] ?? 2 * 60_000;\n  await execa(command, args, { cwd, stdio: options?.stdio ?? \"pipe\", timeout });\n}\n\nexport function extractSkillsBlock(content: string): string {\n  const match = content.match(/<!-- intent-skills:start -->[\\s\\S]*?<!-- intent-skills:end -->/);\n  return match ? match[0] : \"\";\n}\n\nfunction buildChildAgentsInstructions(opts: {\n  overrides: OverrideSection[];\n  plugins?: string[];\n}): string {\n  const has = (section: OverrideSection) => opts.overrides.includes(section);\n  const parts: string[] = [];\n\n  parts.push(`# Agent Instructions\n\nThis document provides operational guidance for AI agents working in this everything.dev project.\n\n## Quick Reference\n\n**Start Development:**\n\\`\\`\\`bash\npnpm install\npnpm run dev\n\\`\\`\\`\n\n**Check Status:**\n\\`\\`\\`bash\nbos ps        # List running processes\nbos status    # Project health check\nbos info      # Show configuration\n\\`\\`\\`\n\n**Deploy:**\n\n[![Deploy on Railway](https://railway.com/button.svg)](https://railway.com/deploy/everything-dev-template?referralCode=MuB_vg&utm_medium=integration&utm_source=template&utm_campaign=generic)\n\nThe Railway template deploys the everything.dev Docker image. Set these variables:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| \\`BOS_ACCOUNT\\` | The NEAR account that owns this app's published configuration on-chain | \\`myapp.near\\` |\n| \\`BOS_GATEWAY\\` | The core domain where this app is served | \\`myapp.com\\` |\n| \\`BETTER_AUTH_SECRET\\` | Secret for session encryption — generate with \\`openssl rand -base64 32\\` | (random) |\n\n**Self-deployed production:**\n\nYou don't need to wait for a PR to merge and run through CI/CD. Publish your own config on-chain under your own NEAR account and run your own host instance, inheriting the base platform via \\`extends\\`.\n\n1. **Install near-cli-rs** (the \\`bos\\` CLI shells out to it for \\`bos publish\\` and \\`bos key generate\\`):\n   \\`\\`\\`bash\n   curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/download/v0.23.5/near-cli-rs-installer.sh | sh\n   \\`\\`\\`\n2. **Create a NEAR account** (testnet or mainnet). Named accounts can own subaccounts; implicit hex accounts cannot:\n   \\`\\`\\`bash\n   near account create-account fund-my-account <your-account>.testnet use-faucet network-config testnet\n   \\`\\`\\`\n3. **Generate a publish key** — a function-call key scoped to the FastKV registry contract:\n   \\`\\`\\`bash\n   bos key generate\n   # Output: NEAR_PRIVATE_KEY=ed25519:...\n   \\`\\`\\`\n   Add the key to your account via near-cli-rs, then set \\`NEAR_PRIVATE_KEY\\` in \\`.env\\` or CI secrets.\n4. **Update \\`bos.app.ts\\`** — set \\`account\\` to your NEAR account, add \\`extends\\` to inherit the base platform, keep \\`domain\\` as the gateway:\n   \\`\\`\\`ts\n   { \"extends\": \"bos://<parent-account>/<parent-gateway>\", \"account\": \"<your-account>.near\", \"domain\": \"<parent-gateway>\" }\n   \\`\\`\\`\n 5. **Publish and deploy:**\n    \\`\\`\\`bash\n    bos deploy           # preflight → build → upload bundles → publish config to FastKV at bos://<your-account>/<gateway> → image/Railway when configured\n    \\`\\`\\`\n6. **Deploy to Railway** (one-click template or \\`railway up\\`), set \\`BOS_ACCOUNT\\`, \\`BOS_GATEWAY\\` (same gateway as parent), and \\`BETTER_AUTH_SECRET\\`. Your Railway host fetches your config from FastKV and serves live.\n\n\\`BOS_GATEWAY\\` is the **FastKV lookup key**, not the DNS domain your Railway instance serves on. By keeping the same gateway while using your own \\`BOS_ACCOUNT\\`, your config lives at a separate FastKV path that \\`extends\\` the base runtime — you inherit the full platform and override only what you change.\n\n**Tenant creation** (for the admin wizard) is DAO-owned: connect a sputnik-dao account via the Trezu wallet in the admin wizard; the wizard publishes the tenant runtime config under \\`bos://<dao-account>/<gateway>\\`. No server-side subaccount keys are needed.`);\n\n  const archLines = [\n    \"This is an everything.dev child project. Depending on your overrides, it may include:\",\n  ];\n  if (has(\"ui\"))\n    archLines.push(\"- **UI** — React 19 + TanStack Router frontend, loaded via Module Federation\");\n  if (has(\"api\")) archLines.push(\"- **API** — Hono.js + oRPC backend with Effect services\");\n  if (has(\"host\"))\n    archLines.push(\"- **Host** — Server-side runtime with Module Federation orchestration\");\n  if (has(\"plugins\"))\n    archLines.push(\"- **Plugins** — Self-contained business logic modules with oRPC contracts\");\n  archLines.push(\n    \"\",\n    \"The parent runtime provides the shared framework; your project provides custom overrides.\",\n  );\n  parts.push(`## Architecture\\n\\n${archLines.join(\"\\n\")}`);\n\n  parts.push(`## Development Workflow\n\n### Starting Development\n1. \\`pnpm install\\`\n2. \\`pnpm run dev\\`\n3. \\`bos dev\\` creates \\`.env\\` on first run and starts local Postgres via docker compose when it is down`);\n\n  parts.push(`### Debugging Issues\n\n**API not responding:**\n- Check \\`bos ps\\` to see if the API process is running\n- Check \\`.bos/logs/api.log\\` for errors\n\n**UI not loading:**\n- Verify the dev server is running: \\`bos ps\\`\n- Check browser console for Module Federation errors\n- Clear browser cache and retry\n\n**Type errors:**\n- Run \\`pnpm run typecheck\\``);\n\n  const changeLines: string[] = [\"### Making Changes\"];\n  if (has(\"ui\"))\n    changeLines.push(\"- **UI Changes**: Edit `ui/src/` files → hot reload automatically\");\n  if (has(\"api\"))\n    changeLines.push(\"- **API Changes**: Edit `api/src/` files → hot reload automatically\");\n  if (has(\"host\"))\n    changeLines.push(\n      \"- **Host Changes**: Edit `host/src/` when changing runtime resolution, auth wiring, SSR, proxying, or plugin mounting\",\n    );\n  changeLines.push(\n    \"- **New Components**: Create in `ui/src/components/ui/`, export from `ui/src/components/index.ts`\",\n  );\n  changeLines.push(\n    \"- **New Routes**: Create file in `ui/src/routes/`, TanStack Router auto-generates tree\",\n  );\n  parts.push(`## Code Changes\\n\\n${changeLines.join(\"\\n\")}`);\n\n  parts.push(`### Style Requirements\n- Use semantic Tailwind classes: \\`bg-background\\`, \\`text-foreground\\`, \\`text-muted-foreground\\`\n- No hardcoded colors like \\`bg-blue-600\\`\n- No code comments in implementation\n- Component file naming: lowercase kebab-case (\\`data-table.tsx\\`, \\`user-profile.tsx\\`)\n- Follow existing patterns in neighboring files`);\n\n  if (has(\"api\")) {\n    parts.push(`### Adding API Endpoints\n1. Define in \\`api/src/contract.ts\\` — the oRPC route definitions and Zod schemas\n2. Implement in \\`api/src/index.ts\\` — the \\`createRouter\\` function\n3. Use in UI via \\`apiClient\\` from \\`useApiClient()\\` in \\`@/app\\``);\n  }\n\n  if (has(\"plugins\")) {\n    parts.push(`### Plugin Architecture\n\nBusiness logic is organized into independent plugins loaded via Module Federation:\n- Each plugin has its own \\`contract.ts\\` — oRPC route definitions and Zod schemas\n- Each plugin has its own \\`index.ts\\` — \\`createPlugin\\` with variables, secrets, context, router\n- Each plugin has its own rspack config for independent deployment\n\nThe UI accesses plugin routes via namespaced clients: \\`apiClient.<plugin>.<method>()\\`.\n\n### Plugin Client (pluginsClient)\n\nThe API plugin receives typed client factories for all other plugins via \\`createPlugin.withPlugins<PluginsClient>()\\`, enabling in-process composition without HTTP roundtrips.\n\n### Generated Types\n\n\\`api/src/lib/plugins-types.gen.ts\\`, \\`api/src/lib/auth-types.gen.ts\\`, \\`ui/src/lib/api-types.gen.ts\\`, and \\`ui/src/lib/auth-types.gen.ts\\` are generated by \\`bos types gen\\` from \\`bos.app.ts\\`. These files are gitignored and auto-regenerated on \\`pnpm install\\`, \\`typecheck\\`, \\`bos dev\\`, \\`bos build\\`, and bos plugin management commands.\n\nIf you hand-edit \\`bos.app.ts\\`, run \\`bos types gen\\` or restart \\`bos dev\\` to regenerate.`);\n  }\n\n  const testCommands: string[] = [];\n  if (has(\"api\") || has(\"host\") || has(\"ui\")) {\n    testCommands.push(\"pnpm run test    # Run all tests\");\n    testCommands.push(\"pnpm run typecheck   # Type check all packages\");\n    testCommands.push(\"pnpm run lint        # Run linting\");\n  }\n  if (testCommands.length > 0) {\n    parts.push(`## Testing & Quality\n\n**Before committing:**\n\\`\\`\\`bash\n${testCommands.join(\"\\n\")}\n\\`\\`\\``);\n  }\n\n  parts.push(`## Common Patterns\n\n### Authentication Check\n\nRoutes requiring auth use \\`_authenticated.tsx\\` layout:\n\\`\\`\\`typescript\nexport const Route = createFileRoute('/_layout/_authenticated')({\n  beforeLoad: async ({ location }) => {\n    const { data: session } = await authClient.getSession();\n    if (!session?.user) {\n      throw redirect({ to: '/login', search: { redirect: location.pathname } });\n    }\n  },\n});\n\\`\\`\\``);\n\n  if (has(\"ui\")) {\n    parts.push(`### API Client Usage\n\\`\\`\\`typescript\nimport { useApiClient } from \"@/app\";\n\nfunction MyComponent() {\n  const apiClient = useApiClient();\n  const { data } = await apiClient.ping();\n}\n\\`\\`\\``);\n  }\n\n  parts.push(`## Workflow Skills\n\nThis repo ships agent workflow skills in \\`.agents/skills/\\` — the ordered development flow (grill → spec → tickets → implement/tdd → code-review). Start \\`/everything-dev-app\\` to orient and pick the right next step; \\`/ask-matt\\` is the router if unsure.\n\n- \\`/grill-with-docs\\` — sharpen an idea by interview, leaving a paper trail in \\`GLOSSARY.md\\` and ADRs\n- \\`/to-spec\\` / \\`/to-tickets\\` — turn a plan into a spec, then tracer-bullet tickets under \\`.scratch/<feature>/issues/\\`\n- \\`/implement\\` + \\`/tdd\\` — build a ticket test-first at pre-agreed seams\n- \\`/code-review\\` — two-axis review (Standards + Spec) of the diff since a fixed point\n- \\`/diagnosing-bugs\\` — diagnosis loop for hard bugs and performance regressions\n\nRun \\`/setup-matt-pocock-skills\\` once before first use. Tracker and triage conventions live in \\`docs/agents/\\`.`);\n\n  parts.push(`## Agent Communication Surface\n\nThe host exposes several surfaces for programmatic agent access:\n\n| Surface | Endpoint | Auth | Use |\n|---------|----------|------|-----|\n| MCP | \\`POST /api/mcp\\` | \\`x-api-key\\` header or session cookie | MCP clients — auto-generated tools from OpenAPI spec, stateless Streamable HTTP transport |\n| REST/OpenAPI | \\`GET/POST/... /api/{path}\\` | \\`x-api-key\\` header or session cookie | Standard REST; Scalar docs at \\`GET /api\\`, spec at \\`GET /api/spec.json\\` |\n| oRPC RPC | \\`POST /api/rpc/{procedure}\\` | \\`x-api-key\\` header or session cookie | Typed JSON-RPC for all API procedures |\n| Plugin RPC | \\`POST /api/rpc/{plugin}/{procedure}\\` | \\`x-api-key\\` header or session cookie | Per-plugin RPC (e.g. \\`/api/rpc/auth/getSession\\`) |\n| MCP discovery | \\`GET /.well-known/mcp.json\\` | None | JSON descriptor with server name, endpoint, and auth scheme |\n\n### Authentication for agents\n\n1. Sign in with your NEAR wallet (SIWN) at the website.\n2. Navigate to **Settings → API Keys** at \\`/settings/api-keys\\`.\n3. Create a new key — the full secret (\\`edk_...\\`) is shown once. Copy it immediately.\n4. Pass it on every request: \\`x-api-key: edk_your_key_here\\`\n\n### Architecture note: remotes are code bundles\n\nRemotes in \\`bos.app.ts\\` are **not hosted APIs** — they are code bundles loaded via Module Federation at runtime. The UI, API, auth, and plugins all run in the same host process. There is no remote server to call; everything is loaded in-process through Module Federation and \\`every-plugin\\`.`);\n\n  parts.push(`## Troubleshooting\n\n**Process won't start:**\n\\`\\`\\`bash\nbos kill        # Kill all tracked processes\npnpm install    # Ensure dependencies\npnpm run dev    # Restart\n\\`\\`\\`\n\n**Module Federation errors:**\n- Check \\`bos.app.ts\\` URLs are accessible\n- Verify shared dependency versions match in package.json\n- Clear browser cache\n\n**Database issues:**\n\\`\\`\\`bash\npnpm run db:push   # Push schema changes\npnpm run db:studio # Open Drizzle Studio\n\\`\\`\\`\n\n## Environment\n\n**Required files:**\n- \\`.env\\` — Secrets (see \\`.env.example\\`)\n- \\`bos.app.ts\\` — Runtime configuration (committed)`);\n\n  return `${parts.join(\"\\n\\n\")}\\n`;\n}\n\nexport function buildChildAgentsMd(\n  skillsBlock: string,\n  opts: {\n    overrides: OverrideSection[];\n    plugins?: string[];\n  },\n): string {\n  return `${skillsBlock}\\n\\n${buildChildAgentsInstructions(opts)}`;\n}\n\nexport async function personalizeAgentsMd(\n  destination: string,\n  opts: {\n    overrides: OverrideSection[];\n    plugins?: string[];\n  },\n): Promise<void> {\n  const agentsMdPath = join(destination, \"AGENTS.md\");\n  if (!existsSync(agentsMdPath)) return;\n\n  const content = readFileSync(agentsMdPath, \"utf-8\");\n  const skillsBlock = extractSkillsBlock(content);\n  if (!skillsBlock) return;\n\n  const childContent = buildChildAgentsMd(skillsBlock, opts);\n  writeFileSync(agentsMdPath, childContent);\n}\n\nfunction generateGitignore(): string {\n  return `node_modules/\ndist/\n.env\n.bos/\ndocker-compose.yml\n*.gen.ts\n*.gen.tsx\n`;\n}\n\nconst WORKFLOW_SKILLS_MARKER = \"everything-dev-app\";\nconst WORKFLOW_SKILLS_NOTE = `\n\n## Workflow skills\n\nThis repo ships agent workflow skills in \\`.agents/skills/\\` — the ordered development flow (grill → spec → tickets → implement/tdd → code-review). Start with \\`/everything-dev-app\\` to orient and pick the right next step. See \\`AGENTS.md\\` → Workflow Skills.\n`;\n\nexport function buildChildLlmsTxt(title: string): string {\n  return `# ${title}\n\n> Application running on the everything.dev runtime.\n\n## Skills\n\n- [Skill](/skill.md): Agent-ready prompt for talking to, running, editing, and publishing this runtime.\n- Workflow skills (in the repo): \\`.agents/skills/\\` — start with \\`everything-dev-app\\` for the ordered development flow.\n\n## API\n\n- [OpenAPI docs](/api): Interactive API reference (Scalar)\n- [OpenAPI spec](/api/spec.json): Machine-readable OpenAPI JSON\n- [oRPC RPC](/api/rpc): Typed JSON-RPC endpoint for all API procedures\n- [Plugin RPC](/api/rpc/auth): Auth plugin RPC (session, NEAR SIWN, relay, API keys, organizations)\n\n## MCP\n\n- [MCP server](/api/mcp): Model Context Protocol server (Streamable HTTP, stateless). Auto-generates tools from the API's OpenAPI spec.\n- [MCP discovery](/.well-known/mcp.json): JSON descriptor with server name, endpoint URL, and auth scheme.\n\n## Auth\n\nAuthenticate to the API using an API key:\n\n1. Sign in with your NEAR wallet (SIWN) at the website.\n2. Go to **Settings → API Keys** at \\`/settings/api-keys\\`.\n3. Create a key — the full secret (\\`edk_...\\`) is shown once.\n4. Pass it on every request: \\`x-api-key: edk_your_key_here\\`\n\nThe \\`x-api-key\\` header works for \\`/api/*\\` (REST), \\`/api/rpc/*\\` (oRPC), and \\`/api/mcp\\` (MCP).\n\n## Source\n\n- [Repository](https://github.com/NEARBuilders/everything-dev): Clone and read \\`AGENTS.md\\` for full development instructions, TanStack Intent skills, and workflow guidance.\n`;\n}\n\nexport function buildChildSkillMd(title: string, repository: string): string {\n  const repoLink = repository\n    ? `- [Repository](${repository}): Clone and read \\`AGENTS.md\\` for full development instructions.`\n    : `- Clone the repository and read \\`AGENTS.md\\` for full development instructions.`;\n\n  return `# ${title} skill\n\nUse this when you want an agent to run, edit, and publish **${title}** — an everything.dev app composed at runtime from \\`bos.app.ts\\`.\n\nThere are two ways to work with this app:\n\n1. **Talk to the app** — use the API via MCP or REST to read/write data without cloning anything.\n2. **Clone and modify** — clone the repository, run locally, edit code, and publish.\n\n## Mode 1: Talk to the app\n\n### MCP endpoint\n\n\\`\\`\\`\nPOST /api/mcp\n\\`\\`\\`\n\nTransport: Streamable HTTP (stateless). Connect your MCP client to \\`{origin}/api/mcp\\` to discover all available tools automatically.\n\n### Authentication\n\nUse an **API key**:\n\n1. Sign in with your NEAR wallet at the website (SIWN).\n2. Navigate to **Settings → API Keys** at \\`/settings/api-keys\\`.\n3. Create a key — the full secret (\\`edk_...\\`) is shown once.\n4. Pass it on every request: \\`x-api-key: edk_your_key_here\\`\n\n### REST / OpenAPI\n\n- **API docs**: \\`GET /api\\`\n- **OpenAPI spec**: \\`GET /api/spec.json\\`\n- **oRPC RPC**: \\`POST /api/rpc/{procedure}\\`\n- **MCP discovery**: \\`GET /.well-known/mcp.json\\`\n\n## Mode 2: Clone and modify\n\n### TanStack Intent\n\n- Registry entry: \\`https://tanstack.com/intent/registry/everything-dev\\`\n- Load with TanStack Intent: \\`npx @tanstack/intent@latest load everything-dev\\`\n\n### Read AGENTS.md first\n\nAfter cloning, read **\\`AGENTS.md\\`** at the repo root. It contains operational guidance, TanStack Intent skills, and workflow instructions.\n\n### Workflow skills\n\nThe repo ships agent workflow skills in \\`.agents/skills/\\` — start with \\`everything-dev-app\\` for the ordered development flow (grill → spec → tickets → implement/tdd → code-review).\n\n### Architecture note\n\nRemotes in \\`bos.app.ts\\` are **not hosted APIs** — they are code bundles loaded via Module Federation at runtime. Everything runs in the same host process.\n\n### Run locally\n\n\\`\\`\\`bash\npnpm install\nbos dev\n\\`\\`\\`\n\n### Publish\n\n\\`\\`\\`bash\nbos deploy\n\\`\\`\\`\n\n## Source\n\n${repoLink}\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,uBAAuB;;;;;;;;AASpC,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;AACF;;;;;;;AAQA,SAAgB,wBACd,YACA,MACS;CACT,MAAM,eAAWA,gBAAK,YAAY,qBAAqB;CACvD,IAAI,MAOA,CAAC;CACL,QAAIC,oBAAW,QAAQ,GACrB,IAAI;EACF,MAAM,aAASC,gBAAUC,sBAAa,UAAU,OAAO,CAAC;EACxD,IAAI,UAAU,OAAO,WAAW,UAAU,MAAM;CAClD,QAAQ;EACN,MAAM,CAAC;CACT;CAGF,IAAI,UAAU,KAACF,oBAAW,QAAQ;CAClC,MAAM,WAAW,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAI,IAAI,YAAY,CAAC,GAAI,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK;CAChF,IAAI,KAAK,UAAU,QA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