@agimon-ai/doompi-git 0.0.1-alpha.30 → 0.0.1-alpha.32

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 (41) hide show
  1. package/README.md +10 -0
  2. package/dist/apiContracts.cjs +51 -2
  3. package/dist/apiContracts.cjs.map +1 -1
  4. package/dist/apiContracts.mjs +51 -2
  5. package/dist/apiContracts.mjs.map +1 -1
  6. package/dist/extensions/pi.cjs +4 -8
  7. package/dist/extensions/pi.cjs.map +1 -1
  8. package/dist/extensions/pi.d.mts +1 -1
  9. package/dist/extensions/pi.mjs +2 -6
  10. package/dist/extensions/pi.mjs.map +1 -1
  11. package/dist/extensions/server.cjs +98 -5
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.mjs +98 -5
  14. package/dist/extensions/server.mjs.map +1 -1
  15. package/dist/extensions/web.mjs +334 -3
  16. package/dist/extensions/web.mjs.map +1 -1
  17. package/dist/{gitDependencies-D-EUEIkE.mjs → gitDependencies-CJFmhrG1.mjs} +2 -2
  18. package/dist/{gitDependencies-D-EUEIkE.mjs.map → gitDependencies-CJFmhrG1.mjs.map} +1 -1
  19. package/dist/{gitDependencies-DKJr5kLQ.cjs → gitDependencies-CWsygnLQ.cjs} +2 -2
  20. package/dist/{gitDependencies-DKJr5kLQ.cjs.map → gitDependencies-CWsygnLQ.cjs.map} +1 -1
  21. package/dist/{index-BQq2vblZ.d.mts → index-D79MSCee.d.mts} +15 -13
  22. package/dist/index-D79MSCee.d.mts.map +1 -0
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.d.mts +1 -1
  25. package/dist/index.mjs +1 -1
  26. package/dist/{runWorktree-BL99h9oH.mjs → runWorktree-BdK3oRtX.mjs} +18 -9
  27. package/dist/runWorktree-BdK3oRtX.mjs.map +1 -0
  28. package/dist/{runWorktree-B6ikYRrG.cjs → runWorktree-D0bsyYc0.cjs} +41 -8
  29. package/dist/runWorktree-D0bsyYc0.cjs.map +1 -0
  30. package/dist/{worktreeOperations-DAbs0ZTX.mjs → worktreeOperations-CijBzYEf.mjs} +130 -21
  31. package/dist/worktreeOperations-CijBzYEf.mjs.map +1 -0
  32. package/dist/{worktreeOperations-DjO_Y5Yv.cjs → worktreeOperations-FJDk44Zt.cjs} +135 -20
  33. package/dist/worktreeOperations-FJDk44Zt.cjs.map +1 -0
  34. package/llms.txt +4 -0
  35. package/package.json +8 -7
  36. package/src/prompts/doompi-use-git/SKILL.md +21 -1
  37. package/dist/index-BQq2vblZ.d.mts.map +0 -1
  38. package/dist/runWorktree-B6ikYRrG.cjs.map +0 -1
  39. package/dist/runWorktree-BL99h9oH.mjs.map +0 -1
  40. package/dist/worktreeOperations-DAbs0ZTX.mjs.map +0 -1
  41. package/dist/worktreeOperations-DjO_Y5Yv.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"runWorktree-B6ikYRrG.cjs","names":["Type","invalidRequest"],"sources":["../src/schemas/runWorktreeTool.ts","../src/services/runWorktree/index.ts"],"sourcesContent":["import { type Static, Type } from 'typebox';\n\n/**\n * The tool's action vocabulary.\n *\n * One tool with an action field rather than six tools, matching `subagent`:\n * the actions share a subject and are meaningless apart from it, and six\n * separate tools would spend six description budgets teaching the same nouns.\n */\nexport const WORKTREE_ACTIONS = {\n spawn_worktree: 'spawn_worktree',\n close_worktree: 'close_worktree',\n list: 'list',\n status: 'status',\n merge: 'merge',\n prune: 'prune',\n send: 'send',\n messages: 'messages',\n} as const;\n\nexport type WorktreeAction = (typeof WORKTREE_ACTIONS)[keyof typeof WORKTREE_ACTIONS];\n\n/**\n * Which fields each action accepts.\n *\n * Rejecting an unknown field is what stops a plausible-looking call from doing\n * something other than what it reads like: `close_worktree` with `branch`\n * instead of `id` would otherwise close whatever the default resolved to.\n */\nexport const WORKTREE_ACTION_FIELDS: Record<WorktreeAction, readonly string[]> = {\n spawn_worktree: ['action', 'branch', 'baseRef', 'task', 'name'],\n close_worktree: ['action', 'id', 'force'],\n list: ['action'],\n status: ['action', 'id'],\n merge: ['action', 'id', 'message'],\n prune: ['action', 'dryRun'],\n send: ['action', 'id', 'message'],\n messages: ['action', 'id'],\n};\n\nconst SpawnParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.spawn_worktree),\n branch: Type.String({ minLength: 1 }),\n baseRef: Type.Optional(Type.String({ minLength: 1 })),\n task: Type.Optional(Type.String({ minLength: 1 })),\n name: Type.Optional(Type.String({ minLength: 1 })),\n },\n { additionalProperties: false },\n);\n\nconst CloseParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.close_worktree),\n id: Type.String({ minLength: 1 }),\n force: Type.Optional(Type.Boolean()),\n },\n { additionalProperties: false },\n);\n\nconst ListParams = Type.Object({ action: Type.Literal(WORKTREE_ACTIONS.list) }, { additionalProperties: false });\n\nconst StatusParams = Type.Object(\n { action: Type.Literal(WORKTREE_ACTIONS.status), id: Type.String({ minLength: 1 }) },\n { additionalProperties: false },\n);\n\nconst MergeParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.merge),\n id: Type.String({ minLength: 1 }),\n message: Type.Optional(Type.String({ minLength: 1 })),\n },\n { additionalProperties: false },\n);\n\nconst PruneParams = Type.Object(\n { action: Type.Literal(WORKTREE_ACTIONS.prune), dryRun: Type.Optional(Type.Boolean()) },\n { additionalProperties: false },\n);\n\nconst SendParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.send),\n id: Type.String({ minLength: 1 }),\n message: Type.String({ minLength: 1 }),\n },\n { additionalProperties: false },\n);\n\nconst MessagesParams = Type.Object(\n { action: Type.Literal(WORKTREE_ACTIONS.messages), id: Type.String({ minLength: 1 }) },\n { additionalProperties: false },\n);\n\nexport const RunWorktreeParams = Type.Union([\n SpawnParams,\n CloseParams,\n ListParams,\n StatusParams,\n MergeParams,\n PruneParams,\n SendParams,\n MessagesParams,\n]);\n\n/** The actions that accept `field`, so the declared docs cannot drift from the validator. */\nfunction acceptingActions(field: string): string {\n return Object.values(WORKTREE_ACTIONS)\n .filter((action) => WORKTREE_ACTION_FIELDS[action].includes(field))\n .join(', ');\n}\n\n/**\n * The schema declared to the model.\n *\n * A flat object rather than `RunWorktreeParams` itself. A top-level union is\n * `{anyOf:[...]}` with no `properties`, and Pi's Anthropic Messages adapter\n * rebuilds tool input as `{type:'object', properties: schema.properties ?? {},\n * required: schema.required ?? []}`, so the union arrived at the model as an\n * empty object while the host went on validating calls against it. Nothing here\n * relaxes what is accepted: `validateParams` still rejects an unknown action, a\n * field the action does not take, and a missing required one.\n */\nexport const RunWorktreeToolSchema = Type.Object(\n {\n action: Type.String({\n enum: Object.values(WORKTREE_ACTIONS),\n description: 'The operation to run. Every other field is accepted only by the actions its description names.',\n }),\n branch: Type.Optional(\n Type.String({ minLength: 1, description: `New branch to create. Actions: ${acceptingActions('branch')}.` }),\n ),\n baseRef: Type.Optional(\n Type.String({\n minLength: 1,\n description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions('baseRef')}.`,\n }),\n ),\n task: Type.Optional(\n Type.String({\n minLength: 1,\n description: `First message for the new session. Actions: ${acceptingActions('task')}.`,\n }),\n ),\n name: Type.Optional(\n Type.String({ minLength: 1, description: `Rail label for the worktree. Actions: ${acceptingActions('name')}.` }),\n ),\n id: Type.Optional(Type.String({ minLength: 1, description: `Worktree id. Actions: ${acceptingActions('id')}.` })),\n force: Type.Optional(\n Type.Boolean({ description: `Close even when the tree is dirty. Actions: ${acceptingActions('force')}.` }),\n ),\n message: Type.Optional(\n Type.String({\n minLength: 1,\n description: `Merge commit message, or the text to send. Actions: ${acceptingActions('message')}.`,\n }),\n ),\n dryRun: Type.Optional(\n Type.Boolean({\n description: `Report the plan without destroying anything. Actions: ${acceptingActions('dryRun')}.`,\n }),\n ),\n },\n { additionalProperties: false },\n);\n\nexport type RunWorktreeToolParams = Static<typeof RunWorktreeParams>;\n","import {\n RunWorktreeParams,\n WORKTREE_ACTION_FIELDS,\n WORKTREE_ACTIONS,\n type WorktreeAction,\n type RunWorktreeToolParams,\n} from '../../schemas/runWorktreeTool';\nimport type { WorktreeRecord } from '../../types/worktreeRegistry';\nimport { invalidRequest } from '../errors';\nimport type { WorktreeOperations } from '../worktreeOperations';\n\nexport { RunWorktreeParams };\nexport type { RunWorktreeToolParams, WorktreeAction };\n\nexport const RUN_WORKTREE_TOOL_NAME = 'run_worktree';\n\nconst IMPLEMENTED_ACTIONS: ReadonlySet<string> = new Set(Object.values(WORKTREE_ACTIONS));\n\nexport const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its own DoomPi session nested under this one.\n\nActions:\n- spawn_worktree: create a worktree on a new branch and start a session in it. Requires 'branch'. Optional 'baseRef' (defaults to the current branch's remote-tracking ref, then the remote default branch), 'name' for the rail, 'task' as the first message.\n- close_worktree: stop a worktree's session, delete its checkout, and remove its generated sync storage. Requires 'id'. Refuses a dirty tree unless 'force' is true.\n- list: every worktree for this repository, with status.\n- status: one worktree and its uncommitted files. Requires 'id'.\n- merge: merge a worktree's branch into this checkout. Requires 'id'. Refuses when this checkout is dirty.\n- prune: remove orphaned worktrees and their generated sync storage. Pass 'dryRun' to see the plan without destroying anything.\n- send: send a message to the other side of a worktree. Requires 'id' and 'message'.\n- messages: read messages waiting for you from a worktree. Requires 'id'.\n\nWorktrees live outside the repository, under ~/.pi/.doom/git/worktrees.`;\n\nexport interface RunWorktreeToolDetails {\n action: WorktreeAction;\n records?: WorktreeRecord[];\n}\n\nexport interface RunWorktreeToolResult {\n content: [{ type: 'text'; text: string }];\n details: RunWorktreeToolDetails;\n}\n\nexport interface RunWorktreeExecutionContext {\n readonly cwd: string;\n readonly sessionId: string;\n}\n\nexport interface RunWorktreeExecutionOptions {\n readonly signal?: AbortSignal;\n readonly onProgress?: (label: string) => void;\n}\n\n/** Rejects calls that do not match one documented action shape. */\nexport function validateParams(input: unknown): RunWorktreeToolParams {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw invalidRequest('run_worktree parameters must be an object.', 'Call it with one documented action shape.');\n }\n const record = input as Record<string, unknown>;\n const action = record.action;\n if (typeof action !== 'string' || !IMPLEMENTED_ACTIONS.has(action)) {\n throw invalidRequest(\n `Unknown action ${typeof action === 'string' ? `'${action}'` : 'value'}.`,\n `Use one of: ${[...IMPLEMENTED_ACTIONS].join(', ')}.`,\n );\n }\n const allowed = WORKTREE_ACTION_FIELDS[action as WorktreeAction];\n const unexpected = Object.keys(record).filter((key) => !allowed.includes(key));\n if (unexpected.length > 0) {\n throw invalidRequest(\n `action='${action}' does not accept: ${unexpected.join(', ')}.`,\n `Fields for '${action}': ${allowed.join(', ')}.`,\n );\n }\n for (const field of ['branch', 'id'] as const) {\n if (allowed.includes(field) && field in record) {\n const value = record[field];\n if (typeof value !== 'string' || value.trim() === '') {\n throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);\n }\n }\n }\n const stringFields = ['baseRef', 'name', 'task', 'message'] as const;\n for (const field of stringFields) {\n if (field in record && (typeof record[field] !== 'string' || record[field].trim() === '')) {\n throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);\n }\n }\n for (const field of ['force', 'dryRun'] as const) {\n if (field in record && typeof record[field] !== 'boolean') {\n throw invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);\n }\n }\n if (action === WORKTREE_ACTIONS.send && typeof record.message !== 'string') {\n throw invalidRequest(\"action='send' requires 'message'.\", 'Pass the message to send.');\n }\n if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== 'string') {\n throw invalidRequest(\"action='spawn_worktree' requires 'branch'.\", 'Name the branch to create.');\n }\n if (\n (action === WORKTREE_ACTIONS.close_worktree ||\n action === WORKTREE_ACTIONS.status ||\n action === WORKTREE_ACTIONS.merge ||\n action === WORKTREE_ACTIONS.send ||\n action === WORKTREE_ACTIONS.messages) &&\n typeof record.id !== 'string'\n ) {\n throw invalidRequest(`action='${action}' requires 'id'.`, 'Call list to see the current ids.');\n }\n return record as RunWorktreeToolParams;\n}\n\nfunction describe(record: WorktreeRecord): string {\n return `${record.id} ${record.branch} ${record.status} ${record.path}`;\n}\n\nfunction text(...lines: readonly string[]): [{ type: 'text'; text: string }] {\n return [{ type: 'text', text: lines.join('\\n') }];\n}\n\nexport async function executeRunWorktreeTool(\n params: RunWorktreeToolParams,\n operations: WorktreeOperations,\n context: RunWorktreeExecutionContext,\n options: RunWorktreeExecutionOptions = {},\n): Promise<RunWorktreeToolResult> {\n switch (params.action) {\n case WORKTREE_ACTIONS.spawn_worktree: {\n const record = await operations.spawn(\n context,\n {\n branch: params.branch,\n ...(params.baseRef === undefined ? {} : { baseRef: params.baseRef }),\n ...(params.name === undefined ? {} : { name: params.name }),\n ...(params.task === undefined ? {} : { task: params.task }),\n },\n options,\n );\n return {\n content: text(\n `Worktree ${record.id} created on ${record.branch} from ${record.baseRef}.`,\n `Path: ${record.path}`,\n params.task === undefined\n ? `Session ${record.sessionId} is starting; it appears nested under this one in the rail.`\n : `Session ${record.sessionId} is starting with its task; it appears nested under this one in the rail.`,\n ),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.close_worktree: {\n const record = await operations.close(context, params.id, params.force ?? false);\n return {\n content: text(`Worktree ${record.id} (${record.branch}) closed and removed.`),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.list: {\n const records = await operations.list(context);\n return {\n content:\n records.length === 0\n ? text('No worktrees for this repository.')\n : text(`${String(records.length)} worktree(s):`, ...records.map(describe)),\n details: { action: params.action, records },\n };\n }\n case WORKTREE_ACTIONS.status: {\n const { record, dirtyFiles } = await operations.status(context, params.id);\n return {\n content: text(\n describe(record),\n `Session: ${record.sessionId}`,\n dirtyFiles.length === 0\n ? 'Clean.'\n : `${String(dirtyFiles.length)} uncommitted file(s): ${dirtyFiles.slice(0, 20).join(', ')}`,\n ),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.merge: {\n const record = await operations.merge(\n context,\n params.id,\n ...(params.message === undefined ? [] : ([params.message] as const)),\n );\n return {\n content: text(`Merged ${record.branch} into this checkout.`),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.send: {\n await operations.send(context, params.id, params.message);\n return { content: text(`Message sent to worktree ${params.id}.`), details: { action: params.action } };\n }\n case WORKTREE_ACTIONS.messages: {\n const waiting = await operations.messages(context, params.id);\n return {\n content:\n waiting.length === 0\n ? text('No messages.')\n : text(\n `${String(waiting.length)} message(s):`,\n ...waiting.map((entry) => `[${entry.sentAt}] ${entry.from}: ${entry.text}`),\n ),\n details: { action: params.action },\n };\n }\n case WORKTREE_ACTIONS.prune: {\n const dryRun = params.dryRun ?? false;\n const plan = await operations.prune(context, dryRun);\n const lines = [\n dryRun ? 'Prune plan (nothing was changed):' : 'Pruned:',\n `Remove: ${plan.remove.length === 0 ? 'none' : plan.remove.map((record) => record.id).join(', ')}`,\n `Forget: ${plan.forget.length === 0 ? 'none' : plan.forget.map((record) => record.id).join(', ')}`,\n `Kept, uncommitted work: ${plan.keptDirty.length === 0 ? 'none' : plan.keptDirty.map((record) => record.id).join(', ')}`,\n `Untracked directories, left alone: ${plan.untracked.length === 0 ? 'none' : plan.untracked.join(', ')}`,\n ...(plan.keptBranches.length === 0\n ? []\n : [`Branches kept, they hold commits: ${plan.keptBranches.join(', ')}`]),\n ];\n return { content: text(...lines), details: { action: params.action } };\n }\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,mBAAmB;CAC9B,gBAAgB;CAChB,gBAAgB;CAChB,MAAM;CACN,QAAQ;CACR,OAAO;CACP,OAAO;CACP,MAAM;CACN,UAAU;AACZ;;;;;;;;AAWA,MAAa,yBAAoE;CAC/E,gBAAgB;EAAC;EAAU;EAAU;EAAW;EAAQ;CAAM;CAC9D,gBAAgB;EAAC;EAAU;EAAM;CAAO;CACxC,MAAM,CAAC,QAAQ;CACf,QAAQ,CAAC,UAAU,IAAI;CACvB,OAAO;EAAC;EA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OAAO,EAAE;GAC5D,OAAO;IACL,SACE,QAAQ,WAAW,IACf,KAAK,cAAc,IACnB,KACE,GAAG,OAAO,QAAQ,MAAM,EAAE,eAC1B,GAAG,QAAQ,KAAK,UAAU,IAAI,MAAM,OAAO,IAAI,MAAM,KAAK,IAAI,MAAM,MAAM,CAC5E;IACN,SAAS,EAAE,QAAQ,OAAO,OAAO;GACnC;EACF;EACA,KAAK,iBAAiB,OAAO;GAC3B,MAAM,SAAS,OAAO,UAAU;GAChC,MAAM,OAAO,MAAM,WAAW,MAAM,SAAS,MAAM;GAWnD,OAAO;IAAE,SAAS,KAAK,GAAG;KATxB,SAAS,sCAAsC;KAC/C,WAAW,KAAK,OAAO,WAAW,IAAI,SAAS,KAAK,OAAO,KAAK,WAAW,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;KAC/F,WAAW,KAAK,OAAO,WAAW,IAAI,SAAS,KAAK,OAAO,KAAK,WAAW,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;KAC/F,2BAA2B,KAAK,UAAU,WAAW,IAAI,SAAS,KAAK,UAAU,KAAK,WAAW,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;KACrH,sCAAsC,KAAK,UAAU,WAAW,IAAI,SAAS,KAAK,UAAU,KAAK,IAAI;KACrG,GAAI,KAAK,aAAa,WAAW,IAC7B,CAAC,IACD,CAAC,qCAAqC,KAAK,aAAa,KAAK,IAAI,GAAG;IAE5C,CAAC;IAAG,SAAS,EAAE,QAAQ,OAAO,OAAO;GAAE;EACvE;CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runWorktree-BL99h9oH.mjs","names":[],"sources":["../src/schemas/runWorktreeTool.ts","../src/services/runWorktree/index.ts"],"sourcesContent":["import { type Static, Type } from 'typebox';\n\n/**\n * The tool's action vocabulary.\n *\n * One tool with an action field rather than six tools, matching `subagent`:\n * the actions share a subject and are meaningless apart from it, and six\n * separate tools would spend six description budgets teaching the same nouns.\n */\nexport const WORKTREE_ACTIONS = {\n spawn_worktree: 'spawn_worktree',\n close_worktree: 'close_worktree',\n list: 'list',\n status: 'status',\n merge: 'merge',\n prune: 'prune',\n send: 'send',\n messages: 'messages',\n} as const;\n\nexport type WorktreeAction = (typeof WORKTREE_ACTIONS)[keyof typeof WORKTREE_ACTIONS];\n\n/**\n * Which fields each action accepts.\n *\n * Rejecting an unknown field is what stops a plausible-looking call from doing\n * something other than what it reads like: `close_worktree` with `branch`\n * instead of `id` would otherwise close whatever the default resolved to.\n */\nexport const WORKTREE_ACTION_FIELDS: Record<WorktreeAction, readonly string[]> = {\n spawn_worktree: ['action', 'branch', 'baseRef', 'task', 'name'],\n close_worktree: ['action', 'id', 'force'],\n list: ['action'],\n status: ['action', 'id'],\n merge: ['action', 'id', 'message'],\n prune: ['action', 'dryRun'],\n send: ['action', 'id', 'message'],\n messages: ['action', 'id'],\n};\n\nconst SpawnParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.spawn_worktree),\n branch: Type.String({ minLength: 1 }),\n baseRef: Type.Optional(Type.String({ minLength: 1 })),\n task: Type.Optional(Type.String({ minLength: 1 })),\n name: Type.Optional(Type.String({ minLength: 1 })),\n },\n { additionalProperties: false },\n);\n\nconst CloseParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.close_worktree),\n id: Type.String({ minLength: 1 }),\n force: Type.Optional(Type.Boolean()),\n },\n { additionalProperties: false },\n);\n\nconst ListParams = Type.Object({ action: Type.Literal(WORKTREE_ACTIONS.list) }, { additionalProperties: false });\n\nconst StatusParams = Type.Object(\n { action: Type.Literal(WORKTREE_ACTIONS.status), id: Type.String({ minLength: 1 }) },\n { additionalProperties: false },\n);\n\nconst MergeParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.merge),\n id: Type.String({ minLength: 1 }),\n message: Type.Optional(Type.String({ minLength: 1 })),\n },\n { additionalProperties: false },\n);\n\nconst PruneParams = Type.Object(\n { action: Type.Literal(WORKTREE_ACTIONS.prune), dryRun: Type.Optional(Type.Boolean()) },\n { additionalProperties: false },\n);\n\nconst SendParams = Type.Object(\n {\n action: Type.Literal(WORKTREE_ACTIONS.send),\n id: Type.String({ minLength: 1 }),\n message: Type.String({ minLength: 1 }),\n },\n { additionalProperties: false },\n);\n\nconst MessagesParams = Type.Object(\n { action: Type.Literal(WORKTREE_ACTIONS.messages), id: Type.String({ minLength: 1 }) },\n { additionalProperties: false },\n);\n\nexport const RunWorktreeParams = Type.Union([\n SpawnParams,\n CloseParams,\n ListParams,\n StatusParams,\n MergeParams,\n PruneParams,\n SendParams,\n MessagesParams,\n]);\n\n/** The actions that accept `field`, so the declared docs cannot drift from the validator. */\nfunction acceptingActions(field: string): string {\n return Object.values(WORKTREE_ACTIONS)\n .filter((action) => WORKTREE_ACTION_FIELDS[action].includes(field))\n .join(', ');\n}\n\n/**\n * The schema declared to the model.\n *\n * A flat object rather than `RunWorktreeParams` itself. A top-level union is\n * `{anyOf:[...]}` with no `properties`, and Pi's Anthropic Messages adapter\n * rebuilds tool input as `{type:'object', properties: schema.properties ?? {},\n * required: schema.required ?? []}`, so the union arrived at the model as an\n * empty object while the host went on validating calls against it. Nothing here\n * relaxes what is accepted: `validateParams` still rejects an unknown action, a\n * field the action does not take, and a missing required one.\n */\nexport const RunWorktreeToolSchema = Type.Object(\n {\n action: Type.String({\n enum: Object.values(WORKTREE_ACTIONS),\n description: 'The operation to run. Every other field is accepted only by the actions its description names.',\n }),\n branch: Type.Optional(\n Type.String({ minLength: 1, description: `New branch to create. Actions: ${acceptingActions('branch')}.` }),\n ),\n baseRef: Type.Optional(\n Type.String({\n minLength: 1,\n description: `Base ref, defaulting to the current branch. Actions: ${acceptingActions('baseRef')}.`,\n }),\n ),\n task: Type.Optional(\n Type.String({\n minLength: 1,\n description: `First message for the new session. Actions: ${acceptingActions('task')}.`,\n }),\n ),\n name: Type.Optional(\n Type.String({ minLength: 1, description: `Rail label for the worktree. Actions: ${acceptingActions('name')}.` }),\n ),\n id: Type.Optional(Type.String({ minLength: 1, description: `Worktree id. Actions: ${acceptingActions('id')}.` })),\n force: Type.Optional(\n Type.Boolean({ description: `Close even when the tree is dirty. Actions: ${acceptingActions('force')}.` }),\n ),\n message: Type.Optional(\n Type.String({\n minLength: 1,\n description: `Merge commit message, or the text to send. Actions: ${acceptingActions('message')}.`,\n }),\n ),\n dryRun: Type.Optional(\n Type.Boolean({\n description: `Report the plan without destroying anything. Actions: ${acceptingActions('dryRun')}.`,\n }),\n ),\n },\n { additionalProperties: false },\n);\n\nexport type RunWorktreeToolParams = Static<typeof RunWorktreeParams>;\n","import {\n RunWorktreeParams,\n WORKTREE_ACTION_FIELDS,\n WORKTREE_ACTIONS,\n type WorktreeAction,\n type RunWorktreeToolParams,\n} from '../../schemas/runWorktreeTool';\nimport type { WorktreeRecord } from '../../types/worktreeRegistry';\nimport { invalidRequest } from '../errors';\nimport type { WorktreeOperations } from '../worktreeOperations';\n\nexport { RunWorktreeParams };\nexport type { RunWorktreeToolParams, WorktreeAction };\n\nexport const RUN_WORKTREE_TOOL_NAME = 'run_worktree';\n\nconst IMPLEMENTED_ACTIONS: ReadonlySet<string> = new Set(Object.values(WORKTREE_ACTIONS));\n\nexport const RUN_WORKTREE_DESCRIPTION = `Create and manage git worktrees, each with its own DoomPi session nested under this one.\n\nActions:\n- spawn_worktree: create a worktree on a new branch and start a session in it. Requires 'branch'. Optional 'baseRef' (defaults to the current branch's remote-tracking ref, then the remote default branch), 'name' for the rail, 'task' as the first message.\n- close_worktree: stop a worktree's session, delete its checkout, and remove its generated sync storage. Requires 'id'. Refuses a dirty tree unless 'force' is true.\n- list: every worktree for this repository, with status.\n- status: one worktree and its uncommitted files. Requires 'id'.\n- merge: merge a worktree's branch into this checkout. Requires 'id'. Refuses when this checkout is dirty.\n- prune: remove orphaned worktrees and their generated sync storage. Pass 'dryRun' to see the plan without destroying anything.\n- send: send a message to the other side of a worktree. Requires 'id' and 'message'.\n- messages: read messages waiting for you from a worktree. Requires 'id'.\n\nWorktrees live outside the repository, under ~/.pi/.doom/git/worktrees.`;\n\nexport interface RunWorktreeToolDetails {\n action: WorktreeAction;\n records?: WorktreeRecord[];\n}\n\nexport interface RunWorktreeToolResult {\n content: [{ type: 'text'; text: string }];\n details: RunWorktreeToolDetails;\n}\n\nexport interface RunWorktreeExecutionContext {\n readonly cwd: string;\n readonly sessionId: string;\n}\n\nexport interface RunWorktreeExecutionOptions {\n readonly signal?: AbortSignal;\n readonly onProgress?: (label: string) => void;\n}\n\n/** Rejects calls that do not match one documented action shape. */\nexport function validateParams(input: unknown): RunWorktreeToolParams {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw invalidRequest('run_worktree parameters must be an object.', 'Call it with one documented action shape.');\n }\n const record = input as Record<string, unknown>;\n const action = record.action;\n if (typeof action !== 'string' || !IMPLEMENTED_ACTIONS.has(action)) {\n throw invalidRequest(\n `Unknown action ${typeof action === 'string' ? `'${action}'` : 'value'}.`,\n `Use one of: ${[...IMPLEMENTED_ACTIONS].join(', ')}.`,\n );\n }\n const allowed = WORKTREE_ACTION_FIELDS[action as WorktreeAction];\n const unexpected = Object.keys(record).filter((key) => !allowed.includes(key));\n if (unexpected.length > 0) {\n throw invalidRequest(\n `action='${action}' does not accept: ${unexpected.join(', ')}.`,\n `Fields for '${action}': ${allowed.join(', ')}.`,\n );\n }\n for (const field of ['branch', 'id'] as const) {\n if (allowed.includes(field) && field in record) {\n const value = record[field];\n if (typeof value !== 'string' || value.trim() === '') {\n throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);\n }\n }\n }\n const stringFields = ['baseRef', 'name', 'task', 'message'] as const;\n for (const field of stringFields) {\n if (field in record && (typeof record[field] !== 'string' || record[field].trim() === '')) {\n throw invalidRequest(`action='${action}' requires a nonblank '${field}'.`, `Pass a ${field}.`);\n }\n }\n for (const field of ['force', 'dryRun'] as const) {\n if (field in record && typeof record[field] !== 'boolean') {\n throw invalidRequest(`action='${action}' requires boolean '${field}'.`, `Pass true or false for ${field}.`);\n }\n }\n if (action === WORKTREE_ACTIONS.send && typeof record.message !== 'string') {\n throw invalidRequest(\"action='send' requires 'message'.\", 'Pass the message to send.');\n }\n if (action === WORKTREE_ACTIONS.spawn_worktree && typeof record.branch !== 'string') {\n throw invalidRequest(\"action='spawn_worktree' requires 'branch'.\", 'Name the branch to create.');\n }\n if (\n (action === WORKTREE_ACTIONS.close_worktree ||\n action === WORKTREE_ACTIONS.status ||\n action === WORKTREE_ACTIONS.merge ||\n action === WORKTREE_ACTIONS.send ||\n action === WORKTREE_ACTIONS.messages) &&\n typeof record.id !== 'string'\n ) {\n throw invalidRequest(`action='${action}' requires 'id'.`, 'Call list to see the current ids.');\n }\n return record as RunWorktreeToolParams;\n}\n\nfunction describe(record: WorktreeRecord): string {\n return `${record.id} ${record.branch} ${record.status} ${record.path}`;\n}\n\nfunction text(...lines: readonly string[]): [{ type: 'text'; text: string }] {\n return [{ type: 'text', text: lines.join('\\n') }];\n}\n\nexport async function executeRunWorktreeTool(\n params: RunWorktreeToolParams,\n operations: WorktreeOperations,\n context: RunWorktreeExecutionContext,\n options: RunWorktreeExecutionOptions = {},\n): Promise<RunWorktreeToolResult> {\n switch (params.action) {\n case WORKTREE_ACTIONS.spawn_worktree: {\n const record = await operations.spawn(\n context,\n {\n branch: params.branch,\n ...(params.baseRef === undefined ? {} : { baseRef: params.baseRef }),\n ...(params.name === undefined ? {} : { name: params.name }),\n ...(params.task === undefined ? {} : { task: params.task }),\n },\n options,\n );\n return {\n content: text(\n `Worktree ${record.id} created on ${record.branch} from ${record.baseRef}.`,\n `Path: ${record.path}`,\n params.task === undefined\n ? `Session ${record.sessionId} is starting; it appears nested under this one in the rail.`\n : `Session ${record.sessionId} is starting with its task; it appears nested under this one in the rail.`,\n ),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.close_worktree: {\n const record = await operations.close(context, params.id, params.force ?? false);\n return {\n content: text(`Worktree ${record.id} (${record.branch}) closed and removed.`),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.list: {\n const records = await operations.list(context);\n return {\n content:\n records.length === 0\n ? text('No worktrees for this repository.')\n : text(`${String(records.length)} worktree(s):`, ...records.map(describe)),\n details: { action: params.action, records },\n };\n }\n case WORKTREE_ACTIONS.status: {\n const { record, dirtyFiles } = await operations.status(context, params.id);\n return {\n content: text(\n describe(record),\n `Session: ${record.sessionId}`,\n dirtyFiles.length === 0\n ? 'Clean.'\n : `${String(dirtyFiles.length)} uncommitted file(s): ${dirtyFiles.slice(0, 20).join(', ')}`,\n ),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.merge: {\n const record = await operations.merge(\n context,\n params.id,\n ...(params.message === undefined ? [] : ([params.message] as const)),\n );\n return {\n content: text(`Merged ${record.branch} into this checkout.`),\n details: { action: params.action, records: [record] },\n };\n }\n case WORKTREE_ACTIONS.send: {\n await operations.send(context, params.id, params.message);\n return { content: text(`Message sent to worktree ${params.id}.`), details: { action: params.action } };\n }\n case WORKTREE_ACTIONS.messages: {\n const waiting = await operations.messages(context, params.id);\n return {\n content:\n waiting.length === 0\n ? text('No messages.')\n : text(\n `${String(waiting.length)} message(s):`,\n ...waiting.map((entry) => `[${entry.sentAt}] ${entry.from}: ${entry.text}`),\n ),\n details: { action: params.action },\n };\n }\n case WORKTREE_ACTIONS.prune: {\n const dryRun = params.dryRun ?? false;\n const plan = await operations.prune(context, dryRun);\n const lines = [\n dryRun ? 'Prune plan (nothing was changed):' : 'Pruned:',\n `Remove: ${plan.remove.length === 0 ? 'none' : plan.remove.map((record) => record.id).join(', ')}`,\n `Forget: ${plan.forget.length === 0 ? 'none' : plan.forget.map((record) => record.id).join(', ')}`,\n `Kept, uncommitted work: ${plan.keptDirty.length === 0 ? 'none' : plan.keptDirty.map((record) => record.id).join(', ')}`,\n `Untracked directories, left alone: ${plan.untracked.length === 0 ? 'none' : plan.untracked.join(', ')}`,\n ...(plan.keptBranches.length === 0\n ? []\n : [`Branches kept, they hold commits: ${plan.keptBranches.join(', ')}`]),\n ];\n return { content: text(...lines), details: { action: params.action } };\n }\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAa,mBAAmB;CAC9B,gBAAgB;CAChB,gBAAgB;CAChB,MAAM;CACN,QAAQ;CACR,OAAO;CACP,OAAO;CACP,MAAM;CACN,UAAU;AACZ;;;;;;;;AAWA,MAAa,yBAAoE;CAC/E,gBAAgB;EAAC;EAAU;EAAU;EAAW;EAAQ;CAAM;CAC9D,gBAAgB;EAAC;EAAU;EAAM;CAAO;CACxC,MAAM,CAAC,QAAQ;CACf,QAAQ,CAAC,UAAU,IAAI;CACvB,OAAO;EAAC;EAAU;EAAM;CAAS;CACjC,OAAO,CAAC,UAAU,QAAQ;CAC1B,MAAM;EAAC;EAAU;EAAM;CAAS;CAChC,UAAU,CAAC,UAAU,IAAI;AAC3B;AAEA,MAAM,cAAc,KAAK,OACvB;CACE,QAAQ,KAAK,QAAQ,iBAAiB,cAAc;CACpD,QAAQ,KAAK,OAAO,EAAE,WAAW,EAAE,CAAC;CACpC,SAAS,KAAK,SAAS,KAAK,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;CACpD,MAAM,KAAK,SAAS,KAAK,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;CACjD,MAAM,KAAK,SAAS,KAAK,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;AACnD,GACA,EAAE,sBAAsB,MAAM,CAChC;AAEA,MAAM,cAAc,KAAK,OACvB;CACE,QAAQ,KAAK,QAAQ,iBAAiB,cAAc;CACpD,IAAI,KAAK,OAAO,EAAE,WAAW,EAAE,CAAC;CAChC,OAAO,KAAK,SAAS,KAAK,QAAQ,CAAC;AACrC,GACA,EAAE,sBAAsB,MAAM,CAChC;AAEA,MAAM,aAAa,KAAK,OAAO,EAAE,QAAQ,KAAK,QAAQ,iBAAiB,IAAI,EAAE,GAAG,EAAE,sBAAsB,MAAM,CAAC;AAE/G,MAAM,eAAe,K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OAAO,QAAQ,MAAM,EAAE,eAC1B,GAAG,QAAQ,KAAK,UAAU,IAAI,MAAM,OAAO,IAAI,MAAM,KAAK,IAAI,MAAM,MAAM,CAC5E;IACN,SAAS,EAAE,QAAQ,OAAO,OAAO;GACnC;EACF;EACA,KAAK,iBAAiB,OAAO;GAC3B,MAAM,SAAS,OAAO,UAAU;GAChC,MAAM,OAAO,MAAM,WAAW,MAAM,SAAS,MAAM;GAWnD,OAAO;IAAE,SAAS,KAAK,GAAG;KATxB,SAAS,sCAAsC;KAC/C,WAAW,KAAK,OAAO,WAAW,IAAI,SAAS,KAAK,OAAO,KAAK,WAAW,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;KAC/F,WAAW,KAAK,OAAO,WAAW,IAAI,SAAS,KAAK,OAAO,KAAK,WAAW,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;KAC/F,2BAA2B,KAAK,UAAU,WAAW,IAAI,SAAS,KAAK,UAAU,KAAK,WAAW,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;KACrH,sCAAsC,KAAK,UAAU,WAAW,IAAI,SAAS,KAAK,UAAU,KAAK,IAAI;KACrG,GAAI,KAAK,aAAa,WAAW,IAC7B,CAAC,IACD,CAAC,qCAAqC,KAAK,aAAa,KAAK,IAAI,GAAG;IAE5C,CAAC;IAAG,SAAS,EAAE,QAAQ,OAAO,OAAO;GAAE;EACvE;CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"worktreeOperations-DAbs0ZTX.mjs","names":[],"sources":["../src/services/gitCli/index.ts","../src/services/compositionMirror/index.ts","../src/services/errors/index.ts","../src/services/atomicJson/index.ts","../src/services/repositoryIdentity/index.ts","../src/services/paths/index.ts","../src/services/worktreeEvents/index.ts","../src/services/worktreeNaming/index.ts","../src/services/worktreeRegistry/index.ts","../src/services/worktreeOperations/index.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\n\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 */\nconst READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n\ninterface GitResult {\n code: number;\n stdout: string;\n stderr: string;\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 two callers below decide what to do by matching\n * git's own wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n */\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n { cwd, timeout, maxBuffer: MAX_OUTPUT_BYTES, env: { ...process.env, LC_ALL: 'C' } },\n (error, stdout, stderr) => {\n const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\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 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 (missingWorktree(result.stderr) && !fs.existsSync(path)) {\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","/**\n * Giving a new worktree the build output its parent checkout already has.\n *\n * DESIGN PATTERNS:\n * - Mirrors, never builds. Everything here is a copy or a symlink of something\n * the parent checkout already produced, so it costs seconds and cannot fail\n * the way a package manager or a compiler can.\n * - `node_modules` is linked, `dist` is copied. The module tree is gigabytes\n * and read-only in practice, so a link is right; build output is small and a\n * link would send a build run inside the worktree straight into the parent's\n * directory.\n * - Absent parent output means nothing to do. A repository with no\n * `node_modules` at its root is either not a JS project or not installed, and\n * either way this has no opinion about it, so a Rust, Go or Python worktree\n * pays nothing.\n *\n * WHY THIS EXISTS:\n * A DoomPi session composes the extensions its repository's config names, and\n * this repository names its own workspace packages by relative path. Those\n * packages declare `pi.extensions` under `dist/`, which git does not track, so\n * a fresh worktree resolves none of them and the session dies on start. The\n * parent checkout has already built exactly what the child needs.\n *\n * AVOID:\n * - Recursing into `node_modules`. The scan is bounded and skips it; without\n * that this walks a gigabyte to find nothing.\n * - Treating a mirror failure as fatal. The worktree is good either way; only\n * the session's composition is poorer for it.\n */\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/** Directories that are build output worth copying into a new worktree. */\nconst OUTPUT_DIRECTORY = 'dist';\nconst MODULES_DIRECTORY = 'node_modules';\nconst GIT_DIRECTORY = '.git';\n/**\n * How deep the scan goes.\n *\n * Four levels reaches `layers/<group>/<package>/dist` in this repository's\n * layout, and a workspace that buries a package deeper than that gets a\n * partial mirror rather than a slow one.\n */\nconst MAX_DEPTH = 4;\n\nexport type MirrorOutcome =\n | { kind: 'skipped'; reason: 'no-modules' }\n | { kind: 'mirrored'; copied: number; linked: number };\n\ninterface Found {\n /** Paths relative to the source root. */\n outputs: string[];\n modules: string[];\n}\n\nfunction scan(root: string): Found {\n const found: Found = { outputs: [], modules: [] };\n const walk = (relative: string, depth: number): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(path.join(root, relative), { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const child = relative === '' ? entry.name : `${relative}/${entry.name}`;\n if (entry.name === GIT_DIRECTORY) continue;\n // Module trees may already be links inherited from an earlier worktree.\n if (entry.name === MODULES_DIRECTORY) {\n try {\n if (entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(path.join(root, child)).isDirectory())) {\n found.modules.push(child);\n }\n } catch {\n // A broken inherited link is not useful to the next worktree.\n }\n continue;\n }\n if (!entry.isDirectory()) continue;\n if (entry.name === OUTPUT_DIRECTORY) {\n found.outputs.push(child);\n continue;\n }\n if (depth < MAX_DEPTH) walk(child, depth + 1);\n }\n };\n walk('', 1);\n return found;\n}\n\n/**\n * Copies the parent's build output into a worktree and links its modules.\n *\n * Individual failures are counted out rather than thrown: a mirror that lands\n * partly is still better than none, and the caller has a worktree either way.\n */\nexport function mirrorComposition(source: string, target: string): MirrorOutcome {\n if (!fs.existsSync(path.join(source, MODULES_DIRECTORY))) return { kind: 'skipped', reason: 'no-modules' };\n\n const found = scan(source);\n let copied = 0;\n let linked = 0;\n\n for (const relative of found.modules) {\n const destination = path.join(target, relative);\n if (fs.existsSync(destination)) continue;\n try {\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.symlinkSync(fs.realpathSync(path.join(source, relative)), destination, 'dir');\n linked += 1;\n } catch {\n // A link the filesystem refuses costs this package one resolution, not\n // the worktree.\n }\n }\n\n for (const relative of found.outputs) {\n const destination = path.join(target, relative);\n if (fs.existsSync(destination)) continue;\n try {\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.cpSync(path.join(source, relative), destination, { recursive: true });\n copied += 1;\n } catch {\n // Same reasoning as a failed link.\n }\n }\n\n return { kind: 'mirrored', copied, linked };\n}\n","/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/doompi-core` does not export `invalidRequest` or\n * an expected-error base, so this mirrors doompi-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 DoomGitErrorCode =\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 | 'worktree_cleanup_failed'\n | 'hub_unavailable'\n | 'spawn_cancelled'\n | 'registry_write_failed'\n | 'registry_busy'\n | 'task_delivery_failed'\n | 'message_delivery_failed'\n | 'message_too_large'\n | 'git_failed';\n\nexport class DoomGitExpectedError extends Error {\n constructor(\n readonly code: DoomGitErrorCode,\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 = 'DoomGitExpectedError';\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): DoomGitExpectedError {\n return new DoomGitExpectedError('invalid_request', message, false, recovery);\n}\n","import fs from 'node:fs';\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 function writeJsonAtomic(file: string, value: unknown): void {\n const directory = path.dirname(file);\n fs.mkdirSync(directory, { recursive: true });\n const temporary = path.join(directory, `.${path.basename(file)}.${String(process.pid)}.tmp`);\n fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: OWNER_ONLY_FILE });\n fs.renameSync(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 function readJson<T>(file: string): T | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as T;\n } catch {\n return undefined;\n }\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\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 function gitCommonDirectory(directory: string): string | undefined {\n let root = path.resolve(directory);\n let marker = path.join(root, '.git');\n let stat: fs.Stats | undefined;\n for (;;) {\n try {\n stat = fs.statSync(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 = fs.readFileSync(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 = fs.readFileSync(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 function repositoryId(root: string): string {\n const common = 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 { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\n\nimport { WORKTREE_RECORD_VERSION, type WorktreeRecord } from '../../types/worktreeRegistry';\nimport { readJson, writeJsonAtomic } from '../atomicJson';\nimport { repositoryId } from '../repositoryIdentity';\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 doomGitRoot(homeDir: string = os.homedir()): string {\n return path.join(homeDir, '.pi', '.doom', 'git');\n}\n\n/** The directory every worktree for every repository is created under. */\nexport function worktreesRoot(homeDir: string = os.homedir()): string {\n return path.join(doomGitRoot(homeDir), 'worktrees');\n}\n\n/** One registry file per repository, keyed by the shared git directory. */\nexport function registryFile(repositoryRoot: string, homeDir: string = os.homedir()): string {\n const id = repositoryId(repositoryRoot);\n const root = path.join(doomGitRoot(homeDir), 'registry');\n const canonical = path.join(root, id, 'worktrees.json');\n if (fs.existsSync(canonical)) return canonical;\n let names: string[];\n try {\n names = fs.readdirSync(root);\n } catch {\n return canonical;\n }\n const legacyFiles = names\n .filter((entry) => entry.endsWith(`--${id}`))\n .sort()\n .map((entry) => path.join(root, entry, 'worktrees.json'))\n .filter((file) => fs.existsSync(file));\n if (legacyFiles.length === 0) return canonical;\n const entries = new Map<string, WorktreeRecord>();\n for (const file of legacyFiles) {\n const legacy = readJson<{ version?: unknown; entries?: unknown }>(file);\n if (legacy?.version !== WORKTREE_RECORD_VERSION || !Array.isArray(legacy.entries)) continue;\n for (const value of legacy.entries) {\n if (\n typeof value !== 'object' ||\n value === null ||\n !('id' in value) ||\n typeof value.id !== 'string' ||\n value.id === ''\n )\n continue;\n const entry = value as WorktreeRecord;\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 writeJsonAtomic(temporary, { version: WORKTREE_RECORD_VERSION, entries: [...entries.values()] });\n try {\n // Publish only if absent. A concurrent writer may already have added records.\n fs.linkSync(temporary, canonical);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n } finally {\n fs.rmSync(temporary);\n }\n return canonical;\n}\n","import type { DoomDirectEventBus } from '@agimon-ai/doompi-core/hubChannel';\n\nexport const GIT_WORKTREE_LIFECYCLE_EVENT = 'git_worktree_lifecycle';\nexport const GIT_WORKTREE_MESSAGE_EVENT = 'git_worktree_message';\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: DoomDirectEventBus, 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 * 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\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 doompi-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 function reconcile(\n records: readonly WorktreeRecord[],\n probe: { alive: (record: WorktreeRecord) => boolean; exists: (path: string) => boolean },\n): Reconciliation {\n const changed: string[] = [];\n const next = records.map((record) => {\n if (record.status === 'orphaned') return record;\n const gone = !probe.exists(record.path) || !probe.alive(record);\n if (!gone) return record;\n changed.push(record.id);\n return { ...record, status: 'orphaned' as const };\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","import fs from 'node:fs';\nimport path from 'node:path';\nimport { setTimeout } from 'node:timers/promises';\n\nimport {\n WORKTREE_RECORD_VERSION,\n type WorktreeRecord,\n type WorktreeRegistryFile,\n type WorktreeRegistryStore,\n} from '../../types/worktreeRegistry';\nimport { readJson, writeJsonAtomic } from '../atomicJson';\nimport { DoomGitExpectedError } from '../errors';\n\nconst LOCK_WAIT_MS = 5000;\nconst LOCK_RETRY_MS = 25;\n\nfunction isRecord(value: unknown): value is WorktreeRecord {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Partial<WorktreeRecord>;\n return (\n record.version === WORKTREE_RECORD_VERSION &&\n typeof record.id === 'string' &&\n record.id !== '' &&\n typeof record.path === 'string' &&\n typeof record.branch === 'string' &&\n typeof record.sessionId === 'string'\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(file: string): WorktreeRegistryStore {\n return {\n list() {\n const parsed = readJson<WorktreeRegistryFile>(file);\n if (!parsed || parsed.version !== WORKTREE_RECORD_VERSION || !Array.isArray(parsed.entries)) return [];\n return parsed.entries.filter(isRecord);\n },\n replace(entries) {\n writeJsonAtomic(file, { version: WORKTREE_RECORD_VERSION, entries } satisfies WorktreeRegistryFile);\n },\n async transaction(operation, signal) {\n const lock = `${file}.lock`;\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const deadline = Date.now() + LOCK_WAIT_MS;\n for (;;) {\n signal?.throwIfAborted();\n try {\n fs.mkdirSync(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 DoomGitExpectedError(\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 fs.writeFileSync(\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 fs.rmSync(lock, { recursive: true });\n }\n },\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\n\nimport type { DoomHubSessionService } from '@agimon-ai/doompi-core/hubChannel';\nimport { removeSyncLocation, resolveWorktreeSyncLocation } from '@agimon-ai/doompi-core/syncLocation';\nimport type { DoomSessionDeliveryService } from '@agimon-ai/doompi-session';\n\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry';\nimport { mirrorComposition } from '../compositionMirror';\nimport { DoomGitExpectedError, HubUnavailableError } from '../errors';\nimport { registryFile, worktreesRoot } from '../paths';\nimport { repositoryId, repositoryLabel, shortId } from '../repositoryIdentity';\nimport { MAX_WORKTREE_MESSAGE_BYTES, type WorktreeMessageInbox, type WorktreeMessageParty } from '../worktreeEvents';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, 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';\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /** The calling session, recorded as the new session's parent. */\n sessionId: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: 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}\n\nexport interface SpawnOptions {\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 spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;\n close(context: WorktreeContext, id: string, force: boolean): 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 /** The canonical hub-owned session lifecycle. */\n sessionService?: DoomHubSessionService;\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?: () => DoomSessionDeliveryService | undefined;\n /** Injected so a test never copies a real dependency tree. */\n mirror?: typeof mirrorComposition;\n /** Injected so tests can observe generated-storage cleanup without touching real sync state. */\n cleanupStorage?: (repositoryRoot: string, worktreeRoot: string) => void;\n homeDir?: string;\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 sessionService = deps.sessionService;\n const mirror = deps.mirror ?? mirrorComposition;\n const removeStorage =\n deps.cleanupStorage ??\n ((repositoryRoot: string, worktreeRoot: string): void => {\n removeSyncLocation(resolveWorktreeSyncLocation(repositoryRoot, worktreeRoot, deps.homeDir));\n });\n const cleanupStorage = (repositoryRoot: string, worktreeRoot: string): void => {\n try {\n removeStorage(repositoryRoot, worktreeRoot);\n } catch (error) {\n throw new DoomGitExpectedError(\n 'worktree_cleanup_failed',\n `The worktree checkout was removed, but its generated storage could not be deleted (${error instanceof Error ? error.message : String(error)}).`,\n true,\n 'Retry close or prune after fixing the storage permissions.',\n );\n }\n };\n const now = deps.now ?? (() => new Date());\n const requireSessionService = (): DoomHubSessionService => {\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 = (): DoomSessionDeliveryService | undefined => deps.sessionDelivery?.();\n const requireSessionDelivery = (): DoomSessionDeliveryService => {\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) => fs.existsSync(path),\n };\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 DoomGitExpectedError(\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(registryFile(root, deps.homeDir));\n return { root, store, records: 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 DoomGitExpectedError(\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 (!requireSessionService().isLive(record.parentSessionId)) return;\n throw new DoomGitExpectedError(\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 (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 DoomGitExpectedError(\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 DoomGitExpectedError(\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 operations: WorktreeOperations = {\n async spawn(context, request, options) {\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 DoomGitExpectedError(\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, context.sessionId);\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),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: shortId(reserved!.sessionId),\n });\n if (\n existing.parentSessionId !== context.sessionId ||\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 !fs.existsSync(existing.path) ||\n !(await git.listWorktreePaths(root)).includes(existing.path) ||\n (await git.repositoryRoot(existing.path)) !== existing.path ||\n (await git.currentBranch(existing.path)) !== request.branch\n )\n throw new DoomGitExpectedError(\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: context.sessionId,\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!, context.sessionId);\n return existing;\n }\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const taskDelivery = request.task === undefined ? undefined : requireSessionDelivery();\n const baseRef = request.baseRef ?? (await git.remoteBaseRef(root));\n if (baseRef === undefined) {\n throw new DoomGitExpectedError(\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 const id = shortId(reserved?.sessionId ?? randomUUID());\n let path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n if (request.reservationId !== undefined) {\n path = (await reservations!.prepare(request.reservationId, context.sessionId, path)).cwd;\n }\n const recovering = reserved?.cwd !== undefined && fs.existsSync(path);\n if (\n recovering &&\n (!(await git.listWorktreePaths(root)).includes(path) || (await git.currentBranch(path)) !== request.branch)\n )\n throw new DoomGitExpectedError(\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 // 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 git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\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 options?.onProgress?.(`creating branch ${request.branch}\\u2026`);\n if (!recovering) await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\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 DoomGitExpectedError(\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 // Before the session, because the session composes the extensions this\n // repository's config names and those live in build output git does not\n // track. A worktree without it starts and dies on the first package it\n // cannot resolve. Nothing here can fail the spawn: a repository with no\n // build output to mirror simply has none.\n options?.onProgress?.('mirroring build output\\u2026');\n if (!recovering) mirror(root, path);\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 parentSessionId: context.sessionId,\n sessionProvenance: 'worktree',\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 DoomGitExpectedError(\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 DoomGitExpectedError(\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 parentSessionId: context.sessionId,\n status: 'running',\n createdAt: now().toISOString(),\n };\n try {\n 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 DoomGitExpectedError(\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 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: request.task,\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 Error(\n admission === 'recovery_required'\n ? 'The recipient could not admit the task.'\n : 'The recipient did not confirm task admission before the timeout.',\n );\n }\n } catch (error) {\n throw new DoomGitExpectedError(\n 'task_delivery_failed',\n `Worktree ${record.id} was created, but its task admission was not confirmed (${(error as Error).message}).`,\n true,\n `Use send with worktree ${record.id} to deliver the task without recreating the worktree.`,\n );\n }\n }\n if (request.reservationId !== undefined) await reservations!.complete(request.reservationId, context.sessionId);\n return record;\n },\n\n async close(context, id, force) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('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 git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n cleanupStorage(root, record.path);\n 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 = reconcile(records, probe);\n if (outcome.changed.length > 0) 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 = fs.existsSync(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 DoomGitExpectedError(\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 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 DoomGitExpectedError(\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 DoomGitExpectedError(\n 'message_delivery_failed',\n `Worktree ${record.id} persisted the message, but its session did not confirm admission.`,\n true,\n admission === 'recovery_required'\n ? 'Call messages from the recipient session to recover the persisted text.'\n : 'The message remains durable; retry after the recipient is ready.',\n );\n }\n return;\n }\n requireMessageInbox().send(peer.sessionId, {\n version: 1,\n worktreeId: record.id,\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 = delivery\n .inbox({ consumed: false, metadata: { worktreeId: record.id } })\n .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 return entries.map((entry) => {\n delivery.consume(entry.deliveryId);\n return {\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\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = reconcile(records, probe);\n const gitPaths = await git.listWorktreePaths(root);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && fs.existsSync(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),\n dirtyByPath,\n });\n if (dryRun) {\n store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force: false });\n cleanupStorage(root, record.path);\n }\n for (const record of plan.forget) cleanupStorage(root, record.path);\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 if (!deleted) plan.keptBranches.push(record.branch);\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n 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 DoomGitExpectedError))\n throw new DoomGitExpectedError(\n 'spawn_cancelled',\n 'The worktree operation was cancelled.',\n false,\n 'Inspect its recorded state before retrying.',\n );\n if (['ENOTDIR', 'EACCES', 'EROFS', 'ENOSPC'].includes(String((error as NodeJS.ErrnoException).code)))\n throw new DoomGitExpectedError(\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 DoomGitExpectedError(\n 'hub_unavailable',\n 'The cockpit session service is unavailable.',\n true,\n 'Use the cockpit worktree tool after its Git server facet is available.',\n ),\n );\n return locked(context, () => operations.spawn(context, request, options), options?.signal);\n },\n close: (context, id, force) => locked(context, () => operations.close(context, id, force)),\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"],"mappings":";;;;;;;;;;;;;;;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;;;;;;;;AAezB,SAAS,IAAI,KAAa,MAAyB,SAAqC;CACtF,OAAO,IAAI,SAAS,YAAY;EAC9B,SACE,OACA,CAAC,GAAG,IAAI,GACR;GAAE;GAAK;GAAS,WAAW;GAAkB,KAAK;IAAE,GAAG,QAAQ;IAAK,QAAQ;GAAI;EAAE,IACjF,OAAO,QAAQ,WAAW;GAEzB,QAAQ;IAAE,MADG,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,QAAQ,IAAI;IAChE,QAAQ,OAAO,MAAM;IAAG,QAAQ,OAAO,MAAM;GAAE,CAAC;EAClE,CACF;CACF,CAAC;AACH;;;;;;;AAQA,SAAS,QAAQ,WAAmB,QAA0B;CAC5D,uBAAO,IAAI,MACT,OAAO,UAAU,gBAAgB,OAAO,OAAO,IAAI,EAAE,IAAI,OAAO,OAAO,OAAO,MAAM,EAAE,kBACxF;AACF;;AAGA,SAAS,gBAAgB,QAAyB;CAChD,MAAM,aAAa,OAAO,YAAY;CACtC,OAAO,WAAW,SAAS,uBAAuB,KAAK,WAAW,SAAS,4BAA4B;AACzG;AAEA,SAAgB,oBAAiC;CAC/C,MAAM,QAAQ,OAAO,mBAA0C;EAC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,MAAM,CAAC;CACrF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"worktreeOperations-DjO_Y5Yv.cjs","names":["fs","fs","path","path","fs","path","fs","createHash","os","path","fs","isDeepStrictEqual","randomUUID","path","setTimeout","resolveWorktreeSyncLocation","fs","require","randomUUID"],"sources":["../src/services/gitCli/index.ts","../src/services/compositionMirror/index.ts","../src/services/errors/index.ts","../src/services/atomicJson/index.ts","../src/services/repositoryIdentity/index.ts","../src/services/paths/index.ts","../src/services/worktreeEvents/index.ts","../src/services/worktreeNaming/index.ts","../src/services/worktreeRegistry/index.ts","../src/services/worktreeOperations/index.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\n\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 */\nconst READ_TIMEOUT_MS = 30_000;\nconst ADD_TIMEOUT_MS = 300_000;\nconst REMOVE_TIMEOUT_MS = 300_000;\nconst PRUNE_TIMEOUT_MS = 15_000;\nconst MAX_OUTPUT_BYTES = 1_000_000;\n\ninterface GitResult {\n code: number;\n stdout: string;\n stderr: string;\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 two callers below decide what to do by matching\n * git's own wording, and a translated message would silently turn a recognised\n * condition into an unrecognised failure.\n */\nfunction git(cwd: string, args: readonly string[], timeout: number): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n [...args],\n { cwd, timeout, maxBuffer: MAX_OUTPUT_BYTES, env: { ...process.env, LC_ALL: 'C' } },\n (error, stdout, stderr) => {\n const code = error && typeof error.code === 'number' ? error.code : error ? 1 : 0;\n resolve({ code, stdout: String(stdout), stderr: String(stderr) });\n },\n );\n });\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 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 (missingWorktree(result.stderr) && !fs.existsSync(path)) {\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","/**\n * Giving a new worktree the build output its parent checkout already has.\n *\n * DESIGN PATTERNS:\n * - Mirrors, never builds. Everything here is a copy or a symlink of something\n * the parent checkout already produced, so it costs seconds and cannot fail\n * the way a package manager or a compiler can.\n * - `node_modules` is linked, `dist` is copied. The module tree is gigabytes\n * and read-only in practice, so a link is right; build output is small and a\n * link would send a build run inside the worktree straight into the parent's\n * directory.\n * - Absent parent output means nothing to do. A repository with no\n * `node_modules` at its root is either not a JS project or not installed, and\n * either way this has no opinion about it, so a Rust, Go or Python worktree\n * pays nothing.\n *\n * WHY THIS EXISTS:\n * A DoomPi session composes the extensions its repository's config names, and\n * this repository names its own workspace packages by relative path. Those\n * packages declare `pi.extensions` under `dist/`, which git does not track, so\n * a fresh worktree resolves none of them and the session dies on start. The\n * parent checkout has already built exactly what the child needs.\n *\n * AVOID:\n * - Recursing into `node_modules`. The scan is bounded and skips it; without\n * that this walks a gigabyte to find nothing.\n * - Treating a mirror failure as fatal. The worktree is good either way; only\n * the session's composition is poorer for it.\n */\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/** Directories that are build output worth copying into a new worktree. */\nconst OUTPUT_DIRECTORY = 'dist';\nconst MODULES_DIRECTORY = 'node_modules';\nconst GIT_DIRECTORY = '.git';\n/**\n * How deep the scan goes.\n *\n * Four levels reaches `layers/<group>/<package>/dist` in this repository's\n * layout, and a workspace that buries a package deeper than that gets a\n * partial mirror rather than a slow one.\n */\nconst MAX_DEPTH = 4;\n\nexport type MirrorOutcome =\n | { kind: 'skipped'; reason: 'no-modules' }\n | { kind: 'mirrored'; copied: number; linked: number };\n\ninterface Found {\n /** Paths relative to the source root. */\n outputs: string[];\n modules: string[];\n}\n\nfunction scan(root: string): Found {\n const found: Found = { outputs: [], modules: [] };\n const walk = (relative: string, depth: number): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(path.join(root, relative), { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const child = relative === '' ? entry.name : `${relative}/${entry.name}`;\n if (entry.name === GIT_DIRECTORY) continue;\n // Module trees may already be links inherited from an earlier worktree.\n if (entry.name === MODULES_DIRECTORY) {\n try {\n if (entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(path.join(root, child)).isDirectory())) {\n found.modules.push(child);\n }\n } catch {\n // A broken inherited link is not useful to the next worktree.\n }\n continue;\n }\n if (!entry.isDirectory()) continue;\n if (entry.name === OUTPUT_DIRECTORY) {\n found.outputs.push(child);\n continue;\n }\n if (depth < MAX_DEPTH) walk(child, depth + 1);\n }\n };\n walk('', 1);\n return found;\n}\n\n/**\n * Copies the parent's build output into a worktree and links its modules.\n *\n * Individual failures are counted out rather than thrown: a mirror that lands\n * partly is still better than none, and the caller has a worktree either way.\n */\nexport function mirrorComposition(source: string, target: string): MirrorOutcome {\n if (!fs.existsSync(path.join(source, MODULES_DIRECTORY))) return { kind: 'skipped', reason: 'no-modules' };\n\n const found = scan(source);\n let copied = 0;\n let linked = 0;\n\n for (const relative of found.modules) {\n const destination = path.join(target, relative);\n if (fs.existsSync(destination)) continue;\n try {\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.symlinkSync(fs.realpathSync(path.join(source, relative)), destination, 'dir');\n linked += 1;\n } catch {\n // A link the filesystem refuses costs this package one resolution, not\n // the worktree.\n }\n }\n\n for (const relative of found.outputs) {\n const destination = path.join(target, relative);\n if (fs.existsSync(destination)) continue;\n try {\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n fs.cpSync(path.join(source, relative), destination, { recursive: true });\n copied += 1;\n } catch {\n // Same reasoning as a failed link.\n }\n }\n\n return { kind: 'mirrored', copied, linked };\n}\n","/**\n * Expected failures, kept private to this package.\n *\n * `@agimon-ai/doompi-core` does not export `invalidRequest` or\n * an expected-error base, so this mirrors doompi-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 DoomGitErrorCode =\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 | 'worktree_cleanup_failed'\n | 'hub_unavailable'\n | 'spawn_cancelled'\n | 'registry_write_failed'\n | 'registry_busy'\n | 'task_delivery_failed'\n | 'message_delivery_failed'\n | 'message_too_large'\n | 'git_failed';\n\nexport class DoomGitExpectedError extends Error {\n constructor(\n readonly code: DoomGitErrorCode,\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 = 'DoomGitExpectedError';\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): DoomGitExpectedError {\n return new DoomGitExpectedError('invalid_request', message, false, recovery);\n}\n","import fs from 'node:fs';\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 function writeJsonAtomic(file: string, value: unknown): void {\n const directory = path.dirname(file);\n fs.mkdirSync(directory, { recursive: true });\n const temporary = path.join(directory, `.${path.basename(file)}.${String(process.pid)}.tmp`);\n fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: OWNER_ONLY_FILE });\n fs.renameSync(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 function readJson<T>(file: string): T | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, 'utf8')) as T;\n } catch {\n return undefined;\n }\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\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 function gitCommonDirectory(directory: string): string | undefined {\n let root = path.resolve(directory);\n let marker = path.join(root, '.git');\n let stat: fs.Stats | undefined;\n for (;;) {\n try {\n stat = fs.statSync(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 = fs.readFileSync(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 = fs.readFileSync(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 function repositoryId(root: string): string {\n const common = 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 { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\n\nimport { WORKTREE_RECORD_VERSION, type WorktreeRecord } from '../../types/worktreeRegistry';\nimport { readJson, writeJsonAtomic } from '../atomicJson';\nimport { repositoryId } from '../repositoryIdentity';\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 doomGitRoot(homeDir: string = os.homedir()): string {\n return path.join(homeDir, '.pi', '.doom', 'git');\n}\n\n/** The directory every worktree for every repository is created under. */\nexport function worktreesRoot(homeDir: string = os.homedir()): string {\n return path.join(doomGitRoot(homeDir), 'worktrees');\n}\n\n/** One registry file per repository, keyed by the shared git directory. */\nexport function registryFile(repositoryRoot: string, homeDir: string = os.homedir()): string {\n const id = repositoryId(repositoryRoot);\n const root = path.join(doomGitRoot(homeDir), 'registry');\n const canonical = path.join(root, id, 'worktrees.json');\n if (fs.existsSync(canonical)) return canonical;\n let names: string[];\n try {\n names = fs.readdirSync(root);\n } catch {\n return canonical;\n }\n const legacyFiles = names\n .filter((entry) => entry.endsWith(`--${id}`))\n .sort()\n .map((entry) => path.join(root, entry, 'worktrees.json'))\n .filter((file) => fs.existsSync(file));\n if (legacyFiles.length === 0) return canonical;\n const entries = new Map<string, WorktreeRecord>();\n for (const file of legacyFiles) {\n const legacy = readJson<{ version?: unknown; entries?: unknown }>(file);\n if (legacy?.version !== WORKTREE_RECORD_VERSION || !Array.isArray(legacy.entries)) continue;\n for (const value of legacy.entries) {\n if (\n typeof value !== 'object' ||\n value === null ||\n !('id' in value) ||\n typeof value.id !== 'string' ||\n value.id === ''\n )\n continue;\n const entry = value as WorktreeRecord;\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 writeJsonAtomic(temporary, { version: WORKTREE_RECORD_VERSION, entries: [...entries.values()] });\n try {\n // Publish only if absent. A concurrent writer may already have added records.\n fs.linkSync(temporary, canonical);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n } finally {\n fs.rmSync(temporary);\n }\n return canonical;\n}\n","import type { DoomDirectEventBus } from '@agimon-ai/doompi-core/hubChannel';\n\nexport const GIT_WORKTREE_LIFECYCLE_EVENT = 'git_worktree_lifecycle';\nexport const GIT_WORKTREE_MESSAGE_EVENT = 'git_worktree_message';\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: DoomDirectEventBus, 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 * 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\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 doompi-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 function reconcile(\n records: readonly WorktreeRecord[],\n probe: { alive: (record: WorktreeRecord) => boolean; exists: (path: string) => boolean },\n): Reconciliation {\n const changed: string[] = [];\n const next = records.map((record) => {\n if (record.status === 'orphaned') return record;\n const gone = !probe.exists(record.path) || !probe.alive(record);\n if (!gone) return record;\n changed.push(record.id);\n return { ...record, status: 'orphaned' as const };\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","import fs from 'node:fs';\nimport path from 'node:path';\nimport { setTimeout } from 'node:timers/promises';\n\nimport {\n WORKTREE_RECORD_VERSION,\n type WorktreeRecord,\n type WorktreeRegistryFile,\n type WorktreeRegistryStore,\n} from '../../types/worktreeRegistry';\nimport { readJson, writeJsonAtomic } from '../atomicJson';\nimport { DoomGitExpectedError } from '../errors';\n\nconst LOCK_WAIT_MS = 5000;\nconst LOCK_RETRY_MS = 25;\n\nfunction isRecord(value: unknown): value is WorktreeRecord {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Partial<WorktreeRecord>;\n return (\n record.version === WORKTREE_RECORD_VERSION &&\n typeof record.id === 'string' &&\n record.id !== '' &&\n typeof record.path === 'string' &&\n typeof record.branch === 'string' &&\n typeof record.sessionId === 'string'\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(file: string): WorktreeRegistryStore {\n return {\n list() {\n const parsed = readJson<WorktreeRegistryFile>(file);\n if (!parsed || parsed.version !== WORKTREE_RECORD_VERSION || !Array.isArray(parsed.entries)) return [];\n return parsed.entries.filter(isRecord);\n },\n replace(entries) {\n writeJsonAtomic(file, { version: WORKTREE_RECORD_VERSION, entries } satisfies WorktreeRegistryFile);\n },\n async transaction(operation, signal) {\n const lock = `${file}.lock`;\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const deadline = Date.now() + LOCK_WAIT_MS;\n for (;;) {\n signal?.throwIfAborted();\n try {\n fs.mkdirSync(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 DoomGitExpectedError(\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 fs.writeFileSync(\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 fs.rmSync(lock, { recursive: true });\n }\n },\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\n\nimport type { DoomHubSessionService } from '@agimon-ai/doompi-core/hubChannel';\nimport { removeSyncLocation, resolveWorktreeSyncLocation } from '@agimon-ai/doompi-core/syncLocation';\nimport type { DoomSessionDeliveryService } from '@agimon-ai/doompi-session';\n\nimport { WORKTREE_RECORD_VERSION } from '../../types/worktreeRegistry';\nimport type { WorktreeGit, WorktreeRecord } from '../../types/worktreeRegistry';\nimport { mirrorComposition } from '../compositionMirror';\nimport { DoomGitExpectedError, HubUnavailableError } from '../errors';\nimport { registryFile, worktreesRoot } from '../paths';\nimport { repositoryId, repositoryLabel, shortId } from '../repositoryIdentity';\nimport { MAX_WORKTREE_MESSAGE_BYTES, type WorktreeMessageInbox, type WorktreeMessageParty } from '../worktreeEvents';\nimport { planPrune, reconcile, refuseClose, refuseSpawn, 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';\nexport interface WorktreeContext {\n /** Where the calling session is working, used to find the repository. */\n cwd: string;\n /** The calling session, recorded as the new session's parent. */\n sessionId: string;\n}\n\nexport interface SpawnWorktreeRequest {\n branch: string;\n baseRef?: 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}\n\nexport interface SpawnOptions {\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 spawn(context: WorktreeContext, request: SpawnWorktreeRequest, options?: SpawnOptions): Promise<WorktreeRecord>;\n close(context: WorktreeContext, id: string, force: boolean): 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 /** The canonical hub-owned session lifecycle. */\n sessionService?: DoomHubSessionService;\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?: () => DoomSessionDeliveryService | undefined;\n /** Injected so a test never copies a real dependency tree. */\n mirror?: typeof mirrorComposition;\n /** Injected so tests can observe generated-storage cleanup without touching real sync state. */\n cleanupStorage?: (repositoryRoot: string, worktreeRoot: string) => void;\n homeDir?: string;\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 sessionService = deps.sessionService;\n const mirror = deps.mirror ?? mirrorComposition;\n const removeStorage =\n deps.cleanupStorage ??\n ((repositoryRoot: string, worktreeRoot: string): void => {\n removeSyncLocation(resolveWorktreeSyncLocation(repositoryRoot, worktreeRoot, deps.homeDir));\n });\n const cleanupStorage = (repositoryRoot: string, worktreeRoot: string): void => {\n try {\n removeStorage(repositoryRoot, worktreeRoot);\n } catch (error) {\n throw new DoomGitExpectedError(\n 'worktree_cleanup_failed',\n `The worktree checkout was removed, but its generated storage could not be deleted (${error instanceof Error ? error.message : String(error)}).`,\n true,\n 'Retry close or prune after fixing the storage permissions.',\n );\n }\n };\n const now = deps.now ?? (() => new Date());\n const requireSessionService = (): DoomHubSessionService => {\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 = (): DoomSessionDeliveryService | undefined => deps.sessionDelivery?.();\n const requireSessionDelivery = (): DoomSessionDeliveryService => {\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) => fs.existsSync(path),\n };\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 DoomGitExpectedError(\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(registryFile(root, deps.homeDir));\n return { root, store, records: 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 DoomGitExpectedError(\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 (!requireSessionService().isLive(record.parentSessionId)) return;\n throw new DoomGitExpectedError(\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 (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 DoomGitExpectedError(\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 DoomGitExpectedError(\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 operations: WorktreeOperations = {\n async spawn(context, request, options) {\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 DoomGitExpectedError(\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, context.sessionId);\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),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: shortId(reserved!.sessionId),\n });\n if (\n existing.parentSessionId !== context.sessionId ||\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 !fs.existsSync(existing.path) ||\n !(await git.listWorktreePaths(root)).includes(existing.path) ||\n (await git.repositoryRoot(existing.path)) !== existing.path ||\n (await git.currentBranch(existing.path)) !== request.branch\n )\n throw new DoomGitExpectedError(\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: context.sessionId,\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!, context.sessionId);\n return existing;\n }\n const refusal = refuseSpawn({ branch: request.branch, existing: records });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('worktree_exists', refusal, false, 'Pick another branch name, or close it.');\n }\n const taskDelivery = request.task === undefined ? undefined : requireSessionDelivery();\n const baseRef = request.baseRef ?? (await git.remoteBaseRef(root));\n if (baseRef === undefined) {\n throw new DoomGitExpectedError(\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 const id = shortId(reserved?.sessionId ?? randomUUID());\n let path = worktreeDirectory({\n worktreesRoot: worktreesRoot(deps.homeDir),\n repositoryLabel: repositoryLabel(root),\n repositoryId: repositoryId(root),\n branch: request.branch,\n shortId: id,\n });\n if (request.reservationId !== undefined) {\n path = (await reservations!.prepare(request.reservationId, context.sessionId, path)).cwd;\n }\n const recovering = reserved?.cwd !== undefined && fs.existsSync(path);\n if (\n recovering &&\n (!(await git.listWorktreePaths(root)).includes(path) || (await git.currentBranch(path)) !== request.branch)\n )\n throw new DoomGitExpectedError(\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 // 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 git.removeWorktree({ repositoryRoot: root, path, force: true }).catch(() => undefined);\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 options?.onProgress?.(`creating branch ${request.branch}\\u2026`);\n if (!recovering) await git.addWorktree({ repositoryRoot: root, path, branch: request.branch, baseRef });\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 DoomGitExpectedError(\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 // Before the session, because the session composes the extensions this\n // repository's config names and those live in build output git does not\n // track. A worktree without it starts and dies on the first package it\n // cannot resolve. Nothing here can fail the spawn: a repository with no\n // build output to mirror simply has none.\n options?.onProgress?.('mirroring build output\\u2026');\n if (!recovering) mirror(root, path);\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 parentSessionId: context.sessionId,\n sessionProvenance: 'worktree',\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 DoomGitExpectedError(\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 DoomGitExpectedError(\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 parentSessionId: context.sessionId,\n status: 'running',\n createdAt: now().toISOString(),\n };\n try {\n 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 DoomGitExpectedError(\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 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: request.task,\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 Error(\n admission === 'recovery_required'\n ? 'The recipient could not admit the task.'\n : 'The recipient did not confirm task admission before the timeout.',\n );\n }\n } catch (error) {\n throw new DoomGitExpectedError(\n 'task_delivery_failed',\n `Worktree ${record.id} was created, but its task admission was not confirmed (${(error as Error).message}).`,\n true,\n `Use send with worktree ${record.id} to deliver the task without recreating the worktree.`,\n );\n }\n }\n if (request.reservationId !== undefined) await reservations!.complete(request.reservationId, context.sessionId);\n return record;\n },\n\n async close(context, id, force) {\n const { root, store, records } = await resolve(context);\n const record = require(records, id);\n requireOwner(context, record, 'close');\n const dirtyFiles = fs.existsSync(record.path) ? await git.dirtyFiles(record.path) : [];\n const refusal = refuseClose({ record, dirtyFiles, force });\n if (refusal !== undefined) {\n throw new DoomGitExpectedError('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 git.removeWorktree({ repositoryRoot: root, path: record.path, force });\n cleanupStorage(root, record.path);\n 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 = reconcile(records, probe);\n if (outcome.changed.length > 0) 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 = fs.existsSync(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 DoomGitExpectedError(\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 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 DoomGitExpectedError(\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 DoomGitExpectedError(\n 'message_delivery_failed',\n `Worktree ${record.id} persisted the message, but its session did not confirm admission.`,\n true,\n admission === 'recovery_required'\n ? 'Call messages from the recipient session to recover the persisted text.'\n : 'The message remains durable; retry after the recipient is ready.',\n );\n }\n return;\n }\n requireMessageInbox().send(peer.sessionId, {\n version: 1,\n worktreeId: record.id,\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 = delivery\n .inbox({ consumed: false, metadata: { worktreeId: record.id } })\n .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 return entries.map((entry) => {\n delivery.consume(entry.deliveryId);\n return {\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\n async prune(context, dryRun) {\n const { root, store, records } = await resolve(context);\n const reconciled = reconcile(records, probe);\n const gitPaths = await git.listWorktreePaths(root);\n const dirtyByPath = new Map<string, readonly string[]>();\n for (const record of reconciled.records) {\n if (record.status === 'orphaned' && fs.existsSync(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),\n dirtyByPath,\n });\n if (dryRun) {\n store.replace(reconciled.records);\n return plan;\n }\n for (const record of plan.remove) {\n await git.removeWorktree({ repositoryRoot: root, path: record.path, force: false });\n cleanupStorage(root, record.path);\n }\n for (const record of plan.forget) cleanupStorage(root, record.path);\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 if (!deleted) plan.keptBranches.push(record.branch);\n }\n const dropped = new Set([...plan.remove, ...plan.forget].map((record) => record.id));\n 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 DoomGitExpectedError))\n throw new DoomGitExpectedError(\n 'spawn_cancelled',\n 'The worktree operation was cancelled.',\n false,\n 'Inspect its recorded state before retrying.',\n );\n if (['ENOTDIR', 'EACCES', 'EROFS', 'ENOSPC'].includes(String((error as NodeJS.ErrnoException).code)))\n throw new DoomGitExpectedError(\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 DoomGitExpectedError(\n 'hub_unavailable',\n 'The cockpit session service is unavailable.',\n true,\n 'Use the cockpit worktree tool after its Git server facet is available.',\n ),\n );\n return locked(context, () => operations.spawn(context, request, options), options?.signal);\n },\n close: (context, id, force) => locked(context, () => operations.close(context, id, force)),\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;;;;;;;;AAezB,SAAS,IAAI,KAAa,MAAyB,SAAqC;CACtF,OAAO,IAAI,SAAS,YAAY;EAC9B,CAAA,GAAA,mBAAA,SAAA,CACE,OACA,CAAC,GAAG,IAAI,GACR;GAAE;GAAK;GAAS,WAAW;GAAkB,KAAK;IAAE,GAAG,QAAQ;IAAK,QAAQ;GAAI;EAAE,IACj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