{"version":3,"file":"init-BSttoDrh.mjs","names":["ensureDirectory","classifyTarget","initializePoConfig"],"sources":["../src/services/init/templates.ts","../src/services/init/sync.ts","../src/services/init/index.ts"],"sourcesContent":["export const PRIVATE_DIRECTORY_MODE = 0o700;\nexport const PRIVATE_FILE_MODE = 0o600;\nexport const REPOSITORY_DIRECTORY_MODE = 0o755;\nexport const REPOSITORY_FILE_MODE = 0o644;\nexport const PO_DIRECTORY = '.po';\n\n/** The global seed files are processed in this fixed order. */\nexport const GLOBAL_PO_SEED_FILES = ['config.yaml', 'presets.yaml', 'domains.yaml', 'profiles.yaml'] as const;\n\nexport type PoSeedFile = (typeof GLOBAL_PO_SEED_FILES)[number];\n\n/** Personal-only: a repository pin would override the layout the person picks during onboarding. */\nconst WEB_TEMPLATE_SEED = `# Default web layout, resolved against the installed web template packages.\nweb:\n  template: po-template-elegant\n\n`;\n\n/** Portable defaults for a new global Po configuration directory. */\nexport const PO_CONFIG_TEMPLATES: Readonly<Record<PoSeedFile, string>> = {\n  'config.yaml': `projectTrust: ask\n\n${WEB_TEMPLATE_SEED}\n# Workspace declarations belong in the repository's .po/workspaces.yaml, not this personal file.\n# Entries accept name, path (default .), alias, instructions and free-form metadata.\n# Autonomous voice is opt-in and uses an explicitly configured Pi model.\n# voice:\n#   autoCapture:\n#     model: provider/model-id\n#     startPhrases:\n#       - hey po\n#     stopPhrases:\n#       - stop speaking\n#     utteranceIdleMs: 3000\n#     # Long prompts only: open a draft, keep talking, then send it in one piece.\n#     # Short utterances are delivered as you finish them and need no phrase.\n#     composeOpenPhrases:\n#       - hey po\n#     composeSendPhrases:\n#       - that's it\n#     composeCancelPhrases:\n#       - scratch that\n#     # Endpoint window while a draft collects, so a short command lands on its own.\n#     composeUtteranceIdleMs: 1200\n#     # Silence before Voice reminds you a draft is open. 0 turns the reminder off.\n#     composeNudgeMs: 10000\n#     tts:\n#       engine: macos-say\n#       voice: Samantha\n#       rate: 190\n`,\n  'presets.yaml': `# A layer is a reusable named bundle of packages, built-in or local extensions,\n# and hook groups. Presets below choose which layers load together for a session.\n#\n# Layers and presets defined here apply to every repository. A repository's own\n# .po/presets.yaml is read after this file and replaces any layer or preset of the\n# same name, so a repository can override one entry without restating the rest.\n#\n# Add a layer by giving it a unique name under layers. Local Pi scripts belong\n# under extensions, while installed Pi packages belong under packages:\n#   review-tools:\n#     extensions:\n#       - './extensions/local-review.ts'\n#     packages:\n#       - '@scope/review-extension'\n# A bare extension name selects a Po built-in. A path beginning with ./ or\n# ../ loads a custom script or extension directory. A bare package loads its\n# ordered package.json pi.extensions entries, while an exported subpath selects\n# one adapter. Relative paths resolve beside this file here (~/.po), or\n# from the repository root in .po/presets.yaml.\n#\n# Use a package mapping when that package accepts configuration. Configuration\n# belongs under the package entry that consumes it, not beside packages.\n# The top-level default bundle loads before every preset. Replace this whole\n# packages list to customize the distribution defaults. Po core packages\n# remain active independently of this list.\ndefault:\n  packages:\n    - '@agimon-ai/po-help'\n    - '@agimon-ai/po-goal'\n    - '@agimon-ai/po-voice'\n    - '@agimon-ai/po-runner'\n    - '@agimon-ai/po-codemode'\n    - '@agimon-ai/po-read'\n    - '@agimon-ai/po-grep'\n    - '@agimon-ai/po-edit'\n    - '@agimon-ai/po-file-edit'\n    - '@agimon-ai/po-scaffold'\n    - '@agimon-ai/po-autocompact'\n    - '@agimon-ai/po-space'\n    - '@agimon-ai/po-plan'\n    - '@agimon-ai/po-computer-use'\n    - '@agimon-ai/po-log'\n    - '@agimon-ai/po-mcp'\n    - '@agimon-ai/po-prompt'\n    - '@agimon-ai/po-template-advanced'\n    - '@agimon-ai/po-template-elegant'\n    - '@agimon-ai/po-template-desktop'\n    - '@agimon-ai/po-backdrop-bamboo'\nlayers:\n  # Durable scheduling. Keep this in the home default preset.\n  calendar:\n    packages:\n      - '@agimon-ai/po-calendar'\n      - '@agimon-ai/po-wake'\n  # Workflow graphs, launch, recovery and the\n  # workflow/dynamicWorkflow code-mode namespaces.\n  # Remove 'workflow' from a preset to turn it off there.\n  workflow:\n    packages:\n      - '@agimon-ai/po-workflow'\n  coding:\n    packages:\n      - '@agimon-ai/po-lint'\n  team:\n    packages:\n      - name: '@agimon-ai/po-team'\n        # Optional Team configuration. Uncomment and choose models available to Pi.\n        # config:\n        #   models:\n        #     - model: openai-codex/gpt-5.6-luna\n        #       thinking: xhigh\n        #   # Tool names excluded from subagents launched by this package. These\n        #   # remove model-visible tools while preserving hidden team transport.\n        #   excludeTools: [ask_user_question, intercom, subagent]\n  ask-user:\n    packages:\n      - '@agimon-ai/po-user-feedback'\n  task:\n    packages:\n      - '@agimon-ai/po-task'\n  sandbox:\n    packages:\n      - '@agimon-ai/po-sandbox'\n  design:\n    packages:\n      - '@agimon-ai/po-style-system'\n  llm:\n    packages:\n      - '@agimon-ai/po-model-guidance'\n      - '@agimon-ai/po-gateway'\n  source-control:\n    packages:\n      - '@agimon-ai/po-git'\n  image-gen:\n    packages:\n      - '@agimon-ai/po-image-gen'\n  # Excel workbooks as an Author canvas, and the spreadsheet code-mode namespace.\n  spreadsheet:\n    packages:\n      - '@agimon-ai/po-spreadsheet'\n  web-search:\n    packages:\n      - '@agimon-ai/po-web-search'\n  browser:\n    packages:\n      - '@agimon-ai/po-browse'\n  # Extra languages for Po's own interface, notifications and replies.\n  lang:\n    packages:\n      - '@agimon-ai/po-lang-zh'\n# A preset explains when it should be used and names its ordered layers.\n# Add another entry under preset, then select it with\n# po --preset <name>. Change defaultPreset to make it the default.\ndefaultPreset: copilot\npreset:\n  minimal:\n    description: Lean preset with Team delegation and persistent tasks.\n    layers: [team, task, llm, workflow, calendar]\n  copilot:\n    description: General-purpose coding preset with delegation, persistent tasks, supervised commands, and structured user feedback.\n    layers: [team, ask-user, task, sandbox, llm, source-control, design, image-gen, spreadsheet, web-search, browser, coding, workflow, calendar, lang]\n  examples:\n    description: Base preset for the repository's plugin and workflow examples.\n    layers: [workflow]\n  # review:\n  #   description: Focused review preset for inspecting changes and reporting risks.\n  #   layers: [team, task, ask-user]\n`,\n  'domains.yaml': `# Plugins are named once in this catalog, then selected by one or more domains.\n# Po automatically inspects personal and repository Codex marketplaces.\n# Each configured root may also be a folder whose direct children are plugins;\n# use roots: [plugins] to discover a repository plugin folder without one entry\n# per plugin. Discovery never scans recursively.\ndefaultDomains: [default]\nplugins:\n  roots: []\n  entries: {}\n  # Local paths resolve beside this file in ~/.po. Repository paths in a\n  # repository .po/domains.yaml resolve from that repository root.\n  # entries:\n  #   development:\n  #     source: local\n  #     path: plugins/development\n  #   remote-review:\n  #     source: url\n  #     url: https://github.com/acme/review-plugin.git\n  #     ref: v1.2.0\n  #   published-review:\n  #     source: npm\n  #     package: '@acme/review-plugin'\n  #     version: 1.2.0\n# Domains carry descriptions and refer to catalog names, not filesystem paths.\ndomains:\n  default:\n    description: Shared skills and repository MCP only.\n    plugins: []\n  # development:\n  #   description: TypeScript implementation and review tools.\n  #   plugins:\n  #     - development\n  #     # Mapping form can load only selected resources from a shared plugin.\n  #     - name: remote-review\n  #       skills: [typescript]\n  #       agents: [reviewer]\n  #       hooks: false\n  #       mcp: true\n  #   # Set false only when this domain should omit shared .claude/skills.\n  #   sharedSkills: false\n  #   # Domain mcp is an allowlist over servers configured elsewhere, not a\n  #   # request to start new ones. Listing servers here drops the tool schemas\n  #   # of the ones left out, usually the largest context saving a domain can\n  #   # make. Run po --explain to see the token cost before and after.\n  #   # Filtering applies only when every selected domain declares mcp, so a\n  #   # selection mixing this with a domain that omits it stays unfiltered.\n  #   mcp:\n  #     servers: [code-intel]\n  #     proxy: [repository-search]\n# Select it with po --domains development, or add it to defaultDomains.\n#\n# Aliases let one selection enable multiple domains. Replace the empty mapping\n# below with entries like the commented example.\naliases: {}\n# aliases:\n#   work: [default, development]\n`,\n  'profiles.yaml': `# Profiles select a persona and optional environment defaults for a session.\n# Each configured root may itself be a profile or contain direct-child profile\n# folders. A folder is discovered when it contains profile.md, SOUL.md, or\n# AGENTS.md; discovery never scans recursively.\nprofiles:\n  roots: []\n  entries: {}\n  # Roots resolve beside this file in ~/.po. Repository roots in a\n  # repository .po/profiles.yaml resolve from that repository root.\n  # roots: [agents/acme]\n  # Explicit entries override an automatically discovered folder of the same\n  # name. Environment values must be strings; already exported values win.\n  # entries:\n  #   writer:\n  #     persona: agents/special/writer\n  #     env:\n  #       BRAND: acme\n  #       TONE: concise\n# Po Pi concatenates profile.md, SOUL.md, then AGENTS.md for the persona.\n# Select one with: po --profile writer\n`,\n};\n\n/** Standalone defaults for a repository that is trying Po through Po. */\nexport const REPOSITORY_PO_CONFIG_TEMPLATES: Readonly<Record<PoSeedFile, string>> = {\n  'config.yaml': PO_CONFIG_TEMPLATES['config.yaml'].replace(WEB_TEMPLATE_SEED, ''),\n  'presets.yaml': `# Repository-local layers and presets. These entries override personal\n# entries with the same name from ~/.po/presets.yaml.\n# This repository-local default replaces the personal top-level default as one\n# whole package list. Edit it to customize the standalone package baseline.\ndefault:\n  packages:\n    - '@agimon-ai/po-help'\n    - '@agimon-ai/po-goal'\n    - '@agimon-ai/po-voice'\n    - '@agimon-ai/po-runner'\n    - '@agimon-ai/po-codemode'\n    - '@agimon-ai/po-read'\n    - '@agimon-ai/po-grep'\n    - '@agimon-ai/po-edit'\n    - '@agimon-ai/po-file-edit'\n    - '@agimon-ai/po-scaffold'\n    - '@agimon-ai/po-autocompact'\n    - '@agimon-ai/po-space'\n    - '@agimon-ai/po-plan'\n    - '@agimon-ai/po-computer-use'\n    - '@agimon-ai/po-log'\n    - '@agimon-ai/po-mcp'\n    - '@agimon-ai/po-prompt'\n    - '@agimon-ai/po-template-advanced'\n    - '@agimon-ai/po-template-elegant'\n    - '@agimon-ai/po-template-desktop'\n    - '@agimon-ai/po-backdrop-bamboo'\nlayers:\n  # Durable scheduling. Keep this in the home default preset.\n  calendar:\n    packages:\n      - '@agimon-ai/po-calendar'\n      - '@agimon-ai/po-wake'\n  # Workflow graphs, launch, recovery and the\n  # workflow/dynamicWorkflow code-mode namespaces.\n  # Remove 'workflow' from a preset to turn it off there.\n  workflow:\n    packages:\n      - '@agimon-ai/po-workflow'\n  coding:\n    packages:\n      - '@agimon-ai/po-lint'\n  team:\n    packages:\n      - name: '@agimon-ai/po-team'\n  ask-user:\n    packages:\n      - '@agimon-ai/po-user-feedback'\n  task:\n    packages:\n      - '@agimon-ai/po-task'\n  sandbox:\n    packages:\n      - '@agimon-ai/po-sandbox'\n  design:\n    packages:\n      - '@agimon-ai/po-style-system'\n  llm:\n    packages:\n      - '@agimon-ai/po-model-guidance'\n      - '@agimon-ai/po-gateway'\n  source-control:\n    packages:\n      - '@agimon-ai/po-git'\n  image-gen:\n    packages:\n      - '@agimon-ai/po-image-gen'\n  spreadsheet:\n    packages:\n      - '@agimon-ai/po-spreadsheet'\n  web-search:\n    packages:\n      - '@agimon-ai/po-web-search'\n  browser:\n    packages:\n      - '@agimon-ai/po-browse'\n  # Extra languages for Po's own interface, notifications and replies.\n  lang:\n    packages:\n      - '@agimon-ai/po-lang-zh'\ndefaultPreset: copilot\npreset:\n  minimal:\n    description: Lean preset with Team delegation and persistent tasks.\n    layers: [team, task, llm, workflow, calendar]\n  copilot:\n    description: General-purpose coding preset with delegation, persistent tasks, supervised commands, and structured user feedback.\n    layers: [team, ask-user, task, sandbox, llm, source-control, design, image-gen, spreadsheet, web-search, browser, coding, workflow, calendar, lang]\n  examples:\n    description: Base preset for the repository's plugin and workflow examples.\n    layers: [workflow]\n`,\n  'domains.yaml': `# Repository-local plugin catalog and domain selection.\ndefaultDomains: [default]\nplugins:\n  roots: []\n  entries: {}\ndomains:\n  default:\n    description: Shared skills and repository MCP only.\n    plugins: []\naliases: {}\n`,\n  'profiles.yaml': `# Repository-local persona roots and environment defaults.\nprofiles:\n  roots: []\n  entries: {}\n`,\n};\n\n/** Result of filling a Po seed directory. File arrays contain names in seed order. */\nexport interface GlobalPoInitResult {\n  directory: string;\n  created: string[];\n  preserved: string[];\n  /** Existing files overwritten from the template. Only ever non-empty under `force`. */\n  replaced: string[];\n}\n\nexport interface GlobalPoInitOptions {\n  /**\n   * Overwrite existing seed files instead of preserving them.\n   *\n   * Off by default: init is safe to re-run, and hand-edited config is the\n   * normal case rather than the exception.\n   */\n  force?: boolean;\n}\n\nexport type RepositoryPoInitOptions = GlobalPoInitOptions;\nexport type RepositoryPoInitResult = GlobalPoInitResult;\n","import { randomUUID } from 'node:crypto';\n// sync: These helpers implement exported Node-only synchronous initialization APIs.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { nodeHost } from '@agimon-ai/po-core/platform';\n\nimport { globalPoConfigDirectory } from '../config';\nimport {\n  PO_CONFIG_TEMPLATES,\n  PO_DIRECTORY,\n  GLOBAL_PO_SEED_FILES,\n  PRIVATE_DIRECTORY_MODE,\n  PRIVATE_FILE_MODE,\n  REPOSITORY_DIRECTORY_MODE,\n  REPOSITORY_PO_CONFIG_TEMPLATES,\n  REPOSITORY_FILE_MODE,\n  type PoSeedFile,\n  type GlobalPoInitOptions,\n  type GlobalPoInitResult,\n  type RepositoryPoInitOptions,\n  type RepositoryPoInitResult,\n} from './templates';\n\nconst UTF8_ENCODING = 'utf8';\nconst FILE_ALREADY_EXISTS = 'EEXIST';\nconst FILE_NOT_FOUND = 'ENOENT';\n\nfunction errorCode(error: unknown): string | undefined {\n  if (!(error instanceof Error)) return undefined;\n  const code = (error as NodeJS.ErrnoException).code;\n  return typeof code === 'string' ? code : undefined;\n}\n\nfunction ensureDirectory(directory: string, mode: number): void {\n  let stats: fs.Stats;\n  try {\n    stats = fs.lstatSync(directory);\n  } catch (error) {\n    if (errorCode(error) !== FILE_NOT_FOUND) throw error;\n    try {\n      fs.mkdirSync(directory, { mode });\n      stats = fs.lstatSync(directory);\n    } catch (mkdirError) {\n      if (errorCode(mkdirError) !== FILE_ALREADY_EXISTS) throw mkdirError;\n      stats = fs.lstatSync(directory);\n    }\n  }\n\n  if (stats.isSymbolicLink()) {\n    throw new Error(`Refusing to initialize through symlinked directory: ${directory}`);\n  }\n  if (!stats.isDirectory()) {\n    throw new Error(`Po config path is not a directory: ${directory}`);\n  }\n}\n\nfunction ensurePoDirectory(directory: string, mode: number): void {\n  ensureDirectory(path.dirname(directory), mode);\n  ensureDirectory(directory, mode);\n}\n\nfunction classifyTarget(targetPath: string): 'missing' | 'file' {\n  let stats: fs.Stats;\n  try {\n    stats = fs.lstatSync(targetPath);\n  } catch (error) {\n    if (errorCode(error) === FILE_NOT_FOUND) return 'missing';\n    throw error;\n  }\n\n  if (stats.isFile()) return 'file';\n  if (stats.isSymbolicLink()) {\n    try {\n      if (fs.statSync(targetPath).isFile()) return 'file';\n    } catch (error) {\n      throw new Error(`Po config seed symlink is not file-like: ${targetPath}`, { cause: error });\n    }\n  }\n  throw new Error(`Po config seed path is not file-like: ${targetPath}`);\n}\n\nfunction cleanupTemporaryFile(temporaryPath: string): void {\n  try {\n    fs.unlinkSync(temporaryPath);\n  } catch (error) {\n    if (errorCode(error) !== FILE_NOT_FOUND) throw error;\n  }\n}\n\nfunction publishExclusively(targetPath: string, content: string, mode: number): boolean {\n  const temporaryPath = `${targetPath}.${nodeHost.processId()}.${randomUUID()}.tmp`;\n  let fileDescriptor: number | undefined;\n  try {\n    fileDescriptor = fs.openSync(temporaryPath, 'wx', mode);\n    fs.writeFileSync(fileDescriptor, content, UTF8_ENCODING);\n    fs.fchmodSync(fileDescriptor, mode);\n    fs.fsyncSync(fileDescriptor);\n    const descriptorToClose = fileDescriptor;\n    fileDescriptor = undefined;\n    fs.closeSync(descriptorToClose);\n\n    try {\n      fs.linkSync(temporaryPath, targetPath);\n      return true;\n    } catch (error) {\n      if (errorCode(error) === FILE_ALREADY_EXISTS && classifyTarget(targetPath) === 'file') return false;\n      throw error;\n    }\n  } finally {\n    if (fileDescriptor !== undefined) {\n      const descriptorToClose = fileDescriptor;\n      fileDescriptor = undefined;\n      fs.closeSync(descriptorToClose);\n    }\n    cleanupTemporaryFile(temporaryPath);\n  }\n}\n\n/**\n * Replaces a seed file with the template, atomically.\n *\n * The rename swaps the directory entry in one step, so a reader either sees the\n * whole old file or the whole new one. Renaming onto a symlinked seed replaces\n * the link rather than writing through it.\n */\nfunction publishForcefully(targetPath: string, content: string, mode: number): void {\n  const temporaryPath = `${targetPath}.${nodeHost.processId()}.${randomUUID()}.tmp`;\n  let fileDescriptor: number | undefined;\n  try {\n    fileDescriptor = fs.openSync(temporaryPath, 'wx', mode);\n    fs.writeFileSync(fileDescriptor, content, UTF8_ENCODING);\n    fs.fchmodSync(fileDescriptor, mode);\n    fs.fsyncSync(fileDescriptor);\n    const descriptorToClose = fileDescriptor;\n    fileDescriptor = undefined;\n    fs.closeSync(descriptorToClose);\n\n    fs.renameSync(temporaryPath, targetPath);\n  } finally {\n    if (fileDescriptor !== undefined) {\n      const descriptorToClose = fileDescriptor;\n      fileDescriptor = undefined;\n      fs.closeSync(descriptorToClose);\n    }\n    cleanupTemporaryFile(temporaryPath);\n  }\n}\n\nfunction initializePoConfig(\n  directory: string,\n  templates: Readonly<Record<PoSeedFile, string>>,\n  options: GlobalPoInitOptions,\n  directoryMode: number,\n  fileMode: number,\n): GlobalPoInitResult {\n  ensurePoDirectory(directory, directoryMode);\n\n  const created: string[] = [];\n  const preserved: string[] = [];\n  const replaced: string[] = [];\n  for (const fileName of GLOBAL_PO_SEED_FILES) {\n    const targetPath = path.join(directory, fileName);\n    const existed = classifyTarget(targetPath) === 'file';\n\n    if (options.force) {\n      publishForcefully(targetPath, templates[fileName], fileMode);\n      (existed ? replaced : created).push(fileName);\n      continue;\n    }\n    if (existed) {\n      preserved.push(fileName);\n      continue;\n    }\n    if (publishExclusively(targetPath, templates[fileName], fileMode)) created.push(fileName);\n    else preserved.push(fileName);\n  }\n\n  return { directory, created, preserved, replaced };\n}\n\n/**\n * Fills missing global seed files.\n *\n * Existing files are left alone so that re-running init never discards\n * hand-edited config; pass `force` to overwrite them from the template. A new\n * file is published with an exclusive hard link, so a concurrent writer in\n * another process never loses its file to this one.\n *\n * @deprecated Node-only sync shim; use initializeGlobalPoConfigAsync. Removed in M2.\n */\nexport function initializeGlobalPoConfig(\n  homeDirectory = nodeHost.homeDirectory(),\n  options: GlobalPoInitOptions = {},\n): GlobalPoInitResult {\n  return initializePoConfig(\n    globalPoConfigDirectory(homeDirectory),\n    PO_CONFIG_TEMPLATES,\n    options,\n    PRIVATE_DIRECTORY_MODE,\n    PRIVATE_FILE_MODE,\n  );\n}\n\n/**\n * Seeds repository-local configuration without creating or changing Pi settings.\n *\n * @deprecated Node-only sync shim; use initializeRepositoryPoConfigAsync. Removed in M2.\n */\nexport function initializeRepositoryPoConfig(\n  repositoryRoot = process.cwd(),\n  options: RepositoryPoInitOptions = {},\n): RepositoryPoInitResult {\n  return initializePoConfig(\n    path.join(path.resolve(repositoryRoot), PO_DIRECTORY),\n    REPOSITORY_PO_CONFIG_TEMPLATES,\n    options,\n    REPOSITORY_DIRECTORY_MODE,\n    REPOSITORY_FILE_MODE,\n  );\n}\n","import path from 'node:path';\n\nimport {\n  createSerialRunner,\n  getOrThrow,\n  nodeHost,\n  writeFileAtomic,\n  type FileSystem,\n} from '@agimon-ai/po-core/platform';\n\nimport { globalPoConfigDirectory } from '../config';\nimport {\n  PO_CONFIG_TEMPLATES,\n  PO_DIRECTORY,\n  GLOBAL_PO_SEED_FILES,\n  PRIVATE_DIRECTORY_MODE,\n  PRIVATE_FILE_MODE,\n  REPOSITORY_DIRECTORY_MODE,\n  REPOSITORY_PO_CONFIG_TEMPLATES,\n  REPOSITORY_FILE_MODE,\n  type PoSeedFile,\n  type GlobalPoInitOptions,\n  type GlobalPoInitResult,\n  type RepositoryPoInitOptions,\n  type RepositoryPoInitResult,\n} from './templates';\n\ntype IoContext = Parameters<FileSystem['readTextFile']>[1];\n\nexport {\n  PO_CONFIG_TEMPLATES,\n  GLOBAL_PO_SEED_FILES,\n  REPOSITORY_PO_CONFIG_TEMPLATES,\n  type GlobalPoInitOptions,\n  type GlobalPoInitResult,\n  type RepositoryPoInitOptions,\n  type RepositoryPoInitResult,\n} from './templates';\nexport { initializeGlobalPoConfig, initializeRepositoryPoConfig } from './sync';\n\n/** Seed writes in this process are queued per file, so a check and its write are not interleaved. */\nconst seedWrites = createSerialRunner();\n\nasync function ensureDirectory(fs: FileSystem, directory: string, mode: number, context: IoContext): Promise<void> {\n  let info = await fs.fileInfo(directory, context);\n  if (!info.ok && info.error.code === 'not_found') {\n    const created = await fs.createDir(directory, { recursive: false }, context);\n    if (created.ok) await nodeHost.setMode(directory, mode);\n    info = await fs.fileInfo(directory, context);\n  }\n  const kind = getOrThrow(info).kind;\n  if (kind === 'symlink') throw new Error(`Refusing to initialize through symlinked directory: ${directory}`);\n  if (kind !== 'directory') throw new Error(`Po config path is not a directory: ${directory}`);\n}\n\nasync function classifyTarget(fs: FileSystem, targetPath: string, context: IoContext): Promise<'missing' | 'file'> {\n  const info = await fs.fileInfo(targetPath, context);\n  if (!info.ok && info.error.code === 'not_found') return 'missing';\n  const kind = getOrThrow(info).kind;\n  if (kind === 'file') return 'file';\n  if (kind === 'symlink') {\n    try {\n      const target = getOrThrow(await fs.canonicalPath(targetPath, context));\n      if (getOrThrow(await fs.fileInfo(target, context)).kind === 'file') return 'file';\n    } catch (error) {\n      throw new Error(`Po config seed symlink is not file-like: ${targetPath}`, { cause: error });\n    }\n  }\n  throw new Error(`Po config seed path is not file-like: ${targetPath}`);\n}\n\nasync function publish(fs: FileSystem, targetPath: string, content: string, mode: number, context: IoContext) {\n  await writeFileAtomic(fs, targetPath, content, context);\n  await nodeHost.setMode(targetPath, mode);\n}\n\n/**\n * Fills one seed directory over a FileSystem.\n *\n * Without `force`, a missing file is checked and written inside one queued step\n * per file. The FileSystem has no exclusive create, so a second process writing\n * the same new file at the same instant can be overwritten; the Node-only sync\n * shim keeps its hard-link publication for that case.\n */\nasync function initializePoConfig(\n  fs: FileSystem,\n  directory: string,\n  templates: Readonly<Record<PoSeedFile, string>>,\n  options: GlobalPoInitOptions,\n  directoryMode: number,\n  fileMode: number,\n  context: IoContext,\n): Promise<GlobalPoInitResult> {\n  await ensureDirectory(fs, path.dirname(directory), directoryMode, context);\n  await ensureDirectory(fs, directory, directoryMode, context);\n\n  const created: string[] = [];\n  const preserved: string[] = [];\n  const replaced: string[] = [];\n  for (const fileName of GLOBAL_PO_SEED_FILES) {\n    const targetPath = path.join(directory, fileName);\n    await seedWrites.forKey(path.resolve(targetPath))(async () => {\n      const existed = (await classifyTarget(fs, targetPath, context)) === 'file';\n      if (existed && !options.force) {\n        preserved.push(fileName);\n        return;\n      }\n      await publish(fs, targetPath, templates[fileName], fileMode, context);\n      (existed ? replaced : created).push(fileName);\n    });\n  }\n  return { directory, created, preserved, replaced };\n}\n\n/**\n * Fills missing global seed files over a FileSystem.\n *\n * Existing files are left alone so that re-running init never discards\n * hand-edited config; pass `force` to overwrite them from the template.\n */\nexport function initializeGlobalPoConfigAsync(\n  fs: FileSystem,\n  context: IoContext,\n  homeDirectory = nodeHost.homeDirectory(),\n  options: GlobalPoInitOptions = {},\n): Promise<GlobalPoInitResult> {\n  return initializePoConfig(\n    fs,\n    globalPoConfigDirectory(homeDirectory),\n    PO_CONFIG_TEMPLATES,\n    options,\n    PRIVATE_DIRECTORY_MODE,\n    PRIVATE_FILE_MODE,\n    context,\n  );\n}\n\n/** Seeds repository-local configuration over a FileSystem without creating or changing Pi settings. */\nexport function initializeRepositoryPoConfigAsync(\n  fs: FileSystem,\n  repositoryRoot: string,\n  context: IoContext,\n  options: RepositoryPoInitOptions = {},\n): Promise<RepositoryPoInitResult> {\n  return initializePoConfig(\n    fs,\n    path.join(path.resolve(repositoryRoot), PO_DIRECTORY),\n    REPOSITORY_PO_CONFIG_TEMPLATES,\n    options,\n    REPOSITORY_DIRECTORY_MODE,\n    REPOSITORY_FILE_MODE,\n    context,\n  );\n}\n"],"mappings":";;;;;;;;AAOA,MAAa,uBAAuB;CAAC;CAAe;CAAgB;CAAgB;AAAe;;AAKnG,MAAM,oBAAoB;;;;;;AAO1B,MAAa,sBAA4D;CACvE,eAAe;;EAEf,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA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