@agimon-ai/po-git 0.0.0-alpha.20 → 0.0.0-alpha.201

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +97 -8
  2. package/README.md +91 -21
  3. package/dist/apiContracts.cjs +78 -12
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +78 -12
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +2255 -544
  10. package/dist/extensions/native.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +1553 -508
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts.map +1 -1
  14. package/dist/extensions/server.mjs +1512 -467
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +1747 -1374
  17. package/dist/extensions/web.mjs.map +1 -1
  18. package/dist/gitDependencies-D8bKxZSc.cjs +2690 -0
  19. package/dist/gitDependencies-D8bKxZSc.cjs.map +1 -0
  20. package/dist/gitDependencies-Delu4xip.mjs +2432 -0
  21. package/dist/gitDependencies-Delu4xip.mjs.map +1 -0
  22. package/dist/index.cjs +13 -22
  23. package/dist/index.d.mts +266 -14
  24. package/dist/index.d.mts.map +1 -1
  25. package/dist/index.mjs +3 -22
  26. package/dist/po-runtime-identity.json +1 -0
  27. package/llms.txt +3 -3
  28. package/package.json +99 -21
  29. package/src/prompts/codemode-how-to-git/SKILL.md +137 -0
  30. package/dist/index.cjs.map +0 -1
  31. package/dist/index.mjs.map +0 -1
  32. package/dist/worktreeOperations-Cd8Q12L4.mjs +0 -1064
  33. package/dist/worktreeOperations-Cd8Q12L4.mjs.map +0 -1
  34. package/dist/worktreeOperations-Dxs3txKL.cjs +0 -1220
  35. package/dist/worktreeOperations-Dxs3txKL.cjs.map +0 -1
  36. package/src/prompts/po-use-git/SKILL.md +0 -87
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gitDependencies-D8bKxZSc.cjs","names":["defineServiceContract","PO_GIT_ENGINE_SERVICE","REMOVE_TIMEOUT_MS","fs","ProfileName","ConeFolder","loadAll","SparsePolicy","randomUUID","path","fs","randomUUID","path","fs","createHash","Type","O","defineApiContract","jsonApiResponses","defineServiceContract","Type","PoWorkflowDefinitionRefSchema","PoWorkflowRunRefSchema","Check","path","ProfileName","ConeFolder","fs","setTimeout","withAbortSignal","BACKGROUND_CONTEXT","getOrThrow","path","isDeepStrictEqual","createHash","os","path","poHomeDirectory","fs","isDeepStrictEqual","randomUUID","spawn","fs","path","fs","require","profilePath","createHash","pathModule","SparsePolicy","randomUUID","SparoError","ConeFolder","PO_FS_SERVICE","requirePoFs","PO_GIT_ENGINE_SERVICE","createRequire","withAbortSignal","BACKGROUND_CONTEXT","readPoWorkspaceRegistry"],"sources":["../src/services/extensionService/index.ts","../src/schemas/gitEngine.ts","../src/services/gitCli/index.ts","../src/constants/git.ts","../src/services/errors/index.ts","../src/services/worktreeConfig/index.ts","../src/services/worktreeEvents/index.ts","../src/services/atomicJson/index.ts","../src/services/repositoryIdentity/index.ts","../src/schemas/apiContracts.ts","../src/schemas/worktreeWorkflows.ts","../src/services/worktreeRegistry/index.ts","../src/services/sparoRegistryImport/index.ts","../src/services/paths/index.ts","../src/services/riftCli/index.ts","../src/services/worktreeNaming/index.ts","../src/services/worktreeOperations/index.ts","../src/services/gitDependencies/index.ts"],"sourcesContent":["// @scaffold-generated\nimport type { GitExtensionResult, GitExtensionService } from '../../types/extension';\n\nexport class DefaultGitExtensionService implements GitExtensionService {\n async execute(): Promise<GitExtensionResult> {\n return { message: 'Show git worktrees owned by this session', level: 'info' };\n }\n}\n","import { defineServiceContract } from '@agimon-ai/po-core/serverPlugin';\nimport { PO_GIT_ENGINE_SERVICE, type GitEngineService } from '@agimon-ai/po-sparo';\n\nexport const GIT_ENGINE_CONTRACT = defineServiceContract<GitEngineService>(PO_GIT_ENGINE_SERVICE, {\n scope: 'workspace',\n});\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/git-engine': GitEngineService;\n }\n}\n","import { execFile } from 'node:child_process';\nimport fs from 'node:fs/promises';\n\nimport type { GitBranches, GitLocalBranch, GitRemoteBranch } from '../../types/gitSessions';\nimport type { WorktreeGit } from '../../types/worktreeRegistry';\n\n/**\n * Git, as this package needs it.\n *\n * The timeouts are not uniform because the operations are not comparable. A\n * read answers in milliseconds; `worktree add` copies an entire checkout and\n * `worktree remove` deletes one, both bounded by the filesystem rather than by\n * git, and both minutes rather than seconds on a large repository or on\n * Windows. A single timeout would either fail honest work or hang on a wedged\n * one.\n */\nexport const READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\n/** fetch and push: bounded by the network, so long enough for a slow link, short enough to notice a dead one. */\nexport const NETWORK_TIMEOUT_MS = 120_000;\n/** A rebase replays commits locally; a large branch on a slow disk takes minutes, never hours. */\nexport const REBASE_TIMEOUT_MS = 300_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n/** Enough for any branch picker; a repository with more refs lists its most recent ones. */\nconst MAX_LISTED_REFS = 2_000;\nconst LOCAL_PREFIX = 'refs/heads/';\nconst REMOTE_PREFIX = 'refs/remotes/';\nconst HEAD_SUFFIX = '/HEAD';\n\nexport interface GitResult {\n code: number;\n stdout: string;\n stderr: string;\n /** The timeout killed git. */\n timedOut: boolean;\n /** Output passed maxBuffer and git was killed; stdout is truncated. */\n overflow: boolean;\n}\n\nexport interface RunGitOptions {\n timeout: number;\n /** The whole environment for this one child. Defaults to the hub's own. */\n env?: NodeJS.ProcessEnv;\n maxBuffer?: number;\n signal?: AbortSignal;\n}\n\n/**\n * Runs git and reports the outcome without ever throwing on a non-zero exit.\n *\n * LC_ALL is pinned because callers decide what to do by matching git's own\n * wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n *\n * `env` replaces the environment for this child only. That is how remote auth\n * reaches fetch and push without ever touching the hub's own process.env,\n * which every session started afterwards would inherit.\n */\nexport function runGit(cwd: string, args: readonly string[], options: RunGitOptions): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n {\n cwd,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n timeout: options.timeout,\n maxBuffer: options.maxBuffer ?? MAX_OUTPUT_BYTES,\n env: { ...(options.env ?? process.env), LC_ALL: 'C' },\n },\n (error, stdout, stderr) => {\n const failure = error as (NodeJS.ErrnoException & { killed?: boolean; signal?: string | null }) | null;\n const code = failure && typeof failure.code === 'number' ? failure.code : failure ? 1 : 0;\n resolve({\n code,\n stdout: String(stdout),\n stderr: String(stderr),\n timedOut: failure?.killed === true && failure.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER',\n overflow: failure?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER',\n });\n },\n );\n });\n}\n\n/** Resolve a commit or configured profile blob without reading the working cone. */\nexport async function revision(\n cwd: string,\n ref: string,\n options: Omit<RunGitOptions, 'timeout'> = {},\n): Promise<string> {\n const result = await runGit(cwd, ['rev-parse', '--verify', ref], { ...options, timeout: READ_TIMEOUT_MS });\n options.signal?.throwIfAborted();\n if (result.code !== 0) throw failure('rev-parse', result);\n return result.stdout.trim();\n}\n\n/** A sparse remote-only checkout creates its tracking branch in the engine. */\nexport async function trackBranch(\n cwd: string,\n branch: string,\n upstream: string,\n options: Omit<RunGitOptions, 'timeout'>,\n): Promise<void> {\n const result = await runGit(cwd, ['branch', `--set-upstream-to=${upstream}`, branch], {\n ...options,\n timeout: READ_TIMEOUT_MS,\n });\n options.signal?.throwIfAborted();\n if (result.code !== 0) throw failure('branch --set-upstream-to', result);\n}\n\n/** Read only the exact named remote branch, never a stale local tracking ref. */\nexport async function remoteBranchHead(\n cwd: string,\n remote: string,\n branch: string,\n options: { env: Readonly<Record<string, string | undefined>>; signal: AbortSignal },\n): Promise<string | undefined> {\n options.signal.throwIfAborted();\n // ls-remote also accepts repository paths and URLs. Require a configured name first,\n // so a missing remote cannot silently become a same-named local directory.\n const configured = await runGit(cwd, ['remote', 'get-url', '--', remote], { ...options, timeout: READ_TIMEOUT_MS });\n options.signal.throwIfAborted();\n if (configured.code !== 0) return undefined;\n const ref = `refs/heads/${branch}`;\n const result = await runGit(cwd, ['ls-remote', '--exit-code', '--refs', '--', remote, ref], {\n ...options,\n timeout: NETWORK_TIMEOUT_MS,\n });\n options.signal.throwIfAborted();\n if (result.code !== 0) return undefined;\n return result.stdout\n .split('\\n')\n .map((line) => line.split('\\t'))\n .find((line) => line[1] === ref)?.[0];\n}\n\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return runGit(cwd, args, { timeout });\n}\n\n/**\n * The message a failed git call is allowed to surface.\n *\n * Raw stderr never travels: it can carry a remote URL with a token in it, and\n * this text ends up in a tool result the model reads and may repeat.\n */\nfunction failure(operation: string, result: GitResult): Error {\n return new Error(\n `git ${operation} failed (exit ${String(result.code)}, ${String(result.stderr.length)} bytes of stderr)`,\n );\n}\n\n/** Git's own words for \"that worktree is not there any more\". */\nfunction missingWorktree(stderr: string): boolean {\n const normalized = stderr.toLowerCase();\n return normalized.includes('is not a working tree') || normalized.includes('cannot remove working tree');\n}\n\nexport function createWorktreeGit(): WorktreeGit {\n const prune = async (repositoryRoot: string): Promise<void> => {\n await git(repositoryRoot, ['worktree', 'prune'], PRUNE_TIMEOUT_MS);\n };\n\n return {\n async addWorktree({ repositoryRoot, path, branch, baseRef }) {\n const result = await git(repositoryRoot, ['worktree', 'add', '-b', branch, path, baseRef], ADD_TIMEOUT_MS);\n if (result.code !== 0) throw failure('worktree add', result);\n },\n\n async addExistingWorktree({ repositoryRoot, path, branch, remote }) {\n const args =\n remote === undefined\n ? ['worktree', 'add', path, branch]\n : ['worktree', 'add', '--track', '-b', branch, path, `${remote}/${branch}`];\n const result = await git(repositoryRoot, args, ADD_TIMEOUT_MS);\n if (result.code !== 0) throw failure('worktree add', result);\n },\n\n async listBranches(repositoryRoot): Promise<GitBranches> {\n const refs = await git(\n repositoryRoot,\n [\n 'for-each-ref',\n '--sort=-committerdate',\n `--count=${String(MAX_LISTED_REFS)}`,\n '--format=%(refname)%09%(worktreepath)%09%(symref)',\n 'refs/heads',\n 'refs/remotes',\n ],\n READ_TIMEOUT_MS,\n );\n if (refs.code !== 0) throw failure('for-each-ref', refs);\n const local: GitLocalBranch[] = [];\n const remotes: GitRemoteBranch[] = [];\n for (const line of refs.stdout.split('\\n')) {\n const [ref = '', worktreePath = '', symref = ''] = line.split('\\t');\n if (ref === '' || symref !== '') continue;\n if (ref.startsWith(LOCAL_PREFIX)) {\n const name = ref.slice(LOCAL_PREFIX.length);\n local.push(worktreePath === '' ? { name } : { name, checkedOutAt: worktreePath });\n } else if (ref.startsWith(REMOTE_PREFIX) && !ref.endsWith(HEAD_SUFFIX)) {\n const rest = ref.slice(REMOTE_PREFIX.length);\n const separator = rest.indexOf('/');\n if (separator > 0) remotes.push({ remote: rest.slice(0, separator), name: rest.slice(separator + 1) });\n }\n }\n const localNames = new Set(local.map((branch) => branch.name));\n const head = await git(repositoryRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD'], READ_TIMEOUT_MS);\n const current = head.code === 0 && head.stdout.trim() !== '' ? head.stdout.trim() : undefined;\n const origin = await git(\n repositoryRoot,\n ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'],\n READ_TIMEOUT_MS,\n );\n const defaultBase = origin.code === 0 && origin.stdout.trim() !== '' ? origin.stdout.trim() : current;\n return {\n ...(current === undefined ? {} : { current }),\n ...(defaultBase === undefined ? {} : { defaultBase }),\n local,\n remote: remotes.filter((branch) => !localNames.has(branch.name)),\n };\n },\n\n async removeWorktree({ repositoryRoot, path, force }) {\n const args = ['worktree', 'remove', ...(force ? ['--force'] : []), path];\n const result = await git(repositoryRoot, args, REMOVE_TIMEOUT_MS);\n if (result.code === 0) return;\n // A directory deleted behind git's back leaves an administrative entry\n // that makes a later `worktree add` at the same path refuse. Treating\n // \"already gone\" as success and pruning is what keeps that path reusable,\n // and it makes remove idempotent for a caller retrying after a crash.\n if (\n missingWorktree(result.stderr) &&\n !(await fs.access(path).then(\n () => true,\n () => false,\n ))\n ) {\n await prune(repositoryRoot);\n return;\n }\n throw failure('worktree remove', result);\n },\n\n async deleteBranch({ repositoryRoot, branch }) {\n // -d, never -D: git refuses a branch that still holds unmerged commits,\n // and that refusal is the whole safety property. A rollback that could\n // throw away work someone committed in the worktree is worse than a\n // branch left behind.\n const result = await git(repositoryRoot, ['branch', '-d', branch], READ_TIMEOUT_MS);\n return result.code === 0;\n },\n pruneWorktrees: prune,\n\n async listWorktreePaths(repositoryRoot) {\n const result = await git(repositoryRoot, ['worktree', 'list', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .filter((line) => line.startsWith('worktree '))\n .map((line) => line.slice('worktree '.length).trim())\n .filter((line) => line !== '');\n },\n\n async dirtyFiles(path) {\n const result = await git(path, ['status', '--porcelain'], READ_TIMEOUT_MS);\n if (result.code !== 0) return [];\n return result.stdout\n .split('\\n')\n .map((line) => line.slice(3).trim())\n .filter((line) => line !== '');\n },\n\n async repositoryRoot(cwd) {\n const result = await git(cwd, ['rev-parse', '--show-toplevel'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const root = result.stdout.trim();\n return root === '' ? undefined : root;\n },\n\n async currentBranch(cwd) {\n const result = await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'], READ_TIMEOUT_MS);\n if (result.code !== 0) return undefined;\n const branch = result.stdout.trim();\n return branch === '' ? undefined : branch;\n },\n\n async remoteBaseRef(cwd) {\n const upstream = await git(\n cwd,\n ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'],\n READ_TIMEOUT_MS,\n );\n if (upstream.code === 0) {\n const branch = upstream.stdout.trim();\n if (branch !== '') return branch;\n }\n const origin = await git(\n cwd,\n ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'],\n READ_TIMEOUT_MS,\n );\n if (origin.code === 0) {\n const branch = origin.stdout.trim();\n if (branch !== '') return branch;\n }\n const defaults = await git(cwd, ['for-each-ref', '--format=%(symref:short)', 'refs/remotes'], READ_TIMEOUT_MS);\n if (defaults.code !== 0) return undefined;\n return defaults.stdout\n .split('\\n')\n .map((line) => line.trim())\n .find((line) => line !== '');\n },\n\n async mergeBranch({ repositoryRoot, branch, message }) {\n // --no-ff so the worktree's work stays identifiable as a unit after the\n // fact. A fast-forward would erase the fact that it was ever separate,\n // which is the one thing worth keeping about a worktree.\n const args = ['merge', '--no-ff', ...(message === undefined ? [] : ['-m', message]), branch];\n const result = await git(repositoryRoot, args, READ_TIMEOUT_MS);\n if (result.code === 0) return;\n // A conflicted merge leaves the parent mid-merge, which is a state the\n // person has to resolve; aborting for them would throw away the conflict\n // markers they need to see.\n throw failure('merge', result);\n },\n };\n}\n","export const COMMAND_NAME = 'po-git';\nexport const COMMAND_DESCRIPTION = 'Show git worktrees owned by this session';\n/** The package API base path; the cockpit mounts it at /api/workspaces/<id>/plugins/git. */\nexport const GIT_API_BASE_PATH = 'git';\n/** Workspace-mounted routes behind the new-session dialog. */\nexport const GIT_BRANCHES_PATH = '/branches';\nexport const GIT_SESSIONS_PATH = '/sessions';\n/** Workspace-mounted: that workspace's remote auth for manual pull, push and rebase. */\nexport const GIT_AUTH_PATH = '/auth';\n/** Session-mounted: the session's change against its base, and one file's hunks. */\nexport const GIT_REVIEW_PATH = '/review';\nexport const GIT_REVIEW_FILE_PATH = '/review/file';\n/** Repository file, relative to the checkout root, whose `setup` commands run in every new worktree. */\nexport const WORKTREE_CONFIG_FILE = '.po/worktree.yaml';\n/** Trusted same-host setup handoff, consumed before starting the child session's runner. */\nexport const WORKTREE_SETUP_EVENT = 'git_worktree_setup';\nexport const WORKTREE_SETUP_RUNNER = 'worktree-setup';\n/** A missing or slow receiver is unconfirmed, never permission to retry a shell command. */\nexport const WORKTREE_SETUP_TIMEOUT_MS = 3000;\n/** Installs the rift CLI. Shown to the person to copy, and named in the error an agent reads. */\nexport const RIFT_INSTALL_COMMAND = 'npm install -g rift-snapshot';\n","/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/po-core` does not export `invalidRequest` or\n * an expected-error base, so this mirrors po-team's shape rather than\n * reaching across a layer boundary for it. The duplication is deliberate and\n * small; a shared helper would be the better answer only once a third package\n * needs one.\n */\n\nexport type PoGitErrorCode =\n | 'invalid_request'\n | 'not_a_repository'\n | 'worktree_exists'\n | 'worktree_not_found'\n | 'worktree_not_owned'\n | 'worktree_peer_unavailable'\n | 'worktree_dirty'\n | 'hub_unavailable'\n | 'spawn_cancelled'\n | 'registry_read_failed'\n | 'registry_write_failed'\n | 'registry_busy'\n | 'task_delivery_failed'\n | 'message_delivery_failed'\n | 'message_too_large'\n | 'git_failed'\n // The repository opted into Rift but the CLI is not on PATH. Dialogs key their install notice on it.\n | 'rift_missing'\n // Remote auth and sync. Each carries its own recovery line; git's stderr is\n // only ever matched, never shown, because it can carry a token in a URL.\n | 'auth_failed'\n | 'host_key_unknown'\n | 'host_key_changed'\n | 'remote_unreachable'\n | 'repository_not_found'\n | 'push_needs_force'\n | 'push_lease_rejected'\n | 'no_upstream'\n | 'no_remote'\n | 'no_base'\n | 'detached_head'\n | 'rebase_in_progress'\n | 'git_timeout';\n\nexport class PoGitExpectedError extends Error {\n constructor(\n readonly code: PoGitErrorCode,\n message: string,\n readonly retryable: boolean,\n readonly recovery: string,\n ) {\n // The recovery line rides in the message because a tool result is read as\n // text: an error the model cannot act on costs a turn to rediscover.\n super(`[${code}] ${message}\\nRecovery: ${recovery}`);\n this.name = 'PoGitExpectedError';\n }\n}\n\n/** Raised when a worktree action needs the canonical hub but it is not injected. */\nexport class HubUnavailableError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'HubUnavailableError';\n }\n}\n\nexport function invalidRequest(message: string, recovery: string): PoGitExpectedError {\n return new PoGitExpectedError('invalid_request', message, false, recovery);\n}\n","import { ConeFolder, ProfileName, SparsePolicy } from '@agimon-ai/po-sparo';\nimport { loadAll } from 'js-yaml';\n\nimport { WORKTREE_CONFIG_FILE } from '../../constants/git';\nimport { invalidRequest } from '../errors';\nimport type { WorktreeConfig, WorktreeConfigReaderInput, WorktreeSparseDefaults } from './type';\n\nfunction object(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(field: string): never {\n throw invalidRequest(`${field} is not valid.`, 'Fix the worktree configuration and try again.');\n}\n\n/** Sparse checkout names are separate from the launcher's selection.profile. */\nexport function validSparseProfile(value: unknown): value is string {\n return ProfileName.safeParse(value).success;\n}\n\n/** Only this plugin's supplied fields are consumed; unrelated workspace metadata is left alone. */\nexport function readWorktreeSparseDefaults(metadata: unknown): WorktreeSparseDefaults {\n if (metadata === undefined) return {};\n if (!object(metadata)) return invalid('Workspace metadata');\n const field = Object.hasOwn(metadata, 'git') ? 'git' : Object.hasOwn(metadata, 'sparo') ? 'sparo' : undefined;\n if (field === undefined) return {};\n const value = metadata[field];\n if (!object(value)) return invalid(`metadata.${field}`);\n const profileKey = field === 'sparo' ? 'profile' : 'sparseProfile';\n if (Object.hasOwn(value, profileKey) && !validSparseProfile(value[profileKey]))\n return invalid(`metadata.${field}.${profileKey}`);\n if (\n Object.hasOwn(value, 'extraFolders') &&\n (!Array.isArray(value.extraFolders) || !value.extraFolders.every((folder) => ConeFolder.safeParse(folder).success))\n )\n return invalid(`metadata.${field}.extraFolders`);\n return {\n ...(value[profileKey] === undefined ? {} : { sparseProfile: value[profileKey] as string }),\n ...(value.extraFolders === undefined ? {} : { extraFolders: [...(value.extraFolders as string[])] }),\n };\n}\n\n/** Parse setup and sparse policy together, without repository-specific defaults. */\nexport function parseWorktreeConfig(text: string): WorktreeConfig {\n let value: unknown;\n try {\n const documents = loadAll(text);\n if (documents.length > 1) return invalid(WORKTREE_CONFIG_FILE);\n value = documents[0];\n } catch {\n return invalid(WORKTREE_CONFIG_FILE);\n }\n // An empty YAML document is the same as a missing file, not an invalid supplied field.\n if (value === undefined || value === null) return {};\n if (!object(value)) return invalid(WORKTREE_CONFIG_FILE);\n const result: WorktreeConfig = {};\n if (Object.hasOwn(value, 'setup')) {\n const commands = Array.isArray(value.setup) ? value.setup : [value.setup];\n if (!commands.every((command): command is string => typeof command === 'string'))\n return invalid(`${WORKTREE_CONFIG_FILE} setup`);\n const setup = commands.filter((command) => command.trim() !== '').join(' && ');\n if (setup !== '') result.setup = setup;\n }\n if (Object.hasOwn(value, 'sparse')) {\n const sparse = SparsePolicy.safeParse(value.sparse);\n if (!sparse.success) return invalid(`${WORKTREE_CONFIG_FILE} sparse`);\n result.sparse = sparse.data;\n }\n return result;\n}\n\n/** One snapshot per repository in this composition, including missing or invalid files. */\nexport function createWorktreeConfigReader(\n input: WorktreeConfigReaderInput,\n): (root: string) => Promise<WorktreeConfig> {\n const snapshots = new Map<string, Promise<WorktreeConfig>>();\n return (root) => {\n let snapshot = snapshots.get(root);\n if (snapshot === undefined) {\n snapshot = (async () => {\n const defaults = readWorktreeSparseDefaults(await input.readMetadata?.());\n let text: string;\n try {\n text = await input.readTextFile(`${root.replace(/\\/$/u, '')}/${WORKTREE_CONFIG_FILE}`);\n } catch (error) {\n if (error instanceof Error && 'code' in error && (error.code === 'not_found' || error.code === 'ENOENT'))\n return Object.keys(defaults).length === 0 ? {} : { defaults };\n throw error;\n }\n const config = parseWorktreeConfig(text);\n return Object.keys(defaults).length === 0 ? config : { ...config, defaults };\n })();\n snapshots.set(root, snapshot);\n }\n return snapshot;\n };\n}\n","import { randomUUID } from 'node:crypto';\n\nimport type { PoDirectEventBus } from '@agimon-ai/po-core/hubChannel';\nimport type { PoRunnerLaunchService } from '@agimon-ai/po-runner/launch';\n\nimport { WORKTREE_SETUP_EVENT, WORKTREE_SETUP_RUNNER, WORKTREE_SETUP_TIMEOUT_MS } from '../../constants/git';\nimport type { WorktreeSetupStage } from '../../types/worktreeRegistry';\n\nexport const GIT_WORKTREE_LIFECYCLE_EVENT = 'git_worktree_lifecycle';\nexport const GIT_WORKTREE_MESSAGE_EVENT = 'git_worktree_message';\n/**\n * A session's checkout may have changed: a tool call ended, or the agent\n * settled. Carries nothing but its version; the '# diff' channel recomputes.\n */\nexport const GIT_SESSION_CHANGED_EVENT = 'git_session_changed';\nexport const WORKTREE_MESSAGE_VERSION = 1 as const;\nexport const MAX_WORKTREE_MESSAGE_BYTES = 64 * 1024;\nexport const MAX_WORKTREE_INBOX_MESSAGES = 100;\n\nexport interface WorktreeLifecycleEvent {\n readonly version: typeof WORKTREE_MESSAGE_VERSION;\n readonly repositoryRoot: string;\n}\n\nexport type WorktreeMessageParty = 'parent' | 'child';\n\nexport interface WorktreeMessage {\n readonly version: typeof WORKTREE_MESSAGE_VERSION;\n readonly worktreeId: string;\n readonly fromSessionId: string;\n readonly from: WorktreeMessageParty;\n readonly text: string;\n readonly sentAt: string;\n}\n\nexport interface WorktreeMessageInbox {\n send(targetSessionId: string, message: WorktreeMessage): void;\n receive(worktreeId: string): WorktreeMessage[];\n close(): void;\n}\n\nfunction isMessageParty(value: unknown): value is WorktreeMessageParty {\n return value === 'parent' || value === 'child';\n}\n\nfunction parseMessage(value: unknown): WorktreeMessage | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Partial<WorktreeMessage>;\n if (record.version !== WORKTREE_MESSAGE_VERSION) return undefined;\n if (typeof record.worktreeId !== 'string' || record.worktreeId === '') return undefined;\n if (typeof record.fromSessionId !== 'string' || record.fromSessionId === '') return undefined;\n if (!isMessageParty(record.from)) return undefined;\n if (typeof record.text !== 'string' || record.text === '') return undefined;\n if (Buffer.byteLength(record.text, 'utf8') > MAX_WORKTREE_MESSAGE_BYTES) return undefined;\n if (typeof record.sentAt !== 'string' || record.sentAt === '') return undefined;\n return record as WorktreeMessage;\n}\n\nexport function createWorktreeMessageInbox(directEvents: PoDirectEventBus, sessionId: string): WorktreeMessageInbox {\n if (sessionId === '') throw new Error('The Git message service requires a session identity.');\n const messages = new Map<string, WorktreeMessage[]>();\n const unsubscribe = directEvents.subscribe(GIT_WORKTREE_MESSAGE_EVENT, sessionId, (payload) => {\n const message = parseMessage(payload);\n if (message === undefined) return;\n const inbox = messages.get(message.worktreeId) ?? [];\n if (inbox.length >= MAX_WORKTREE_INBOX_MESSAGES) inbox.shift();\n inbox.push(message);\n messages.set(message.worktreeId, inbox);\n });\n let closed = false;\n return {\n send(targetSessionId, message) {\n if (closed) throw new Error('The Git message service is closed.');\n directEvents.publish(GIT_WORKTREE_MESSAGE_EVENT, targetSessionId, message);\n },\n receive(worktreeId) {\n if (closed) return [];\n const inbox = messages.get(worktreeId);\n if (inbox === undefined) return [];\n messages.delete(worktreeId);\n return inbox;\n },\n close() {\n if (closed) return;\n closed = true;\n unsubscribe();\n messages.clear();\n },\n };\n}\n\nexport function isWorktreeLifecycleEvent(value: unknown): value is WorktreeLifecycleEvent {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Partial<WorktreeLifecycleEvent>;\n return (\n record.version === WORKTREE_MESSAGE_VERSION &&\n typeof record.repositoryRoot === 'string' &&\n record.repositoryRoot !== ''\n );\n}\n\n/**\n * One bounded issue/receipt on the trusted host bus. Timeout and cancellation\n * overwrite the retained request so a late receiver cannot run abandoned setup.\n * There are deliberately no retries: a lost receipt can mean the runner exists.\n */\nexport function startWorktreeSetup(\n directEvents: PoDirectEventBus,\n sessionId: string,\n command: string,\n signal?: AbortSignal,\n): Promise<WorktreeSetupStage> {\n if (signal?.aborted) return Promise.resolve('unconfirmed');\n const requestId = randomUUID();\n return new Promise((resolve) => {\n let settled = false;\n const finish = (stage: WorktreeSetupStage) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n signal?.removeEventListener('abort', abort);\n if (stage === 'unconfirmed')\n directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, { version: 1, kind: 'cancel', requestId });\n resolve(stage);\n };\n const abort = () => finish('unconfirmed');\n const unsubscribe = directEvents.subscribe(WORKTREE_SETUP_EVENT, sessionId, (value) => {\n if (!value || typeof value !== 'object') return;\n const receipt = value as { version?: unknown; kind?: unknown; requestId?: unknown; stage?: unknown };\n if (receipt.version !== 1 || receipt.kind !== 'receipt' || receipt.requestId !== requestId) return;\n if (receipt.stage === 'started' || receipt.stage === 'failed' || receipt.stage === 'unconfirmed')\n finish(receipt.stage);\n });\n const timer = setTimeout(() => finish('unconfirmed'), WORKTREE_SETUP_TIMEOUT_MS);\n signal?.addEventListener('abort', abort, { once: true });\n if (signal?.aborted) abort();\n if (!settled)\n directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, { version: 1, kind: 'request', requestId, command });\n });\n}\n\n/**\n * Runs only under the child's runner service injection. This receiver never\n * reads the registry: the parent can hold its transaction through the receipt.\n * Consuming retained requests synchronously prevents a remount replaying setup.\n */\nexport function receiveWorktreeSetup(\n directEvents: PoDirectEventBus,\n sessionId: string,\n cwd: string,\n runner: Pick<PoRunnerLaunchService, 'start'>,\n signal?: AbortSignal,\n): () => void {\n const pending = new Map<string, AbortController>();\n const seen = new Set<string>();\n let closed = false;\n let unsubscribe = () => {};\n const receipt = (requestId: string, stage: WorktreeSetupStage) =>\n directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, { version: 1, kind: 'receipt', requestId, stage });\n const close = () => {\n if (closed) return;\n closed = true;\n unsubscribe();\n signal?.removeEventListener('abort', close);\n for (const [requestId, controller] of pending) {\n controller.abort();\n receipt(requestId, 'unconfirmed');\n }\n pending.clear();\n };\n if (signal?.aborted) return close;\n unsubscribe = directEvents.subscribe(\n WORKTREE_SETUP_EVENT,\n sessionId,\n (value) => {\n if (closed || !value || typeof value !== 'object') return;\n const event = value as { version?: unknown; kind?: unknown; requestId?: unknown; command?: unknown };\n if (event.version !== 1 || typeof event.requestId !== 'string' || !event.requestId) return;\n const requestId = event.requestId;\n if (event.kind === 'cancel') {\n pending.get(requestId)?.abort();\n return;\n }\n if (event.kind !== 'request' || typeof event.command !== 'string' || !event.command.trim() || seen.has(requestId))\n return;\n seen.add(requestId);\n const command = event.command;\n const controller = new AbortController();\n pending.set(requestId, controller);\n // This is before the first await, including a synchronous replayLatest.\n directEvents.publish(WORKTREE_SETUP_EVENT, sessionId, { version: 1, kind: 'consumed', requestId });\n void Promise.resolve()\n .then(async () => {\n controller.signal.throwIfAborted();\n await runner.start(\n { name: WORKTREE_SETUP_RUNNER, command: [command], cwd, wakeOnExit: true },\n controller.signal,\n );\n if (!controller.signal.aborted && !closed) receipt(requestId, 'started');\n })\n .catch(() => {\n if (!closed) receipt(requestId, controller.signal.aborted ? 'unconfirmed' : 'failed');\n })\n .finally(() => pending.delete(requestId));\n },\n { replayLatest: true },\n );\n signal?.addEventListener('abort', close, { once: true });\n if (signal?.aborted) close();\n return close;\n}\n\nexport function isSessionChangedEvent(value: unknown): boolean {\n return (\n typeof value === 'object' && value !== null && (value as { version?: unknown }).version === WORKTREE_MESSAGE_VERSION\n );\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nconst OWNER_ONLY_FILE = 0o600;\n\n/**\n * Writes JSON so a reader never sees a half-written file.\n *\n * The registry is read by the same process that writes it, and by a later\n * process after a crash. A plain write can be interrupted between the truncate\n * and the last byte, which leaves a file that parses as nothing and loses every\n * record in it. Writing beside the target and renaming makes the swap atomic on\n * the same filesystem, so a reader sees either the old file or the new one.\n */\nexport async function writeJsonAtomic(file: string, value: unknown): Promise<void> {\n const directory = path.dirname(file);\n await fs.mkdir(directory, { recursive: true });\n const temporary = path.join(directory, `.${path.basename(file)}.${randomUUID()}.tmp`);\n await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: OWNER_ONLY_FILE });\n await fs.rename(temporary, file);\n}\n\n/**\n * Reads JSON, treating every failure as absent.\n *\n * A missing file and an unparseable one mean the same thing to every caller\n * here: there is nothing to act on. Distinguishing them would only offer a\n * choice no caller wants to make.\n */\nexport async function readJson<T>(file: string): Promise<T | undefined> {\n try {\n return JSON.parse(await fs.readFile(file, 'utf8')) as T;\n } catch {\n return undefined;\n }\n}\n","import { createHash } from 'node:crypto';\nimport type { Stats } from 'node:fs';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nconst ID_LENGTH = 12;\nconst MAX_LABEL_LENGTH = 32;\n\n/**\n * The git directory shared by a repository and all of its worktrees.\n *\n * A normal checkout has a `.git` directory. A linked worktree has a `.git`\n * FILE pointing at `<common>/worktrees/<name>`, whose `commondir` points back\n * at the shared directory. Following that chain is what makes every worktree of\n * one repository agree on the repository's identity, which matters here because\n * the registry is per repository and must be found from inside a worktree too.\n * A session may run in a subdirectory, so the nearest enclosing checkout is used.\n */\nexport async function gitCommonDirectory(directory: string): Promise<string | undefined> {\n let root = path.resolve(directory);\n let marker = path.join(root, '.git');\n let stat: Stats | undefined;\n for (;;) {\n try {\n stat = await fs.stat(marker);\n break;\n } catch {\n const parent = path.dirname(root);\n if (parent === root) return undefined;\n root = parent;\n marker = path.join(root, '.git');\n }\n }\n if (stat.isDirectory()) return marker;\n let pointer: string;\n try {\n pointer = (await fs.readFile(marker, 'utf8')).trim();\n } catch {\n return undefined;\n }\n if (!pointer.startsWith('gitdir:')) return undefined;\n const gitDir = path.resolve(root, pointer.slice('gitdir:'.length).trim());\n try {\n const common = (await fs.readFile(path.join(gitDir, 'commondir'), 'utf8')).trim();\n return path.resolve(gitDir, common);\n } catch {\n // A submodule's .git file has no commondir; its gitdir is already common.\n return gitDir;\n }\n}\n\n/** A directory name that is recognisable to a person and safe on a filesystem. */\nexport function repositoryLabel(root: string): string {\n const label = path\n .basename(root)\n .toLowerCase()\n .replace(/[^a-z0-9]+/gu, '-')\n .replace(/^-+|-+$/gu, '')\n .slice(0, MAX_LABEL_LENGTH);\n return label === '' ? 'repository' : label;\n}\n\n/**\n * A stable id for the repository a directory belongs to.\n *\n * Keyed on the common git directory rather than the given path, so the main\n * checkout and every worktree of it resolve to one id and therefore to one\n * registry. Falling back to the path keeps a non-repository directory usable\n * instead of failing, though nothing here should reach that case.\n */\nexport async function repositoryId(root: string): Promise<string> {\n const common = await gitCommonDirectory(root);\n const token = common === undefined ? `root:${path.resolve(root)}` : `git:${common}`;\n return createHash('sha256').update(token).digest('hex').slice(0, ID_LENGTH);\n}\n\n/** A short, collision-resistant suffix for one worktree directory. */\nexport function shortId(seed: string): string {\n return createHash('sha256').update(seed).digest('hex').slice(0, 8);\n}\n","import { defineApiContract, jsonApiResponses } from '@agimon-ai/po-core/apiContracts';\nimport { Type } from 'typebox';\n\nconst S = Type.String();\nconst B = Type.Boolean();\nconst O = Type.Optional;\nconst SparseProfileSchema = Type.String({ pattern: '^[A-Za-z0-9][A-Za-z0-9_-]*$' });\nconst SelectionSchema = Type.Object({ profile: Type.Union([S, Type.Null()]) });\nconst literals = <T extends string>(values: T[]) => Type.Union(values.map((value) => Type.Literal(value)));\nexport const WorktreeRecordSchema = Type.Object({\n version: Type.Literal(2),\n id: S,\n branch: S,\n baseRef: S,\n path: S,\n repositoryRoot: S,\n sessionId: S,\n parentSessionId: Type.Optional(S),\n status: literals(['spawning', 'running', 'closing', 'orphaned']),\n setupStage: O(literals(['none', 'started', 'failed', 'unconfirmed'])),\n backend: O(Type.Literal('rift')),\n sparseProfile: O(SparseProfileSchema),\n extraFolders: O(Type.Array(S)),\n sparseFingerprint: O(S),\n baseCommit: O(S),\n workflow: O(\n Type.Object({\n attemptId: S,\n fingerprint: S,\n state: literals(['spawned', 'admitted', 'retained']),\n admissionId: O(S),\n runId: O(S),\n reason: O(S),\n }),\n ),\n createdAt: S,\n});\nconst ErrorTargetSchema = Type.Union([\n Type.Object({ action: Type.Literal('create'), riftMissing: O(Type.Literal(true)) }),\n Type.Object({ action: Type.Literal('close'), id: S }),\n]);\nexport const WorktreesPayloadSchema = Type.Object({\n worktrees: Type.Array(\n Type.Object({ id: S, branch: S, path: S, sessionId: Type.Union([S, Type.Null()]), orphaned: B, unowned: B }),\n ),\n pending: O(S),\n error: O(S),\n errorTarget: O(ErrorTargetSchema),\n});\nexport const WorktreesCommandSchema = Type.Union([\n Type.Object({\n action: Type.Literal('create'),\n branch: S,\n baseRef: O(S),\n reservationId: O(Type.String({ minLength: 1, pattern: '^[A-Za-z0-9_-]+$' })),\n }),\n Type.Object({ action: Type.Literal('close'), id: S, force: O(B) }),\n]);\nconst N = Type.Integer({ minimum: 0 });\nconst ChangesSchema = Type.Object({\n branch: O(S),\n base: O(S),\n added: N,\n removed: N,\n files: N,\n truncated: O(B),\n upstream: O(Type.Object({ ref: S, ahead: N, behind: N })),\n rebase: O(Type.Object({ conflicts: Type.Array(S) })),\n});\nconst SyncErrorTargetSchema = Type.Union([\n Type.Object({ action: literals(['pull', 'rebase', 'abort-rebase']) }),\n Type.Object({ action: Type.Literal('push'), forceRequired: O(Type.Literal(true)) }),\n]);\nexport const GitChangesPayloadSchema = Type.Object({\n changes: O(ChangesSchema),\n pending: O(S),\n error: O(S),\n errorTarget: O(SyncErrorTargetSchema),\n});\nexport const GitChangesCommandSchema = Type.Union([\n Type.Object({ action: literals(['pull', 'rebase', 'abort-rebase']) }),\n Type.Object({ action: Type.Literal('push'), force: O(Type.Literal(true)) }),\n]);\nconst AuthViewSchema = Type.Object({\n method: literals(['none', 'ssh', 'https']),\n ssh: O(Type.Object({ keyPath: O(S) })),\n https: O(Type.Object({ host: S, username: S, hasToken: B })),\n});\nconst AuthSaveSchema = Type.Union([\n Type.Object({ method: Type.Literal('none') }),\n Type.Object({ method: Type.Literal('ssh'), keyPath: O(S) }),\n Type.Object({ method: Type.Literal('https'), host: S, username: S, token: O(Type.String({ writeOnly: true })) }),\n]);\nconst DiffRowSchema = Type.Object({ marker: literals(['+', '-', ' ']), line: N, content: S });\nconst ReviewSummarySchema = Type.Object({\n repository: B,\n branch: O(S),\n base: O(S),\n mergeBase: O(S),\n truncated: O(B),\n files: Type.Array(\n Type.Object({\n path: S,\n status: literals(['added', 'modified', 'deleted', 'untracked', 'conflicted']),\n added: N,\n removed: N,\n binary: O(B),\n }),\n ),\n});\nconst ReviewFileSchema = Type.Object({\n path: S,\n hunks: Type.Array(Type.Object({ start: N, rows: Type.Array(DiffRowSchema) })),\n binary: O(Type.Literal(true)),\n tooLarge: O(Type.Literal(true)),\n});\nconst query = [\n { name: 'repositoryId', in: 'query' as const, required: true, schema: S },\n { name: 'sessionId', in: 'query' as const, required: true, schema: S },\n];\nexport const apiContracts = defineApiContract({\n version: 1,\n dynamic: [],\n http: (['host', 'workspace'] as const).flatMap((scope) => [\n {\n id: 'git.list',\n scope,\n basePath: 'git',\n path: '/worktrees',\n method: 'GET',\n authentication: 'owner',\n description: 'List admitted repository worktrees.',\n parameters: query.map((item) => ({ ...item, required: item.name === 'repositoryId' })),\n responses: jsonApiResponses(Type.Object({ worktrees: Type.Array(WorktreeRecordSchema) })),\n },\n {\n id: 'git.create',\n scope,\n basePath: 'git',\n path: '/worktrees',\n method: 'POST',\n authentication: 'owner',\n description: 'Create a worktree and session.',\n parameters: query,\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Object({\n branch: Type.String({ minLength: 1 }),\n baseRef: O(S),\n name: O(S),\n sparseProfile: O(SparseProfileSchema),\n selection: O(SelectionSchema),\n }),\n },\n responses: jsonApiResponses(Type.Object({ worktree: WorktreeRecordSchema }), 201),\n },\n {\n id: 'git.close',\n scope,\n basePath: 'git',\n path: '/worktrees/{id}',\n method: 'DELETE',\n authentication: 'owner',\n description: 'Close a worktree.',\n parameters: [...query, { name: 'force', in: 'query', required: false, schema: B }],\n responses: jsonApiResponses(Type.Object({ worktree: WorktreeRecordSchema })),\n },\n // The new-session dialog's routes and a workspace's remote auth exist only on a workspace mount.\n ...(scope === 'workspace'\n ? [\n {\n id: 'git.auth.read',\n scope,\n basePath: 'git',\n path: '/auth',\n method: 'GET' as const,\n authentication: 'owner' as const,\n description: \"Read a workspace's remote auth for manual sync. The token is never returned.\",\n parameters: [{ name: 'repositoryId', in: 'query' as const, required: true, schema: S }],\n responses: jsonApiResponses(AuthViewSchema),\n },\n {\n id: 'git.auth.save',\n scope,\n basePath: 'git',\n path: '/auth',\n method: 'PUT' as const,\n authentication: 'owner' as const,\n description: \"Replace a workspace's remote auth. Passkey step-up gated for remote devices.\",\n parameters: [{ name: 'repositoryId', in: 'query' as const, required: true, schema: S }],\n body: { required: true, contentType: 'application/json', schema: AuthSaveSchema },\n responses: jsonApiResponses(AuthViewSchema),\n },\n {\n id: 'git.branches',\n scope,\n basePath: 'git',\n path: '/branches',\n method: 'GET' as const,\n authentication: 'owner' as const,\n description: 'List the workspace branches for the new-session dialog.',\n responses: jsonApiResponses(\n Type.Object({\n repository: B,\n current: O(S),\n defaultBase: O(S),\n sparseProfiles: O(Type.Array(S)),\n defaultSparseProfile: O(S),\n local: Type.Array(Type.Object({ name: S, checkedOutAt: O(S) })),\n remote: Type.Array(Type.Object({ remote: S, name: S })),\n }),\n ),\n },\n {\n id: 'git.branches.delete',\n scope,\n basePath: 'git',\n path: '/branches',\n method: 'DELETE' as const,\n authentication: 'owner' as const,\n description: 'Safely delete a local branch that is not checked out. Never force-deletes unmerged work.',\n body: { required: true, contentType: 'application/json', schema: Type.Object({ branch: S }) },\n responses: jsonApiResponses(Type.Object({ deleted: B })),\n },\n {\n id: 'git.branches.open',\n scope,\n basePath: 'git',\n path: '/branches/open',\n method: 'POST' as const,\n authentication: 'owner' as const,\n description: 'Open the branch checkout in Finder. Local callers only, no client-supplied path.',\n body: { required: true, contentType: 'application/json', schema: Type.Object({ branch: S }) },\n responses: jsonApiResponses(Type.Object({ opened: B })),\n },\n {\n id: 'git.sessions.create',\n scope,\n basePath: 'git',\n path: '/sessions',\n method: 'POST' as const,\n authentication: 'owner' as const,\n description: 'Start a top-level worktree session on an existing or new branch.',\n body: {\n required: true,\n contentType: 'application/json',\n schema: Type.Union([\n Type.Object({\n mode: Type.Literal('existing-branch'),\n branch: S,\n remote: O(S),\n name: O(S),\n sparseProfile: O(SparseProfileSchema),\n selection: O(SelectionSchema),\n }),\n Type.Object({\n mode: Type.Literal('new-branch'),\n branch: S,\n baseRef: O(S),\n name: O(S),\n sparseProfile: O(SparseProfileSchema),\n selection: O(SelectionSchema),\n }),\n ]),\n },\n responses: jsonApiResponses(Type.Object({ sessionId: S, worktreeId: S }), 201),\n },\n ]\n : []),\n // The review routes exist only on a session mount; listed once, beside the host entries.\n ...(scope === 'host'\n ? [\n {\n id: 'git.review.summary',\n scope: 'session' as const,\n basePath: 'git',\n path: '/review',\n method: 'GET' as const,\n authentication: 'owner' as const,\n description: \"List the files the session's checkout changed against its base.\",\n responses: jsonApiResponses(ReviewSummarySchema),\n },\n {\n id: 'git.review.file',\n scope: 'session' as const,\n basePath: 'git',\n path: '/review/file',\n method: 'GET' as const,\n authentication: 'owner' as const,\n description: \"One changed file's hunks; the path must be in the session's change set.\",\n parameters: [{ name: 'path', in: 'query' as const, required: true, schema: Type.String({ minLength: 1 }) }],\n responses: jsonApiResponses(ReviewFileSchema),\n },\n ]\n : []),\n ]),\n sockets: (['host', 'workspace'] as const).flatMap((scope) => [\n {\n id: 'git.changes.channel',\n scope,\n service: 'po.hub',\n member: 'git_changes',\n kind: 'channel',\n direction: 'server-to-client',\n description: \"The session's change against its base, and manual sync state.\",\n input: GitChangesPayloadSchema,\n },\n {\n id: 'git.changes.command',\n scope,\n service: 'po.hub',\n member: 'git_changes',\n kind: 'channel',\n direction: 'client-to-server',\n description: 'Manual pull, push, rebase or abort-rebase for the session.',\n input: GitChangesCommandSchema,\n },\n {\n id: 'git.channel',\n scope,\n service: 'po.hub',\n member: 'git_worktrees',\n kind: 'channel',\n direction: 'server-to-client',\n description: 'Worktree channel payload.',\n input: WorktreesPayloadSchema,\n },\n {\n id: 'git.command',\n scope,\n service: 'po.hub',\n member: 'git_worktrees',\n kind: 'channel',\n direction: 'client-to-server',\n description: 'Worktree channel command payload.',\n input: WorktreesCommandSchema,\n },\n ]),\n});\nexport default apiContracts;\n","import { defineServiceContract } from '@agimon-ai/po-core/serverPlugin';\nimport { PoWorkflowDefinitionRefSchema, PoWorkflowRunRefSchema } from '@agimon-ai/po-core/workflow';\nimport { Type } from 'typebox';\n\nimport type { WorktreeWorkflows } from '../services/worktreeWorkflows/type';\n\nexport const PO_GIT_WORKFLOWS_SERVICE = 'po/git-workflows';\nexport const GIT_WORKFLOWS_CONTRACT = defineServiceContract<WorktreeWorkflows>(PO_GIT_WORKFLOWS_SERVICE, {\n scope: 'session',\n});\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/git-workflows': WorktreeWorkflows;\n }\n}\n\nconst Text = Type.String({ minLength: 1 });\nconst O = Type.Optional;\nconst Binding = O(Type.Unknown());\nexport const WorktreeWorkflowAttemptSchema = Type.Object({\n attemptId: Text,\n fingerprint: Text,\n launcherSessionId: Text,\n branch: Text,\n definition: O(PoWorkflowDefinitionRefSchema),\n createdAt: Text,\n state: Type.Union(\n ['reserved', 'spawned', 'admitting', 'admitted', 'retained', 'closed', 'rejected'].map((state) =>\n Type.Literal(state),\n ),\n ),\n worktreeId: O(Text),\n sessionId: O(Text),\n admission: O(\n Type.Union([\n Type.Object({ attemptId: Text, admissionId: Text, state: Type.Literal('pending'), binding: Binding }),\n Type.Object({ attemptId: Text, admissionId: Text, state: Type.Literal('rejected'), errors: Type.Array(Text) }),\n Type.Object({\n attemptId: Text,\n admissionId: Text,\n state: Type.Literal('registered'),\n run: PoWorkflowRunRefSchema,\n binding: Binding,\n }),\n ]),\n ),\n});\n\n/** Model-facing repository launch only. Trusted overrides and allocation never cross this boundary. */\nexport const StartWorktreeWorkflowSchema = Type.Object(\n {\n key: Text,\n attemptId: O(Text),\n branch: O(Text),\n sparseProfile: O(Text),\n inputs: O(Type.Record(Type.String(), Type.String())),\n },\n { additionalProperties: false },\n);\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { setTimeout } from 'node:timers/promises';\n\nimport { ConeFolder, ProfileName } from '@agimon-ai/po-sparo';\nimport { Check } from 'typebox/value';\n\nimport { WorktreeRecordSchema } from '../../schemas/apiContracts';\nimport { WorktreeWorkflowAttemptSchema } from '../../schemas/worktreeWorkflows';\nimport {\n WORKTREE_RECORD_VERSION,\n type WorktreeRecord,\n type WorktreeWorkflowAttempt,\n type WorktreeRegistryFile,\n type WorktreeRegistryStore,\n} from '../../types/worktreeRegistry';\nimport { writeJsonAtomic } from '../atomicJson';\nimport { PoGitExpectedError } from '../errors';\n\nconst LOCK_WAIT_MS = 5000;\nconst LOCK_RETRY_MS = 25;\n\nfunction malformedRegistry(): never {\n throw new PoGitExpectedError(\n 'registry_read_failed',\n 'The worktree registry is unreadable or malformed.',\n false,\n 'Inspect and repair the registry before retrying. It has not been replaced.',\n );\n}\n\n/** Explicit v1/v2 read compatibility. Nothing is rewritten until a caller replaces the file. */\nexport function parseWorktreeRegistry(value: unknown): WorktreeRecord[] {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return malformedRegistry();\n const file = value as { version?: unknown; entries?: unknown; workflowAttempts?: unknown; sparoImport?: unknown };\n if ((file.version !== 1 && file.version !== 2) || !Array.isArray(file.entries)) return malformedRegistry();\n if (Object.hasOwn(file, 'workflowAttempts')) {\n if (file.version !== 2 || !Array.isArray(file.workflowAttempts)) return malformedRegistry();\n const keys = new Set<string>();\n for (const attempt of file.workflowAttempts) {\n if (!Check(WorktreeWorkflowAttemptSchema, attempt)) return malformedRegistry();\n const key = JSON.stringify([attempt.launcherSessionId, attempt.attemptId]);\n if (keys.has(key)) return malformedRegistry();\n keys.add(key);\n if (attempt.admission && attempt.admission.attemptId !== attempt.attemptId) return malformedRegistry();\n if (attempt.admission?.state === 'registered' && attempt.admission.run.ownerSessionId !== attempt.sessionId)\n return malformedRegistry();\n }\n }\n if (Object.hasOwn(file, 'sparoImport')) {\n const marker = file.sparoImport as WorktreeRegistryFile['sparoImport'];\n if (\n file.version !== 2 ||\n !marker ||\n typeof marker !== 'object' ||\n Array.isArray(marker) ||\n typeof marker.source !== 'string' ||\n !path.isAbsolute(marker.source) ||\n typeof marker.sourceDigest !== 'string' ||\n !/^[a-f0-9]{64}$/u.test(marker.sourceDigest) ||\n typeof marker.completedAt !== 'string' ||\n !Number.isFinite(Date.parse(marker.completedAt)) ||\n !Array.isArray(marker.recordIds) ||\n !marker.recordIds.every((id) => typeof id === 'string' && id !== '')\n )\n return malformedRegistry();\n }\n return file.entries.map((value: unknown) => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return malformedRegistry();\n const record = value as Record<string, unknown>;\n if (record.version !== file.version) return malformedRegistry();\n if (\n file.version === 1 &&\n ['sparseProfile', 'extraFolders', 'sparseFingerprint'].some((key) => Object.hasOwn(record, key))\n )\n return malformedRegistry();\n const normalized = { ...record, version: WORKTREE_RECORD_VERSION };\n if (!Check(WorktreeRecordSchema, normalized) || normalized.id === '') return malformedRegistry();\n if (Object.hasOwn(record, 'sparseProfile') && !ProfileName.safeParse(record.sparseProfile).success)\n return malformedRegistry();\n if (\n Object.hasOwn(record, 'extraFolders') &&\n (!Array.isArray(record.extraFolders) ||\n !record.extraFolders.every((folder) => ConeFolder.safeParse(folder).success))\n )\n return malformedRegistry();\n return normalized;\n });\n}\n\n/** Read metadata and records together, with the same fail-closed validation. */\nexport async function readWorktreeRegistryFile(file: string): Promise<WorktreeRegistryFile> {\n let text: string;\n try {\n text = await fs.readFile(file, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { version: WORKTREE_RECORD_VERSION, entries: [] };\n return malformedRegistry();\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return malformedRegistry();\n }\n const entries = parseWorktreeRegistry(parsed);\n const { sparoImport } = parsed as WorktreeRegistryFile;\n const workflowAttempts = [...((parsed as WorktreeRegistryFile).workflowAttempts ?? [])];\n // Imported fork records predate top-level intents. Preserve their attempt identity before any later close.\n for (const record of entries) {\n if (\n !record.workflow ||\n !record.parentSessionId ||\n workflowAttempts.some(\n (attempt) =>\n attempt.launcherSessionId === record.parentSessionId && attempt.attemptId === record.workflow!.attemptId,\n )\n )\n continue;\n workflowAttempts.push({\n attemptId: record.workflow.attemptId,\n fingerprint: record.workflow.fingerprint,\n launcherSessionId: record.parentSessionId,\n branch: record.branch,\n createdAt: record.createdAt,\n state: record.workflow.state,\n worktreeId: record.id,\n sessionId: record.sessionId,\n });\n }\n return {\n version: WORKTREE_RECORD_VERSION,\n entries,\n ...(sparoImport ? { sparoImport } : {}),\n ...(workflowAttempts.length ? { workflowAttempts } : {}),\n };\n}\n\n/**\n * Repository mutations hold an exclusive directory lock from the read through\n * the final commit. This works across independently loaded packages and hosts.\n * A crashed owner leaves a visible lock, never a lease another writer may steal.\n */\nexport function createWorktreeRegistry(\n file: string,\n options: { createDirectory?: boolean } = {},\n): WorktreeRegistryStore {\n return {\n async list() {\n return [...(await readWorktreeRegistryFile(file)).entries];\n },\n async workflowAttempts() {\n return [...((await readWorktreeRegistryFile(file)).workflowAttempts ?? [])];\n },\n async replaceWorkflowAttempts(workflowAttempts: readonly WorktreeWorkflowAttempt[]) {\n const previous = await readWorktreeRegistryFile(file);\n const value = { ...previous, workflowAttempts };\n parseWorktreeRegistry(value);\n await writeJsonAtomic(file, value);\n },\n async replace(entries) {\n // Completion is durable registry metadata, not a record. Closing imported\n // entries must not make a later cutover resurrect them from the old source.\n const previous = await readWorktreeRegistryFile(file);\n const value: WorktreeRegistryFile = {\n version: WORKTREE_RECORD_VERSION,\n entries,\n ...(previous.sparoImport ? { sparoImport: previous.sparoImport } : {}),\n ...(previous.workflowAttempts ? { workflowAttempts: previous.workflowAttempts } : {}),\n };\n parseWorktreeRegistry(value);\n await writeJsonAtomic(file, value);\n },\n async transaction(operation, signal) {\n const lock = `${file}.lock`;\n if (options.createDirectory !== false) await fs.mkdir(path.dirname(file), { recursive: true });\n const deadline = Date.now() + LOCK_WAIT_MS;\n for (;;) {\n signal?.throwIfAborted();\n try {\n await fs.mkdir(lock, { mode: 0o700 });\n break;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n if (Date.now() >= deadline)\n throw new PoGitExpectedError(\n 'registry_busy',\n 'Another worktree operation holds the repository registry.',\n true,\n 'Retry after it finishes. After a host crash, inspect and remove the abandoned worktrees.json.lock directory.',\n );\n await setTimeout(LOCK_RETRY_MS, undefined, { signal });\n }\n }\n try {\n await fs.writeFile(\n path.join(lock, 'owner.json'),\n JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }),\n { mode: 0o600 },\n );\n signal?.throwIfAborted();\n return await operation();\n } finally {\n await fs.rm(lock, { recursive: true });\n }\n },\n };\n}\n","import { createHash } from 'node:crypto';\nimport path from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\n\nimport { BACKGROUND_CONTEXT, getOrThrow, withAbortSignal } from '@agimon-ai/po-core/platform';\n\nimport type { WorktreeRecord, WorktreeRegistryFile } from '../../types/worktreeRegistry';\nimport { writeJsonAtomic } from '../atomicJson';\nimport { gitCommonDirectory } from '../repositoryIdentity';\nimport { createWorktreeRegistry, parseWorktreeRegistry, readWorktreeRegistryFile } from '../worktreeRegistry';\nimport type { SparoImportOptions, SparoImportResult } from './type';\n\nfunction refuse(reason: string): never {\n throw new Error(`Sparo registry import refused: ${reason}. No import was committed.`);\n}\n\nfunction sourceEntries(text: string): WorktreeRecord[] {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return refuse('malformed source JSON');\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) return refuse('malformed source registry');\n const file = value as { version?: unknown; entries?: unknown };\n if (file.version !== 2 || !Array.isArray(file.entries)) return refuse('expected Sparo v2 records');\n const entries = file.entries.map((value: unknown) => {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return refuse('malformed source record');\n const record = value as Record<string, unknown>;\n if (record.version !== 2 || record.provider !== 'po-sparo' || record.backend !== undefined)\n return refuse('unsupported source provider or backend');\n if (['sparseProfile', 'sparseFingerprint'].some((key) => Object.hasOwn(record, key)))\n return refuse('source contains destination-only sparse fields');\n for (const key of ['baseCommit', 'fingerprint', 'reservationId']) {\n if (Object.hasOwn(record, key) && (typeof record[key] !== 'string' || record[key] === ''))\n return refuse(`invalid ${key}`);\n }\n if (Object.hasOwn(record, 'setupStage') && !['none', 'started', 'failed'].includes(String(record.setupStage)))\n return refuse('invalid setup stage');\n if (Object.hasOwn(record, 'workflow')) {\n const workflow = record.workflow;\n if (!workflow || typeof workflow !== 'object' || Array.isArray(workflow)) return refuse('invalid workflow');\n const evidence = workflow as Record<string, unknown>;\n for (const key of ['attemptId', 'fingerprint']) {\n if (typeof evidence[key] !== 'string' || evidence[key] === '') return refuse(`invalid workflow ${key}`);\n }\n if (!['spawned', 'admitted', 'retained'].includes(String(evidence.state)))\n return refuse('invalid workflow state');\n for (const key of ['admissionId', 'runId', 'reason']) {\n if (Object.hasOwn(evidence, key) && typeof evidence[key] !== 'string') return refuse(`invalid workflow ${key}`);\n }\n }\n const { profile, fingerprint, ...preserved } = record;\n return {\n ...preserved,\n provider: 'po-git',\n ...(Object.hasOwn(record, 'profile') ? { sparseProfile: profile } : {}),\n ...(Object.hasOwn(record, 'fingerprint') ? { sparseFingerprint: fingerprint } : {}),\n };\n });\n return parseWorktreeRegistry({ version: 2, entries });\n}\n\n/**\n * The caller has stopped po-sparo. Destination lock is outermost; the source's\n * actual directory-lock protocol excludes a racing old writer through publish.\n * Only that transient source sidecar is touched, never its records or checkouts.\n */\nexport async function importSparoRegistry(\n options: SparoImportOptions,\n source: string,\n destination: string,\n managedRoot: string,\n): Promise<SparoImportResult> {\n const files = options.fs;\n const context = options.signal ? withAbortSignal(options.signal, BACKGROUND_CONTEXT) : BACKGROUND_CONTEXT;\n const canonical = async (file: string) => getOrThrow(await files.canonicalPath(file, context));\n const readText = async (file: string) => getOrThrow(await files.readTextFile(file, context));\n const inside = (root: string, candidate: string) => {\n const relative = path.relative(root, candidate);\n return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);\n };\n if (options.sourceProviderStopped !== true) return refuse('stop the source provider before cutover');\n const result = { source, destination, imported: 0, duplicates: 0 };\n return createWorktreeRegistry(destination).transaction(async () => {\n const current = await readWorktreeRegistryFile(destination);\n if (current.sparoImport) {\n if (current.sparoImport.source !== source) return refuse('completion belongs to a different source');\n return { ...result, status: 'already-imported' };\n }\n const sourceInfo = await files.fileInfo(source, context);\n if (!sourceInfo.ok && sourceInfo.error.code === 'not_found') return { ...result, status: 'source-absent' };\n getOrThrow(sourceInfo);\n return createWorktreeRegistry(source, { createDirectory: false }).transaction(async () => {\n const snapshot = await readText(source);\n const imported = sourceEntries(snapshot);\n const common = await gitCommonDirectory(options.repositoryRoot);\n if (!common) return refuse('destination is not a Git repository');\n const identity = await canonical(common);\n const canonicalManagedRoot = imported.length ? await canonical(managedRoot) : managedRoot;\n // A prunable worktree (folder deleted outside Git) can never match an existing checkout, so skip it.\n const listed = await Promise.all(\n (await options.git.listWorktreePaths(options.repositoryRoot)).map(async (entry) => {\n const resolved = await files.canonicalPath(entry, context);\n return !resolved.ok && resolved.error.code === 'not_found' ? undefined : getOrThrow(resolved);\n }),\n );\n const membership = new Set(listed.filter((entry) => entry !== undefined));\n const combined = [...current.entries];\n for (const entry of imported) {\n options.signal?.throwIfAborted();\n if (!path.isAbsolute(entry.path) || !path.isAbsolute(entry.repositoryRoot)) return refuse('non-absolute path');\n const entryCommon = await gitCommonDirectory(entry.repositoryRoot);\n const checkoutCommon = await gitCommonDirectory(entry.path);\n if (\n !entryCommon ||\n !checkoutCommon ||\n (await canonical(entryCommon)) !== identity ||\n (await canonical(checkoutCommon)) !== identity\n )\n return refuse(`wrong repository for '${entry.id}'`);\n const realPath = await canonical(entry.path);\n if (!inside(managedRoot, path.resolve(entry.path)) || !inside(canonicalManagedRoot, realPath))\n return refuse(`'${entry.id}' is outside the admitted Sparo worktrees root`);\n if (getOrThrow(await files.fileInfo(path.join(realPath, '.git'), context)).kind !== 'file')\n return refuse(`'${entry.id}' is not a linked worktree`);\n if (!membership.has(realPath)) return refuse(`Git does not list '${entry.id}'`);\n if ((await options.git.currentBranch(entry.path)) !== entry.branch)\n return refuse(`branch mismatch for '${entry.id}'`);\n if (!entry.sessionId || !Number.isFinite(Date.parse(entry.createdAt)))\n return refuse(`invalid ownership or timestamp for '${entry.id}'`);\n const collisions: WorktreeRecord[] = [];\n for (const existing of combined) {\n // realpath when present, lexical identity for stale canonical records.\n const resolved = await files.canonicalPath(existing.path, context);\n const existingPath =\n !resolved.ok && resolved.error.code === 'not_found' ? path.resolve(existing.path) : getOrThrow(resolved);\n if (\n existing.id === entry.id ||\n existingPath === realPath ||\n existing.sessionId === entry.sessionId ||\n ('reservationId' in entry && 'reservationId' in existing && entry.reservationId === existing.reservationId)\n )\n collisions.push(existing);\n }\n if (collisions.length) {\n if (collisions.length !== 1 || !isDeepStrictEqual(collisions[0], entry))\n return refuse(`conflicting id, path or owner for '${entry.id}'`);\n result.duplicates++;\n } else {\n combined.push(entry);\n result.imported++;\n }\n }\n // Detect out-of-protocol writes as well. A stopped provider remains a\n // prerequisite, not a claim of safety while both plugins are running.\n if ((await readText(source)) !== snapshot) return refuse('source changed during import');\n options.signal?.throwIfAborted();\n const value: WorktreeRegistryFile = {\n version: 2,\n entries: combined,\n ...(current.workflowAttempts ? { workflowAttempts: current.workflowAttempts } : {}),\n sparoImport: {\n source,\n sourceDigest: createHash('sha256').update(snapshot).digest('hex'),\n completedAt: new Date().toISOString(),\n recordIds: imported.map((entry) => entry.id),\n },\n };\n parseWorktreeRegistry(value);\n await writeJsonAtomic(destination, value);\n return { ...result, status: 'imported' };\n }, options.signal);\n }, options.signal);\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\n\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\n\nimport {\n WORKTREE_RECORD_VERSION,\n type WorktreeRecord,\n type WorktreeWorkflowAttempt,\n} from '../../types/worktreeRegistry';\nimport { writeJsonAtomic } from '../atomicJson';\nimport { repositoryId } from '../repositoryIdentity';\nimport { importSparoRegistry } from '../sparoRegistryImport';\nimport type { SparoImportOptions, SparoImportResult } from '../sparoRegistryImport/type';\nimport { readWorktreeRegistryFile } from '../worktreeRegistry';\n\n/**\n * Where this package keeps its own state.\n *\n * Outside the repository on purpose. A worktree directory inside the checkout\n * would be found by every glob the repository's own tooling runs, and would\n * resolve workspace imports against the parent checkout rather than the\n * worktree, so a session there would build the wrong source while appearing to\n * work.\n */\nexport function poGitRoot(\n homeDir: string = os.homedir(),\n environment: Readonly<Record<string, string | undefined>> = {},\n): string {\n return path.join(poHomeDirectory(homeDir, environment), 'git');\n}\n\n/**\n * Deliberate operator cutover, never called by normal registry discovery.\n * Stop po-sparo first and pass admitted home/environment and Git capabilities.\n * Label migration completes first; the import then owns the canonical transaction,\n * even when the canonical registry already existed. No checkout is moved.\n */\nexport async function importSparoWorktrees(options: SparoImportOptions): Promise<SparoImportResult> {\n if (!path.isAbsolute(options.homeDirectory) || !path.isAbsolute(options.repositoryRoot))\n throw new Error('Sparo cutover requires explicit absolute home and repository roots.');\n if (!options.fs) throw new Error('Sparo cutover requires the admitted host filesystem.');\n if (!options.environment || options.sourceProviderStopped !== true)\n throw new Error('Sparo cutover requires an admitted environment and a stopped source provider.');\n const destination = await registryFile(options.repositoryRoot, options.homeDirectory, options.environment);\n const source = path.join(\n poHomeDirectory(options.homeDirectory, options.environment),\n 'sparo',\n 'registry',\n await repositoryId(options.repositoryRoot),\n 'worktrees.json',\n );\n return importSparoRegistry(\n options,\n source,\n destination,\n path.join(poHomeDirectory(options.homeDirectory, options.environment), 'sparo', 'worktrees'),\n );\n}\n\n/** The directory every worktree for every repository is created under. */\nexport function worktreesRoot(\n homeDir: string = os.homedir(),\n environment: Readonly<Record<string, string | undefined>> = {},\n): string {\n return path.join(poGitRoot(homeDir, environment), 'worktrees');\n}\n\n/**\n * Remote auth for every workspace, one entry per workspace root.\n *\n * Outside every repository, so a token can never be committed, and readable\n * only by the owner. It holds secrets, which no other file here does.\n */\nexport function credentialsFile(\n homeDir: string = os.homedir(),\n environment: Readonly<Record<string, string | undefined>> = {},\n): string {\n return path.join(poGitRoot(homeDir, environment), 'credentials.json');\n}\n/** One registry file per repository, keyed by the shared git directory. */\nexport async function registryFile(\n repositoryRoot: string,\n homeDir: string = os.homedir(),\n environment: Readonly<Record<string, string | undefined>> = {},\n): Promise<string> {\n const id = await repositoryId(repositoryRoot);\n const root = path.join(poGitRoot(homeDir, environment), 'registry');\n const canonical = path.join(root, id, 'worktrees.json');\n if (\n await fs.access(canonical).then(\n () => true,\n () => false,\n )\n )\n return canonical;\n let names: string[];\n try {\n names = await fs.readdir(root);\n } catch {\n return canonical;\n }\n const legacyFiles: string[] = [];\n for (const entry of names.filter((name) => name.endsWith(`--${id}`)).sort()) {\n const file = path.join(root, entry, 'worktrees.json');\n if (\n await fs.access(file).then(\n () => true,\n () => false,\n )\n )\n legacyFiles.push(file);\n }\n if (legacyFiles.length === 0) return canonical;\n const entries = new Map<string, WorktreeRecord>();\n const workflowAttempts = new Map<string, WorktreeWorkflowAttempt>();\n for (const file of legacyFiles) {\n const snapshot = await readWorktreeRegistryFile(file);\n for (const attempt of snapshot.workflowAttempts ?? []) {\n const key = JSON.stringify([attempt.launcherSessionId, attempt.attemptId]);\n const previous = workflowAttempts.get(key);\n if (previous && !isDeepStrictEqual(previous, attempt))\n throw new Error('Conflicting legacy workflow attempt metadata.');\n workflowAttempts.set(key, attempt);\n }\n for (const entry of snapshot.entries) {\n const existing = entries.get(entry.id);\n if (existing !== undefined && !isDeepStrictEqual(existing, entry)) {\n throw new Error(`Conflicting legacy worktree registry entries for '${entry.id}'.`);\n }\n entries.set(entry.id, entry);\n }\n }\n const temporary = `${canonical}.${randomUUID()}.migration`;\n await writeJsonAtomic(temporary, {\n version: WORKTREE_RECORD_VERSION,\n entries: [...entries.values()],\n ...(workflowAttempts.size ? { workflowAttempts: [...workflowAttempts.values()] } : {}),\n });\n try {\n // Publish only if absent. A concurrent writer may already have added records.\n await fs.link(temporary, canonical);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n } finally {\n await fs.rm(temporary);\n }\n return canonical;\n}\n","import { spawn } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { RIFT_INSTALL_COMMAND } from '../../constants/git';\nimport { PoGitExpectedError } from '../errors';\nimport { READ_TIMEOUT_MS, runGit } from '../gitCli';\n\n/** Present at a repository root, it makes worktrees Rift copy-on-write workspaces instead of git worktrees. */\nexport const RIFT_CONFIG_FILE = '.rift.toml';\n/** Rift's identity marker; a root without it was never `rift init`ed. */\nconst RIFT_MARKER = '.rift';\n/** Cloning is instant, but `.rift.toml` hooks such as an install run inside create. */\nconst CREATE_TIMEOUT_MS = 600_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\n\nexport interface WorktreeRift {\n /** Whether the repository opted into Rift with a `.rift.toml` at its root. */\n enabled(repositoryRoot: string): Promise<boolean>;\n /**\n * Copies the repository to `path`, then leaves the copy on `branch`. Rift copies the\n * working state; the branch switch and clean put it back on the ref, as a git worktree would be.\n */\n create(input: {\n repositoryRoot: string;\n path: string;\n branch: string;\n baseRef: string;\n existing: boolean;\n remote?: string;\n }): Promise<void>;\n /** Moves the workspace to Rift's trash. A path already gone counts as removed. */\n remove(path: string): Promise<void>;\n /** A Rift copy has its own `.git`, so its branch is fetched into the root before a merge. */\n fetchBranch(input: { repositoryRoot: string; path: string; branch: string }): Promise<void>;\n}\n\n/**\n * Runs the rift CLI. Stderr is dropped rather than piped: hooks inherit it and may keep it open\n * after rift exits (a `docker compose up -d`), and raw output never reaches a tool result anyway.\n */\nfunction rift(cwd: string, args: readonly string[], timeout: number): Promise<{ code: number; stdout: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn('rift', [...args], { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout });\n let stdout = '';\n child.stdout.on('data', (chunk: Buffer) => (stdout += String(chunk)));\n child.on('error', (error: NodeJS.ErrnoException) =>\n reject(\n error.code === 'ENOENT'\n ? new PoGitExpectedError(\n 'rift_missing',\n `This repository has ${RIFT_CONFIG_FILE}, but the rift CLI is not installed.`,\n false,\n `Install it with \\`${RIFT_INSTALL_COMMAND}\\`, run \\`rift init\\` in the repository root, then try again. An agent asks the person with ask_user_question before installing. Removing ${RIFT_CONFIG_FILE} falls back to git worktrees.`,\n )\n : error,\n ),\n );\n child.on('exit', (code) => resolve({ code: code ?? 1, stdout }));\n });\n}\n\nconst exists = (file: string) =>\n fs.access(file).then(\n () => true,\n () => false,\n );\n\nexport function createWorktreeRift(): WorktreeRift {\n const remove = async (target: string): Promise<void> => {\n if (!(await exists(target))) return;\n const result = await rift(path.dirname(target), ['remove', target], REMOVE_TIMEOUT_MS);\n if (result.code !== 0) throw new Error(`rift remove failed (exit ${String(result.code)})`);\n };\n\n return {\n enabled: (repositoryRoot) => exists(path.join(repositoryRoot, RIFT_CONFIG_FILE)),\n\n async create({ repositoryRoot, path: target, branch, baseRef, existing, remote }) {\n if (!(await exists(path.join(repositoryRoot, RIFT_MARKER)))) {\n // A machine without the CLI was never initialized either; probing first asks for the install, not the init.\n await rift(repositoryRoot, ['--help'], READ_TIMEOUT_MS);\n throw new PoGitExpectedError(\n 'invalid_request',\n `This repository has ${RIFT_CONFIG_FILE}, but Rift is not initialized for ${repositoryRoot}.`,\n false,\n 'Run `rift init` in the repository root (not inside a git worktree), then try again.',\n );\n }\n // Checked first so a failure below can only ever remove what this call made.\n if (await exists(target)) throw new Error(`The worktree path ${target} already exists.`);\n await fs.mkdir(path.dirname(target), { recursive: true });\n // ponytail: always --copy-all so node_modules and build caches clone instantly; add a\n // filtered option if a repository's artifacts turn out to be unsafe to share across branches.\n const created = await rift(\n repositoryRoot,\n ['create', repositoryRoot, '--into', path.dirname(target), '--name', path.basename(target), '--copy-all'],\n CREATE_TIMEOUT_MS,\n );\n if (created.code !== 0) {\n // A failed postcreate hook leaves the workspace registered and on disk.\n await remove(target).catch(() => undefined);\n throw new Error(`rift create failed (exit ${String(created.code)})`);\n }\n const switchArgs = existing\n ? remote === undefined\n ? ['switch', '--discard-changes', branch]\n : ['switch', '--discard-changes', '--track', '-c', branch, `${remote}/${branch}`]\n : ['switch', '--discard-changes', '-c', branch, baseRef];\n // Untracked work in progress is dropped too; ignored files (env, node_modules) stay.\n for (const args of [switchArgs, ['clean', '-fd']]) {\n const result = await runGit(target, args, { timeout: READ_TIMEOUT_MS });\n if (result.code !== 0) {\n await remove(target).catch(() => undefined);\n throw new Error(`git ${String(args[0])} in the rift failed (exit ${String(result.code)})`);\n }\n }\n },\n\n remove,\n\n async fetchBranch({ repositoryRoot, path: source, branch }) {\n // No `+`: a branch the root moved on its own is refused rather than overwritten.\n const result = await runGit(repositoryRoot, ['fetch', source, `refs/heads/${branch}:refs/heads/${branch}`], {\n timeout: READ_TIMEOUT_MS,\n });\n if (result.code !== 0) throw new Error(`git fetch from the rift failed (exit ${String(result.code)})`);\n },\n };\n}\n","/**\n * Naming and reconciliation rules for worktrees, as pure functions.\n *\n * Everything here is a function of its arguments so the interesting decisions,\n * which are the ones about destroying work, can be tested without a repository\n * or a filesystem.\n */\n\nimport type { WorktreeRecord } from '../../types/worktreeRegistry';\n\nconst MAX_SLUG_LENGTH = 64;\n/** Anything git forbids in a ref, plus a leading `-` that `worktree add` would read as an option. */\nconst INVALID_REF = /(^[-/.])|[\\s~^:?*[\\\\]|\\.\\.|@\\{|\\/\\/|\\/\\.|\\.lock$|\\/$|\\.$/u;\nconst MAX_REF_LENGTH = 255;\nconst FIRST_PRINTABLE = 0x20;\nconst DELETE = 0x7f;\n\n/**\n * A branch name reduced to one safe path segment.\n *\n * Slashes are the point: `wt/fix-auth` is a perfectly good branch and a\n * terrible directory name, because the nested directory it implies is not the\n * one the worktree lives in.\n */\nexport function branchSlug(branch: string): string {\n const slug = branch\n .toLowerCase()\n .replace(/[^a-z0-9]+/gu, '-')\n .replace(/^-+|-+$/gu, '')\n .slice(0, MAX_SLUG_LENGTH)\n .replace(/-+$/gu, '');\n return slug === '' ? 'worktree' : slug;\n}\n\n/**\n * The directory for one worktree.\n *\n * The short id disambiguates two branches whose slugs collide, such as\n * `feature/x` and `feature_x`, which would otherwise want the same directory.\n */\nexport function worktreeDirectory(input: {\n worktreesRoot: string;\n repositoryLabel: string;\n repositoryId: string;\n branch: string;\n shortId: string;\n}): string {\n const repository = `${input.repositoryLabel}--${input.repositoryId}`;\n return `${input.worktreesRoot}/${repository}/${branchSlug(input.branch)}--${input.shortId}`;\n}\n\n/** Why a worktree cannot be created, or undefined when it can. */\nexport function refuseSpawn(input: { branch: string; existing: readonly WorktreeRecord[] }): string | undefined {\n if (input.branch.trim() === '') return 'A branch name is required.';\n // Git refuses a second worktree on one branch, but its message names a path\n // the caller never chose, so this says it in the caller's own terms first.\n const live = input.existing.find((record) => record.branch === input.branch && record.status !== 'orphaned');\n if (live) return `Branch ${input.branch} already has a worktree (${live.id}).`;\n return undefined;\n}\n\n/** Why a worktree cannot be closed, or undefined when it can. */\nexport function refuseClose(input: {\n record: WorktreeRecord | undefined;\n dirtyFiles: readonly string[];\n force: boolean;\n}): string | undefined {\n if (!input.record) return 'No worktree with that id. Call list to see the current ids.';\n if (input.dirtyFiles.length === 0 || input.force) return undefined;\n // Naming the files is the point: \"the tree is dirty\" sends the reader to go\n // look, and the answer is usually a file they forgot rather than one they\n // meant to keep.\n const names = input.dirtyFiles.slice(0, 10).join(', ');\n const more = input.dirtyFiles.length > 10 ? `, and ${String(input.dirtyFiles.length - 10)} more` : '';\n return `${String(input.dirtyFiles.length)} uncommitted file(s): ${names}${more}. Pass force: true to discard them.`;\n}\n\nexport interface Reconciliation {\n records: WorktreeRecord[];\n /** Ids whose status changed, so a caller can report what it noticed. */\n changed: string[];\n}\n\n/**\n * Marks records whose process or directory is gone as orphaned.\n *\n * Nothing is deleted here. A po-git orphan owns a directory that may hold\n * uncommitted work, so losing the record would lose the only pointer to it.\n * Deletion is always a separate, named decision.\n */\nexport async function reconcile(\n records: readonly WorktreeRecord[],\n probe: { alive: (record: WorktreeRecord) => boolean; exists: (path: string) => boolean | Promise<boolean> },\n): Promise<Reconciliation> {\n const changed: string[] = [];\n const next: WorktreeRecord[] = [];\n for (const record of records) {\n if (record.status === 'orphaned' || ((await probe.exists(record.path)) && probe.alive(record))) {\n next.push(record);\n continue;\n }\n changed.push(record.id);\n next.push({ ...record, status: 'orphaned' });\n }\n return { records: next, changed };\n}\n\nexport interface PrunePlan {\n /** Orphans whose directory git still lists, safe to remove. */\n remove: WorktreeRecord[];\n /** Orphans whose directory is already gone; drop the record only. */\n forget: WorktreeRecord[];\n /** Paths git lists under our root that we have no record of; report, never touch. */\n untracked: string[];\n /** Orphans left alone because they still hold uncommitted work. */\n keptDirty: WorktreeRecord[];\n /**\n * Branches git refused to delete because they hold commits.\n *\n * Filled by the prune itself, not by the plan: a dry run destroys nothing, so\n * it has nothing to report here and leaves it empty.\n */\n keptBranches: string[];\n}\n\n/**\n * What a prune would do, decided before anything is destroyed.\n *\n * Separating the plan from the execution is what makes dryRun honest and lets\n * the destructive half be reviewed on its own.\n */\nexport function planPrune(input: {\n records: readonly WorktreeRecord[];\n gitPaths: readonly string[];\n worktreesRoot: string;\n dirtyByPath: ReadonlyMap<string, readonly string[]>;\n}): PrunePlan {\n const plan: PrunePlan = { remove: [], forget: [], untracked: [], keptDirty: [], keptBranches: [] };\n const known = new Set(input.records.map((record) => record.path));\n const listed = new Set(input.gitPaths);\n for (const record of input.records) {\n if (record.status !== 'orphaned') continue;\n if (!listed.has(record.path)) {\n plan.forget.push(record);\n continue;\n }\n if ((input.dirtyByPath.get(record.path) ?? []).length > 0) {\n plan.keptDirty.push(record);\n continue;\n }\n plan.remove.push(record);\n }\n for (const path of input.gitPaths) {\n // Only ever inside our own root: a worktree the user made by hand is none\n // of this package's business, even when it looks abandoned.\n if (path.startsWith(`${input.worktreesRoot}/`) && !known.has(path)) plan.untracked.push(path);\n }\n return plan;\n}\n\n/** Whether a user-supplied branch or base ref is safe to hand to git as a positional argument. */\nexport function validRefName(name: string): boolean {\n if (name === '' || name === '@' || name.length > MAX_REF_LENGTH || INVALID_REF.test(name)) return false;\n for (const character of name) {\n const code = character.charCodeAt(0);\n if (code < FIRST_PRINTABLE || code === DELETE) return false;\n }\n return true;\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport pathModule from 'node:path';\n\nimport type { PoHubSessionSelection, PoHubSessionService } from '@agimon-ai/po-core/hubChannel';\nimport type { PoSessionDeliveryService } from '@agimon-ai/po-session';\nimport { ConeFolder, profilePath, SparsePolicy, SparoError, type GitEngineService } from '@agimon-ai/po-sparo';\n\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry';\nimport type {\n WorktreeGit,\n WorktreeRecord,\n WorktreeWorkflow,\n WorktreeWorkflowCloseEvidence,\n WorktreeSetupStage,\n} from '../../types/worktreeRegistry';\nimport { PoGitExpectedError, HubUnavailableError } from '../errors';\nimport { revision, trackBranch } from '../gitCli';\nimport { registryFile, worktreesRoot } from '../paths';\nimport { repositoryId, repositoryLabel, shortId } from '../repositoryIdentity';\nimport { createWorktreeRift, type WorktreeRift } from '../riftCli';\nimport { createWorktreeConfigReader, validSparseProfile } from '../worktreeConfig';\nimport type { WorktreeConfig } from '../worktreeConfig/type';\nimport { MAX_WORKTREE_MESSAGE_BYTES, type WorktreeMessageInbox, type WorktreeMessageParty } from '../worktreeEvents';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, validRefName, worktreeDirectory } from '../worktreeNaming';\nimport { createWorktreeRegistry } from '../worktreeRegistry';\n\nconst GIT_WORKTREE_DELEGATION_KIND = 'git.worktree.delegation';\nconst GIT_WORKTREE_MESSAGE_KIND = 'git.worktree.message';\nconst GIT_WORKTREE_REPORT_KIND = 'git.worktree.report';\n\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /**\n * The calling session, recorded as the new session's parent. Absent when the\n * new-session dialog opens a top-level worktree session for the workspace.\n */\n sessionId?: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: string;\n /** Sparse checkout selection, independent of selection.profile. */\n sparseProfile?: string;\n name?: string;\n task?: string;\n /** Host-owned execution setup, exposed by the UI rather than the agent tool. */\n reservationId?: string;\n /** `existing` checks out a branch that already exists instead of creating one from `baseRef`. */\n checkout?: 'new' | 'existing';\n /** With `existing`: the branch exists only on this remote; a local tracking branch is created. */\n remote?: string;\n /** The launcher's profile choice for the new session, left out when none was made. */\n selection?: PoHubSessionSelection;\n}\n\nexport interface SpawnOptions {\n /** Trusted workflow launcher only. Never part of tool or HTTP input. */\n workflow?: Pick<WorktreeWorkflow, 'attemptId' | 'fingerprint'>;\n preset?: string;\n /** Aborted when the caller gives up, so a spawn nobody is waiting for stops. */\n signal?: AbortSignal;\n /** Phase labels, for a caller that can show them while the work runs. */\n onProgress?: (label: string) => void;\n}\n\nexport interface WorktreeOperations {\n profiles(\n context: WorktreeContext,\n baseRef?: string,\n options?: SpawnOptions,\n ): Promise<{ sparseProfiles?: string[]; defaultSparseProfile?: string }>;\n expand(\n context: WorktreeContext,\n id: string,\n folders: readonly string[],\n options?: SpawnOptions,\n ): Promise<WorktreeRecord>;\n reapply(context: WorktreeContext, id: string, options?: SpawnOptions): Promise<WorktreeRecord>;\n spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;\n linkWorkflow(context: WorktreeContext, id: string, workflow: WorktreeWorkflow): Promise<WorktreeRecord>;\n close(\n context: WorktreeContext,\n id: string,\n force: boolean,\n expectedWorkflow?: WorktreeWorkflowCloseEvidence,\n ): Promise<WorktreeRecord>;\n list(context: WorktreeContext): Promise<WorktreeRecord[]>;\n status(context: WorktreeContext, id: string): Promise<{ record: WorktreeRecord; dirtyFiles: string[] }>;\n merge(context: WorktreeContext, id: string, message?: string): Promise<WorktreeRecord>;\n prune(context: WorktreeContext, dryRun: boolean): Promise<ReturnType<typeof planPrune>>;\n send(context: WorktreeContext, id: string, message: string): Promise<void>;\n messages(context: WorktreeContext, id: string): Promise<import('../worktreeEvents').WorktreeMessage[]>;\n}\n\nexport interface WorktreeOperationsDeps {\n git: WorktreeGit;\n gitEngine?: () => GitEngineService | undefined;\n /** Trusted plugin-resolved installed CLI, never a request parameter. */\n sparoCliPath?: () => string;\n /** One bounded handoff to the child's own runner provider, without registry access. */\n startSetup?: (sessionId: string, command: string, signal?: AbortSignal) => Promise<WorktreeSetupStage>;\n signal?: AbortSignal;\n /** A composition-owned snapshot reader, using admitted PoFs on wired hosts. */\n worktreeConfig?: (root: string) => Promise<WorktreeConfig>;\n /** Used instead of git worktrees when the repository has a `.rift.toml`. */\n rift?: WorktreeRift;\n /** The canonical hub-owned session lifecycle. */\n sessionService?: PoHubSessionService;\n /** Legacy in-memory fallback used outside the fixed Session composition. */\n messageInbox?: WorktreeMessageInbox;\n /** Reads the active Session provider when an operation executes. */\n sessionDelivery?: () => PoSessionDeliveryService | undefined;\n homeDir?: string;\n /** Host-admitted environment, read for PO_HOME. */\n environment?: Readonly<Record<string, string | undefined>>;\n /** Injected so a record's createdAt is reproducible in a test. */\n now?: () => Date;\n}\n\nexport function createWorktreeOperations(deps: WorktreeOperationsDeps): WorktreeOperations {\n const { git } = deps;\n const readConfig =\n deps.worktreeConfig ?? createWorktreeConfigReader({ readTextFile: (file) => fs.readFile(file, 'utf8') });\n const rift = deps.rift ?? createWorktreeRift();\n const sessionService = deps.sessionService;\n const now = deps.now ?? (() => new Date());\n const requireSessionService = (): PoHubSessionService => {\n if (sessionService === undefined)\n throw new HubUnavailableError('The cockpit session service is unavailable. Start the cockpit and try again.');\n return sessionService;\n };\n const requireMessageInbox = (): WorktreeMessageInbox => {\n if (deps.messageInbox === undefined)\n throw new HubUnavailableError('The Git message service is unavailable. Start the cockpit and try again.');\n return deps.messageInbox;\n };\n const readSessionDelivery = (): PoSessionDeliveryService | undefined => deps.sessionDelivery?.();\n const requireSessionDelivery = (): PoSessionDeliveryService => {\n const delivery = readSessionDelivery();\n if (delivery === undefined)\n throw new HubUnavailableError('The Session delivery service is unavailable. Start the cockpit and try again.');\n return delivery;\n };\n const probe = {\n alive: (record: WorktreeRecord) => requireSessionService().isLive(record.sessionId),\n exists: (path: string) =>\n fs.access(path).then(\n () => true,\n () => false,\n ),\n };\n /** What git lists as worktrees, plus Rift workspaces, which git cannot see. */\n const listedPaths = async (root: string, records: readonly WorktreeRecord[]): Promise<string[]> => {\n const rifts = records.filter((record) => record.backend === 'rift');\n const present = await Promise.all(rifts.map((record) => probe.exists(record.path)));\n return [...(await git.listWorktreePaths(root)), ...rifts.filter((_, index) => present[index]).map((r) => r.path)];\n };\n const removeCheckout = (root: string, record: Pick<WorktreeRecord, 'path' | 'backend'>, force: boolean) =>\n record.backend === 'rift'\n ? rift.remove(record.path)\n : git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n\n /**\n * Everything an action needs about the repository it is acting on.\n *\n * Resolved per call rather than cached: a session's cwd is stable, but the\n * worktree registry is shared and another process may have written it since\n * the last call.\n */\n const resolve = async (context: WorktreeContext) => {\n const root = await git.repositoryRoot(context.cwd);\n if (root === undefined) {\n throw new PoGitExpectedError(\n 'not_a_repository',\n `${context.cwd} is not inside a git repository.`,\n false,\n 'Run this from a repository checkout.',\n );\n }\n const store = createWorktreeRegistry(await registryFile(root, deps.homeDir, deps.environment));\n return { root, store, records: await store.list() };\n };\n\n const require = (records: readonly WorktreeRecord[], id: string): WorktreeRecord => {\n const record = records.find((entry) => entry.id === id);\n if (record === undefined) {\n throw new PoGitExpectedError(\n 'worktree_not_found',\n `No worktree with id ${id}.`,\n false,\n 'Call list to see the current ids.',\n );\n }\n return record;\n };\n\n /**\n * Refuses to destroy or merge a worktree another live session is using.\n *\n * `parentSessionId` records who asked for the worktree. Two sessions in one\n * checkout share this registry, so without the check either could close the\n * other's work in progress by id.\n *\n * Once that session is gone there is no owner left to protect, and refusing\n * would strand the worktree: nothing else could ever close it.\n */\n const requireOwner = (context: WorktreeContext, record: WorktreeRecord, action: string): void => {\n if (record.parentSessionId === context.sessionId) return;\n if (record.parentSessionId === undefined || !requireSessionService().isLive(record.parentSessionId)) return;\n throw new PoGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n `Ask the session that created it to ${action} it, or close that session first.`,\n );\n };\n\n const peerFor = (\n context: WorktreeContext,\n record: WorktreeRecord,\n ): { sessionId: string; party: WorktreeMessageParty } => {\n if (record.parentSessionId === undefined)\n throw new PoGitExpectedError(\n 'worktree_peer_unavailable',\n `Worktree ${record.id} was opened on its own and has no parent session to message.`,\n false,\n 'Message a worktree this session created.',\n );\n if (context.sessionId === record.parentSessionId) return { sessionId: record.sessionId, party: 'parent' };\n if (context.sessionId === record.sessionId) return { sessionId: record.parentSessionId, party: 'child' };\n throw new PoGitExpectedError(\n 'worktree_not_owned',\n `Worktree ${record.id} belongs to another session.`,\n false,\n 'Use a worktree owned by this session.',\n );\n };\n\n const requirePeerLive = (peerSessionId: string): void => {\n if (!requireSessionService().isLive(peerSessionId)) {\n throw new PoGitExpectedError(\n 'worktree_peer_unavailable',\n 'The other worktree session is no longer live.',\n false,\n 'Start a new worktree session before sending a message.',\n );\n }\n };\n\n const operation = (options?: SpawnOptions) => ({\n environment: deps.environment ?? {},\n signal: AbortSignal.any([...(deps.signal ? [deps.signal] : []), ...(options?.signal ? [options.signal] : [])]),\n });\n const engine = (): GitEngineService => {\n const service = deps.gitEngine?.();\n if (!service)\n throw new PoGitExpectedError(\n 'invalid_request',\n 'Sparse checkout requires po/git-engine.',\n false,\n 'Enable the Git engine workspace service.',\n );\n return service;\n };\n const fingerprint = async (\n root: string,\n config: WorktreeConfig,\n ref: string,\n options?: SpawnOptions,\n ): Promise<string> => {\n const policy = config.sparse!;\n const request = operation(options);\n const names = await engine().profiles(root, policy, request, ref);\n const blobs = await Promise.all(\n names\n .filter((name) => name !== 'full')\n .map(async (name) => [\n profilePath(name, policy),\n await revision(root, `${ref}:${profilePath(name, policy)}`, {\n env: request.environment,\n signal: request.signal,\n }),\n ]),\n );\n return createHash('sha256')\n .update(JSON.stringify([policy, blobs]))\n .digest('hex');\n };\n const sparseMutation = async (\n context: WorktreeContext,\n id: string,\n folders: readonly string[] | undefined,\n options?: SpawnOptions,\n ) => {\n const { store, records } = await resolve(context);\n const record = require(records, id);\n if (context.sessionId !== record.sessionId) requireOwner(context, record, folders ? 'expand' : 'reapply');\n if (!record.sparseProfile)\n throw new PoGitExpectedError(\n 'invalid_request',\n 'This worktree has no sparse profile.',\n false,\n 'Choose a sparse worktree.',\n );\n const config = await readConfig(record.repositoryRoot);\n if (!config.sparse)\n throw new PoGitExpectedError(\n 'invalid_request',\n 'Sparse policy is not configured.',\n false,\n 'Restore the worktree sparse configuration.',\n );\n const result = folders\n ? await engine().expand(record.path, folders, config.sparse, operation(options))\n : await engine().reapply(record.path, config.sparse, operation(options));\n const updated = {\n ...record,\n extraFolders: [...new Set([...(record.extraFolders ?? []), ...(folders ?? [])])].sort(),\n sparseFingerprint: await fingerprint(record.path, config, 'HEAD', options),\n };\n await store.replace(records.map((entry) => (entry.id === id ? updated : entry)));\n return { ...updated, coneFolders: result.coneFolders };\n };\n\n const operations: WorktreeOperations = {\n async profiles(context, baseRef, options) {\n if (baseRef !== undefined && !validRefName(baseRef))\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The profile base ref is invalid.',\n false,\n 'Use a valid Git ref.',\n );\n const { root } = await resolve(context);\n const config = await readConfig(root);\n if (!config.sparse) return {};\n const ref = baseRef ?? (await git.remoteBaseRef(root)) ?? 'HEAD';\n return {\n sparseProfiles: await engine().profiles(root, config.sparse, operation(options), ref),\n ...(config.defaults?.sparseProfile ? { defaultSparseProfile: config.defaults.sparseProfile } : {}),\n };\n },\n expand: (context, id, folders, options) => sparseMutation(context, id, folders, options),\n reapply: (context, id, options) => sparseMutation(context, id, undefined, options),\n async spawn(context, request, options) {\n const parentSessionId = context.sessionId;\n const parented = parentSessionId === undefined ? {} : { parentSessionId };\n const { root, store, records } = await resolve(context);\n const reservations = request.reservationId === undefined ? undefined : requireSessionService().reservations;\n if (request.reservationId !== undefined && (!reservations || request.task !== undefined))\n throw new PoGitExpectedError(\n 'invalid_request',\n 'Reserved worktree sessions require host setup and cannot start a task.',\n false,\n 'Create the session from its pending setup card.',\n );\n const reserved =\n request.reservationId === undefined ? undefined : reservations!.read(request.reservationId, parentSessionId!);\n const existing =\n reserved === undefined ? undefined : records.find((record) => record.sessionId === reserved.sessionId);\n if (existing) {\n const expectedPath = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir, deps.environment),\n repositoryLabel: repositoryLabel(root),\n repositoryId: await repositoryId(root),\n branch: request.branch,\n shortId: shortId(reserved!.sessionId),\n });\n if (\n existing.parentSessionId !== parentSessionId ||\n existing.repositoryRoot !== root ||\n existing.branch !== request.branch ||\n existing.path !== expectedPath ||\n existing.path !== reserved?.cwd ||\n (request.baseRef !== undefined && existing.baseRef !== request.baseRef) ||\n !(await probe.exists(existing.path)) ||\n !(await listedPaths(root, records)).includes(existing.path) ||\n (await git.repositoryRoot(existing.path)) !== existing.path ||\n (await git.currentBranch(existing.path)) !== request.branch\n )\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The reserved checkout no longer matches this setup.',\n false,\n 'Inspect the existing branch and checkout; they will not be replaced.',\n );\n if (!requireSessionService().isLive(existing.sessionId)) {\n const session = await requireSessionService().create({\n cwd: existing.path,\n name: request.name ?? request.branch,\n parentSessionId,\n sessionProvenance: 'worktree',\n reservationId: request.reservationId,\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n });\n if (session.sessionId !== existing.sessionId)\n throw new Error('The host did not use the reserved session identity.');\n }\n await reservations!.complete(request.reservationId!, parentSessionId!);\n return existing;\n }\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new PoGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const taskDelivery = request.task === undefined ? undefined : requireSessionDelivery();\n // Read before any Git state exists, so a broken file refuses the spawn instead of half-running it.\n const config = await readConfig(root);\n const setup = options?.workflow ? undefined : config.setup;\n const sparseProfile = config.sparse ? (config.defaults?.sparseProfile ?? request.sparseProfile) : undefined;\n if (\n request.sparseProfile !== undefined &&\n (!config.sparse ||\n (config.defaults?.sparseProfile !== undefined && request.sparseProfile !== config.defaults.sparseProfile))\n )\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The sparse profile does not match the workspace configuration.',\n false,\n 'Use the workspace sparse default.',\n );\n let setupCommand = setup;\n if (setup !== undefined && sparseProfile !== undefined) {\n const cli = deps.sparoCliPath?.();\n if (!cli || !pathModule.isAbsolute(cli) || cli.includes('\\0'))\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The installed Sparo setup CLI is unavailable.',\n false,\n 'Repair the plugin installation before creating this checkout.',\n );\n const quote = (value: string) => `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n // Snapshot and validate the policy before any checkout or child exists.\n const policy = JSON.stringify(SparsePolicy.parse(config.sparse));\n setupCommand = `${quote(cli)} --policy-json ${quote(policy)} install . && ${setup}`;\n }\n const useRift = sparseProfile === undefined && (await rift.enabled(root));\n const existingBranch = request.checkout === 'existing';\n const id = shortId(reserved?.sessionId ?? randomUUID());\n let path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir, deps.environment),\n repositoryLabel: repositoryLabel(root),\n repositoryId: await repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n if (request.reservationId !== undefined) {\n path = (await reservations!.prepare(request.reservationId, parentSessionId!, path)).cwd;\n }\n const recovering = reserved?.cwd !== undefined && (await probe.exists(path));\n if (\n recovering &&\n (!(useRift ? (await git.repositoryRoot(path)) === path : (await git.listWorktreePaths(root)).includes(path)) ||\n (await git.currentBranch(path)) !== request.branch)\n )\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The reserved checkout no longer matches this setup.',\n false,\n 'Inspect the existing directory; it will not be replaced.',\n );\n if (!recovering) {\n if (existingBranch) {\n const branches = await git.listBranches(root);\n const local = branches.local.find((branch) => branch.name === request.branch);\n const available =\n request.remote === undefined\n ? local !== undefined && local.checkedOutAt === undefined\n : local === undefined &&\n branches.remote.some((branch) => branch.remote === request.remote && branch.name === request.branch);\n if (!available)\n throw new PoGitExpectedError(\n 'invalid_request',\n local?.checkedOutAt === undefined\n ? `The branch ${request.branch} is not available to check out.`\n : `The branch ${request.branch} is already checked out at ${local.checkedOutAt}.`,\n false,\n 'Pick another branch, or create a new one.',\n );\n } else {\n // ponytail: the branch list caps at 2,000 refs; use show-ref --verify if older duplicates need covering.\n if ((await git.listBranches(root)).local.some((branch) => branch.name === request.branch))\n throw new PoGitExpectedError(\n 'invalid_request',\n `The branch ${request.branch} already exists.`,\n false,\n 'Pick another name, or open it as an existing branch.',\n );\n }\n }\n const baseRef = existingBranch\n ? request.remote === undefined\n ? request.branch\n : `${request.remote}/${request.branch}`\n : (request.baseRef ?? (await git.remoteBaseRef(root)));\n if (baseRef === undefined) {\n throw new PoGitExpectedError(\n 'git_failed',\n 'No remote base branch is available for this repository.',\n false,\n 'Fetch a remote branch or pass an explicit baseRef.',\n );\n }\n // The worktree and the branch are made by one command, so they are undone\n // by one too. `worktree remove` leaves the branch behind, and a branch\n // nobody asked for is what a failed spawn used to leave on the floor.\n const cancelled = (): boolean => options?.signal?.aborted === true;\n const rollback = async (): Promise<string> => {\n if (reserved) return ` The reserved checkout at ${path} was retained for recovery.`;\n await removeCheckout(root, { path, ...(useRift ? { backend: 'rift' as const } : {}) }, true).catch(\n () => undefined,\n );\n // A Rift copy has its own `.git`, so its branch went with it.\n if (useRift) return '';\n // A branch that existed before this spawn is never deleted; only one it created is.\n if (existingBranch && request.remote === undefined) return '';\n const deleted = await git.deleteBranch({ repositoryRoot: root, branch: request.branch }).catch(() => false);\n return deleted ? '' : ` The branch ${request.branch} has work on it and was kept.`;\n };\n\n const workflowBaseCommit = options?.workflow\n ? await revision(root, baseRef, { env: deps.environment ?? {}, signal: operation(options).signal })\n : undefined;\n options?.onProgress?.(`creating branch ${request.branch}\\u2026`);\n let coneFolders: string[] | undefined;\n let sparseFingerprint: string | undefined;\n if (!recovering) {\n if (sparseProfile !== undefined) {\n // Resolve before creating anything so malformed profiles cannot leave a branch behind.\n sparseFingerprint = await fingerprint(root, config, baseRef, options);\n try {\n const result = await engine().create(\n {\n repoRoot: root,\n path,\n branch: request.branch,\n base: baseRef,\n profile: sparseProfile,\n extraFolders: config.defaults?.extraFolders ?? [],\n install: false,\n },\n config.sparse!,\n operation(options),\n );\n coneFolders = result.coneFolders;\n if (existingBranch && request.remote !== undefined)\n await trackBranch(path, request.branch, baseRef, {\n env: deps.environment ?? {},\n signal: operation(options).signal,\n });\n } catch (error) {\n await rollback();\n throw error;\n }\n } else if (useRift)\n await rift.create({\n repositoryRoot: root,\n path,\n branch: request.branch,\n baseRef,\n existing: existingBranch,\n ...(request.remote === undefined ? {} : { remote: request.remote }),\n });\n else if (existingBranch)\n await git.addExistingWorktree({\n repositoryRoot: root,\n path,\n branch: request.branch,\n ...(request.remote === undefined ? {} : { remote: request.remote }),\n });\n else await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\n }\n\n // Checked here rather than only inside the session call: this is the\n // point where a checkout exists that nothing has recorded yet, which is\n // exactly the state an interrupted spawn used to leave behind.\n if (cancelled()) {\n const kept = await rollback();\n throw new PoGitExpectedError(\n 'spawn_cancelled',\n `Cancelled before the session started.${kept}`,\n false,\n reserved\n ? 'Retry setup with the same branch to recover the reserved checkout.'\n : 'The worktree was removed; run it again when you are ready.',\n );\n }\n\n // The worktree exists from here on, so every later failure has to leave\n // it removed or recorded. An unrecorded directory on disk is the one\n // outcome with no way back: nothing would ever list it again.\n options?.onProgress?.('starting session\\u2026');\n let sessionId: string;\n try {\n const session = await requireSessionService().create({\n cwd: path,\n name: request.name ?? request.branch,\n ...parented,\n sessionProvenance: 'worktree',\n ...(options?.preset === undefined\n ? request.selection === undefined\n ? {}\n : { selection: request.selection }\n : { selection: { preset: options.preset } }),\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n ...(request.reservationId === undefined ? {} : { reservationId: request.reservationId }),\n });\n sessionId = session.sessionId;\n if (reserved && sessionId !== reserved.sessionId)\n throw new Error('The host did not use the reserved session identity.');\n } catch (error) {\n const kept = await rollback();\n if (cancelled()) {\n throw new PoGitExpectedError(\n 'spawn_cancelled',\n `Cancelled while the session was starting.${kept}`,\n false,\n reserved\n ? 'Retry setup with the same branch to recover the reserved checkout.'\n : 'The worktree was removed; run it again when you are ready.',\n );\n }\n if (error instanceof HubUnavailableError) {\n throw new PoGitExpectedError(\n 'hub_unavailable',\n `${error.message}${kept}`,\n true,\n 'Start the cockpit and try again.',\n );\n }\n throw error;\n }\n\n const record: WorktreeRecord = {\n version: WORKTREE_RECORD_VERSION,\n id,\n branch: request.branch,\n baseRef,\n path,\n repositoryRoot: root,\n sessionId,\n ...parented,\n status: 'running',\n setupStage: setup === undefined ? 'none' : 'unconfirmed',\n ...(sparseProfile === undefined\n ? {}\n : { sparseProfile, extraFolders: config.defaults?.extraFolders ?? [], sparseFingerprint }),\n ...(useRift ? { backend: 'rift' as const } : {}),\n createdAt: now().toISOString(),\n ...(options?.workflow\n ? {\n baseCommit: workflowBaseCommit,\n workflow: { ...options.workflow, state: 'spawned' as const },\n }\n : {}),\n };\n try {\n await store.replace([...records, record]);\n } catch (error) {\n // A live session with no record is the worst outcome available here:\n // it runs, and no id anything can name points at it. The session goes\n // back too, rather than being left for someone to find by hand.\n await requireSessionService()\n .close(sessionId)\n .catch(() => undefined);\n const kept = await rollback();\n throw new PoGitExpectedError(\n 'registry_write_failed',\n `The worktree was created but the registry could not be written (${(error as Error).message}).${kept}`,\n true,\n 'Check the registry file for permissions or free space, then try again.',\n );\n }\n // The child confirms runner.start without acquiring this registry lock.\n // Failed, cancelled, or ambiguous setup retains this registered checkout.\n if (setupCommand !== undefined) {\n try {\n const stage = await deps.startSetup?.(sessionId, setupCommand, operation(options).signal);\n record.setupStage = stage === 'started' || stage === 'failed' ? stage : 'unconfirmed';\n } catch {\n record.setupStage = operation(options).signal.aborted ? 'unconfirmed' : 'failed';\n }\n await store.replace([...records, record]);\n if (record.setupStage !== 'started')\n options?.onProgress?.(\n `worktree setup ${record.setupStage}; inspect worktree-setup before deciding whether to retry. Do not retry automatically.`,\n );\n }\n const setupStarted = record.setupStage === 'started';\n if (request.task !== undefined && taskDelivery !== undefined) {\n try {\n const receipt = await taskDelivery.deliver({\n recipientKey: sessionId,\n kind: GIT_WORKTREE_DELEGATION_KIND,\n prompt: setupStarted\n ? `${request.task}\\n\\nThe worktree setup (${setup}) is running as the runner \"worktree-setup\". Check it with po-runner before relying on installed dependencies or builds.`\n : setup === undefined\n ? request.task\n : `${request.task}\\n\\nThe worktree setup handoff is ${record.setupStage}. Inspect the runner \"worktree-setup\" before relying on dependencies or deciding whether to retry. Do not retry automatically.`,\n metadata: {\n worktreeId: record.id,\n fromRole: 'parent',\n text: request.task,\n sentAt: record.createdAt,\n },\n });\n const admission = await taskDelivery.waitForAdmission(receipt.deliveryId);\n if (admission !== 'admitted') {\n throw new PoGitExpectedError(\n 'task_delivery_failed',\n `Worktree ${record.id} was created and task delivery ${receipt.deliveryId} was persisted, but admission ${admission === 'recovery_required' ? 'requires recovery' : 'was not confirmed before the timeout'}.`,\n true,\n admission === 'recovery_required'\n ? `Call messages from worktree ${record.id} to recover the task in the recipient session. Do not resend it automatically.`\n : `Check delivery ${receipt.deliveryId} in the sender outbox or call messages from worktree ${record.id} in the recipient session before deciding whether to resend.`,\n );\n }\n } catch (error) {\n if (error instanceof PoGitExpectedError) throw error;\n throw new PoGitExpectedError(\n 'task_delivery_failed',\n `Worktree ${record.id} was created, but task delivery failed (${String(error)}).`,\n true,\n `Inspect worktree ${record.id} and the sender outbox before using send to deliver the task. Do not recreate the worktree.`,\n );\n }\n }\n if (request.reservationId !== undefined) await reservations!.complete(request.reservationId, parentSessionId!);\n return coneFolders === undefined ? record : { ...record, coneFolders };\n },\n\n async linkWorkflow(context, id, workflow) {\n const { store, records } = await resolve(context);\n const record = require(records, id);\n if (\n record.parentSessionId !== context.sessionId ||\n record.workflow?.attemptId !== workflow.attemptId ||\n record.workflow.fingerprint !== workflow.fingerprint\n )\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The workflow does not own this checkout.',\n false,\n 'Inspect the recorded workflow owner.',\n );\n if (\n (record.workflow.admissionId && record.workflow.admissionId !== workflow.admissionId) ||\n (record.workflow.runId && record.workflow.runId !== workflow.runId) ||\n (record.workflow.state === 'retained' && workflow.state !== 'retained')\n )\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The workflow admission or terminal identity changed.',\n false,\n 'Keep and inspect the recorded workflow.',\n );\n const updated = { ...record, workflow };\n await store.replace(records.map((entry) => (entry.id === id ? updated : entry)));\n return updated;\n },\n\n async close(context, id, force, expectedWorkflow) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n if (\n expectedWorkflow &&\n (record.status !== 'running' ||\n record.workflow?.state !== 'admitted' ||\n record.sessionId !== expectedWorkflow.sessionId ||\n record.path !== expectedWorkflow.path ||\n (await revision(record.path, 'HEAD', { env: deps.environment ?? {}, signal: operation().signal })) !==\n expectedWorkflow.head ||\n record.parentSessionId !== context.sessionId ||\n ['attemptId', 'fingerprint', 'admissionId', 'runId'].some(\n (key) =>\n record.workflow?.[key as keyof WorktreeWorkflow] !== expectedWorkflow[key as keyof WorktreeWorkflow],\n ))\n )\n throw new PoGitExpectedError(\n 'invalid_request',\n 'The workflow checkout evidence changed.',\n false,\n 'Keep and inspect this checkout.',\n );\n const dirtyFiles = (await probe.exists(record.path)) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new PoGitExpectedError('worktree_dirty', refusal, false, 'Commit the work, or pass force: true.');\n }\n // The session is stopped before the directory goes. Removing a checkout\n // while a process still holds files open in it is how a half-removed\n // worktree and a stale git administrative entry are made.\n await requireSessionService().close(record.sessionId);\n await removeCheckout(root, record, force);\n await store.replace(records.filter((entry) => entry.id !== id));\n return record;\n },\n\n async list(context) {\n const { store, records } = await resolve(context);\n const outcome = await reconcile(records, probe);\n if (outcome.changed.length > 0) await store.replace(outcome.records);\n return outcome.records;\n },\n\n async status(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const dirtyFiles = (await probe.exists(record.path)) ? await git.dirtyFiles(record.path) : [];\n return { record, dirtyFiles };\n },\n\n async merge(context, id, message) {\n const { root, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'merge');\n // The merge lands in the parent, so the parent is what must be clean. A\n // dirty parent would mix the person's in-flight edits into a merge commit\n // they did not intend to make.\n const parentDirty = await git.dirtyFiles(root);\n if (parentDirty.length > 0) {\n throw new PoGitExpectedError(\n 'worktree_dirty',\n `The parent checkout has ${String(parentDirty.length)} uncommitted file(s): ${parentDirty.slice(0, 10).join(', ')}.`,\n false,\n 'Commit or stash the parent checkout first.',\n );\n }\n if (record.backend === 'rift')\n await rift.fetchBranch({ repositoryRoot: root, path: record.path, branch: record.branch });\n await git.mergeBranch({\n repositoryRoot: root,\n branch: record.branch,\n ...(message === undefined ? {} : { message }),\n });\n return record;\n },\n\n /** Sends only between the parent session and its own worktree session. */\n async send(context, id, message) {\n if (Buffer.byteLength(message, 'utf8') > MAX_WORKTREE_MESSAGE_BYTES) {\n throw new PoGitExpectedError(\n 'message_too_large',\n `A message may not exceed ${String(MAX_WORKTREE_MESSAGE_BYTES)} bytes.`,\n false,\n 'Send a shorter message.',\n );\n }\n const { records } = await resolve(context);\n const record = require(records, id);\n const peer = peerFor(context, record);\n requirePeerLive(peer.sessionId);\n const sentAt = new Date().toISOString();\n const delivery = readSessionDelivery();\n if (delivery !== undefined) {\n const kind = peer.party === 'parent' ? GIT_WORKTREE_MESSAGE_KIND : GIT_WORKTREE_REPORT_KIND;\n const receipt = await delivery.deliver({\n recipientKey: peer.sessionId,\n kind,\n prompt:\n peer.party === 'parent'\n ? `Parent message for worktree ${record.id}:\\n\\n${message}`\n : `Report from worktree ${record.id}:\\n\\n${message}`,\n metadata: { worktreeId: record.id, fromRole: peer.party, text: message, sentAt },\n });\n const admission = await delivery.waitForAdmission(receipt.deliveryId);\n if (admission !== 'admitted') {\n throw new PoGitExpectedError(\n 'message_delivery_failed',\n `Worktree ${record.id} persisted message delivery ${receipt.deliveryId}, but admission ${admission === 'recovery_required' ? 'requires recovery' : 'was not confirmed before the timeout'}.`,\n true,\n admission === 'recovery_required'\n ? `Call messages from the recipient session to recover delivery ${receipt.deliveryId}. Do not resend it automatically.`\n : `Check delivery ${receipt.deliveryId} in the sender outbox or call messages from the recipient session before deciding whether to resend.`,\n );\n }\n return;\n }\n requireMessageInbox().send(peer.sessionId, {\n version: 1,\n worktreeId: record.id,\n // peerFor only answers for the worktree's parent or child session, so the caller has one.\n fromSessionId: context.sessionId!,\n from: peer.party,\n text: message,\n sentAt,\n });\n },\n\n async messages(context, id) {\n const { records } = await resolve(context);\n const record = require(records, id);\n const peer = peerFor(context, record);\n const delivery = readSessionDelivery();\n if (delivery === undefined) return requireMessageInbox().receive(record.id);\n const entries = (await delivery.inbox({ consumed: false, metadata: { worktreeId: record.id } })).filter(\n (entry) =>\n entry.senderKey === peer.sessionId &&\n (entry.state === 'admitted' || entry.state === 'recovery_required') &&\n (peer.party === 'parent'\n ? entry.kind === GIT_WORKTREE_REPORT_KIND\n : entry.kind === GIT_WORKTREE_MESSAGE_KIND || entry.kind === GIT_WORKTREE_DELEGATION_KIND),\n );\n for (const entry of entries) await delivery.consume(entry.deliveryId);\n return entries.map((entry) => ({\n version: 1,\n worktreeId: record.id,\n fromSessionId: entry.senderKey,\n from: peer.party === 'parent' ? ('child' as const) : ('parent' as const),\n text:\n entry.state === 'recovery_required'\n ? `[Recovery required: prompt admission was not confirmed] ${entry.metadata.text ?? entry.prompt}`\n : (entry.metadata.text ?? entry.prompt),\n sentAt: entry.metadata.sentAt ?? '',\n }));\n },\n\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = await reconcile(records, probe);\n const gitPaths = await listedPaths(root, reconciled.records);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && (await probe.exists(record.path))) {\n dirtyByPath.set(record.path, await git.dirtyFiles(record.path));\n }\n }\n const plan = planPrune({\n records: reconciled.records,\n gitPaths,\n worktreesRoot: worktreesRoot(deps.homeDir, deps.environment),\n dirtyByPath,\n });\n if (dryRun) {\n await store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await removeCheckout(root, record, false);\n }\n // The checkout goes, so the branch it was made for goes with it. Safe\n // delete only: git keeps anything holding commits, and the plan says\n // which ones it kept rather than leaving the reader to notice later.\n for (const record of [...plan.remove, ...plan.forget]) {\n const deleted = await git.deleteBranch({ repositoryRoot: root, branch: record.branch }).catch(() => false);\n // A Rift branch lives in the removed copy; one in the root exists only if it was merged.\n if (!deleted && record.backend !== 'rift') plan.keptBranches.push(record.branch);\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n await store.replace(reconciled.records.filter((record) => !dropped.has(record.id)));\n return plan;\n },\n };\n const locked = async <T>(context: WorktreeContext, operation: () => Promise<T>, signal?: AbortSignal): Promise<T> => {\n try {\n const { store } = await resolve(context);\n return await store.transaction(operation, signal);\n } catch (error) {\n if (signal?.aborted && !(error instanceof PoGitExpectedError))\n throw new PoGitExpectedError(\n 'spawn_cancelled',\n 'The worktree operation was cancelled.',\n false,\n 'Inspect its recorded state before retrying.',\n );\n if (error instanceof SparoError && error.code !== 'COMMAND_FAILED')\n throw new PoGitExpectedError(\n 'invalid_request',\n error.message,\n false,\n 'Run sparo init explicitly before sparse checkout, or fix the configured profile.',\n );\n if (['ENOTDIR', 'EACCES', 'EROFS', 'ENOSPC'].includes(String((error as NodeJS.ErrnoException).code)))\n throw new PoGitExpectedError(\n 'registry_write_failed',\n 'The worktree registry is not writable.',\n true,\n 'Check permissions and free space before retrying.',\n );\n throw error;\n }\n };\n // ponytail: serialize Git lifecycle mutations, not session execution. Keeping\n // the lock across startup avoids a second lease system for partially created trees.\n return {\n ...operations,\n spawn: (context, request, options) => {\n if (sessionService === undefined)\n return Promise.reject(\n new PoGitExpectedError(\n 'hub_unavailable',\n 'The cockpit session service is unavailable.',\n true,\n 'Use the cockpit worktree tool after its Git server plugin is available.',\n ),\n );\n // Checked before the repository lock, so unsafe input never reaches git at all.\n if (\n (request.sparseProfile !== undefined && !validSparseProfile(request.sparseProfile)) ||\n !validRefName(request.branch) ||\n (request.baseRef !== undefined && !validRefName(request.baseRef))\n )\n return Promise.reject(\n new PoGitExpectedError('invalid_request', 'That is not a valid branch name.', false, 'Pick another name.'),\n );\n if (request.reservationId !== undefined && context.sessionId === undefined)\n return Promise.reject(\n new PoGitExpectedError(\n 'invalid_request',\n 'A reserved worktree session requires its owning parent.',\n false,\n 'Create the session from its pending setup card.',\n ),\n );\n return locked(context, () => operations.spawn(context, request, options), options?.signal);\n },\n expand: (context, id, folders, options) => {\n if (\n !Array.isArray(folders) ||\n folders.length === 0 ||\n !folders.every((folder) => ConeFolder.safeParse(folder).success)\n )\n return Promise.reject(\n new PoGitExpectedError(\n 'invalid_request',\n 'Pass nonempty relative cone folders.',\n false,\n 'Use repository-relative folders.',\n ),\n );\n return locked(context, () => operations.expand(context, id, folders, options), options?.signal);\n },\n reapply: (context, id, options) => locked(context, () => operations.reapply(context, id, options), options?.signal),\n linkWorkflow: (context, id, workflow) => locked(context, () => operations.linkWorkflow(context, id, workflow)),\n close: (context, id, force, expectedWorkflow) =>\n locked(context, () => operations.close(context, id, force, expectedWorkflow)),\n list: (context) => locked(context, () => operations.list(context)),\n merge: (context, id, message) => locked(context, () => operations.merge(context, id, message)),\n prune: (context, dryRun) => locked(context, () => operations.prune(context, dryRun)),\n };\n}\n","import { createRequire } from 'node:module';\n\nimport { BACKGROUND_CONTEXT, PO_FS_SERVICE, requirePoFs, withAbortSignal } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\nimport { readPoWorkspaceRegistry } from '@agimon-ai/po-core/workspaceRegistry';\nimport { PO_GIT_ENGINE_SERVICE, type GitEngineService } from '@agimon-ai/po-sparo';\n\nimport '../../schemas/gitEngine';\nimport type { GitExtensionDependencies } from '../../types/extension';\nimport { DefaultGitExtensionService } from '../extensionService';\n// @scaffold-generated\nimport { createWorktreeGit } from '../gitCli';\nimport { createWorktreeConfigReader } from '../worktreeConfig';\nimport { startWorktreeSetup } from '../worktreeEvents';\nimport type { WorktreeOperationsDeps } from '../worktreeOperations';\nimport { createWorktreeOperations } from '../worktreeOperations';\n\nexport function createGitDependencies(overrides: Partial<GitExtensionDependencies> = {}): GitExtensionDependencies {\n return {\n service: overrides.service ?? new DefaultGitExtensionService(),\n operations: overrides.operations ?? createWorktreeOperations({ git: createWorktreeGit() }),\n };\n}\n\n/** One admitted environment and config snapshot per session or API composition. */\nexport function createGitOperationDependencies(\n { context, host, signal }: Pick<PoServerPluginContext, 'context' | 'host' | 'signal'>,\n scope: { environment?: Readonly<Record<string, string | undefined>>; workspaceId?: string } = host.context,\n): Pick<\n WorktreeOperationsDeps,\n 'gitEngine' | 'worktreeConfig' | 'environment' | 'homeDir' | 'signal' | 'startSetup' | 'sparoCliPath'\n> {\n let files: ReturnType<typeof requirePoFs> | undefined;\n let gitEngine: GitEngineService | undefined;\n context.inject([PO_FS_SERVICE], (child) => {\n files = requirePoFs(child);\n return () => {\n files = undefined;\n };\n });\n context.inject([PO_GIT_ENGINE_SERVICE], (child) => {\n gitEngine = child.get(PO_GIT_ENGINE_SERVICE);\n return () => {\n gitEngine = undefined;\n };\n });\n return {\n gitEngine: () => gitEngine,\n sparoCliPath: () => createRequire(import.meta.url).resolve('@agimon-ai/po-sparo/bin/cli'),\n startSetup: (sessionId, command, setupSignal) =>\n host.context.directEvents\n ? startWorktreeSetup(host.context.directEvents, sessionId, command, setupSignal)\n : Promise.resolve('unconfirmed'),\n environment: scope.environment ?? {},\n homeDir: host.context.homeDirectory,\n signal,\n worktreeConfig: createWorktreeConfigReader({\n async readTextFile(file) {\n if (!files) throw new Error('The Git host filesystem is unavailable.');\n const result = await files.readTextFile(file, withAbortSignal(signal, BACKGROUND_CONTEXT));\n if (!result.ok) throw result.error;\n return result.value;\n },\n async readMetadata() {\n const registry = readPoWorkspaceRegistry(context);\n if (!scope.workspaceId || !registry) return undefined;\n const result = await registry.resolve({ id: scope.workspaceId });\n return result.status === 'found' ? result.workspace.metadata : undefined;\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAa,6BAAb,MAAuE;CACrE,MAAM,UAAuC;EAC3C,OAAO;GAAE,SAAS;GAA4C,OAAO;EAAO;CAC9E;AACF;;;ACJA,MAAa,uBAAA,GAAsBA,gCAAAA,sBAAAA,CAAwCC,oBAAAA,uBAAuB,EAChG,OAAO,YACT,CAAC;;;;;;;;;;;;;ACWD,MAAa,kBAAkB;AAC/B,MAAM,iBAAiB;AACvB,MAAMC,sBAAoB;AAC1B,MAAM,mBAAmB;;AAEzB,MAAa,qBAAqB;;AAElC,MAAa,oBAAoB;AACjC,MAAM,mBAAmB;;AAEzB,MAAM,kBAAkB;AACxB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,cAAc;;;;;;;;;;;;AA+BpB,SAAgB,OAAO,KAAa,MAAyB,SAA4C;CACvG,OAAO,IAAI,SAAS,YAAY;EAC9B,CAAA,GAAA,mBAAA,SAAA,CACE,OACA,CAAC,GAAG,IAAI,GACR;GACE;GACA,GAAI,QAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;GACjE,SAAS,QAAQ;GACjB,WAAW,QAAQ,aAAa;GAChC,KAAK;IAAE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