alchemylab 1.0.4 → 1.0.6

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.
@@ -12,30 +12,30 @@ u.info("Using project ID from context",{projectId:l}),c.incrementCounter("create
12
12
  try{const e=i.getRequestClient(),t=await e.getRequest(a.requestId)
13
13
  u.info("Raw request verification response data",{responseData:JSON.stringify(t)})
14
14
  const r=(0,o.extractDataFromResponse)(t,{logger:u,operationName:"verifyRequestExists",throwOnNoData:!0})
15
- g="object"==typeof r&&null!==r&&"data"in r?r.data:r,u.info(`Verified request ${a.requestId} exists`,{requestId:a.requestId,projectId:l,requestStatus:g.status})}catch(e){throw new n.NotFoundError(`Request ${a.requestId} not found in project ${l}. Please provide a valid request ID.`,{requestId:a.requestId,projectId:l,originalError:e})}if("pending_approval"===g.status||"completed"===g.status||"canceled"===g.status||"ready_for_review"===g.status||"reverted"===g.status){const e={pending_approval:"is pending approval. Approve the request before creating tasks.",completed:"is already completed and merged. Create a new request for additional changes.",canceled:"was canceled. Create a new request or reopen this one if needed.",ready_for_review:"is ready for review. Complete review process or reopen to make changes.",reverted:"was reverted and cannot accept new tasks. Re-complete the request first or create a new request."}[g.status]||`has status '${g.status}' and cannot accept new tasks.`
15
+ g="object"==typeof r&&null!==r&&"data"in r?r.data:r,u.info(`Verified request ${a.requestId} exists`,{requestId:a.requestId,projectId:l,requestStatus:g.status})}catch(e){throw new n.NotFoundError(`Request ${a.requestId} not found in project ${l}. Please provide a valid request ID.`,{requestId:a.requestId,projectId:l,originalError:e})}if(["pending_approval","completed","canceled","ready_for_review","ready_for_merge","reverted"].includes(g.status)){const e={pending_approval:"is pending approval. Approve the request before creating tasks.",completed:"is already completed and merged. Create a new request for additional changes.",canceled:"was canceled. Create a new request or reopen this one if needed.",ready_for_review:"is being tested. Wait for test results before making changes.",ready_for_merge:"is ready to merge. Call merge to complete it.",reverted:"was reverted and cannot accept new tasks. Re-complete the request first or create a new request."}[g.status]||`has status '${g.status}' and cannot accept new tasks.`
16
16
  throw u.warn(`Task creation blocked on ${g.status} request`,{requestId:a.requestId,requestStatus:g.status,projectId:l}),new n.ValidationError(`The request ID "${a.requestId}" ${e}`,{requestId:a.requestId,requestStatus:g.status,reason:"request_"+g.status})}u.info("Request status validation passed for "+a.requestId,{requestId:a.requestId,requestStatus:g.status,projectId:l})
17
- const p=i.getTaskClient()
17
+ const f=i.getTaskClient()
18
18
  u.info("Creating task with project context",{projectId:l})
19
- const f={requestId:a.requestId,projectId:l,title:a.title,description:a.description,status:"pending",...d&&{cliOrigin:d}}
20
- u.info("Task input prepared",{taskInput:JSON.stringify(f)}),u.info("Creating task via task client",{projectId:l,requestId:a.requestId,title:a.title})
21
- const m=await p.createTask(f)
19
+ const p={requestId:a.requestId,projectId:l,title:a.title,description:a.description,status:"pending",...d&&{cliOrigin:d}}
20
+ u.info("Task input prepared",{taskInput:JSON.stringify(p)}),u.info("Creating task via task client",{projectId:l,requestId:a.requestId,title:a.title})
21
+ const m=await f.createTask(p)
22
22
  u.debug("Task creation response structure",{type:typeof m,isArray:Array.isArray(m),hasData:null!=m,properties:m?Object.keys(m):[],dataPreview:m?JSON.stringify(m).substring(0,200)+"...":"null"})
23
- const y=(0,o.extractDataFromResponse)(m,{logger:u,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:f.title,description:f.description,status:"pending",requestId:f.requestId,projectId:l,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),w="data"in y?y.data:y,k=w.localId||w.id||"tas"+Date.now().toString().substring(5,11),b=w.title||f.title,I=w.description||f.description,v=w.status||"pending",C=w.requestId||f.requestId
23
+ const y=(0,o.extractDataFromResponse)(m,{logger:u,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:p.title,description:p.description,status:"pending",requestId:p.requestId,projectId:l,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),w="data"in y?y.data:y,k=w.localId||w.id||"tas"+Date.now().toString().substring(5,11),b=w.title||p.title,I=w.description||p.description,v=w.status||"pending",C=w.requestId||p.requestId
24
24
  let _,E="unknown"
25
25
  w&&"object"==typeof w&&"_workingEndpoint"in w&&(E=w._workingEndpoint),u.info("Successfully extracted task data from response",{taskId:k,requestId:C,title:b})
26
26
  try{const e=i.getToolRecordClient()
27
27
  if(e){const t=await e.createToolRecord({taskId:k,requestId:C,projectId:l,type:"create-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:b,taskDescription:I,taskStatus:v},note:"Created task "+b})
28
28
  _=t?.id}}catch(e){u.error("Failed to create tool record for task creation, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:k,requestId:C})}h({success:!0,requestId:a.requestId,projectId:l}),u.info("Task created successfully",{taskId:k,requestId:C,title:b,projectId:l})
29
- let q="Created Task "+k
29
+ let q=`Created Task ${k}: ${b}`
30
30
  return _&&(q+=`\n[RECORD:${_}]`),{content:[{type:"text",text:q}]}}catch(r){if(u.error("Failed to create task",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new tasks")||r.message.includes("disabled due to tier limits")||r.message.includes("Project is inactive due to tier limits")))u.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
31
31
  else{const n=i.getToolRecordClient()
32
32
  n&&await n.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"create-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.title,taskDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),error:(0,s.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create task: "+e.title})}}catch(e){u.error("Failed to create failure record for task creation",{error:e instanceof Error?e.message:e+""})}h({success:!1,error:r instanceof Error?r.name:"unknown"})
33
33
  let o=(0,s.getErrorMessage)(r),c=""
34
34
  return r instanceof n.NotFoundError?o=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`:r instanceof n.ValidationError&&(o.includes("Project cannot accept new tasks")||o.includes("Project is inactive due to tier limits")?c="\n\nThis project is currently inactive due to tier limits. Only your oldest projects can accept new tasks. Please use an active project or upgrade your tier for more simultaneous projects.":o="Invalid input: "+o),a.error("Detailed error when creating task",{error:(0,s.getErrorMessage)(r),stack:r instanceof Error?r.stack:void 0}),i.isOffline,i.apiClient,{content:[{type:"text",text:`Error: ${o}${c}`}],isError:!0}}}
35
35
  const r=t(6183),n=t(9860),o=t(2960),s=t(8824)},184(e,exports,t){function r(e,t,r,n,o={}){const s=d.default.resolve(e)
36
- if(A.has(s))return t.child({component:"mcp-server-registry"}).debug("Using existing server for path",{path:s}),A.get(s)
36
+ if(D.has(s))return t.child({component:"mcp-server-registry"}).debug("Using existing server for path",{path:s}),D.get(s)
37
37
  const i=new $(s,t,r,n,o)
38
- return A.set(s,i),i}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
38
+ return D.set(s,i),i}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
39
39
  var o=Object.getOwnPropertyDescriptor(t,r)
40
40
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[]
41
41
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -44,9 +44,9 @@ var t={}
44
44
  if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
45
45
  return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
46
46
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=O},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
47
- const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),f=t(7660),m=t(1253),y=t(5172),w=t(7976),k=i(t(7478)),b=t(4139),I=new Set,v=t(9860),C=t(1472),_=t(3328),E=t(8955),q=t(3217),S=t(8411),T=t(5278),M=t(446),R=t(9060),P=t(8824),x=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),O=process.stdout.write,j=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
48
- !(0,p.isDebugToolsEnabled)()||j&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,p.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&x.debug("Stdout output",{content:e.substring(0,100),length:e.length}),O.call(process.stdout,e)}catch(e){return x.error("Error in safeStdoutWrite",{error:e+""}),!0}})
49
- class ${constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.clientInfo=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.multiAgentMode=o.multiAgentMode||!1,this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,multiAgentMode:o.multiAgentMode||!1,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,b.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new f.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new M.LockOverrideManager(t),this.configManager=new R.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),this.metrics.incrementCounter("mcp_server_init_started",1),this.interceptConnectMethod(),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
47
+ const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),f=t(3444),p=t(7660),m=t(1253),y=t(5172),w=t(7976),k=i(t(7478)),b=t(4139),I=new Set,v=t(9860),C=t(1472),_=t(3328),E=t(8955),q=t(3217),S=t(8411),T=t(5278),M=t(446),R=t(9060),P=t(8824),x=(0,f.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),O=process.stdout.write,j=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
48
+ !(0,f.isDebugToolsEnabled)()||j&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,f.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&x.debug("Stdout output",{content:e.substring(0,100),length:e.length}),O.call(process.stdout,e)}catch(e){return x.error("Error in safeStdoutWrite",{error:e+""}),!0}})
49
+ class ${constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.clientInfo=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.multiAgentMode=o.multiAgentMode||!1,this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,multiAgentMode:o.multiAgentMode||!1,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,b.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new p.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new M.LockOverrideManager(t),this.configManager=new R.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),this.metrics.incrementCounter("mcp_server_init_started",1),this.interceptConnectMethod(),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
50
50
  const e=this.workspaceManager.getCurrentContext()
51
51
  return{currentBranch:e.branchName,activeRequestId:e.requestId,isOnMainBranch:e.isMainBranch}}async updateBranchState(e,t){this.logger.debug("updateBranchState called - managed by WorkspaceManager",{branch:e,requestId:t})}async getCurrentBranchContext(){if(!this.workspaceManager)return{branch:null,requestId:null,isMain:!0}
52
52
  const e=this.workspaceManager.getCurrentContext()
@@ -166,7 +166,7 @@ try{const t=await k.getCurrentBranch(this.git,this.logger,this.metrics)
166
166
  return this.logger.info("Single-agent Git instance branch status",{requestId:e,currentBranch:t,expectedBranch:n.branchName,basePath:n.basePath}),{success:!0,message:`Switched to request ${e} context`}}catch(t){return this.logger.warn("Branch verification failed but continuing",{requestId:e,error:t instanceof Error?t.message:t+""}),{success:!0,message:`Switched to request ${e} context (branch verification warning)`}}}catch(t){return this.logger.error("Failed to switch to single-agent request context",{requestId:e,error:(0,P.getErrorMessage)(t)}),{success:!1,message:"Failed to switch to request context: "+(0,P.getErrorMessage)(t)}}}async getEffectiveBasePath(e){if(!this.multiAgentMode||!this.workspaceManager||!e)return this.basePath
167
167
  const t=await this.workspaceManager.getWorkspaceInfo(e)
168
168
  return t?.path||this.basePath}}exports.McpServer=$
169
- const A=new Map},213(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
169
+ const D=new Map},213(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
170
170
  const r=t(6183),n=t(3707)
171
171
  exports.def={name:"quick_write",description:"Create or update a file or document. Wraps the change in a request/task workflow that auto-completes.\n\nUse 'path' for filesystem files or 'documentId' for tracked documents.\nSet append:true to add content to existing content.\n\nRequires: title, description, path/documentId, content.",schema:r.QuickWriteSchema,annotations:{title:"Quick Write",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"write",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},233(e,exports,t){function r(e,t){const r=e.toLowerCase().indexOf(t.toLowerCase())
172
172
  return-1===r?e:`${e.substring(0,r)}**${e.substring(r,r+t.length)}**${e.substring(r+t.length)}`}function n(e,t,r){const n=e.toLowerCase().indexOf(t)
@@ -184,12 +184,12 @@ case"quick-edit":return"\u26a1"
184
184
  default:return"\u{1f4e6}"}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearchRequests=async function(e,t,c,l,d){const u=l.child({tool:"search_requests"}),h=d.startTimer("tool_execution_time")
185
185
  try{const{query:a,searchIn:l="all",filters:g={}}=e.search||e
186
186
  if(!a||0===a.trim().length)throw new i.ValidationError("Search query is required")
187
- const p=t.projectId
188
- if(!p)throw new i.ValidationError("Project ID is required for searching requests")
189
- u.info("Searching requests",{query:a,searchIn:l,filters:g,projectId:p})
190
- const f={limit:g.limit||100,offset:g.offset||0,sortBy:"updated_at",sortDirection:"desc"}
191
- g.status&&(f.status=g.status),g.type&&(f.type=g.type),g.dateFrom&&(f.dateFrom=g.dateFrom),g.dateTo&&(f.dateTo=g.dateTo),c.setProjectId(p)
192
- const m=c.getRequestClient(),y=await m.listRequests(f)
187
+ const f=t.projectId
188
+ if(!f)throw new i.ValidationError("Project ID is required for searching requests")
189
+ u.info("Searching requests",{query:a,searchIn:l,filters:g,projectId:f})
190
+ const p={limit:g.limit||100,offset:g.offset||0,sortBy:"updated_at",sortDirection:"desc"}
191
+ g.status&&(p.status=g.status),g.type&&(p.type=g.type),g.dateFrom&&(p.dateFrom=g.dateFrom),g.dateTo&&(p.dateTo=g.dateTo),c.setProjectId(f)
192
+ const m=c.getRequestClient(),y=await m.listRequests(p)
193
193
  u.debug("Fetched requests for search",{count:y.length})
194
194
  const w=[],k=a.toLowerCase()
195
195
  for(const e of y){const t=[]
@@ -222,12 +222,18 @@ case"ready_for_review":t="ready_for_review"
222
222
  break
223
223
  case"pending_approval":case o.RequestStatus.PENDING_APPROVAL:t="pending_approval"
224
224
  break
225
+ case"pending_verification":t="ready_for_review"
226
+ break
227
+ case"ready_for_merge":t="ready_for_merge"
228
+ break
229
+ case"resolving_conflicts":t="resolving_conflicts"
230
+ break
225
231
  default:t="open"}else t="open"
226
232
  const n=Array.isArray(e.acceptanceCriteria)?e.acceptanceCriteria.map(r):[]
227
233
  return{id:e.id,title:e.title,description:e.description,type:e.type,status:t,acceptanceCriteria:n,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.projectId?{projectId:e.projectId}:{},...e.completionSummary?{completionSummary:e.completionSummary}:{},...e.completedAt?{completedAt:e.completedAt}:{},...e.metadata?{metadata:e.metadata}:{},...e.lockInfo?{lockInfo:e.lockInfo}:{}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.adaptApiAcceptanceCriterionToDomain=r,exports.adaptApiRequestToDomain=n,exports.adaptApiRequestsToDomain=function(e){return e.map(n)}
228
- const o=t(6756)},355(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const p=h.child({tool:"complete_task"})
229
- p.info("Completing task",{args:e})
230
- const f=g.startTimer("tool_handler_duration")
234
+ const o=t(6756)},355(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const f=h.child({tool:"complete_task"})
235
+ f.info("Completing task",{args:e})
236
+ const p=g.startTimer("tool_handler_duration")
231
237
  try{const{taskId:o,summary:h}=function(e){if(void 0!==e.verificationSteps){const{verificationSteps:t,...r}=e
232
238
  e=r}try{return r.CompleteTaskSchema.parse(e)}catch(e){if(e instanceof i.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
233
239
  throw new n.ValidationError("Invalid input: "+(0,l.getErrorMessage)(e))}}(e),m=d.projectId
@@ -236,35 +242,35 @@ g.incrementCounter("complete_task_attempts",1,{taskId:o}),u.setProjectId(m)
236
242
  const y=u.getTaskClient()
237
243
  let w
238
244
  try{const e=await y.getTask(o)
239
- p.info("Raw task response data",{responseData:JSON.stringify(e)}),p.debug("Task response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
240
- const t=(0,s.extractDataFromResponse)(e,{logger:p,operationName:"getTask",throwOnNoData:!0})
241
- w="data"in t?t.data:t,p.info("Current task status: "+w.status,{taskId:o,currentStatus:w.status})}catch(e){if(e instanceof n.ValidationError)throw e
245
+ f.info("Raw task response data",{responseData:JSON.stringify(e)}),f.debug("Task response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
246
+ const t=(0,s.extractDataFromResponse)(e,{logger:f,operationName:"getTask",throwOnNoData:!0})
247
+ w="data"in t?t.data:t,f.info("Current task status: "+w.status,{taskId:o,currentStatus:w.status})}catch(e){if(e instanceof n.ValidationError)throw e
242
248
  throw new n.NotFoundError(`Task ${o} not found in project ${m}. Please provide a valid task ID.`,{taskId:o,projectId:m,originalError:e})}if("completed"===w.status){const e="Task is already completed."
243
- throw p.warn(e,{taskId:o,currentStatus:w.status}),new n.ValidationError(e)}if("canceled"===w.status){const e="Task is canceled and can not be completed."
244
- throw p.warn(e,{taskId:o,currentStatus:w.status}),new n.ValidationError(e)}if(d.multiAgentMode&&w.requestId){p.debug("Multi-agent mode: checking request lock for task operation",{taskId:o,requestId:w.requestId})
249
+ throw f.warn(e,{taskId:o,currentStatus:w.status}),new n.ValidationError(e)}if("canceled"===w.status){const e="Task is canceled and can not be completed."
250
+ throw f.warn(e,{taskId:o,currentStatus:w.status}),new n.ValidationError(e)}if(d.multiAgentMode&&w.requestId){f.debug("Multi-agent mode: checking request lock for task operation",{taskId:o,requestId:w.requestId})
245
251
  try{const e=u.getRequestClient(),{sessionTag:t}=(0,a.getGlobalClientInfo)(),r=await e.getRequestLockStatus(w.requestId)
246
252
  if(r.isLocked){if(r.lockedBySessionTag!==t){let e=`Request ${w.requestId} is locked by another agent (${r.lockedBySessionTag}). `
247
- throw r.isExpired?e+="Lock has expired but cleanup may be pending. ":e+=`Lock expires in: ${r.timeRemainingFormatted}. `,e+="Only the agent that locked the request can modify its tasks.",new n.ValidationError(e,{taskId:o,requestId:w.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{p.debug("Lock not held, auto-acquiring for task completion",{requestId:w.requestId,sessionTag:t})
253
+ throw r.isExpired?e+="Lock has expired but cleanup may be pending. ":e+=`Lock expires in: ${r.timeRemainingFormatted}. `,e+="Only the agent that locked the request can modify its tasks.",new n.ValidationError(e,{taskId:o,requestId:w.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{f.debug("Lock not held, auto-acquiring for task completion",{requestId:w.requestId,sessionTag:t})
248
254
  const r=await e.lockRequest(w.requestId,t)
249
255
  if(!r.locked)throw new n.ValidationError(`Failed to acquire lock for request ${w.requestId}. Another agent may have just locked it. Try again shortly.`,{taskId:o,requestId:w.requestId})
250
- p.info("Auto-acquired lock for task completion",{requestId:w.requestId,sessionTag:t,lockedAt:r.lockedAt})}p.info("Request lock validation passed",{taskId:o,requestId:w.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
251
- throw p.error("Failed to check request lock status",{taskId:o,requestId:w.requestId,error:(0,l.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,l.getErrorMessage)(e),{taskId:o,requestId:w.requestId})}}else p.debug("Single-agent mode or task without requestId: skipping lock check",{taskId:o,isMultiAgent:(0,c.isMultiAgentModeEnabled)(),hasRequestId:!!w.requestId})
256
+ f.info("Auto-acquired lock for task completion",{requestId:w.requestId,sessionTag:t,lockedAt:r.lockedAt})}f.info("Request lock validation passed",{taskId:o,requestId:w.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
257
+ throw f.error("Failed to check request lock status",{taskId:o,requestId:w.requestId,error:(0,l.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,l.getErrorMessage)(e),{taskId:o,requestId:w.requestId})}}else f.debug("Single-agent mode or task without requestId: skipping lock check",{taskId:o,isMultiAgent:(0,c.isMultiAgentModeEnabled)(),hasRequestId:!!w.requestId})
252
258
  let k=d.git
253
259
  if(d.workspaceManager){const e=d.workspaceManager.getCurrentContext()
254
260
  if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
255
- k=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),p.debug("Using workspace-aware git instance for task completion",{taskId:o,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let b=null
256
- if(k)try{(await k.status()).isClean()||(b=(await k.commit(`Complete task ${o}: ${h}`)).commit,p.info("Created commit for task completion",{taskId:o,commitId:b}))}catch(e){p.warn("Failed to commit changes",{error:(0,l.getErrorMessage)(e)})}let I=null
261
+ k=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),f.debug("Using workspace-aware git instance for task completion",{taskId:o,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let b=null
262
+ if(k)try{(await k.status()).isClean()||(b=(await k.commit(`Complete task ${o}: ${h}`)).commit,f.info("Created commit for task completion",{taskId:o,commitId:b}))}catch(e){f.warn("Failed to commit changes",{error:(0,l.getErrorMessage)(e)})}let I=null
257
263
  try{const e=u.getToolRecordClient()
258
- e&&(I={id:(await e.createToolRecord({taskId:o,requestId:w.requestId,projectId:m,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:w.title,completionSummary:h,lastCommit:b,completedAt:(new Date).toISOString()},note:`Completed task: ${h.substring(0,100)}${h.length>100?"...":""}`})).id})}catch(e){p.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:o,requestId:w.requestId})}try{const e=w.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:b,completionSummary:h,completionRecordId:I?.id,completedAt:t}},n=await y.updateTask(o,r)
259
- p.info("Raw task update response data",{responseData:JSON.stringify(n)}),p.debug("Task update response structure",{type:typeof n,isArray:Array.isArray(n),hasData:null!=n,properties:n?Object.keys(n):[],dataPreview:n?JSON.stringify(n).substring(0,200)+"...":"null"}),(0,s.extractDataFromResponse)(n,{logger:p,operationName:"updateTask",defaultValue:{id:o,status:"completed"}}),p.info("Successfully completed task",{taskId:o,recordId:I?.id})
264
+ e&&(I={id:(await e.createToolRecord({taskId:o,requestId:w.requestId,projectId:m,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:w.title,completionSummary:h,lastCommit:b,completedAt:(new Date).toISOString()},note:`Completed task: ${h.substring(0,100)}${h.length>100?"...":""}`})).id})}catch(e){f.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:o,requestId:w.requestId})}try{const e=w.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:b,completionSummary:h,completionRecordId:I?.id,completedAt:t}},n=await y.updateTask(o,r)
265
+ f.info("Raw task update response data",{responseData:JSON.stringify(n)}),f.debug("Task update response structure",{type:typeof n,isArray:Array.isArray(n),hasData:null!=n,properties:n?Object.keys(n):[],dataPreview:n?JSON.stringify(n).substring(0,200)+"...":"null"}),(0,s.extractDataFromResponse)(n,{logger:f,operationName:"updateTask",defaultValue:{id:o,status:"completed"}}),f.info("Successfully completed task",{taskId:o,recordId:I?.id})
260
266
  const i=w.requestId
261
- let a=`Task ${o} has been marked as completed.`
267
+ let a=`Task ${o} (${w.title}) has been marked as completed.`
262
268
  if(I?.id&&(a+=`\n[RECORD:${I.id}]`),b&&(a+="\nCommit: "+b.substring(0,8)),i)try{const e=await y.listTasks({requestId:i})
263
- p.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),p.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
264
- const t=(0,s.extractArrayFromResponse)(e,{logger:p,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
265
- p.info("Task progress check",{requestId:i,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${i} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){p.warn("Failed to check task progress",{error:(0,l.getErrorMessage)(e),requestId:i})}return f({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw p.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:o}),Error("Failed to complete task: "+(0,l.getErrorMessage)(e))}}catch(t){if(p.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
269
+ f.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),f.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
270
+ const t=(0,s.extractArrayFromResponse)(e,{logger:f,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
271
+ f.info("Task progress check",{requestId:i,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${i} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){f.warn("Failed to check task progress",{error:(0,l.getErrorMessage)(e),requestId:i})}return p({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw f.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:o}),Error("Failed to complete task: "+(0,l.getErrorMessage)(e))}}catch(t){if(f.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
266
272
  if(r){const o=t instanceof n.NotFoundError||t instanceof n.ValidationError||t instanceof i.ZodError
267
- await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:d.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,l.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){p.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}f({success:!1,error:t instanceof Error?t.name:"unknown"})
273
+ await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:d.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,l.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){f.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}p({success:!1,error:t instanceof Error?t.name:"unknown"})
268
274
  let r=(0,l.getErrorMessage)(t)
269
275
  return t instanceof n.NotFoundError&&(r=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),t instanceof o.ConnectionError&&(r="Unable to complete task: Connection to the server failed. Please check your network connection and try again."),t instanceof i.ZodError&&t.errors.length>0&&(r=t.errors[0].message),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
270
276
  const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(5218),l=t(8824)},405(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
@@ -276,19 +282,21 @@ var t={}
276
282
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
277
283
  return o(t,e),t})
278
284
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlanWrite=async function(e,t,r,n,o){const s=n.child({tool:"plan_write"})
279
- try{const n=a.validateArgs(e,i.PlanWriteSchema),{operation:u}=n
280
- switch(s.info("Processing plan_write",{operation:u}),u){case"update":{const e=await(0,c.handleUpdatePlan)(n.update,t,r,s,o)
281
- return o.incrementCounter("plan_write_total",1,{operation:"update",success:!e.isError}),e}case"append":{const e=await(0,l.handleAppendPlan)(n.append,r,s,o)
282
- return o.incrementCounter("plan_write_total",1,{operation:"append",success:!e.isError}),e}case"replace":{const e=await(0,d.handleReplacePlan)(n.replace,r,s,o)
283
- return o.incrementCounter("plan_write_total",1,{operation:"replace",success:!e.isError}),e}case"create-snapshot":{const{planId:e,versionLabel:t,changeSummary:s}=n.createSnapshot,i=r.getDocumentClient(),a=await i.createVersionSnapshot(e,t,s)
284
- return o.incrementCounter("plan_write_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Plan Snapshot Created**\n\n**Plan:** ${e}\n**Version:** ${a.versionNumber}\n**Label:** ${t||"None"}\n**Summary:** ${s||"None"}\n**Created:** `+new Date(a.createdAt).toLocaleString()}]}}case"restore":{const{planId:e,versionNumber:t}=n.restore,s=r.getDocumentClient(),i=await s.restoreToVersion(e,t)
285
- return o.incrementCounter("plan_write_total",1,{operation:"restore",success:!0}),{content:[{type:"text",text:`\u2705 **Plan Restored**\n\n**Plan:** ${e}\n**Restored to Version:** ${t}\n**Filename:** ${i.filename}\n\nThe plan has been successfully restored to version ${t}.`}]}}case"set-active":{const{planId:e}=n.setActive,s=t.projectId
286
- if(!s)return{content:[{type:"text",text:"\u274c No project context available."}],isError:!0}
287
- const i=r.getDocumentClient(),a=await i.getDocument(e)
288
- if(!a)return{content:[{type:"text",text:"\u274c Plan not found: "+e}],isError:!0}
289
- if("Plan"!==a.type)return{content:[{type:"text",text:`\u274c Document ${e} is not a Plan (type: ${a.type}).`}],isError:!0}
290
- const c=r.getProjectClient()
291
- return await c.updateProject(s,{activePlanId:e}),o.incrementCounter("plan_write_total",1,{operation:"set-active",success:!0}),{content:[{type:"text",text:`\u2705 **Active Plan Updated**\n\n**Plan:** ${a.localId||a.id}\n**Filename:** ${a.filename}\n**Project:** ${s}\n\nThis plan is now the active project plan.`}]}}default:throw Error("Unknown plan_write operation: "+u)}}catch(e){return s.error("plan_write failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("plan_write_errors",1),{content:[{type:"text",text:"\u274c **Plan Write Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
285
+ try{const n=["update","append","replace","createSnapshot","restore","setActive"]
286
+ for(const t of n)e?.[t]&&"object"==typeof e[t]&&(Object.assign(e,e[t]),delete e[t])
287
+ const u=a.validateArgs(e,i.PlanWriteSchema),{operation:h,planId:g}=u
288
+ switch(s.info("Processing plan_write",{operation:h}),h){case"update":{const e=await(0,c.handleUpdatePlan)({planId:g,content:u.content,name:u.name},t,r,s,o)
289
+ return o.incrementCounter("plan_write_total",1,{operation:"update",success:!e.isError}),e}case"append":{const e=await(0,l.handleAppendPlan)({planId:g,content:u.content,name:u.name},r,s,o)
290
+ return o.incrementCounter("plan_write_total",1,{operation:"append",success:!e.isError}),e}case"replace":{const e=await(0,d.handleReplacePlan)({planId:g,old:u.old,new:u.new,name:u.name},r,s,o)
291
+ return o.incrementCounter("plan_write_total",1,{operation:"replace",success:!e.isError}),e}case"create-snapshot":{const{versionLabel:e,changeSummary:t}=u,n=r.getDocumentClient(),s=await n.createVersionSnapshot(g,e,t)
292
+ return o.incrementCounter("plan_write_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Plan Snapshot Created**\n\n**Plan:** ${g}\n**Version:** ${s.versionNumber}\n**Label:** ${e||"None"}\n**Summary:** ${t||"None"}\n**Created:** `+new Date(s.createdAt).toLocaleString()}]}}case"restore":{const{versionNumber:e}=u,t=r.getDocumentClient(),n=await t.restoreToVersion(g,e)
293
+ return o.incrementCounter("plan_write_total",1,{operation:"restore",success:!0}),{content:[{type:"text",text:`\u2705 **Plan Restored**\n\n**Plan:** ${g}\n**Restored to Version:** ${e}\n**Filename:** ${n.filename}\n\nThe plan has been successfully restored to version ${e}.`}]}}case"set-active":{const e=t.projectId
294
+ if(!e)return{content:[{type:"text",text:"\u274c No project context available."}],isError:!0}
295
+ const n=r.getDocumentClient(),s=await n.getDocument(g)
296
+ if(!s)return{content:[{type:"text",text:"\u274c Plan not found: "+g}],isError:!0}
297
+ if("Plan"!==s.type)return{content:[{type:"text",text:`\u274c Document ${g} is not a Plan (type: ${s.type}).`}],isError:!0}
298
+ const i=r.getProjectClient()
299
+ return await i.updateProject(e,{activePlanId:g}),o.incrementCounter("plan_write_total",1,{operation:"set-active",success:!0}),{content:[{type:"text",text:`\u2705 **Active Plan Updated**\n\n**Plan:** ${s.localId||s.id}\n**Filename:** ${s.filename}\n**Project:** ${e}\n\nThis plan is now the active project plan.`}]}}default:throw Error("Unknown plan_write operation: "+h)}}catch(e){return s.error("plan_write failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("plan_write_errors",1),{content:[{type:"text",text:"\u274c **Plan Write Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
292
300
  const i=t(6183),a=s(t(5967)),c=t(7609),l=t(4419),d=t(2352),u=t(8824)},410(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
293
301
  var o=Object.getOwnPropertyDescriptor(t,r)
294
302
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
@@ -298,11 +306,12 @@ var t={}
298
306
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
299
307
  return o(t,e),t})
300
308
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTaskOperations=async function(e,t,r,n,o){const s=n.child({tool:"task_operations"})
301
- try{const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:d,operation:u}=n
309
+ try{e?.list?.filters&&"object"==typeof e.list.filters?(Object.assign(e,e.list.filters),delete e.list):e?.list&&"object"==typeof e.list&&(Object.assign(e,e.list),delete e.list)
310
+ const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:d,operation:u}=n
302
311
  let h
303
312
  switch(s.info("Processing task_operations",{taskId:d,operation:u}),u){case"get-info":s.info("Routing to get-task-information handler",{taskId:d}),h=await(0,c.handleGetTaskInformation)({taskId:d},t,r,s,o)
304
313
  break
305
- case"list":s.info("Routing to list-tasks handler",{requestId:n.requestId}),h=await(0,l.handleListTasks)({requestId:n.requestId,filters:n.list?.filters},t,r,s,o)
314
+ case"list":s.info("Routing to list-tasks handler",{requestId:n.requestId}),h=await(0,l.handleListTasks)({requestId:n.requestId,filters:{status:n.status,limit:n.limit,offset:n.offset,sortBy:n.sortBy,sortDirection:n.sortDirection}},t,r,s,o)
306
315
  break
307
316
  default:throw Error("Unknown operation type: "+u)}return s.info("task_operations completed",{taskId:d,operation:u,success:!h.isError}),o.incrementCounter("task_operations_total",1,{operation:u,success:!h.isError}),h}catch(e){return s.error("task_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("task_operations_errors",1),{content:[{type:"text",text:"\u274c **Task Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
308
317
  const i=t(6183),a=s(t(5967)),c=t(3420),l=t(9863),d=t(8824)},441(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.BAD_REQUEST=exports.INTERNAL_ERROR=exports.NOT_FOUND=exports.FORBIDDEN=exports.UNAUTHORIZED=exports.VALIDATION_ERROR=exports.MCP_PROTOCOL_ERROR=exports.REQUEST_VALIDATION_FAILED=exports.REQUEST_ID_INVALID_FORMAT=exports.REQUEST_NOT_FOUND=exports.CONNECTION_ERROR=exports.SERVICE_UNAVAILABLE=exports.CONNECTION_TIMEOUT=exports.SERVER_ERROR=exports.NETWORK_ERROR=exports.TASK_VALIDATION_FAILED=exports.TASK_ID_INVALID_FORMAT=exports.TASK_NOT_FOUND=void 0,exports.TASK_NOT_FOUND="TASK_NOT_FOUND",exports.TASK_ID_INVALID_FORMAT="TASK_ID_INVALID_FORMAT",exports.TASK_VALIDATION_FAILED="TASK_VALIDATION_FAILED",exports.NETWORK_ERROR="NETWORK_ERROR",exports.SERVER_ERROR="SERVER_ERROR",exports.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",exports.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",exports.CONNECTION_ERROR="CONNECTION_ERROR",exports.REQUEST_NOT_FOUND="REQUEST_NOT_FOUND",exports.REQUEST_ID_INVALID_FORMAT="REQUEST_ID_INVALID_FORMAT",exports.REQUEST_VALIDATION_FAILED="REQUEST_VALIDATION_FAILED",exports.MCP_PROTOCOL_ERROR="MCP_PROTOCOL_ERROR",exports.VALIDATION_ERROR="VALIDATION_ERROR",exports.UNAUTHORIZED="UNAUTHORIZED",exports.FORBIDDEN="FORBIDDEN",exports.NOT_FOUND="NOT_FOUND",exports.INTERNAL_ERROR="INTERNAL_ERROR",exports.BAD_REQUEST="BAD_REQUEST"},446(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.LockOverrideManager=void 0,exports.createLockOverrideManager=function(e){return new n(e)}
@@ -381,23 +390,23 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
381
390
  var t={}
382
391
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
383
392
  return o(t,e),t})
384
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const p=o.child({tool:"query_history"})
393
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const f=o.child({tool:"query_history"})
385
394
  try{const o=a.validateArgs(e,i.QueryHistorySchema),{queryType:h}=o
386
- let f
387
- switch(p.info("Processing query_history request",{queryType:h}),h){case"file-history":p.info("Routing to file-history handler",{path:o.fileHistory.path}),f=await(0,c.handleFileHistory)({path:o.fileHistory.path,limit:o.fileHistory.limit,showDiff:o.fileHistory.showDiff,showTraceability:o.fileHistory.showTraceability,branch:o.fileHistory.branch,since:o.fileHistory.since},r,n,p,s)
395
+ let p
396
+ switch(f.info("Processing query_history request",{queryType:h}),h){case"file-history":f.info("Routing to file-history handler",{path:o.fileHistory.path}),p=await(0,c.handleFileHistory)({path:o.fileHistory.path,limit:o.fileHistory.limit,showDiff:o.fileHistory.showDiff,showTraceability:o.fileHistory.showTraceability,branch:o.fileHistory.branch,since:o.fileHistory.since},r,n,f,s)
388
397
  break
389
- case"request-file-history":p.info("Routing to request-file-history handler",{requestId:o.requestHistory.requestId}),f=await(0,l.handleRequestFileHistory)({requestId:o.requestHistory.requestId,showDiff:o.requestHistory.showDiff,detailLevel:o.requestHistory.detailLevel,taskId:o.requestHistory.taskId,fileFilter:o.requestHistory.fileFilter},r,n,p,s)
398
+ case"request-file-history":f.info("Routing to request-file-history handler",{requestId:o.requestHistory.requestId}),p=await(0,l.handleRequestFileHistory)({requestId:o.requestHistory.requestId,showDiff:o.requestHistory.showDiff,detailLevel:o.requestHistory.detailLevel,taskId:o.requestHistory.taskId,fileFilter:o.requestHistory.fileFilter},r,n,f,s)
390
399
  break
391
- case"recover":p.info("Routing to file-recover handler",{taskId:o.recover.taskId,path:o.recover.path,commitHash:o.recover.commitHash})
400
+ case"recover":f.info("Routing to file-recover handler",{taskId:o.recover.taskId,path:o.recover.path,commitHash:o.recover.commitHash})
392
401
  let e=o.recover.commitHash
393
402
  if(!e){const n=o.recover.path,s=r.basePath||process.cwd(),{resolve:i}=await Promise.resolve().then(t.t.bind(t,6928,23)),a=i(s,n)
394
403
  try{const{execSync:r}=await Promise.resolve().then(t.t.bind(t,5317,23)),o=r(`git log --format=%H -n 2 -- "${a}"`,{cwd:s,encoding:"utf8"}).trim().split("\n").filter(Boolean)
395
404
  if(e=o[1]||o[0],!e)return{content:[{type:"text",text:"No previous versions found for "+n}],isError:!0}
396
- p.info("Auto-resolved previous version",{filePath:n,commitHash:e})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+n}],isError:!0}}}f=await(0,d.handleFileRecover)({taskId:o.recover.taskId,path:o.recover.path,commitHash:e,createBackup:o.recover.createBackup},r,n,n.getToolRecordClient(),p,s,g)
405
+ f.info("Auto-resolved previous version",{filePath:n,commitHash:e})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+n}],isError:!0}}}p=await(0,d.handleFileRecover)({taskId:o.recover.taskId,path:o.recover.path,commitHash:e,createBackup:o.recover.createBackup},r,n,n.getToolRecordClient(),f,s,g)
397
406
  break
398
- case"blame":p.info("Routing to file-blame handler",{path:o.blame.path,lines:o.blame.lines}),f=await(0,u.handleFileBlame)({path:o.blame.path,lines:o.blame.lines,branch:o.blame.branch},r,n,p,s)
407
+ case"blame":f.info("Routing to file-blame handler",{path:o.blame.path,lines:o.blame.lines}),p=await(0,u.handleFileBlame)({path:o.blame.path,lines:o.blame.lines,branch:o.blame.branch},r,n,f,s)
399
408
  break
400
- default:throw Error("Unknown query type: "+h)}return p.info("query_history request completed",{queryType:h,success:!f.isError}),s.incrementCounter("query_history_total",1,{success:!f.isError,queryType:h}),f}catch(e){return p.error("query_history request failed",{error:e instanceof Error?e.stack:e+""}),s.incrementCounter("query_history_errors",1),{content:[{type:"text",text:"\u274c **Query History Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
409
+ default:throw Error("Unknown query type: "+h)}return f.info("query_history request completed",{queryType:h,success:!p.isError}),s.incrementCounter("query_history_total",1,{success:!p.isError,queryType:h}),p}catch(e){return f.error("query_history request failed",{error:e instanceof Error?e.stack:e+""}),s.incrementCounter("query_history_errors",1),{content:[{type:"text",text:"\u274c **Query History Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
401
410
  const i=t(6183),a=s(t(5967)),c=t(8828),l=t(8317),d=t(4640),u=t(4811),h=t(8824)},1038(e,exports){function t(e){let t
402
411
  if("string"==typeof e.metadata&&e.metadata)try{t=JSON.parse(e.metadata)}catch(e){t=void 0}else e.metadata&&"object"==typeof e.metadata&&(t=e.metadata)
403
412
  return{id:e.id,localId:e.local_id||e.localId,taskId:e.task_id||e.taskId||void 0,requestId:e.request_id||e.requestId||void 0,projectId:e.project_id||e.projectId||e.id,type:e.type,metadata:t,note:e.note||void 0,createdAt:e.created_at||e.createdAt||"",updatedAt:e.updated_at||e.updatedAt||""}}function r(e){let t=null
@@ -503,9 +512,9 @@ const t=this.remoteServerUrl+"/auth/validate"
503
512
  this.logger.debug("Making token validation request",{validationUrl:t})
504
513
  const r=await fetch(t,{method:"GET",headers:{Authorization:"Bearer "+e.token,"Content-Type":"application/json"},signal:AbortSignal.timeout(1e4)})
505
514
  if(r.ok){const e=await r.json()
506
- return this.logger.info("Token validation successful",{status:e.status||"unknown",username:e.username||"unknown"}),!0}return this.logger.info("Token validation failed - token may be invalid or expired",{status:r.status,statusText:r.statusText}),this.invalidateCache(),!1}catch(e){return e instanceof Error&&"AbortError"===e.name?(this.logger.info("Token validation request timed out - assuming offline or server unavailable"),!0):(this.logger.info("Token validation request failed",{error:(0,c.getErrorMessage)(e)}),!0)}}async hasValidAndWorkingToken(){return!!await this.hasValidToken()&&await this.validateTokenWithRemoteServer()}async isGoogleOAuthAvailable(){return await this.authFlow.isGoogleOAuthAvailable()}async startGoogleOAuthFlow(){return await this.authFlow.startGoogleOAuthFlow()}async startGoogleOAuthPolling(e,t,r,n,o){return await this.authFlow.startGoogleOAuthPolling(e,t,r,n,o)}}},1281(e,exports,t){async function r(e,t,o,s,i,a,c,l,d,u=0){let p=0,f=0,m=0
515
+ return this.logger.info("Token validation successful",{status:e.status||"unknown",username:e.username||"unknown"}),!0}return this.logger.info("Token validation failed - token may be invalid or expired",{status:r.status,statusText:r.statusText}),this.invalidateCache(),!1}catch(e){return e instanceof Error&&"AbortError"===e.name?(this.logger.info("Token validation request timed out - assuming offline or server unavailable"),!0):(this.logger.info("Token validation request failed",{error:(0,c.getErrorMessage)(e)}),!0)}}async hasValidAndWorkingToken(){return!!await this.hasValidToken()&&await this.validateTokenWithRemoteServer()}async isGoogleOAuthAvailable(){return await this.authFlow.isGoogleOAuthAvailable()}async startGoogleOAuthFlow(){return await this.authFlow.startGoogleOAuthFlow()}async startGoogleOAuthPolling(e,t,r,n,o){return await this.authFlow.startGoogleOAuthPolling(e,t,r,n,o)}}},1281(e,exports,t){async function r(e,t,o,s,i,a,c,l,d,u=0){let f=0,p=0,m=0
507
516
  const y=[]
508
- if(o.length>=I||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:I,depth:c}),{filesCount:p,fileMatchesCount:f,subdirCount:m,subdirStats:y}
517
+ if(o.length>=I||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:I,depth:c}),{filesCount:f,fileMatchesCount:p,subdirCount:m,subdirStats:y}
509
518
  try{const w=await g.default.readdir(e,{withFileTypes:!0}),v=[],C=[]
510
519
  for(const t of w){const r=h.default.join(e,t.name)
511
520
  if(t.isDirectory()){if(b.includes(t.name)||t.name.startsWith(".")){a.debug("Skipping excluded directory: "+t.name)
@@ -514,15 +523,15 @@ continue}v.push({entry:t,fullPath:r})}}if(v.length>0){const e=[]
514
523
  for(let t=0;t<v.length;t+=16)e.push(v.slice(t,t+16))
515
524
  for(const r of e){if(o.length>=I)break
516
525
  const e=await Promise.all(r.map((({entry:e,fullPath:r})=>n(r,t,0,o,l,d,e.name,u))))
517
- for(const t of e){p++,t.hasMatches&&f++
518
- for(const e of t.matches){if(o.length>=I)return{filesCount:p,fileMatchesCount:f,subdirCount:m,subdirStats:y}
526
+ for(const t of e){f++,t.hasMatches&&p++
527
+ for(const e of t.matches){if(o.length>=I)return{filesCount:f,fileMatchesCount:p,subdirCount:m,subdirStats:y}
519
528
  o.push(e)}}}}for(const{entry:e,fullPath:n}of C){if(o.length>=I)break
520
529
  m++
521
530
  const e={path:n,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
522
531
  try{const l=await r(n,t,o,s,i,a,c+1,e,d,u)
523
- p+=l.filesCount,f+=l.fileMatchesCount,e.filesProcessed=l.filesCount,e.filesMatched=l.fileMatchesCount,e.subdirectories=l.subdirCount,y.push(e),l.subdirStats&&l.subdirStats.length>0&&y.push(...l.subdirStats)}catch(t){const r=`Error processing subdirectory ${n}: ${(0,k.getErrorMessage)(t)}`
532
+ f+=l.filesCount,p+=l.fileMatchesCount,e.filesProcessed=l.filesCount,e.filesMatched=l.fileMatchesCount,e.subdirectories=l.subdirCount,y.push(e),l.subdirStats&&l.subdirStats.length>0&&y.push(...l.subdirStats)}catch(t){const r=`Error processing subdirectory ${n}: ${(0,k.getErrorMessage)(t)}`
524
533
  e.errors.push(r),y.push(e),a.error(r)}}}catch(t){const r=`Error searching directory ${e}: ${(0,k.getErrorMessage)(t)}`
525
- l.errors.push(r),a.warn(r)}return{filesCount:p,fileMatchesCount:f,subdirCount:m,subdirStats:y}}async function n(e,t,r,n,o,s,i,a=0){const c=[]
534
+ l.errors.push(r),a.warn(r)}return{filesCount:f,fileMatchesCount:p,subdirCount:m,subdirStats:y}}async function n(e,t,r,n,o,s,i,a=0){const c=[]
526
535
  let l,d=!1
527
536
  const u=async()=>{if(void 0===l)try{const t=await g.default.stat(e)
528
537
  l=t.mtime.getTime()}catch(e){l=void 0}return l}
@@ -555,31 +564,31 @@ if(null!=e)for(var r=a(e),n=0;n<r.length;n++)"default"!==r[n]&&c(t,e,r[n])
555
564
  return l(t,e),t}),u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
556
565
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearch=async function(e,t,n,a,c){const l=a.child({tool:"search"}),d=c.startTimer("tool_execution_time"),u=Date.now()
557
566
  let b=0
558
- const I={searchDirectory:"",resolvedPath:"",patternInfo:{needle:"",regex:"",caseSensitive:!1,fileExtension:"",normalizedExtension:""},environmentInfo:{platform:process.platform,nodeVersion:process.version,hostname:p.default.hostname(),username:p.default.userInfo().username,workingDirectory:process.cwd(),contextBasePath:t?.basePath||"unknown"},startTime:u,endTime:0,phases:{initializationTime:0,searchTime:0,directoryListingTime:0},totalFiles:0,totalMatches:0,directoryStats:[],errors:[]}
559
- try{const{needle:n,directory:p,options:v={}}=e
560
- if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all mode"),await(0,w.handleListDirectory)({path:p||".",levels:v.levels||1,sortBy:v.sortBy||"name"},t,a,c)
561
- if("string"!=typeof n)throw I.errors.push("Search term (needle) must be a string"),(0,f.createValidationError)("Search term (needle) must be a string")
567
+ const I={searchDirectory:"",resolvedPath:"",patternInfo:{needle:"",regex:"",caseSensitive:!1,fileExtension:"",normalizedExtension:""},environmentInfo:{platform:process.platform,nodeVersion:process.version,hostname:f.default.hostname(),username:f.default.userInfo().username,workingDirectory:process.cwd(),contextBasePath:t?.basePath||"unknown"},startTime:u,endTime:0,phases:{initializationTime:0,searchTime:0,directoryListingTime:0},totalFiles:0,totalMatches:0,directoryStats:[],errors:[]}
568
+ try{const{needle:n,directory:f,options:v={}}=e
569
+ if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all mode"),await(0,w.handleListDirectory)({path:f||".",levels:v.levels||1,sortBy:v.sortBy||"name"},t,a,c)
570
+ if("string"!=typeof n)throw I.errors.push("Search term (needle) must be a string"),(0,p.createValidationError)("Search term (needle) must be a string")
562
571
  let C
563
- if(I.searchDirectory=p||".",p){const{normalizedPath:e,fullPath:r}=m.validateAndNormalizePath(p,t)
572
+ if(I.searchDirectory=f||".",f){const{normalizedPath:e,fullPath:r}=m.validateAndNormalizePath(f,t)
564
573
  C=r}else C=t.basePath
565
574
  I.resolvedPath=C
566
575
  let _=!1
567
576
  try{_=(await g.default.stat(C)).isFile()}catch(e){const t=`Cannot access path ${C}: ${(0,k.getErrorMessage)(e)}`
568
577
  throw I.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,M=v.searchIn||"content"
569
578
  let R=void 0!==v.contextLines?v.contextLines:0
570
- if(0>R?R=0:R>10&&(l.warn(`contextLines ${R} exceeds maximum of 10, clamping to 10`),R=10),!_&&!T)throw I.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,f.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
579
+ if(0>R?R=0:R>10&&(l.warn(`contextLines ${R} exceeds maximum of 10, clamping to 10`),R=10),!_&&!T)throw I.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,p.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
571
580
  let P,x=""
572
581
  if(_)x="*"
573
582
  else if("*"===T)x="*"
574
583
  else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),x=e.startsWith(".")?e:"."+e}try{P=S?q?RegExp(n):RegExp(n,"i"):q?RegExp(o(n)):RegExp(o(n),"i")}catch(e){const t=`Invalid ${S?"regex":"search"} pattern: ${(0,k.getErrorMessage)(e)}`
575
- throw I.errors.push(t),(0,f.createValidationError)(t)}if(I.patternInfo={needle:n,regex:P.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:x},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
584
+ throw I.errors.push(t),(0,p.createValidationError)(t)}if(I.patternInfo={needle:n,regex:P.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:x},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
576
585
  for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
577
586
  I.initialScan={totalEntries:t.length,directories:r,files:n,firstFewFiles:n.slice(0,10),scanTime:Date.now()-e},I.phases.directoryListingTime=I.initialScan.scanTime}catch(e){const t="Failed to scan directory contents: "+(0,k.getErrorMessage)(e)
578
587
  I.errors.push(t),l.error(t)}const O=_?"file":"directory"
579
588
  l.info(`Searching for "${n}" in ${O} ${C} (mode: ${M})`,{needle:n,searchTarget:O,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:x,searchIn:M}}),b=Date.now(),I.phases.initializationTime=b-u
580
589
  const j=Date.now()
581
- let $=[],A=0,D=0
582
- try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,p=[]
590
+ let $=[],D=0,A=0
591
+ try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,f=[]
583
592
  if(s.info("performLocalSearch started",{searchPath:e,pattern:t.toString(),options:n}),d)return await async function(e,t,r,n,o,s=0){const i=[],a=h.default.basename(e)
584
593
  let c
585
594
  n.info("Searching single file: "+e,{searchIn:r})
@@ -591,20 +600,20 @@ t.contextBefore=r.slice(e,n).map((e=>(0,y.truncate)(e.trim(),120)))
591
600
  const o=Math.min(r.length,n+1+s)
592
601
  t.contextAfter=r.slice(n+1,o).map((e=>(0,y.truncate)(e.trim(),120)))}i.push(t)}n.info(`Found ${i.filter((e=>"content"===e.matchType)).length} content matches`)}catch(t){const r=`Error reading file ${e}: ${(0,k.getErrorMessage)(t)}`
593
602
  o.errors.push(r),n.error(r)}return{matches:i,totalFiles:1}}(e,t,l,s,i,u)
594
- const f={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
595
- try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,p,a,o,s,0,f,l,u)
596
- return f.filesProcessed=n,f.filesMatched=c,f.subdirectories=d,i.directoryStats.push(f),h&&h.length>0&&i.directoryStats.push(...h),s.info("performLocalSearch completed",{totalFiles:n,matchesFound:p.length,directories:d+1}),{matches:p,totalFiles:n}}catch(t){const r="Error in performLocalSearch: "+(0,k.getErrorMessage)(t)
597
- return f.errors.push(r),i.directoryStats.push(f),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:p,totalFiles:f.filesProcessed}}}(C,P,{maxResults:E,fileExtension:x,searchIn:M,isFile:_,contextLines:R},x,l,I)
598
- $=e.matches,A=e.totalFiles
603
+ const p={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
604
+ try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,f,a,o,s,0,p,l,u)
605
+ return p.filesProcessed=n,p.filesMatched=c,p.subdirectories=d,i.directoryStats.push(p),h&&h.length>0&&i.directoryStats.push(...h),s.info("performLocalSearch completed",{totalFiles:n,matchesFound:f.length,directories:d+1}),{matches:f,totalFiles:n}}catch(t){const r="Error in performLocalSearch: "+(0,k.getErrorMessage)(t)
606
+ return p.errors.push(r),i.directoryStats.push(p),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:f,totalFiles:p.filesProcessed}}}(C,P,{maxResults:E,fileExtension:x,searchIn:M,isFile:_,contextLines:R},x,l,I)
607
+ $=e.matches,D=e.totalFiles
599
608
  const t=1e3
600
- $.length>0&&$.length<=t?($.sort(((e,t)=>void 0!==e.modifiedTime&&void 0!==t.modifiedTime?t.modifiedTime-e.modifiedTime:void 0!==e.modifiedTime&&void 0===t.modifiedTime?-1:void 0===e.modifiedTime&&void 0!==t.modifiedTime?1:0)),l.info(`Sorted ${$.length} matches by modification time (newest first)`)):$.length>t&&l.info(`Skipped sorting ${$.length} matches (exceeds hard cap of ${t} for performance)`),D=$.length,$.length>E&&($=$.slice(0,E),l.info(`Limited results to ${E} (from ${D} total matches)`)),$.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
601
- return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${D||$.length} total matches in ${A} files, returning ${$.length} results`),I.phases.searchTime=Date.now()-j}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
602
- I.errors.push(t),l.error(t),I.phases.searchTime=Date.now()-j}I.totalFiles=A,I.totalMatches=$.length,I.endTime=Date.now()
609
+ $.length>0&&$.length<=t?($.sort(((e,t)=>void 0!==e.modifiedTime&&void 0!==t.modifiedTime?t.modifiedTime-e.modifiedTime:void 0!==e.modifiedTime&&void 0===t.modifiedTime?-1:void 0===e.modifiedTime&&void 0!==t.modifiedTime?1:0)),l.info(`Sorted ${$.length} matches by modification time (newest first)`)):$.length>t&&l.info(`Skipped sorting ${$.length} matches (exceeds hard cap of ${t} for performance)`),A=$.length,$.length>E&&($=$.slice(0,E),l.info(`Limited results to ${E} (from ${A} total matches)`)),$.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
610
+ return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||$.length} total matches in ${D} files, returning ${$.length} results`),I.phases.searchTime=Date.now()-j}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
611
+ I.errors.push(t),l.error(t),I.phases.searchTime=Date.now()-j}I.totalFiles=D,I.totalMatches=$.length,I.endTime=Date.now()
603
612
  let F,N=""
604
613
  try{if(t.getCurrentBranchContext){const e=await t.getCurrentBranchContext()
605
614
  e.branch&&(N=e.isMain?` (searched on main branch: ${e.branch})`:` (searched on request branch: ${e.branch}${e.requestId?" for "+e.requestId:""})`)}}catch(e){l.debug("Could not get branch context",{error:e}),N=" (branch context unavailable)"}l.debug("Search diagnostic information",{diagnostic:I})
606
615
  const L="content"===M?"content":"filename"===M?"filenames":"content and filenames"
607
- if(D>$.length?(F=`Found ${D} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=`${N}. Showing first ${$.length}:\n\n`):(F=`Found ${$.length} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=N+":\n\n"),$.length>0)if(R>0){const{filenameMatches:e,mergedGroups:t}=function(e,t){const r=e.filter((e=>"filename"===e.matchType)),n=e.filter((e=>"content"===e.matchType))
616
+ if(A>$.length?(F=`Found ${A} results for "${n}" (searching ${L})`,f&&(F+=" in "+f),T&&(F+=" with extension "+T),F+=`${N}. Showing first ${$.length}:\n\n`):(F=`Found ${$.length} results for "${n}" (searching ${L})`,f&&(F+=" in "+f),T&&(F+=" with extension "+T),F+=N+":\n\n"),$.length>0)if(R>0){const{filenameMatches:e,mergedGroups:t}=function(e,t){const r=e.filter((e=>"filename"===e.matchType)),n=e.filter((e=>"content"===e.matchType))
608
617
  if(0===n.length)return{filenameMatches:r,mergedGroups:[]}
609
618
  const o=new Map
610
619
  for(const e of n){const t=o.get(e.file)||[]
@@ -628,7 +637,7 @@ else F+="No matches found."
628
637
  return d({success:!0}),{content:[{type:"text",text:F}]}}catch(t){l.error("Search failed",{args:e,error:t instanceof Error?t.stack:t+""}),I.errors.push((0,k.getErrorMessage)(t)),I.endTime=Date.now(),l.debug("Search diagnostic information on error",{diagnostic:I})
629
638
  let r="Search failed: "+(0,k.getErrorMessage)(t)
630
639
  return d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:r}],isError:!0}}}
631
- const h=u(t(6928)),g=u(t(1943)),p=u(t(857)),f=t(9860),m=d(t(5967)),y=t(5967),w=t(2537),k=t(8824),b=["node_modules"],I=1e4,v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore"]),C=1048576},1318(e,exports,t){async function r(e,t,r){try{const r=(await e.revparse(["--show-toplevel"])).trim(),n=c.default.isAbsolute(t)?t:c.default.resolve(t)
640
+ const h=u(t(6928)),g=u(t(1943)),f=u(t(857)),p=t(9860),m=d(t(5967)),y=t(5967),w=t(2537),k=t(8824),b=["node_modules"],I=1e4,v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore"]),C=1048576},1318(e,exports,t){async function r(e,t,r){try{const r=(await e.revparse(["--show-toplevel"])).trim(),n=c.default.isAbsolute(t)?t:c.default.resolve(t)
632
641
  return c.default.relative(r,n)}catch(e){return r.warn("Failed to get repo-relative path, using original",{filePath:t,error:(0,l.getErrorMessage)(e)}),t}}function n(e){return/\(trec\d{6}\)/.test(e)}async function o(e,t,n,o,s){try{const i=await r(e,t,s),a=await e.raw(["log","-1","--pretty=format:%H|%s",`-L${n},${o}:${i}`])
633
642
  if(!a||""===a.trim())return null
634
643
  const c=a.trim().split("\n")[0],[l,...d]=c.split("|"),u=d.join("|")
@@ -645,12 +654,12 @@ for(const e of r){const r=e.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/)
645
654
  if(r){const e=parseInt(r[3],10),n=r[4]?parseInt(r[4],10):1,o=e+n-1
646
655
  n>0&&t.push({start:e,end:o})}}return t}(s)
647
656
  return{ranges:i,diff:s}}catch(e){return n.warn("Failed to get uncommitted changes",{filePath:t,error:(0,l.getErrorMessage)(e)}),{ranges:[],diff:""}}}(e,t.path,i),d=c.ranges,u=c.diff,h=await async function(e,t,n){try{const o=await r(e,t,n),s=await e.log({file:o,maxCount:1})
648
- return s.latest?.message||null}catch(e){return null}}(e,t.path,i),g=!!h&&n(h),p=t.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),f=d.map((e=>`${e.start}-${e.end}`)).join(", ")||"none",m=u?u.substring(0,300):"no diff"
657
+ return s.latest?.message||null}catch(e){return null}}(e,t.path,i),g=!!h&&n(h),f=t.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),p=d.map((e=>`${e.start}-${e.end}`)).join(", ")||"none",m=u?u.substring(0,300):"no diff"
649
658
  if(0===d.length){const r=[]
650
659
  for(const s of t.lineRanges){const a=await o(e,t.path,s.start,s.end,i)
651
- a&&(n(a.message)||r.push({range:`${s.start}-${s.end}`,commit:a}))}if(r.length>0){const e=r.map((e=>`Lines ${e.range}: ${e.commit.hash.substring(0,8)} - ${e.commit.message}`)).join("; "),n=[`\u26a0\ufe0f Warning: Lines ${p} were last modified by external commits (not alchemy).`,"","Commit details: "+e,"\nThese changes may have been made manually or by another tool.\nReview recent commits before proceeding."].join("\n")
652
- return{hasExternalEdits:!0,conflictingLines:t.lineRanges.flatMap((e=>Array.from({length:e.end-e.start+1},((t,r)=>e.start+r)))),message:n,debugInfo:{detectionRan:!0,affectedRegion:p,uncommittedChanges:"none",lastCommit:r[0].commit.message,wasLastCommitAlchemy:!1,diffPreview:e,overlapDetected:!0}}}return{hasExternalEdits:!1,conflictingLines:[],debugInfo:{detectionRan:!0,affectedRegion:p,uncommittedChanges:"none",lastCommit:h,wasLastCommitAlchemy:g,diffPreview:"no uncommitted changes, last commits from alchemy",overlapDetected:!1}}}const y={path:t.path,lineRanges:d,totalLines:d.reduce(((e,t)=>e+(t.end-t.start+1)),0),operationType:"modification"},w=(0,a.getOverlappingLines)(t,y)
653
- return 0===w.length?{hasExternalEdits:!1,conflictingLines:[],message:"File has uncommitted changes, but they do not conflict with this operation.",debugInfo:{detectionRan:!0,affectedRegion:p,uncommittedChanges:f,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:m,overlapDetected:!1}}:{hasExternalEdits:!0,conflictingLines:w,message:["\u26a0\ufe0f Warning: File has uncommitted changes in lines you're about to modify.\n","Affected lines: "+p,"Conflicting lines: "+s(w),"",g?"Last commit was by alchemy, but file has been edited since.":"Last commit was NOT from alchemy - these may be manual edits.","\nReview the changes before proceeding."].join("\n"),details:{totalExternalChanges:y.totalLines,overlappingChanges:w.length,changedLineRanges:d},debugInfo:{detectionRan:!0,affectedRegion:p,uncommittedChanges:f,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:m,overlapDetected:!0}}}catch(e){return i.error("Failed to detect external edits",{path:t.path,error:(0,l.getErrorMessage)(e)}),{hasExternalEdits:!1,conflictingLines:[],message:"Unable to check for external edits (Git error). Proceeding with caution."}}},exports.hasUncommittedChanges=async function(e,t){try{return(await e.status([t])).files.some((e=>e.path===t))}catch(e){return!1}}
660
+ a&&(n(a.message)||r.push({range:`${s.start}-${s.end}`,commit:a}))}if(r.length>0){const e=r.map((e=>`Lines ${e.range}: ${e.commit.hash.substring(0,8)} - ${e.commit.message}`)).join("; "),n=[`\u26a0\ufe0f Warning: Lines ${f} were last modified by external commits (not alchemy).`,"","Commit details: "+e,"\nThese changes may have been made manually or by another tool.\nReview recent commits before proceeding."].join("\n")
661
+ return{hasExternalEdits:!0,conflictingLines:t.lineRanges.flatMap((e=>Array.from({length:e.end-e.start+1},((t,r)=>e.start+r)))),message:n,debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:"none",lastCommit:r[0].commit.message,wasLastCommitAlchemy:!1,diffPreview:e,overlapDetected:!0}}}return{hasExternalEdits:!1,conflictingLines:[],debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:"none",lastCommit:h,wasLastCommitAlchemy:g,diffPreview:"no uncommitted changes, last commits from alchemy",overlapDetected:!1}}}const y={path:t.path,lineRanges:d,totalLines:d.reduce(((e,t)=>e+(t.end-t.start+1)),0),operationType:"modification"},w=(0,a.getOverlappingLines)(t,y)
662
+ return 0===w.length?{hasExternalEdits:!1,conflictingLines:[],message:"File has uncommitted changes, but they do not conflict with this operation.",debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:p,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:m,overlapDetected:!1}}:{hasExternalEdits:!0,conflictingLines:w,message:["\u26a0\ufe0f Warning: File has uncommitted changes in lines you're about to modify.\n","Affected lines: "+f,"Conflicting lines: "+s(w),"",g?"Last commit was by alchemy, but file has been edited since.":"Last commit was NOT from alchemy - these may be manual edits.","\nReview the changes before proceeding."].join("\n"),details:{totalExternalChanges:y.totalLines,overlappingChanges:w.length,changedLineRanges:d},debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:p,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:m,overlapDetected:!0}}}catch(e){return i.error("Failed to detect external edits",{path:t.path,error:(0,l.getErrorMessage)(e)}),{hasExternalEdits:!1,conflictingLines:[],message:"Unable to check for external edits (Git error). Proceeding with caution."}}},exports.hasUncommittedChanges=async function(e,t){try{return(await e.status([t])).files.some((e=>e.path===t))}catch(e){return!1}}
654
663
  const a=t(9947),c=i(t(6928)),l=t(8824)},1387(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.WorkspaceRequestProcessor=void 0
655
664
  const r=t(7075),n=t(5964),o=t(8824)
656
665
  exports.WorkspaceRequestProcessor=class{constructor(e,t,r,n,o){this.gitAdapter=e,this.conflictDetector=t,this.safetyAnalyzer=r,this.conflictResolver=n,this.logger=o}async completeRequest(e,t,s){const i=r.WorkspaceValidation.validateRequestId(e)
@@ -703,31 +712,31 @@ const y=!!i,w=async()=>{if(!y)return!0
703
712
  try{return await i.hasValidToken()}catch(e){return m.error("Error checking authentication status",{error:(0,l.getErrorMessage)(e)}),!1}},k=async()=>{const e=(0,c.areTestsRequiredForCompletion)(),t=await w()
704
713
  m.info(`Generating tools list with testsRequired=${e}, authenticated=${t}`)
705
714
  const r={testsRequired:e,authenticated:t}
706
- return(0,f.generateVisibleToolsList)(r)}
715
+ return(0,p.generateVisibleToolsList)(r)}
707
716
  let b=k(),I=[]
708
717
  b.then((e=>{I=e})).catch((e=>{m.error("Error generating initial tools list",{error:(0,l.getErrorMessage)(e)}),I=[]})),e.setRequestHandler(a.ListToolsRequestSchema,(async()=>{try{return I=await k(),{tools:I}}catch(e){return m.error("Error generating tools list",{error:(0,l.getErrorMessage)(e)}),{tools:[]}}}))
709
718
  let v=!1
710
- e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:i,arguments:a={},_meta:c}=e.params;(0,p.logSessionIdentity)(i,"_meta-debug",{has_meta:!!c,sessionId:c?.sessionId||null,messageId:c?.messageId||null,paramKeys:Object.keys(e.params)}),m.info("Tool call received: "+i,{tool:i}),s.incrementCounter("tool_calls_total",1,{tool:i})
719
+ e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:i,arguments:a={},_meta:c}=e.params;(0,f.logSessionIdentity)(i,"_meta-debug",{has_meta:!!c,sessionId:c?.sessionId||null,messageId:c?.messageId||null,paramKeys:Object.keys(e.params)}),m.info("Tool call received: "+i,{tool:i}),s.incrementCounter("tool_calls_total",1,{tool:i})
711
720
  const k=s.startTimer("tool_execution_time")
712
721
  Date.now()
713
722
  let b=Date.now()
714
723
  const I=r(a)
715
724
  if(Date.now(),b=Date.now(),y){const e=await w()
716
- if(Date.now(),!e)return m.warn("Unauthenticated tool call attempt",{tool:i}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const C=(0,f.getToolByName)(i)
725
+ if(Date.now(),!e)return m.warn("Unauthenticated tool call attempt",{tool:i}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const C=(0,p.getToolByName)(i)
717
726
  if(b=Date.now(),n?(n.setOptions({createRecords:C?.createsRecords??!1}),m.info(`Setting record creation for tool ${i}: ${C?.createsRecords??!1}`)):m.debug(`No API client available for tool ${i} (minimal mode)`),Date.now(),b=Date.now(),t?.workspaceManager&&!t.workspaceManager.readonlyBranchCheckDone)try{const e=await(0,d.getServerUrl)(t,m)
718
727
  e&&n&&await t.workspaceManager.ensureReadonlyBranchIfNeeded(e,i,n,c?.sessionId)}catch(e){m.debug("Error during readonly branch check",{error:(0,l.getErrorMessage)(e)})}let _,E
719
728
  if(Date.now(),Date.now(),b=Date.now(),C&&!C.readOnly)if(c?.sessionId){const e=c.sessionId,r=c.messageId,n=u.sessionIdentity.getIdentity()
720
- if(n)n.sessionId!==e&&((0,p.logSessionIdentity)(i,"_meta-session-switch",{prevSessionId:n.sessionId,prevAgentType:n.agentType,newSessionId:e}),u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:n.serverUrl}))
729
+ if(n)n.sessionId!==e&&((0,f.logSessionIdentity)(i,"_meta-session-switch",{prevSessionId:n.sessionId,prevAgentType:n.agentType,newSessionId:e}),u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:n.serverUrl}))
721
730
  else{const r=await(0,d.getServerUrl)(t,m)
722
- u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r||""}),u.sessionIdentity.markDiscoveryAttempted()}_={providerId:"opencode",sessionId:e,messageId:r,createdAt:(new Date).toISOString()},(0,p.logSessionIdentity)(i,"_meta",{sessionId:e,messageId:r})}else{const e=u.sessionIdentity.getIdentity()
723
- if(e){let t,r=!1
724
- try{t=await(0,d.findMessageIdForTool)(e.serverUrl,e.sessionId,i)}catch{r=!0}if(t)_=u.sessionIdentity.buildCliOrigin(t)
725
- else if(r)_=u.sessionIdentity.buildCliOrigin()
726
- else{m.info("Session identity mismatch: tool call not found in cached session, re-discovering",{prevSessionId:e.sessionId,prevAgentType:e.agentType,tool:i}),u.sessionIdentity.reset()
731
+ u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r||""}),u.sessionIdentity.markDiscoveryAttempted()}_={providerId:"opencode",sessionId:e,messageId:r,createdAt:(new Date).toISOString()},(0,f.logSessionIdentity)(i,"_meta",{sessionId:e,messageId:r})}else{const e=u.sessionIdentity.getIdentity()
732
+ if(e){let r,n=!1
733
+ try{r=await(0,d.findMessageIdForTool)(e.serverUrl,e.sessionId,i)}catch{n=!0}if(r)_=u.sessionIdentity.buildCliOrigin(r)
734
+ else if(n)_=u.sessionIdentity.buildCliOrigin()
735
+ else{m.info("Session identity mismatch: tool call not found in cached session, re-discovering",{prevSessionId:e.sessionId,prevAgentType:e.agentType,tool:i}),u.sessionIdentity.reset(),t?.workspaceManager?.resetCurrentContext?.()
727
736
  try{const t=await(0,d.getAndStoreSessionId)(e.serverUrl,m,i)
728
- t?(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e.serverUrl}),(0,p.logSessionIdentity)(i,"re-discovery",{sessionId:t.sessionId,messageId:t.messageId}),_=u.sessionIdentity.buildCliOrigin(t.messageId)):(u.sessionIdentity.setIdentity(e),_=u.sessionIdentity.buildCliOrigin(),m.info("Re-discovery found no other session, keeping current identity",{sessionId:e.sessionId})),u.sessionIdentity.markDiscoveryAttempted()}catch(t){u.sessionIdentity.setIdentity(e),_=u.sessionIdentity.buildCliOrigin(),u.sessionIdentity.markDiscoveryAttempted(),m.warn("Re-discovery failed, keeping current identity (may be stale)",{error:(0,l.getErrorMessage)(t),tool:i,sessionId:e.sessionId})}}}else if(!u.sessionIdentity.hasDiscoveryBeenAttempted())try{const e=await(0,d.getServerUrl)(t,m)
737
+ t?(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e.serverUrl}),(0,f.logSessionIdentity)(i,"re-discovery",{sessionId:t.sessionId,messageId:t.messageId}),_=u.sessionIdentity.buildCliOrigin(t.messageId)):(u.sessionIdentity.setIdentity(e),_=u.sessionIdentity.buildCliOrigin(),m.info("Re-discovery found no other session, keeping current identity",{sessionId:e.sessionId})),u.sessionIdentity.markDiscoveryAttempted()}catch(t){u.sessionIdentity.setIdentity(e),_=u.sessionIdentity.buildCliOrigin(),u.sessionIdentity.markDiscoveryAttempted(),m.warn("Re-discovery failed, keeping current identity (may be stale)",{error:(0,l.getErrorMessage)(t),tool:i,sessionId:e.sessionId})}}}else if(!u.sessionIdentity.hasDiscoveryBeenAttempted())try{const e=await(0,d.getServerUrl)(t,m)
729
738
  if(e){const t=await(0,d.getAndStoreSessionId)(e,m,i)
730
- t&&(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e}),(0,p.logSessionIdentity)(i,"http-discovery",{sessionId:t.sessionId,messageId:t.messageId}),_=u.sessionIdentity.buildCliOrigin(t.messageId))}u.sessionIdentity.markDiscoveryAttempted()}catch(e){u.sessionIdentity.markDiscoveryAttempted(),(0,p.logSessionIdentity)(i,"discovery-failed",{error:(0,l.getErrorMessage)(e)}),m.debug("cliOrigin discovery failed",{error:(0,l.getErrorMessage)(e),tool:i})}}if(u.sessionIdentity.setCurrentCallOrigin(_),!v&&n){const e=u.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
739
+ t&&(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e}),(0,f.logSessionIdentity)(i,"http-discovery",{sessionId:t.sessionId,messageId:t.messageId}),_=u.sessionIdentity.buildCliOrigin(t.messageId))}u.sessionIdentity.markDiscoveryAttempted()}catch(e){u.sessionIdentity.markDiscoveryAttempted(),(0,f.logSessionIdentity)(i,"discovery-failed",{error:(0,l.getErrorMessage)(e)}),m.debug("cliOrigin discovery failed",{error:(0,l.getErrorMessage)(e),tool:i})}}if(u.sessionIdentity.setCurrentCallOrigin(_),!v&&n){const e=u.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
731
740
  if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),o="1"===process.env.ALCHEMY_ALLOW_PARALLEL
732
741
  if(r&&!o){const t=r[1]
733
742
  v=!0
@@ -752,13 +761,13 @@ const a=t(9150),c=t(2478),l=t(8824),d=t(7617),u=t(6688),h=t(5172)
752
761
  i(t(9896)),i(t(6928))
753
762
  var g=t(7280)
754
763
  Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return g.logSessionIdentity}})
755
- const p=t(7280)
764
+ const f=t(7280)
756
765
  t(2462)
757
- const f=t(2245)},1483(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearchDocuments=async function(e,t,s,i,a){const c=i.child({tool:"search_documents"}),l=a.startTimer("tool_execution_time")
766
+ const p=t(2245)},1483(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearchDocuments=async function(e,t,s,i,a){const c=i.child({tool:"search_documents"}),l=a.startTimer("tool_execution_time")
758
767
  try{let i
759
768
  try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
760
- return c.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,dateFrom:g,dateTo:p,searchIn:f}=i
761
- c.info("Searching documents",{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,searchIn:f})
769
+ return c.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,dateFrom:g,dateTo:f,searchIn:p}=i
770
+ c.info("Searching documents",{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,searchIn:p})
762
771
  const m=t.projectId
763
772
  if(!m){const e="Project ID is required. Make sure you are in a project context."
764
773
  return c.warn("No project context"),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}s.setProjectId(m)
@@ -767,11 +776,11 @@ try{const e={limit:h||100,offset:0,sortBy:"updatedAt",sortDirection:"desc",searc
767
776
  l&&(e.type=l),d&&(e.requestId=d),c.debug("Fetching documents with filters",{filters:e})
768
777
  let t=await y.listDocuments(e)
769
778
  if(g){const e=new Date(g)
770
- t=t.filter((t=>new Date(t.createdAt)>=e))}if(p){const e=new Date(p)
779
+ t=t.filter((t=>new Date(t.createdAt)>=e))}if(f){const e=new Date(f)
771
780
  t=t.filter((t=>new Date(t.createdAt)<=e))}c.info(`Fetched and filtered ${t.length} documents for search`)
772
781
  const r=[],n=a.toLowerCase()
773
782
  for(const e of t){let t,o=null
774
- if("filename"!==f&&"both"!==f||!e.filename.toLowerCase().includes(n)||(o="filename",t=e.filename),("content"===f||"both"===f)&&e.content&&e.content.toLowerCase().includes(n)){o="content"
783
+ if("filename"!==p&&"both"!==p||!e.filename.toLowerCase().includes(n)||(o="filename",t=e.filename),("content"===p||"both"===p)&&e.content&&e.content.toLowerCase().includes(n)){o="content"
775
784
  const r=e.content.split("\n")
776
785
  for(let e=0;e<r.length;e++)if(r[e].toLowerCase().includes(n)){const n=Math.max(0,e-1),o=Math.min(r.length-1,e+1)
777
786
  t=r.slice(n,o+1).map(((t,r)=>n+r===e?"> "+t.trim():" "+t.trim())).join("\n")
@@ -849,16 +858,16 @@ try{let i
849
858
  try{i=r.CreateDocumentSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
850
859
  return d.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{requestId:a,filename:c,content:u,type:h,comment:g}=i
851
860
  d.info("Creating new document",{requestId:a||"standalone",filename:c,contentLength:u.length,type:h,comment:g})
852
- const p=t.projectId
853
- if(!p){const e="Project ID is required. Make sure you are in a project context."
861
+ const f=t.projectId
862
+ if(!f){const e="Project ID is required. Make sure you are in a project context."
854
863
  return d.warn("No project context"),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}if(!c.toLowerCase().endsWith(".md")){const e="Filename must end with .md extension: "+c
855
- return d.warn("Invalid filename extension",{filename:c}),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}try{s.setProjectId(p)
864
+ return d.warn("Invalid filename extension",{filename:c}),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}try{s.setProjectId(f)
856
865
  const e=s.getDocumentClient(),t=a?{requestId:a}:{},r=(await e.listDocuments(t)).find((e=>e.filename===c&&!e.archived))
857
866
  if(r){const e=`\u274c A document with filename "${c}" already exists ${a?"for this request":"in this project"}.\n\n**Existing Document ID:** ${r.id}\n**Created:** ${r.createdAt}\n\nPlease either:\n- Use a different filename\n- Delete or archive the existing document first\n- Use write_file with documentId "${r.id}" to update the existing document`
858
867
  return d.warn("Duplicate filename detected",{filename:c,requestId:a||"standalone",existingDocId:r.id}),{content:[{type:"text",text:e}],isError:!0}}const n=await e.createDocument(a,{filename:c,content:u,type:h,...l&&{cliOrigin:l}})
859
868
  d.info("Document created successfully",{documentId:n.id,filename:n.filename,requestId:a||"standalone"})
860
869
  try{const e=s.getToolRecordClient()
861
- await e.createToolRecord({type:"create-document",projectId:p,metadata:{documentId:n.id,filename:n.filename,type:n.type,contentLength:u.length,requestId:a,projectId:p},note:g})}catch(e){d.warn("Failed to create tool record",{recordError:e})}const o=a?`**Request:** ${a}\n`:"**Standalone:** Yes (not tied to a request)\n"
870
+ await e.createToolRecord({type:"create-document",projectId:f,metadata:{documentId:n.id,filename:n.filename,type:n.type,contentLength:u.length,requestId:a,projectId:f},note:g})}catch(e){d.warn("Failed to create tool record",{recordError:e})}const o=a?`**Request:** ${a}\n`:"**Standalone:** Yes (not tied to a request)\n"
862
871
  return{content:[{type:"text",text:`\u2705 Document created successfully!\n\n**Document ID:** ${n.id}\n**Filename:** ${n.filename}\n**Type:** ${n.type}\n**Size:** ${u.length} characters\n`+o+`**Created:** ${n.createdAt}\n\n`+`The document is now stored in the tracking system and can be edited using standard file modification tools by referencing its document ID (${n.id}) instead of a file path.\n\n**Examples:**\n`+`- \`replace_string\` with \`documentId: "${n.id}"\`\n`+`- \`write_file\` with \`documentId: "${n.id}"\`\n`+`- \`file_history\` with \`documentId: "${n.id}"\``}]}}catch(e){const t="Failed to create document: "+(0,o.getErrorMessage)(e)
863
872
  return d.error("Failed to create document",{error:e}),{content:[{type:"text",text:"\u274c "+t}],isError:!0}}}catch(e){return d.error("Unexpected error in create document",{error:e}),{content:[{type:"text",text:"\u274c Unexpected error: "+(0,o.getErrorMessage)(e)}],isError:!0}}finally{u({tool:"create_document"})}}
864
873
  const r=t(6183),n=t(1569),o=t(8824)},1599(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionRequestAssociationClient=void 0
@@ -904,11 +913,10 @@ this.logger.debug("Retrieved main branch hash via direct rev-parse",{branch:n,co
904
913
  try{if(i=await this.git.revparse(["HEAD"]),!/^[a-f0-9]{40}$/i.test(i))throw Error("Invalid HEAD commit hash format: "+i)
905
914
  this.logger.warn("Used HEAD as fallback for main branch commit hash",{originalBranch:n,fallbackCommit:i.substring(0,8)+"..."})}catch(e){throw Error(`Failed to get commit hash for branch '${n}' and HEAD fallback failed: ${e instanceof Error?e.message:e+""}`)}}return this.logger.info("Main branch commit hash detection completed",{selectedBranch:n,detectionMethod:o,commitHashShort:i.substring(0,8)+"...",currentBranchContext:t,validFormat:/^[a-f0-9]{40}$/i.test(i),strategy:"context-aware-detection"}),i}catch(e){throw this.logger.error("Failed to get main branch commit hash",{error:(0,n.getErrorMessage)(e),stack:e instanceof Error?e.stack:void 0}),Error("Failed to get main branch commit hash: "+(0,n.getErrorMessage)(e))}}hasExactConflictMarkers(e){return!(!e||!e.trim())&&[/^\s*<{7}(?:\s|$)/m,/^\s*={7}(?:\s|$)/m,/^\s*>{7}(?:\s|$)/m].some((t=>t.test(e)))}async handleConflicts(e){const{requestId:t}=e
906
915
  this.logger.info("Starting conflict resolution workflow",{requestId:t,conflictedFiles:e.conflictedFiles.length,mode:e.mode})
907
- try{await this.updateRequestStatus(t,"conflicted"),this.logger.info("Updated request status to conflicted",{requestId:t})
908
- const r=await this.writeConflictMarkersToFiles(e)
916
+ try{const r=await this.writeConflictMarkersToFiles(e)
909
917
  this.logger.info("Wrote conflict markers to files",{requestId:t,filesWritten:r})
910
918
  const n=await this.createConflictResolutionTask(e)
911
- return this.logger.info("Created conflict resolution task",{requestId:t,taskId:n}),{statusUpdated:!0,taskCreated:!0,taskId:n,conflictFilesWritten:r,userMessage:this.generateConflictResolutionMessage(e,n)}}catch(e){return this.logger.error("Conflict resolution workflow failed",{requestId:t,error:(0,n.getErrorMessage)(e)}),{statusUpdated:!1,taskCreated:!1,conflictFilesWritten:0,userMessage:"Conflict resolution workflow failed: "+(0,n.getErrorMessage)(e)}}}async updateRequestStatus(e,t){const r=this.apiClient.getRequestClient(),n={status:t}
919
+ return this.logger.info("Created conflict resolution task",{requestId:t,taskId:n}),{statusUpdated:!1,taskCreated:!0,taskId:n,conflictFilesWritten:r,userMessage:this.generateConflictResolutionMessage(e,n)}}catch(e){return this.logger.error("Conflict resolution workflow failed",{requestId:t,error:(0,n.getErrorMessage)(e)}),{statusUpdated:!1,taskCreated:!1,conflictFilesWritten:0,userMessage:"Conflict resolution workflow failed: "+(0,n.getErrorMessage)(e)}}}async updateRequestStatus(e,t){const r=this.apiClient.getRequestClient(),n={status:t}
912
920
  this.logger.info("Updating request status",{requestId:e,status:t}),await r.updateRequest(e,n)}async runStructuredMergeTree(e){const t="git merge-tree --write-tree --name-only main requests/"+e
913
921
  this.logger.debug("Running structured merge-tree command",{requestId:e,command:t,cwd:this.workingDirectory})
914
922
  try{const r=await(0,c.execAsync)(t,{cwd:this.workingDirectory}),n=r.stdout.trim().split("\n").filter((e=>e.trim()))
@@ -952,7 +960,7 @@ if(!r)throw Error("Project ID is required for task creation but not available")
952
960
  const o=`**Merge conflicts detected during request completion.**\n\n## Conflicted Files:\n${e.conflictedFiles.map((e=>"- "+e.path)).join("\n")}\n\n## Resolution Instructions:\n1. **Review the conflict markers** in the files above\n2. **Resolve conflicts using standard file editing tools**:\n - Use \`write-file\` to replace entire file content with resolved version\n - Use \`replace-string\` for targeted conflict resolution\n - Remove ALL conflict markers: \`<<<<<<<\`, \`=======\`, \`>>>>>>>\`\n3. **Ensure no conflict markers remain** in any file\n4. **Test your resolution** if applicable\n5. **Try completing the request again** when conflicts are resolved\n\n## Conflict Details:\n- **Detection Method**: ${e.detectionMethod}\n- **Mode**: ${e.mode}\n- **Summary**: ${e.summary}\n\n${e.safetyAnalysis?`\n## Auto-Merge Analysis:\n- **Attempted**: ${e.autoMergeAttempted?"Yes":"No"}\n- **Safe for auto-merge**: ${e.safetyAnalysis.isSafe?"Yes":"No"}\n- **Reason**: ${e.safetyAnalysis.reason}\n${e.safetyAnalysis.failureReasons.length>0?"- **Issues**: "+e.safetyAnalysis.failureReasons.join(", "):""}\n`:""}\n\n## Next Steps:\n1. Resolve the conflicts in the files listed above\n2. Call \`complete-request\` again with the same requestId\n3. The system will detect the resolution and complete the merge\n\n**Note**: The request status has been set to 'conflicted' and will remain so until conflicts are resolved.`
953
961
  let s
954
962
  try{s=await this.getCurrentMainCommitHash(),this.logger.info("Storing main branch commit hash for conflict tracking",{requestId:e.requestId,mainCommitHash:s.substring(0,8)+"..."})}catch(t){this.logger.warn("Could not get main branch commit hash, conflict re-detection will be disabled",{requestId:e.requestId,error:(0,n.getErrorMessage)(t)})}const i={requestId:e.requestId,projectId:r,title:t,description:o,metadata:{conflictedFiles:e.conflictedFiles.map((e=>e.path)),detectionTime:(new Date).toISOString(),mainBranchCommitHash:s,detectionMethod:e.detectionMethod,mode:e.mode,originalRequestId:e.requestId,safetyAnalysis:e.safetyAnalysis,conflictType:"merge-conflicts"}},a=this.apiClient.getTaskClient()
955
- return(await a.createTask(i)).id}generateConflictResolutionMessage(e,t){return`## \u26a0\ufe0f Merge Conflicts Detected\n\nRequest **${e.requestId}** has merge conflicts that need to be resolved before completion.\n\n### Status Update:\n- **Request Status**: Changed to \`conflicted\`\n- **Conflict Resolution Task**: Created task \`${t}\`\n- **Files with Conflicts**: ${e.conflictedFiles.length} files\n\n### Conflicted Files:\n${e.conflictedFiles.map((e=>`- \`${e.path}\``)).join("\n")}\n\n### What Happened:\n${e.summary}\n\n### How to Resolve:\n1. **Use standard file editing tools** to resolve conflicts:\n - \`write-file\` to replace entire file content\n - \`replace-string\` for targeted edits\n - Remove all \`<<<<<<<\`, \`=======\`, \`>>>>>>>\` markers\n\n2. **Ensure all conflict markers are removed** from all files\n\n3. **Call \`complete-request\` again** with the same requestId when done\n\n### The system will:\n- \u2705 Detect that conflicts are resolved (no markers remaining)\n- \u2705 Complete the merge automatically\n- \u2705 Mark the request as completed\n\n**Note**: You can use any file editing approach - the system just validates that conflict markers are gone before allowing completion.`}async validateConflictsResolved(e){const t=[]
963
+ return(await a.createTask(i)).id}generateConflictResolutionMessage(e,t){return`## \u26a0\ufe0f Merge Conflicts Detected\n\nRequest **${e.requestId}** has merge conflicts that need to be resolved before completion.\n\n### Status Update:\n- **Conflict Resolution Task**: Created task \`${t}\`\n- **Files with Conflicts**: ${e.conflictedFiles.length} files\n\n### Conflicted Files:\n${e.conflictedFiles.map((e=>`- \`${e.path}\``)).join("\n")}\n\n### What Happened:\n${e.summary}\n\n### How to Resolve:\n1. **Use standard file editing tools** to resolve conflicts:\n - \`write-file\` to replace entire file content\n - \`replace-string\` for targeted edits\n - Remove all \`<<<<<<<\`, \`=======\`, \`>>>>>>>\` markers\n\n2. **Ensure all conflict markers are removed** from all files\n\n3. **Complete the conflict resolution task** when done\n\n4. **Call \`merge\` again** with the same requestId to merge to main\n\n**Note**: You can use any file editing approach. Remove all conflict markers, complete the task, then call merge.`}async validateConflictsResolved(e){const t=[]
956
964
  for(const r of e.conflictedFiles)try{const e=i.default.resolve(this.workingDirectory,r.path)
957
965
  if(a.default.existsSync(e)){const n=a.default.readFileSync(e,"utf8")
958
966
  this.hasExactConflictMarkers(n)&&t.push(r.path)}}catch(e){this.logger.warn("Failed to check conflict resolution in file",{filePath:r.path,error:(0,n.getErrorMessage)(e)}),t.push(r.path)}return{resolved:0===t.length,remainingConflicts:t}}async hasMainBranchChanged(e){try{const t=this.apiClient.getTaskClient(),r=await t.listTasks({requestId:e})
@@ -1090,11 +1098,11 @@ if(h=e?.requestContextMode,!h){const e=(0,T.getBuiltInAgentConfig)(a)
1090
1098
  h=e?.requestContextMode}}catch{}if(h&&"none"!==h&&!l)return{content:[{type:"text",text:`\u274c Agent '${a}' requires a requestId to be provided.\n\nThis agent has requestContextMode: '${h}' which means it needs to work in the context of a specific request.\n\nPlease provide a requestId when spawning this agent.`}],isError:!0}
1091
1099
  const g=await(0,b.getServerUrl)(t,o)
1092
1100
  r(t,"serverUrl resolved",{serverUrl:g})
1093
- const p=t.basePath
1094
- if(!p)throw new w.ValidationError("Working directory not available in context")
1095
- const f=(0,I.getCachedSession)()
1101
+ const f=t.basePath
1102
+ if(!f)throw new w.ValidationError("Working directory not available in context")
1103
+ const p=(0,I.getCachedSession)()
1096
1104
  let m
1097
- if(g)try{m=i?.sessionId||f?.sessionId||await(0,b.discoverParentSessionId)(g,o)}catch{}let y=""
1105
+ if(g)try{m=i?.sessionId||p?.sessionId||await(0,b.discoverParentSessionId)(g,o)}catch{}let y=""
1098
1106
  if(s&&l)try{const e=s.getSessionRequestAssociationClient()
1099
1107
  if(e){const t=await e.getSessionsForRequest(l,!0),r=m?t.filter((e=>e.opencodeSessionId!==m)):t
1100
1108
  if(r.length>0){const e=r.map((e=>e.opencodeSessionId)).join(", ")
@@ -1107,10 +1115,10 @@ try{let e
1107
1115
  try{const t=await fetch(`http://localhost:${R}/api/project-settings`)
1108
1116
  if(t.ok){const r=await t.json()
1109
1117
  if(r.data?.defaultModel){const[t,...n]=r.data.defaultModel.split("/")
1110
- e={providerID:t,modelID:n.join("/")}}}}catch{}const t=`${g.replace(/\/$/,"")}/session/${_}/message`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:q}],...a?{agent:a}:{},...e?{model:e}:{}})})
1118
+ e={providerID:t,modelID:n.join("/")}}}}catch{}const t=`${g.replace(/\/$/,"")}/session/${_}/prompt_async`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:q}],...a?{agent:a}:{},...e?{model:e}:{}}),signal:AbortSignal.timeout(1e4)})
1111
1119
  if(!r.ok){const e=await r.text().catch((()=>"Unknown error"))
1112
1120
  throw Error(`Failed to send to existing session: ${r.status} ${e}`)}o.info("Prompt sent to existing session",{sessionId:_,agent:a})}catch(e){throw Error("Failed to use existing session: "+(0,E.getErrorMessage)(e))}}else{if(S=!0,r(t,"Creating session via HTTP and spawning CLI"),!g)throw Error("Cannot spawn subagent: no server URL available")
1113
- const i=m||f?.sessionId||await(0,b.discoverParentSessionId)(g,o);(0,v.logSessionIdentity)("subagent_operations.spawn",m?"early-discovery":f?"_meta":"http-discovery",{parentSessionId:i}),r(t,"Parent session discovered",{parentSessionId:i})
1121
+ const i=m||p?.sessionId||await(0,b.discoverParentSessionId)(g,o);(0,v.logSessionIdentity)("subagent_operations.spawn",m?"early-discovery":p?"_meta":"http-discovery",{parentSessionId:i}),r(t,"Parent session discovered",{parentSessionId:i})
1114
1122
  const u=g.replace(/\/$/,"")+"/session",h=e.title?e.title:l?`[${l}] ${c.slice(0,40)}${c.length>40?"...":""}`:`${c.slice(0,50)}${c.length>50?"...":""}`,y=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentID:i,title:h})})
1115
1123
  if(!y.ok)throw Error("Failed to create session: "+y.status)
1116
1124
  const w=await y.json()
@@ -1124,22 +1132,22 @@ if(i){const e=await n.createOrUpdateSession({externalSessionId:i,providerId:"ope
1124
1132
  o=e.id,c=e.workflowId,r(t,"Registered parent session in DB",{parentSessionId:i,parentDbId:o,parentWorkflowId:c})}const l=await n.createOrUpdateSession({externalSessionId:P,providerId:"opencode",parentSessionId:o||null,title:h,status:"active",agentType:a,specialization:e.specialization,workflowId:c||void 0})
1125
1133
  r(t,"Registered child session in DB",{childSessionId:P,childDbId:l.id,parentDbId:o})}catch(e){r(t,"Failed to register sessions in DB",{error:(0,E.getErrorMessage)(e)}),o.warn("Failed to register sessions in alchemy DB",{error:(0,E.getErrorMessage)(e)})}})()
1126
1134
  let O
1127
- r(t,"Starting model resolution",{agent:a,cwd:p})
1135
+ r(t,"Starting model resolution",{agent:a,cwd:f})
1128
1136
  try{r(t,"Fetching agent config from action server",{agent:a,url:`http://localhost:${R}/api/agents/by-name/${a}`})
1129
1137
  const e=await n(a)
1130
1138
  if(r(t,"Agent config result",{agent:a,agentConfig:e||"null",hasConfig:!!e}),e){const n=e.preferredProvider||"inherit",o=e.preferredModelTier||"same"
1131
1139
  r(t,"Agent preferences",{agent:a,preferredProvider:n,preferredTier:o,rawProvider:e.preferredProvider,rawTier:e.preferredModelTier})
1132
- const s=(0,M.resolveAgentModel)(p,n,o)
1140
+ const s=(0,M.resolveAgentModel)(f,n,o)
1133
1141
  r(t,"Model resolution result",{agent:a,result:s}),s.resolved?(O=s.fullModel,r(t,"Resolved agent model",{agent:a,model:O,preferredProvider:n,preferredTier:o})):r(t,"Model resolution fallback",{agent:a,reason:s.reason})}else{const e=(0,T.getBuiltInAgentConfig)(a)
1134
1142
  if(r(t,"No API agent config, checking built-in defaults",{agent:a,builtInConfig:e||"null"}),e){const n=e.preferredProvider||"inherit",o=e.preferredModelTier||"same"
1135
1143
  r(t,"Using built-in agent preferences",{agent:a,preferredProvider:n,preferredTier:o})
1136
- const s=(0,M.resolveAgentModel)(p,n,o)
1144
+ const s=(0,M.resolveAgentModel)(f,n,o)
1137
1145
  r(t,"Built-in model resolution result",{agent:a,result:s}),s.resolved&&(O=s.fullModel,r(t,"Resolved built-in agent model",{agent:a,model:O,preferredProvider:n,preferredTier:o}))}else r(t,"No built-in config found - using default model",{agent:a})}}catch(e){r(t,"Error resolving agent model",{agent:a,error:(0,E.getErrorMessage)(e)})}try{const e=await async function(){try{const e=`http://localhost:${R}/api/project-settings`,t=await fetch(e)
1138
1146
  if(t.ok){const e=await t.json()
1139
1147
  return e?.data?.defaultModel||null}}catch{}return null}()
1140
1148
  if(e)if(O){const o=await n(a)
1141
1149
  "same"===(o?.preferredModelTier||"same")&&(O=e,r(t,"Applied user default model (same tier)",{agent:a,userDefaultModel:e}))}else O=e,r(t,"Using user default model (no agent resolution)",{agent:a,userDefaultModel:e})}catch(e){r(t,"Failed to fetch user default model",{error:(0,E.getErrorMessage)(e)})}r(t,"Final resolved model before spawn",{agent:a,resolvedModel:O||"undefined (will use default)"}),await x
1142
- const j=(0,k.spawnDetachedSubagent)({agent:a,prompt:q,cwd:p,sessionId:P,model:O,initialBranch:C,allowParallel:d,serverUrl:g})
1150
+ const j=(0,k.spawnDetachedSubagent)({agent:a,prompt:q,cwd:f,sessionId:P,model:O,initialBranch:C,allowParallel:d,serverUrl:g})
1143
1151
  if(!j.success)throw Error("Failed to spawn subagent: "+j.error)
1144
1152
  _=P,r(t,"CLI spawn successful with pre-created session",{sessionId:P,pid:j.pid,parentSessionId:i}),o.info("Background subagent spawned via CLI with pre-created session",{agent:a,requestId:l,sessionId:P,pid:j.pid,parentSessionId:i})}if(s&&l&&_&&"unknown"!==_&&"spawning"!==_)try{const e=s.getSessionRequestAssociationClient()
1145
1153
  if(e&&(e.createAssociation(_,l).then((()=>o.info("Created session-request association",{sessionId:_,requestId:l}))).catch((e=>o.warn("Failed to create session-request association",{error:(0,E.getErrorMessage)(e),sessionId:_,requestId:l}))),"coder"===a)){const e=s.getRequestClient()
@@ -1157,7 +1165,7 @@ try{let r
1157
1165
  try{const e=await fetch(`http://localhost:${R}/api/project-settings`)
1158
1166
  if(e.ok){const t=await e.json()
1159
1167
  if(t.data?.defaultModel){const[e,...n]=t.data.defaultModel.split("/")
1160
- r={providerID:e,modelID:n.join("/")}}}}catch{}const o=`${a.replace(/\/$/,"")}/session/${e}/message`,s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:t}],...c?{agent:c}:{},...r?{model:r}:{}})})
1168
+ r={providerID:e,modelID:n.join("/")}}}}catch{}const o=`${a.replace(/\/$/,"")}/session/${e}/prompt_async`,s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:t}],...c?{agent:c}:{},...r?{model:r}:{}}),signal:AbortSignal.timeout(1e4)})
1161
1169
  if(!s.ok){const e=await s.text().catch((()=>"Unknown error"))
1162
1170
  throw Error(`Failed to send message: ${s.status} ${e}`)}return n.info("Message sent to subagent session",{sessionId:e,agent:c}),{content:[{type:"text",text:`Message sent to session ${e}.\nThe subagent will process it in the background.`}]}}catch(e){throw Error("Failed to continue session: "+(0,E.getErrorMessage)(e))}}function i(e){const t=Math.floor(e/1e3)
1163
1171
  if(60>t)return t+"s"
@@ -1177,12 +1185,12 @@ if(!s)throw new w.ValidationError("Could not determine OpenCode server URL")
1177
1185
  n.info("Checking status of subagent session",{sessionId:e})
1178
1186
  try{const c=`${s.replace(/\/$/,"")}/session/${e}`,u=await fetch(c)
1179
1187
  if(!u.ok)return{content:[{type:"text",text:`Session ${e} not found or has exited.`}],isError:!0}
1180
- const h=await u.json(),g=`${s.replace(/\/$/,"")}/session/${e}/message`,p=await fetch(g)
1181
- let f={input:0,output:0,reasoning:0},m="",y=l(null,h.time.updated)
1182
- if(p.ok){const e=await p.json()
1183
- for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(f.input+=t.info.tokens.input||0,f.output+=t.info.tokens.output||0,f.reasoning+=t.info.tokens.reasoning||0)
1188
+ const h=await u.json(),g=`${s.replace(/\/$/,"")}/session/${e}/message`,f=await fetch(g)
1189
+ let p={input:0,output:0,reasoning:0},m="",y=l(null,h.time.updated)
1190
+ if(f.ok){const e=await f.json()
1191
+ for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(p.input+=t.info.tokens.input||0,p.output+=t.info.tokens.output||0,p.reasoning+=t.info.tokens.reasoning||0)
1184
1192
  const t=a(e)
1185
- y=l(t.lastActivityTime,h.time.updated),t.current&&(m+="\nCurrent: "+t.current),t.recent.length>0&&(m+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,b=y.isReady,I=f.input+f.output+f.reasoning
1193
+ y=l(t.lastActivityTime,h.time.updated),t.current&&(m+="\nCurrent: "+t.current),t.recent.length>0&&(m+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,b=y.isReady,I=p.input+p.output+p.reasoning
1186
1194
  let v="",C="",_=null
1187
1195
  if(o)try{const t=o.getSessionRequestAssociationClient()
1188
1196
  if(t){const r=await t.getActiveRequestsForSession(e,!1)
@@ -1197,7 +1205,7 @@ if(e.trim())return d(e)}try{const t=n(`git log main --merges --oneline -n 50 --g
1197
1205
  if(t){const e=t.split("\n")[0].split(" ")[0],o=n(`git diff ${e}^1...${e} --numstat`,{cwd:r,encoding:"utf8"})
1198
1206
  if(o.trim())return{...d(o),merged:!0}}}catch{}return null}catch{return null}}(_,r.basePath)
1199
1207
  if(e){const t=e.additions+e.deletions,r=e.merged?" (merged)":""
1200
- v=`\nDiff vs main (${_}): +${e.additions}/-${e.deletions} lines (${t} total) in ${e.files} file${1!==e.files?"s":""}${r}`}}return{content:[{type:"text",text:`Session ${e}\nTitle: ${h.title||"Untitled"}\nStatus: ${k} (${y.detail})\nReady for input: ${b?"Yes":"No"}\nAge: ${i(w)}\nTokens: ${I.toLocaleString()} (in: ${f.input.toLocaleString()}, out: ${f.output.toLocaleString()}${f.reasoning>0?", reasoning: "+f.reasoning.toLocaleString():""})${m}${C}${v}`}]}}catch(e){throw Error("Failed to check session status: "+(0,E.getErrorMessage)(e))}}async function h(e,t,r){const n=await(0,b.getServerUrl)(t,r)
1208
+ v=`\nDiff vs main (${_}): +${e.additions}/-${e.deletions} lines (${t} total) in ${e.files} file${1!==e.files?"s":""}${r}`}}return{content:[{type:"text",text:`Session ${e}\nTitle: ${h.title||"Untitled"}\nStatus: ${k} (${y.detail})\nReady for input: ${b?"Yes":"No"}\nAge: ${i(w)}\nTokens: ${I.toLocaleString()} (in: ${p.input.toLocaleString()}, out: ${p.output.toLocaleString()}${p.reasoning>0?", reasoning: "+p.reasoning.toLocaleString():""})${m}${C}${v}`}]}}catch(e){throw Error("Failed to check session status: "+(0,E.getErrorMessage)(e))}}async function h(e,t,r){const n=await(0,b.getServerUrl)(t,r)
1201
1209
  if(!n)throw new w.ValidationError("Could not determine OpenCode server URL")
1202
1210
  r.info("Aborting subagent session",{sessionId:e})
1203
1211
  try{const t=`${n.replace(/\/$/,"")}/session/${e}/abort`,o=await fetch(t,{method:"POST"})
@@ -1207,11 +1215,11 @@ if(!g)throw new w.ValidationError("Could not determine OpenCode server URL")
1207
1215
  t.info("Listing sessions",{filters:n})
1208
1216
  try{const e=g.replace(/\/$/,"")+"/session",t=await fetch(e)
1209
1217
  if(!t.ok)throw Error("Failed to fetch sessions: "+t.status)
1210
- let p=await t.json()
1211
- if(0===p.length)return{content:[{type:"text",text:"No sessions found."}]}
1212
- n.parentSessionId&&(p=p.filter((e=>(e.parentId||e.parentID)===n.parentSessionId))),p.sort(((e,t)=>t.time.created-e.time.created))
1213
- const f=g.replace(/\/$/,"")+"/session/status",m=await fetch(f),y=m.ok?await m.json():{}
1214
- let w=p
1218
+ let f=await t.json()
1219
+ if(0===f.length)return{content:[{type:"text",text:"No sessions found."}]}
1220
+ n.parentSessionId&&(f=f.filter((e=>(e.parentId||e.parentID)===n.parentSessionId))),f.sort(((e,t)=>t.time.created-e.time.created))
1221
+ const p=g.replace(/\/$/,"")+"/session/status",m=await fetch(p),y=m.ok?await m.json():{}
1222
+ let w=f
1215
1223
  if(o&&(w=w.filter((e=>"idle"!==(y[e.id]?.type||"idle")))),void 0!==h){const e=36e5*h,t=Date.now()-e
1216
1224
  w=w.filter((e=>e.time.created>=t))}if(0===w.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
1217
1225
  let k={}
@@ -1219,10 +1227,10 @@ if(r)try{const e=r.getCLISessionClient()
1219
1227
  e&&(k=await e.batchEnrich(w.map((e=>e.id))))}catch{}const b=g.replace(/\/$/,""),I=await Promise.allSettled(w.map((e=>fetch(`${b}/session/${e.id}/message`).then((e=>e.ok?e.json():[])).catch((()=>[]))))),v=[]
1220
1228
  for(let e=0;e<w.length;e++){const t=w[e],r=Date.now()-t.time.created
1221
1229
  let o=0,i=null,c=[],h=l(null,t.time.updated)
1222
- const g=I[e],p="fulfilled"===g.status?g.value:[]
1223
- for(const e of p)"assistant"===e.info.role&&e.info.tokens&&(o+=(e.info.tokens.input||0)+(e.info.tokens.output||0)+(e.info.tokens.reasoning||0))
1224
- if(p.length>0){const e=a(p)
1225
- h=l(e.lastActivityTime,t.time.updated),i=e.current||null,c=e.recent}const f=h.status
1230
+ const g=I[e],f="fulfilled"===g.status?g.value:[]
1231
+ for(const e of f)"assistant"===e.info.role&&e.info.tokens&&(o+=(e.info.tokens.input||0)+(e.info.tokens.output||0)+(e.info.tokens.reasoning||0))
1232
+ if(f.length>0){const e=a(f)
1233
+ h=l(e.lastActivityTime,t.time.updated),i=e.current||null,c=e.recent}const p=h.status
1226
1234
  if(void 0!==d&&d>o)continue
1227
1235
  if(void 0!==u&&o>u)continue
1228
1236
  const m=k[t.id]
@@ -1235,31 +1243,31 @@ b.push(...e,...t)
1235
1243
  const r=[]
1236
1244
  e.length>0&&r.push("active: "+e.join(", ")),t.length>0&&r.push("prev: "+t.join(", ")),r.length>0&&(y=` [${r.join(" | ")}]`)}if(s&&!b.includes(s))continue
1237
1245
  const C=t.title||"Untitled",_=C.length>50?C.slice(0,47)+"...":C
1238
- v.push({id:t.id,title:_,status:f,age:r,totalTokens:o,requestsInfo:y,allRequestIds:b,statusDetail:h.detail,specialization:m?.specialization??null,currentAction:i,recentActions:c})}if(0===v.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
1246
+ v.push({id:t.id,title:_,status:p,age:r,totalTokens:o,requestsInfo:y,allRequestIds:b,statusDetail:h.detail,specialization:m?.specialization??null,currentAction:i,recentActions:c})}if(0===v.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
1239
1247
  const C=c?v.slice(0,c):v,_=C.map((e=>{const t=e.specialization?"\n Specialization: "+e.specialization:"",r=e.currentAction?"\n Current: "+e.currentAction:"",n=e.recentActions.length>0?"\n Recent: "+e.recentActions.join(", "):""
1240
1248
  return`\u2022 ${e.id}\n ${e.title}${t}\n Status: ${e.status} (${e.statusDetail}) | Age: ${i(e.age)} | ${e.totalTokens.toLocaleString()} tokens${e.requestsInfo}${r}${n}`})),E=c&&v.length>c?` (showing ${c} of ${v.length})`:""
1241
- return{content:[{type:"text",text:`Found ${C.length} session${1!==C.length?"s":""}${E}:\n\n${_.join("\n\n")}`}]}}catch(e){throw Error("Failed to list sessions: "+(0,E.getErrorMessage)(e))}}var p,f=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
1249
+ return{content:[{type:"text",text:`Found ${C.length} session${1!==C.length?"s":""}${E}:\n\n${_.join("\n\n")}`}]}}catch(e){throw Error("Failed to list sessions: "+(0,E.getErrorMessage)(e))}}var f,p=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
1242
1250
  var o=Object.getOwnPropertyDescriptor(t,r)
1243
- o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),m=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),y=this&&this.__importStar||(p=function(e){return p=Object.getOwnPropertyNames||function(e){var t=[]
1251
+ o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),m=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),y=this&&this.__importStar||(f=function(e){return f=Object.getOwnPropertyNames||function(e){var t=[]
1244
1252
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
1245
- return t},p(e)},function(e){if(e&&e.__esModule)return e
1253
+ return t},f(e)},function(e){if(e&&e.__esModule)return e
1246
1254
  var t={}
1247
- if(null!=e)for(var r=p(e),n=0;n<r.length;n++)"default"!==r[n]&&f(t,e,r[n])
1255
+ if(null!=e)for(var r=f(e),n=0;n<r.length;n++)"default"!==r[n]&&p(t,e,r[n])
1248
1256
  return m(t,e),t})
1249
1257
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpawn=o,exports.handleContinue=s,exports.handleCheckStatus=u,exports.handleAbort=h,exports.handleListSessions=g,exports.handleSubagentOperations=async function(e,t,r,n,i,a){const c=r.child({tool:"subagent_operations"}),l=n.startTimer("tool_execution_time")
1250
- try{e&&!e.operation&&(e.spawn?e.operation="spawn":e.continue?e.operation="continue":e.readMessages?e.operation="read-messages":e.listSessions?e.operation="list-sessions":e.prompt&&(e.agent||e.description)?e={operation:"spawn",spawn:{agent:e.agent||"coder",prompt:e.prompt,description:e.description||e.prompt.slice(0,60),requestId:e.requestId,allowParallel:e.allowParallel,useExistingSession:e.useExistingSession}}:e.sessionId&&e.prompt&&!e.spawn?e={operation:"continue",sessionId:e.sessionId,continue:{prompt:e.prompt}}:e.sessionId&&(e={operation:"check-status",sessionId:e.sessionId})),"spawn"===e?.operation&&e?.prompt&&!e?.spawn&&(e.spawn={agent:e.agent||"coder",prompt:e.prompt,description:e.description||e.prompt.slice(0,60),requestId:e.requestId},delete e.prompt,delete e.agent,delete e.description,delete e.requestId),"continue"===e?.operation&&e?.prompt&&!e?.continue&&(e.continue={prompt:e.prompt},delete e.prompt)
1251
- const r=_.validateArgs(e,C.SubagentOperationsSchema),{sessionId:d,operation:p}=r
1252
- let f
1253
- switch(c.info("Processing subagent_operations",{operation:p,sessionId:d}),p){case"spawn":f=await o(r.spawn,t,c,i,a)
1258
+ try{if(e&&!e.operation&&(e.spawn?e.operation="spawn":e.continue?e.operation="continue":e.readMessages?e.operation="read-messages":e.listSessions?e.operation="list-sessions":e.prompt&&(e.agent||e.description)?e={operation:"spawn",spawn:{agent:e.agent||"coder",prompt:e.prompt,description:e.description||e.prompt.slice(0,60),requestId:e.requestId,allowParallel:e.allowParallel,useExistingSession:e.useExistingSession}}:e.sessionId&&e.prompt&&!e.spawn?e={operation:"continue",sessionId:e.sessionId,continue:{prompt:e.prompt}}:e.sessionId&&(e={operation:"check-status",sessionId:e.sessionId})),e?.spawn&&"string"==typeof e.spawn)try{e.spawn=JSON.parse(e.spawn)}catch{}if(e?.continue&&"string"==typeof e.continue)try{e.continue=JSON.parse(e.continue)}catch{}"spawn"===e?.operation&&e?.prompt&&!e?.spawn&&(e.spawn={agent:e.agent||"coder",prompt:e.prompt,description:e.description||e.prompt.slice(0,60),requestId:e.requestId},delete e.prompt,delete e.agent,delete e.description,delete e.requestId),"continue"===e?.operation&&e?.prompt&&!e?.continue&&(e.continue={prompt:e.prompt},delete e.prompt)
1259
+ const r=_.validateArgs(e,C.SubagentOperationsSchema),{sessionId:d,operation:f}=r
1260
+ let p
1261
+ switch(c.info("Processing subagent_operations",{operation:f,sessionId:d}),f){case"spawn":p=await o(r.spawn,t,c,i,a)
1254
1262
  break
1255
- case"continue":f=await s(d,r.continue.prompt,t,c,i,void 0,a)
1263
+ case"continue":p=await s(d,r.continue.prompt,t,c,i,void 0,a)
1256
1264
  break
1257
- case"check-status":f=await u(d,t,c,i)
1265
+ case"check-status":p=await u(d,t,c,i)
1258
1266
  break
1259
- case"abort":f=await h(d,t,c)
1267
+ case"abort":p=await h(d,t,c)
1260
1268
  break
1261
1269
  case"read-messages":const e=r.readMessages?.limit??1
1262
- f=await async function(e,t,r,n){const o=await(0,b.getServerUrl)(r,n)
1270
+ p=await async function(e,t,r,n){const o=await(0,b.getServerUrl)(r,n)
1263
1271
  if(!o)throw new w.ValidationError("Could not determine OpenCode server URL")
1264
1272
  n.info("Reading messages from subagent session",{sessionId:e,limit:t})
1265
1273
  try{const r=`${o.replace(/\/$/,"")}/session/${e}/message?limit=${t}`,n=await fetch(r)
@@ -1271,9 +1279,9 @@ return`[${t+1}] ${r} (${new Date(e.info.time.created).toLocaleTimeString()}):\n$
1271
1279
  return{content:[{type:"text",text:`Session ${e} - Last ${s.length} messages:\n\n${i}`}]}}catch(e){throw Error("Failed to read messages: "+(0,E.getErrorMessage)(e))}}(d,e,t,c)
1272
1280
  break
1273
1281
  case"list-sessions":const n={activeOnly:r.listSessions?.activeOnly,requestId:r.listSessions?.requestId,limit:r.listSessions?.limit,minTokens:r.listSessions?.minTokens,maxTokens:r.listSessions?.maxTokens,maxAgeHours:r.listSessions?.maxAgeHours,parentSessionId:a?.sessionId||(0,I.getCachedSession)()?.sessionId}
1274
- f=await g(t,c,i,n)
1282
+ p=await g(t,c,i,n)
1275
1283
  break
1276
- default:throw new w.ValidationError("Unknown operation: "+p)}return l({success:!0}),n.incrementCounter(`subagent_operations_${p}_success`,1),f}catch(e){return c.error("Subagent operations failed",{error:e instanceof Error?e.stack:e+""}),l({success:!1}),n.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:"Subagent operation failed: "+(0,E.getErrorMessage)(e)}],isError:!0}}}
1284
+ default:throw new w.ValidationError("Unknown operation: "+f)}return l({success:!0}),n.incrementCounter(`subagent_operations_${f}_success`,1),p}catch(e){return c.error("Subagent operations failed",{error:e instanceof Error?e.stack:e+""}),l({success:!1}),n.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:"Subagent operation failed: "+(0,E.getErrorMessage)(e)}],isError:!0}}}
1277
1285
  const w=t(9860),k=t(8035),b=t(7617),I=t(715),v=t(7280),C=t(6183),_=y(t(5967)),E=t(8824),q=t(9896),S=t(6928),T=t(8955),M=t(5671),R=3456,P=6e4,x=3e5},1791(e,exports,t){function r(e,t){return t.info("Creating project context middleware",{projectId:e}),(t,r,n)=>{"GET"===t.method&&(t.query.projectId=e),["POST","PATCH","PUT"].includes(t.method)&&t.body&&(t.body.projectId=e),n()}}var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
1278
1286
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectContext=void 0,exports.projectContextMiddleware=r
1279
1287
  const o=n(t(9896)),s=n(t(6928)),i=t(4139),a=t(4055),c=t(8824)
@@ -1421,20 +1429,22 @@ try{const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=e.ge
1421
1429
  if(g.push("session: "+(r?.sessionId||"NONE")),r?.sessionId){const t=await e.getSessionRequestId(o,s)
1422
1430
  if(g.push("reqId: "+(t||"NONE")),t){const e=await o.proxyGet(`/api/projects/${n.projectId}/requests/${t}/test-runs`),r=e?.data||e||[],s=Array.isArray(r)?r.find((e=>e.worktreePath||e.worktree_path)):null
1423
1431
  g.push(`runs: ${Array.isArray(r)?r.length:0}, withWorktree: ${s?.id||"NONE"}, path: ${s?.worktreePath||s?.worktree_path||"NONE"}`),s&&(h=s.worktreePath||s.worktree_path,c.info("Using test worktree from request test run",{worktreePath:h,reqId:t}))}}}catch(e){c.warn("Failed to resolve test worktree",{error:(0,r.getErrorMessage)(e)})}if(!h)return a({success:!1,error:"no_worktree"}),{content:[{type:"text",text:`No test worktree found.\n\nDiagnostics:\n${g.length>0?g.map((e=>"\u2022 "+e)).join("\n"):"\u2022 No session identity found"}\n\nEnsure this session is linked to a test process and a test run has been created.`}],isError:!0}
1424
- const p=[]
1432
+ const f=[]
1425
1433
  for(const t of l){c.info("Executing test command",{name:t.name,command:t.command,timeout:t.timeout,cwd:h})
1426
1434
  try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"/bin/sh",env:{...u.env,FORCE_COLOR:"0"}})
1427
- p.push({name:t.name,command:t.command,exitCode:0,output:e.slice(-4e3),timedOut:!1})}catch(r){const n=!0===r.killed,o=((r.stdout||"")+"\n"+(r.stderr||"")).trim().slice(-4e3),s=r.status??1
1428
- if(p.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const f=p.every((e=>0===e.exitCode)),m=p.map((e=>{const t=e.timedOut?"\u23f1 TIMEOUT":0===e.exitCode?"\u2705 PASS":`\u274c FAIL (exit ${e.exitCode})`
1435
+ f.push({name:t.name,command:t.command,exitCode:0,output:e.slice(-4e3),timedOut:!1})}catch(r){const n=!0===r.killed,o=((r.stdout||"")+"\n"+(r.stderr||"")).trim().slice(-4e3),s=r.status??1
1436
+ if(f.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const p=f.every((e=>0===e.exitCode)),m=f.map((e=>{const t=e.timedOut?"\u23f1 TIMEOUT":0===e.exitCode?"\u2705 PASS":`\u274c FAIL (exit ${e.exitCode})`
1429
1437
  return`### ${e.name}: ${t}\n\`\`\`\n$ ${e.command}\n${e.output}\n\`\`\``})).join("\n\n")
1430
- return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${f?"PASSED":"FAILED"}\n\n${m}`}]}}catch(e){return a({success:!1,error:"execution_error"}),{content:[{type:"text",text:"Failed to execute test command: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleReportTestResults=async function(e,o,s,i,a){const c=a.startTimer("tool_execution_time")
1438
+ return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${p?"PASSED":"FAILED"}\n\n${m}`}]}}catch(e){return a({success:!1,error:"execution_error"}),{content:[{type:"text",text:"Failed to execute test command: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleReportTestResults=async function(e,o,s,i,a){const c=a.startTimer("tool_execution_time")
1431
1439
  try{const{sessionIdentity:l}=await Promise.resolve().then(t.bind(t,6688)),d=await l.getSessionRequestId(s,i)
1432
1440
  if(!d)return c({success:!1,error:"no_request_association"}),{content:[{type:"text",text:"Cannot report test results: this session is not associated with a request."}],isError:!0}
1433
- const u=await s.proxyGet(`/api/projects/${o.projectId}/requests/${d}/test-runs`),h=u?.data||u||[],g=Array.isArray(h)?h:[],p=g.find((e=>"pending"===e.status||"running"===e.status))||g[0]
1434
- if(!p)return c({success:!1,error:"no_test_run"}),{content:[{type:"text",text:`No test run found for request ${d}.`}],isError:!0}
1435
- const f=p.id
1436
- await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${f}`,{status:e.status,results:e.results})
1437
- const m="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f",y="passed"===e.status?"\n\nAll tests passed \u2014 run `complete_request` to finalize this request.":"",w=`${m} Test run ${e.status} for request ${d}\n\n${e.results.summary}${y}`
1441
+ const u=await s.proxyGet(`/api/projects/${o.projectId}/requests/${d}/test-runs`),h=u?.data||u||[],g=Array.isArray(h)?h:[],f=g.find((e=>"pending"===e.status||"running"===e.status))||g[0]
1442
+ if(!f)return c({success:!1,error:"no_test_run"}),{content:[{type:"text",text:`No test run found for request ${d}.`}],isError:!0}
1443
+ const p=f.id
1444
+ await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${p}`,{status:e.status,results:e.results})
1445
+ const m="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f"
1446
+ try{const t=s.getRequestClient()
1447
+ "passed"===e.status?(await t.updateRequest(d,{status:"ready_for_merge"}),i.info("Tests passed, set request to ready_for_merge",{requestId:d})):(await t.updateRequest(d,{status:"in_progress"}),i.info("Tests failed, set request back to in_progress",{requestId:d}))}catch(e){i.warn("Failed to update request status after test results",{requestId:d,error:(0,r.getErrorMessage)(e)})}const y="passed"===e.status?"\n\nAll tests passed \u2014 the coder can now call `merge` to merge this request.":"\n\nTests failed \u2014 the coder should fix the issues and call `complete` again.",w=`${m} Test run ${e.status} for request ${d}\n\n${e.results.summary}${y}`
1438
1448
  try{const t=await(0,n.handleSessionMessageOperations)({operation:"send",type:"report",status:"passed"===e.status?"success":"failure",summary:w,details:e.results.commands?.map((e=>`${"passed"===e.status?"\u2705":"\u274c"} ${e.name}: ${e.status}${e.diagnosis?" - "+e.diagnosis:""}`)).join("\n"),finish:!0},o,i,a,s),r=t?.content?.[0]?.text||"unknown",l=t?.isError
1439
1449
  return c({success:!0}),{content:[{type:"text",text:`Test run for request ${d} reported as **${e.status}**.${l?" Parent notification FAILED: "+r:" Parent session notified."}\n\n${e.results.summary}`}]}}catch(t){return c({success:!0}),{content:[{type:"text",text:`Test run for request ${d} reported as **${e.status}** but failed to notify parent: ${(0,r.getErrorMessage)(t)}\n\n${e.results.summary}`}]}}}catch(e){return c({success:!1,error:"api_error"}),{content:[{type:"text",text:"Failed to report test results: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleTestingReference=async function(e,t,r,n,o){return o.startTimer("tool_execution_time")({success:!0}),{content:[{type:"text",text:'# Test Process Design Guide\n\n## Overview\n\nA test process defines how to verify code changes for a project. It consists of:\n- **Setup**: Commands to prepare the environment (install deps, link node_modules, etc.) \u2014 runs once per worktree\n- **Commands**: The actual test commands (build, lint, test, etc.) \u2014 the verification steps\n\n## Command Properties\n\n- **name**: Human-readable name (e.g., "Build", "Unit Tests")\n- **command**: Shell command to run (e.g., `npm test`)\n- **required** (default: true): If a required command fails, the request won\'t be merged\n- **timeout** (default: 300s): Maximum execution time. Exit code 0 = pass, non-zero = fail.\n\n## Scope (Monorepo Support)\n\nSet `scope` to a path prefix to limit when a process runs:\n- `scope: "packages/api/"` \u2192 only runs when files under packages/api/ change\n- `scope: null` \u2192 runs for all changes (global process)\n\nMultiple active processes per project are supported.\n\n## Common Patterns\n\n### Node.js / TypeScript\n```json\n{\n "setup": ["ln -s ../../node_modules node_modules"],\n "commands": [\n { "name": "Build", "command": "npm run build" },\n { "name": "Lint", "command": "npm run lint", "required": false },\n { "name": "Unit Tests", "command": "npm test" }\n ]\n}\n```\n\n### Python\n```json\n{\n "setup": ["pip install -e \'.[dev]\'"],\n "commands": [\n { "name": "Type Check", "command": "mypy src/" },\n { "name": "Lint", "command": "ruff check .", "required": false },\n { "name": "Tests", "command": "pytest" }\n ]\n}\n```\n\n### Go\n```json\n{\n "setup": ["go mod download"],\n "commands": [\n { "name": "Build", "command": "go build ./..." },\n { "name": "Vet", "command": "go vet ./...", "required": false },\n { "name": "Tests", "command": "go test ./..." }\n ]\n}\n```\n\n### Rust\n```json\n{\n "setup": ["cargo fetch"],\n "commands": [\n { "name": "Build", "command": "cargo build" },\n { "name": "Clippy", "command": "cargo clippy -- -D warnings", "required": false },\n { "name": "Tests", "command": "cargo test" }\n ]\n}\n```\n\n## Project Analysis Checklist\n\nWhen setting up testing for a new project, check for:\n1. **package.json** \u2192 Node.js/TypeScript (check "scripts" for test/build/lint commands)\n2. **Cargo.toml** \u2192 Rust\n3. **go.mod** \u2192 Go\n4. **pyproject.toml** / **requirements.txt** \u2192 Python\n5. **Makefile** \u2192 Custom build system (check for test/build targets)\n6. **.github/workflows/** \u2192 Existing CI configuration (great source of test commands)\n7. **.gitlab-ci.yml** \u2192 GitLab CI\n8. **tsconfig.json** \u2192 TypeScript type checking\n9. **.eslintrc** / **biome.json** \u2192 Linting configuration\n10. **vitest.config.ts** / **jest.config.ts** / **pytest.ini** \u2192 Test framework configuration'}]}}
1440
1450
  const r=t(8824),n=t(9072)},2085(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRequestTimelineForFile=async function(e,t,s,i){let a=`# File History: ${t}\n\n`
@@ -1546,7 +1556,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
1546
1556
  var t={}
1547
1557
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
1548
1558
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
1549
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,t,r,n,o,s,i,f){const m=s.child({tool:"move_files"}),y=Date.now()
1559
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,t,r,n,o,s,i,p){const m=s.child({tool:"move_files"}),y=Date.now()
1550
1560
  let w,k,b=d.FileOperationPhase.VALIDATION
1551
1561
  const I={toolName:"move-files",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"move-files",metricsPrefix:"move_files",successMessage:"Successfully moved files",failureMessage:"Failed to move files"}
1552
1562
  try{const s=d.validateArgs(e,l.MoveFilesSchema),{taskId:u,operations:h,comment:v}=s
@@ -1565,7 +1575,7 @@ throw Error(M.error)}let R={hadUserMods:!1,userModsCommitHash:void 0}
1565
1575
  if(t.git)try{m.debug("[MOVE-FILES] Checking for user changes before move operations")
1566
1576
  const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"move-files",{requestId:q,taskId:u,workspaceManager:t.workspaceManager},m,i)
1567
1577
  e.userChangesCommitted&&(m.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),m.info("User changes committed before move-files operation",{taskId:u,moveOperationsCount:_.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),R={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){m.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),m.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:u,moveOperationsCount:_.length,error:e instanceof Error?e.message:e+""})}m.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:_.length}),b=d.FileOperationPhase.RECORD_CREATION,i.incrementCounter("move_files_phase",1,{phase:b})
1568
- const{toolRecordId:P,localToolRecordId:x}=await d.createFileOperationRecords(u,q,t.projectId,I.recordType,_[0].source,{operationCount:h.length,operations:_.map((e=>({source:e.source,destination:e.destination}))),userComment:v,hadUserMods:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},r,n,m,i,I.metricsPrefix,f)
1578
+ const{toolRecordId:P,localToolRecordId:x}=await d.createFileOperationRecords(u,q,t.projectId,I.recordType,_[0].source,{operationCount:h.length,operations:_.map((e=>({source:e.source,destination:e.destination}))),userComment:v,hadUserMods:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},r,n,m,i,I.metricsPrefix,p)
1569
1579
  w=P,k=P,b=I.fileOperationPhase,i.incrementCounter("move_files_phase",1,{phase:b})
1570
1580
  const O=[]
1571
1581
  let j=0
@@ -1573,27 +1583,27 @@ for(const e of _){const t={operation:{source:e.source,destination:e.destination}
1573
1583
  try{try{await a.default.access(e.fullSource)}catch(t){throw Error("Source path not accessible: "+e.source)}const r=(await a.default.stat(e.fullSource)).isDirectory()
1574
1584
  t.isDirectory=r
1575
1585
  const n=c.default.dirname(e.fullDestination)
1576
- try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,j++,m.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),m.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}O.push(t)}const $=Date.now()-y
1586
+ try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,j++,m.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,f.getErrorMessage)(r),m.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}O.push(t)}const $=Date.now()-y
1577
1587
  i.recordValue("move_files_time",$),i.incrementCounter("move_files_operations_total",h.length),i.incrementCounter("move_files_operations_success",j),i.incrementCounter("move_files_operations_failed",h.length-j),j===h.length?i.incrementCounter("move_files_success",1):j>0?i.incrementCounter("move_files_partial_success",1):i.incrementCounter("move_files_total_failure",1)
1578
- let A=null
1588
+ let D=null
1579
1589
  if(j>0){b=d.FileOperationPhase.GIT_COMMIT,i.incrementCounter("move_files_phase",1,{phase:b})
1580
1590
  const e=O.filter((e=>e.success)),r=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${v}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${v}`
1581
- A=await d.commitToGit(u,_[0].destination,P,x,r,t,m,i,I.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("move_files_phase",1,{phase:b})
1582
- const D=O.filter((e=>e.success)),F=O.filter((e=>!e.success))
1583
- await d.updateFileOperationRecords(u,w,k,_[0].source,I.recordType,j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,{status:j===h.length?"completed":"partial_success",commitHash:A?.commitHash,previousCommitHash:A?.previousCommitHash,operationCount:h.length,successCount:j,failureCount:h.length-j,successfulOperations:D.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:F.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:v,hadUserMods:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,r,n,m,i,I.metricsPrefix)
1591
+ D=await d.commitToGit(u,_[0].destination,P,x,r,t,m,i,I.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("move_files_phase",1,{phase:b})
1592
+ const A=O.filter((e=>e.success)),F=O.filter((e=>!e.success))
1593
+ await d.updateFileOperationRecords(u,w,k,_[0].source,I.recordType,j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,{status:j===h.length?"completed":"partial_success",commitHash:D?.commitHash,previousCommitHash:D?.previousCommitHash,operationCount:h.length,successCount:j,failureCount:h.length-j,successfulOperations:A.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:F.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:v,hadUserMods:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,r,n,m,i,I.metricsPrefix)
1584
1594
  const N=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
1585
1595
  let L=""
1586
1596
  if(j===h.length)L=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
1587
1597
  else if(j>0){const e=O.filter((e=>!e.success))
1588
1598
  L=`Successfully moved ${j}/${h.length} items.\n\nFailed operations:\n`+e.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")}else L="All move operations failed:\n"+O.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
1589
- return A?.commitHash&&(L+="\nCommit: "+A.commitHash.substring(0,8)),N.requestId&&(L+="\nBranch: "+N.requestId),M.lockAcquired&&M.lockedRequestId&&(L+="\n\u{1f512} **Locked request:** "+M.lockedRequestId),{content:[{type:"text",text:L}],isError:0===j}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
1590
- await n.createToolRecord({...r?{}:{taskId:e.taskId},projectId:t.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:"Failed to move files - "+(0,p.getErrorMessage)(o)})}catch(t){m.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-y
1591
- if(i.recordValue("move_files_time",s),i.incrementCounter("move_files_errors",1),m.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(o),time:s}),(w||k)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
1592
- try{await d.updateFileOperationRecords(e.taskId,w,k,e.operations?.[0]?.source||"unknown",I.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(o),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",r,n,m,i,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(o,b,m,i,e,I)}}
1593
- const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(7478),p=t(8824)},2422(module){module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1599
+ return D?.commitHash&&(L+="\nCommit: "+D.commitHash.substring(0,8)),N.requestId&&(L+="\nBranch: "+N.requestId),M.lockAcquired&&M.lockedRequestId&&(L+="\n\u{1f512} **Locked request:** "+M.lockedRequestId),{content:[{type:"text",text:L}],isError:0===j}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
1600
+ await n.createToolRecord({...r?{}:{taskId:e.taskId},projectId:t.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,f.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:"Failed to move files - "+(0,f.getErrorMessage)(o)})}catch(t){m.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-y
1601
+ if(i.recordValue("move_files_time",s),i.incrementCounter("move_files_errors",1),m.error("Error in move-files operation:",{error:(0,f.getErrorMessage)(o),time:s}),(w||k)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
1602
+ try{await d.updateFileOperationRecords(e.taskId,w,k,e.operations?.[0]?.source||"unknown",I.recordType,"Failed to move files",{status:"failed",error:(0,f.getErrorMessage)(o),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",r,n,m,i,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(o,b,m,i,e,I)}}
1603
+ const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(7478),f=t(8824)},2422(module){module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1594
1604
  const r=t(6183),n=t(3707)
1595
1605
  exports.def={name:"quick_manage",description:"Move, delete, or create directories. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with operationType and corresponding data:\n\u2022 create-directory: { createDirectory: { path } }\n\u2022 move-files: { moveFiles: { moves: [{ source, destination }] } }\n\u2022 delete-files: { deleteFiles: { targets: [{ path }] } }\n\nFor read-only operations like get-file-info, use manage_files instead.\n\nRequires: title, description, operations.",schema:r.QuickManageSchema,annotations:{title:"Quick Manage",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"manage",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},2462(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0})
1596
- const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),f=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),b=t(6111),I=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(5216),T=t(6473),M=t(4921),R=t(8850),P=t(3556),x=t(1391),O=t(6315),j=t(7713),$=t(6252),A=t(213),D=t(7250),F=t(2425),N=t(1540),L=t(5767),z=t(4973),B=t(7613),H=t(3322),U=t(5247),W=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(p.def),(0,r.registerTool)(f.def),(0,r.registerTool)(m.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(b.def),(0,r.registerTool)(I.def),(0,r.registerTool)(v.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(S.def),(0,r.registerTool)(T.def),(0,r.registerTool)(M.def),(0,r.registerTool)(R.def),(0,r.registerTool)(P.def),(0,r.registerTool)(x.def),(0,r.registerTool)(O.def),(0,r.registerTool)(j.def),(0,r.registerTool)($.def),(0,r.registerTool)(A.def),(0,r.registerTool)(D.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(B.def),(0,r.registerTools)(H.metaDefs),(0,r.registerTools)(U.testingDefs),(0,r.registerTools)(W.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.requestConfig=void 0,exports.areTestsRequiredForCompletion=function(){return exports.requestConfig.requireTestsForCompletion},exports.setTestsRequiredForCompletion=function(e){exports.requestConfig.requireTestsForCompletion=e},exports.getCompletionMode=function(e){return e&&["auto-merge","auto-test-then-merge","manual-review"].includes(e)?e:"auto-merge"},exports.getApprovalMode=function(e){return e&&["none","require-approval"].includes(e)?e:"none"},exports.requestConfig={requireTestsForCompletion:!1}},2537(e,exports,t){async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
1606
+ const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),f=t(4805),p=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),b=t(6111),I=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(5216),T=t(6473),M=t(4921),R=t(8850),P=t(3556),x=t(1391),O=t(6315),j=t(7713),$=t(6252),D=t(213),A=t(7250),F=t(2425),N=t(1540),L=t(5767),z=t(4973),B=t(7613),H=t(3322),W=t(5247),U=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(f.def),(0,r.registerTool)(p.def),(0,r.registerTool)(m.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(b.def),(0,r.registerTool)(I.def),(0,r.registerTool)(v.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(S.def),(0,r.registerTool)(T.def),(0,r.registerTool)(M.def),(0,r.registerTool)(R.def),(0,r.registerTool)(P.def),(0,r.registerTool)(x.def),(0,r.registerTool)(O.def),(0,r.registerTool)(j.def),(0,r.registerTool)($.def),(0,r.registerTool)(D.def),(0,r.registerTool)(A.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(B.def),(0,r.registerTools)(H.metaDefs),(0,r.registerTools)(W.testingDefs),(0,r.registerTools)(U.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.requestConfig=void 0,exports.areTestsRequiredForCompletion=function(){return exports.requestConfig.requireTestsForCompletion},exports.setTestsRequiredForCompletion=function(e){exports.requestConfig.requireTestsForCompletion=e},exports.getCompletionMode=function(e){return e&&["auto-merge","auto-test-then-merge","manual-review"].includes(e)?e:"auto-merge"},exports.getApprovalMode=function(e){return e&&["none","require-approval"].includes(e)?e:"none"},exports.requestConfig={requireTestsForCompletion:!1}},2537(e,exports,t){async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
1597
1607
  try{return(await y.default.readFile(e,"utf-8")).split("\n").length}catch{return}}}function n(e,t,r){const n="depth"in e,o=n?e:r,s=n?e.isDirectory:e.isDirectory(),a=e.name,c=s?"[\u{1f4c1} DIR]":"[\u{1f4c4} FILE]"
1598
1608
  let l=""
1599
1609
  if(s||void 0===o?.lineCount||(l=` (${i(o.lineCount)} lines)`),s&&o?.subtreeTotals){const{files:e,lines:t}=o.subtreeTotals
@@ -1616,10 +1626,10 @@ let t=e,r=0
1616
1626
  for(;t>=1024&&4>r;)t/=1024,r++
1617
1627
  return`${0===r?t.toString():t.toFixed(10>t?1:0)}${["bytes","KB","MB","GB","TB"][r]}`}(o.size)})`)}return`${c} ${a}${l}`}async function o(e,t,n=0,s,i,l){if(n>=s)return[]
1618
1628
  try{const{fullPath:d}=b.validateAndNormalizePath(e,t),h=await y.default.readdir(d,{withFileTypes:!0}),g=[]
1619
- for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=b.validateAndNormalizePath(u,t),p=await y.default.stat(h),f=d.isFile()?w.default.extname(d.name).toLowerCase():""
1629
+ for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=b.validateAndNormalizePath(u,t),f=await y.default.stat(h),p=d.isFile()?w.default.extname(d.name).toLowerCase():""
1620
1630
  let m
1621
- d.isFile()&&(m=await r(h,p.size,f))
1622
- const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:p.size,modified:p.mtime,extension:f,lineCount:m}
1631
+ d.isFile()&&(m=await r(h,f.size,p))
1632
+ const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:f.size,modified:f.mtime,extension:p,lineCount:m}
1623
1633
  d.isDirectory()&&(s-1>n?(k.children=await o(u,t,n+1,s,i,l),k.children&&k.children.length>0&&(k.subtreeTotals=c(k.children))):k.subtreeTotals=await a(u,t,l)),g.push(k)}catch(e){l.debug("Excluding entry from tree: "+d.name,{reason:(0,v.getErrorMessage)(e)})}return u(g,i)}catch(t){return l.debug(`Failed to build tree for ${e}:`,{error:(0,v.getErrorMessage)(t)}),[]}}function s(e,t="name",r=""){if(0===e.length)return""
1624
1634
  const o=[]
1625
1635
  return e.forEach(((i,a)=>{const c=a===e.length-1,l=c?"\u2514\u2500\u2500 ":"\u251c\u2500\u2500 ",d=n(i,t),u=i.isDirectory?"/":""
@@ -1645,21 +1655,21 @@ case"type":const o=e.extension||"",s=r.extension||""
1645
1655
  return o!==s?o.localeCompare(s):e.name.localeCompare(r.name)
1646
1656
  default:return e.name.localeCompare(r.name)}}))}var h,g=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
1647
1657
  var o=Object.getOwnPropertyDescriptor(t,r)
1648
- o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),p=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),f=this&&this.__importStar||(h=function(e){return h=Object.getOwnPropertyNames||function(e){var t=[]
1658
+ o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),f=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),p=this&&this.__importStar||(h=function(e){return h=Object.getOwnPropertyNames||function(e){var t=[]
1649
1659
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
1650
1660
  return t},h(e)},function(e){if(e&&e.__esModule)return e
1651
1661
  var t={}
1652
1662
  if(null!=e)for(var r=h(e),n=0;n<r.length;n++)"default"!==r[n]&&g(t,e,r[n])
1653
- return p(t,e),t}),m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
1663
+ return f(t,e),t}),m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
1654
1664
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListDirectory=async function(e,t,i,a){const h=Date.now()
1655
1665
  let g=b.FileOperationPhase.VALIDATION
1656
1666
  b.FileOperationPhase.FILE_WRITE
1657
- try{const p=b.validateArgs(e,k.ListDirectorySchema),{path:f,levels:m=1,sortBy:I="name"}=p
1658
- i.info("Listing directory: "+f)
1659
- const{normalizedPath:C,fullPath:_}=b.validateAndNormalizePath(f,t)
1667
+ try{const f=b.validateArgs(e,k.ListDirectorySchema),{path:p,levels:m=1,sortBy:I="name"}=f
1668
+ i.info("Listing directory: "+p)
1669
+ const{normalizedPath:C,fullPath:_}=b.validateAndNormalizePath(p,t)
1660
1670
  g=b.FileOperationPhase.FILE_WRITE
1661
- try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+f}],isError:!0}
1662
- await y.default.access(_,y.default.constants.R_OK)}catch(e){return e instanceof Error&&"ENOENT"===e.code?{content:[{type:"text",text:"Directory does not exist: "+f}],isError:!0}:e instanceof Error&&"EACCES"===e.code?{content:[{type:"text",text:"Directory not accessible: "+f}],isError:!0}:{content:[{type:"text",text:"Cannot access directory: "+f}],isError:!0}}let E,q
1671
+ try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+p}],isError:!0}
1672
+ await y.default.access(_,y.default.constants.R_OK)}catch(e){return e instanceof Error&&"ENOENT"===e.code?{content:[{type:"text",text:"Directory does not exist: "+p}],isError:!0}:e instanceof Error&&"EACCES"===e.code?{content:[{type:"text",text:"Directory not accessible: "+p}],isError:!0}:{content:[{type:"text",text:"Cannot access directory: "+p}],isError:!0}}let E,q
1663
1673
  if(m>1){i.info(`Building tree structure for: ${C} (levels: ${m}, sortBy: ${I})`)
1664
1674
  const e=await o(C,t,0,m,I,i)
1665
1675
  if(e.length>0){const t=s(e,I)
@@ -1672,7 +1682,7 @@ E+="\n\nBranch: "+(S?.branchName||"unknown")
1672
1682
  const T=Date.now()-h
1673
1683
  return a.recordValue("list_directory_time",T),a.recordValue("list_directory_entries",q),a.incrementCounter("list_directory_success",1),i.info("Successfully listed directory: "+C,{entryCount:q,levels:m,time:T}),{content:[{type:"text",text:E}]}}catch(e){const t=Date.now()-h
1674
1684
  return a.recordValue("list_directory_time",t),a.incrementCounter("list_directory_errors",1),i.error("Error listing directory:",{error:(0,v.getErrorMessage)(e),time:t}),{content:[{type:"text",text:(0,v.getErrorMessage)(e)}],isError:!0}}}
1675
- const y=m(t(1943)),w=m(t(6928)),k=t(6183),b=f(t(5967)),I=t(3253),v=t(8824),C=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore",".config",".conf",".ini",".cfg"]),_=1048576},2601(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1685
+ const y=m(t(1943)),w=m(t(6928)),k=t(6183),b=p(t(5967)),I=t(3253),v=t(8824),C=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore",".config",".conf",".ini",".cfg"]),_=1048576},2601(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1676
1686
  const r=t(6183),n=t(76)
1677
1687
  exports.def={name:"create_task",description:"Create a new task under an existing request.",schema:r.CreateTaskSchema,annotations:{title:"Create Task",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleCreateTask)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},2690(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionMessageClient=void 0
1678
1688
  const r=t(7645),n=t(2161)
@@ -1725,12 +1735,12 @@ if(!r())return t.level=(0,l.isDevBuild)()?c.LogLevel.INFO:c.LogLevel.ERROR,t.log
1725
1735
  if("true"===process.env.DEBUG_LOGGING?.toLowerCase()){t.level=c.LogLevel.DEBUG,t.logToFile=!0
1726
1736
  const r=e||process.cwd()
1727
1737
  t.logFilePath=i.default.join(r,"logs","debug.log")}const n=process.env.DEBUG_LEVEL?.toLowerCase()
1728
- return n&&Object.values(c.LogLevel).includes(n)&&(t.level=n),t}(e.baseDir),...e},{level:o=c.LogLevel.INFO,serviceName:g="mcp-service",logToFile:p=!1,logFilePath:f="./logs/app.log",console=!0}=t,m=[]
1729
- if(console&&m.push(new s.default.transports.Console({format:d,stderrLevels:["error","warn","info","debug"]})),p){!function(e){const t=i.default.dirname(e)
1730
- a.default.existsSync(t)||a.default.mkdirSync(t,{recursive:!0})}(f)
1738
+ return n&&Object.values(c.LogLevel).includes(n)&&(t.level=n),t}(e.baseDir),...e},{level:o=c.LogLevel.INFO,serviceName:g="mcp-service",logToFile:f=!1,logFilePath:p="./logs/app.log",console=!0}=t,m=[]
1739
+ if(console&&m.push(new s.default.transports.Console({format:d,stderrLevels:["error","warn","info","debug"]})),f){!function(e){const t=i.default.dirname(e)
1740
+ a.default.existsSync(t)||a.default.mkdirSync(t,{recursive:!0})}(p)
1731
1741
  const e=o===c.LogLevel.DEBUG&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()
1732
- m.push(new s.default.transports.File({filename:f,format:e?h:u}))}const y=s.default.createLogger({level:o,defaultMeta:{service:g},transports:m})
1733
- return o===c.LogLevel.DEBUG&&p&&r()&&y.info("Enhanced logging initialized",{level:o,serviceName:g,logToFile:p,logFilePath:f,debugLogging:process.env.DEBUG_LOGGING}),{error(e,t){y.error(e,t)},warn(e,t){y.warn(e,t)},info(e,t){y.info(e,t)},debug(e,t){y.debug(e,t)},child(e){const r=y.child(e)
1742
+ m.push(new s.default.transports.File({filename:p,format:e?h:u}))}const y=s.default.createLogger({level:o,defaultMeta:{service:g},transports:m})
1743
+ return o===c.LogLevel.DEBUG&&f&&r()&&y.info("Enhanced logging initialized",{level:o,serviceName:g,logToFile:f,logFilePath:p,debugLogging:process.env.DEBUG_LOGGING}),{error(e,t){y.error(e,t)},warn(e,t){y.warn(e,t)},info(e,t){y.info(e,t)},debug(e,t){y.debug(e,t)},child(e){const r=y.child(e)
1734
1744
  return{error(e,t){r.error(e,t)},warn(e,t){r.warn(e,t)},info(e,t){r.info(e,t)},debug(e,t){r.debug(e,t)},child(e){return n({...t,serviceName:`${g}:${e.component||"nested"}`})}}}}}var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
1735
1745
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.createLogger=n,exports.createEnvLogger=function(e={}){return n(e)},exports.isDebugToolsEnabled=r,exports.isDebugLoggingEnabled=function(){return!!r()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()},exports.getDebugLevelFromEnv=function(){if(!r())return c.LogLevel.INFO
1736
1746
  const e=process.env.DEBUG_LEVEL?.toLowerCase()
@@ -1762,14 +1772,14 @@ const a="binary"!==n?i.split("\n").length:void 0
1762
1772
  if(e.lines&&"binary"!==n){const t=(0,g.parseLineSpec)(e.lines)
1763
1773
  i=(0,g.extractLines)(i,t).text}const c="binary"!==n?i.split("\n").length:void 0
1764
1774
  return{type:"file",path:r,content:i,success:!0,lineCount:c,totalLines:a,size:s.size,originalRequest:e}}catch(t){let r
1765
- return r=t instanceof Error&&"ENOENT"===t.code?"File not found: "+e.path:(0,p.getErrorMessage)(t),{type:"file",path:e.path,content:"",success:!1,error:r,originalRequest:e}}}async function n(e,t,r,n){try{if(!t.documentFileManager)return{type:"document",documentId:e.documentId,content:"",success:!1,error:"Document file manager not available"}
1775
+ return r=t instanceof Error&&"ENOENT"===t.code?"File not found: "+e.path:(0,f.getErrorMessage)(t),{type:"file",path:e.path,content:"",success:!1,error:r,originalRequest:e}}}async function n(e,t,r,n){try{if(!t.documentFileManager)return{type:"document",documentId:e.documentId,content:"",success:!1,error:"Document file manager not available"}
1766
1776
  const r=await t.documentFileManager.getDocumentAsFile(e.documentId),o=t.documentFileManager.getCachedDocumentInfo(e.documentId)
1767
1777
  let s
1768
1778
  s="binary"===n?(await l.default.readFile(r)).toString("base64"):await l.default.readFile(r,n)
1769
1779
  const i="binary"!==n?s.split("\n").length:void 0
1770
1780
  if(e.lines&&"binary"!==n){const t=(0,g.parseLineSpec)(e.lines)
1771
1781
  s=(0,g.extractLines)(s,t).text}const a="binary"!==n?s.split("\n").length:void 0,c=await l.default.stat(r)
1772
- return{type:"document",documentId:e.documentId,filename:o?.filename,content:s,success:!0,lineCount:a,totalLines:i,size:c.size,originalRequest:e}}catch(t){return{type:"document",documentId:e.documentId,content:"",success:!1,error:(0,p.getErrorMessage)(t),originalRequest:e}}}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
1782
+ return{type:"document",documentId:e.documentId,filename:o?.filename,content:s,success:!0,lineCount:a,totalLines:i,size:c.size,originalRequest:e}}catch(t){return{type:"document",documentId:e.documentId,content:"",success:!1,error:(0,f.getErrorMessage)(t),originalRequest:e}}}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
1773
1783
  var o=Object.getOwnPropertyDescriptor(t,r)
1774
1784
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[]
1775
1785
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -1786,20 +1796,20 @@ i.info("Reading multiple files and documents",{totalRequests:c.length,encoding:l
1786
1796
  const h=[],g=[]
1787
1797
  for(const e of c)e.path?h.push({type:"file",path:e.path,lines:e.lines}):e.documentId&&g.push({type:"document",documentId:e.documentId,lines:e.lines})
1788
1798
  i.info("Request breakdown",{fileRequests:h.length,documentRequests:g.length})
1789
- const p=[]
1790
- for(const e of h)p.push(r(e,t,0,l))
1791
- for(const e of g)p.push(n(e,t,0,l))
1792
- const f=await Promise.all(p)
1799
+ const f=[]
1800
+ for(const e of h)f.push(r(e,t,0,l))
1801
+ for(const e of g)f.push(n(e,t,0,l))
1802
+ const p=await Promise.all(f)
1793
1803
  let m=""
1794
1804
  if(t.getCurrentBranchContext)try{const e=await t.getCurrentBranchContext()
1795
- e.branch&&(m=`**Current Branch:** ${e.branch}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=f.filter((e=>e.success)).length,w=f.filter((e=>!e.success)).length,k=f.length
1805
+ e.branch&&(m=`**Current Branch:** ${e.branch}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=p.filter((e=>e.success)).length,w=p.filter((e=>!e.success)).length,k=p.length
1796
1806
  let b="## Read Files/Documents\n\n"
1797
1807
  m&&(b+=m),b+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
1798
- for(let e=0;e<f.length;e++){const t=f[e]
1808
+ for(let e=0;e<p.length;e++){const t=p[e]
1799
1809
  "file"===t.type?b+=`File ${e+1}: ${t.path}\n`:(b+=`Document ${e+1}: ${t.documentId}`,t.filename&&(b+=` (${t.filename})`),b+="\n"),t.success?(b+="**Status:** Success\n",t.lineCount&&t.totalLines&&(b+=`Lines Read / Total Lines ${t.lineCount} / ${t.totalLines}\n`),t.originalRequest?.lines&&t.totalLines&&(b+=`**Lines:** ${t.originalRequest.lines}\n`),b+=`\n**Content:**\n\`\`\`\n${t.content}\n\`\`\`\n`):(b+="**Status:** Failed\n",b+=`**Error:** ${t.error}\n`),b+="\n"}const I=0===w
1800
1810
  return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:I}),s.incrementCounter("read_files_total",1,{success:I}),{content:[{type:"text",text:b}],isError:!I}}catch(e){const t=Date.now()-a
1801
- return i.error("Read multiple files operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),s.incrementCounter("read_files_errors",1),{content:[{type:"text",text:"\u274c **Read Operation Failed:** "+(0,p.getErrorMessage)(e)}],isError:!0}}}
1802
- const l=c(t(1943)),d=t(6183),u=t(1569),h=a(t(5967)),g=t(9470),p=t(8824)},2968(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskClient=void 0
1811
+ return i.error("Read multiple files operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),s.incrementCounter("read_files_errors",1),{content:[{type:"text",text:"\u274c **Read Operation Failed:** "+(0,f.getErrorMessage)(e)}],isError:!0}}}
1812
+ const l=c(t(1943)),d=t(6183),u=t(1569),h=a(t(5967)),g=t(9470),f=t(8824)},2968(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskClient=void 0
1803
1813
  const r=t(8824),n=t(7645),o=t(2161),s=t(5172)
1804
1814
  class i extends n.ConnectionAwareClient{async createTask(e){if(this.logger.debug("Creating task",{taskInput:e}),!e.projectId){const t=this.projectClient.getProjectId()
1805
1815
  if(!t)throw this.logger.error("No project ID available for task creation"),Error("Project ID is required for task creation")
@@ -1874,17 +1884,17 @@ return n.info(`Task ID ${e} validated successfully`,{taskId:e,requestId:o.reques
1874
1884
  if(c.includes("404")||c.toLowerCase().includes("not found")||c.toLowerCase().includes("task not found"))throw n.error(`Task ID ${e} does not exist (404 Not Found)`,{taskId:e,path:t,error:c}),i.incrementCounter(a+"_task_not_found",1),new o.NotFoundError(`Task ${e} not found in project. Please provide a valid task ID.`,{taskId:e,path:t,originalError:r})
1875
1885
  throw n.error("Could not validate task ID "+e,{taskId:e,path:t,error:c}),i.incrementCounter(a+"_task_validation_error",1),new o.ValidationError(`Could not validate task ${e}: ${c}`,{taskId:e,path:t,originalError:r})}},exports.createReopenGuidanceMessage=r,exports.validateWorkItemStates=async function(e,t,n,a,c,l,d,u){try{const h=await n.getTask(e)
1876
1886
  if(l.info("Validating work item states for task "+e,{taskId:e,taskStatus:h.status,requestId:h.requestId,path:t}),l.info("STRICT VALIDATION - Task details",{taskId:e,taskStatus:h.status,requestId:h.requestId,taskTitle:h.title,path:t,timestamp:(new Date).toISOString()}),"completed"===h.status||"canceled"===h.status||"reverted"===h.status){const n=r(e,h.requestId,h.status)
1877
- throw l.error(`STRICT VALIDATION - File operation blocked on ${h.status} task`,{taskId:e,taskStatus:h.status,path:t,errorMessage:n}),d.incrementCounter(`${u}_blocked_${h.status}_task`,1),new o.ValidationError(n,{taskId:e,taskStatus:h.status,path:t,reason:"task_"+h.status})}let g,p
1887
+ throw l.error(`STRICT VALIDATION - File operation blocked on ${h.status} task`,{taskId:e,taskStatus:h.status,path:t,errorMessage:n}),d.incrementCounter(`${u}_blocked_${h.status}_task`,1),new o.ValidationError(n,{taskId:e,taskStatus:h.status,path:t,reason:"task_"+h.status})}let g,f
1878
1888
  if(h.requestId)try{if(g=await a.getRequest(h.requestId),l.info("Validating request status for "+h.requestId,{requestId:h.requestId,requestStatus:g.status,taskId:e,path:t}),l.info("STRICT VALIDATION - Request details",{requestId:h.requestId,requestStatus:g.status,requestTitle:g.title,taskId:e,path:t,timestamp:(new Date).toISOString()}),"pending_approval"===g.status||"ready_for_review"===g.status||"completed"===g.status||"canceled"===g.status){const n=r(e,h.requestId,h.status,g.status)
1879
1889
  throw l.error(`STRICT VALIDATION - File operation blocked on ${g.status} request`,{taskId:e,requestId:h.requestId,requestStatus:g.status,path:t,errorMessage:n}),d.incrementCounter(`${u}_blocked_${g.status}_request`,1),new o.ValidationError(n,{taskId:e,requestId:h.requestId,requestStatus:g.status,path:t,reason:"request_"+g.status})}}catch(r){if(r instanceof o.ValidationError)throw r
1880
1890
  const n=(0,s.getErrorMessage)(r)
1881
1891
  l.warn("Could not validate request status for "+h.requestId,{taskId:e,requestId:h.requestId,error:n,path:t}),d.incrementCounter(u+"_request_validation_warning",1)}if(l.info("Work item state validation passed",{taskId:e,taskStatus:h.status,requestId:h.requestId,requestStatus:g?.status,path:t}),h.requestId){const r=c.workspaceManager
1882
- if("multi-agent"===r?.getCurrentContext().mode)l.debug("Skipping branch switching in multi-agent mode - worktrees handle branch isolation",{taskId:e,requestId:h.requestId,mode:"multi-agent",reason:"worktree_isolation"}),p={switched:!1,message:"Branch switching skipped in multi-agent mode (using worktrees)"}
1883
- else try{p=await(0,i.ensureCorrectBranch)(h.requestId,e,t,c,l,d,u),p.switched&&l.info("Automatically switched to feature branch for file operation",{taskId:e,requestId:h.requestId,branchName:p.branchName,filePath:t})}catch(r){l.warn("Error during automatic branch switching",{taskId:e,requestId:h.requestId,filePath:t,error:(0,s.getErrorMessage)(r)}),p={switched:!1,message:"Branch switching error: "+(0,s.getErrorMessage)(r)}}}return d.incrementCounter(u+"_state_validation_success",1),{task:h,request:g,branchSwitch:p}}catch(r){if(r instanceof o.ValidationError)throw r
1892
+ if("multi-agent"===r?.getCurrentContext().mode)l.debug("Skipping branch switching in multi-agent mode - worktrees handle branch isolation",{taskId:e,requestId:h.requestId,mode:"multi-agent",reason:"worktree_isolation"}),f={switched:!1,message:"Branch switching skipped in multi-agent mode (using worktrees)"}
1893
+ else try{f=await(0,i.ensureCorrectBranch)(h.requestId,e,t,c,l,d,u),f.switched&&l.info("Automatically switched to feature branch for file operation",{taskId:e,requestId:h.requestId,branchName:f.branchName,filePath:t})}catch(r){l.warn("Error during automatic branch switching",{taskId:e,requestId:h.requestId,filePath:t,error:(0,s.getErrorMessage)(r)}),f={switched:!1,message:"Branch switching error: "+(0,s.getErrorMessage)(r)}}}return d.incrementCounter(u+"_state_validation_success",1),{task:h,request:g,branchSwitch:f}}catch(r){if(r instanceof o.ValidationError)throw r
1884
1894
  const n=(0,s.getErrorMessage)(r)
1885
- throw l.error("Could not validate work item states for task "+e,{taskId:e,path:t,error:n}),d.incrementCounter(u+"_state_validation_error",1),new o.ValidationError("Could not validate work item states: "+n,{taskId:e,path:t,originalError:r})}},exports.autoPromoteTaskStatus=async function(e,t,r,o,i,a,c,l,d,u){try{let s,h,g=!1,p=!1
1895
+ throw l.error("Could not validate work item states for task "+e,{taskId:e,path:t,error:n}),d.incrementCounter(u+"_state_validation_error",1),new o.ValidationError("Could not validate work item states: "+n,{taskId:e,path:t,originalError:r})}},exports.autoPromoteTaskStatus=async function(e,t,r,o,i,a,c,l,d,u){try{let s,h,g=!1,f=!1
1886
1896
  if("pending"===t&&(l.info(`Auto-promoting task ${e} from pending to in_progress`,{taskId:e,currentStatus:t,path:i}),await a.updateTaskStatus(e,"in_progress"),l.info(`Successfully auto-promoted task ${e} to in_progress`,{taskId:e,previousStatus:t,newStatus:"in_progress",path:i}),d.incrementCounter(u+"_auto_promotion_success",1),g=!0,s="in_progress",r&&o)){const t=await n(r,o,e,"in_progress",c,l,d,u)
1887
- p=t.promoted,h=t.newStatus}return{taskPromoted:g,newTaskStatus:s,requestPromoted:p,newRequestStatus:h}}catch(r){const n=(0,s.getErrorMessage)(r)
1897
+ f=t.promoted,h=t.newStatus}return{taskPromoted:g,newTaskStatus:s,requestPromoted:f,newRequestStatus:h}}catch(r){const n=(0,s.getErrorMessage)(r)
1888
1898
  return l.warn(`Failed to auto-promote task ${e} from pending to in_progress`,{taskId:e,currentStatus:t,error:n,path:i}),d.incrementCounter(u+"_auto_promotion_failure",1),{taskPromoted:!1,requestPromoted:!1}}},exports.autoPromoteRequestStatus=n,exports.validateRequestCompletionEligibility=async function(e,t,r,n,i){try{const s=await t.listTasks({requestId:e})
1889
1899
  if(r.info("Validating request completion eligibility for "+e,{requestId:e,totalTasks:s.length}),0===s.length){r.warn(`Request ${e} has no tasks - cannot be completed`,{requestId:e})
1890
1900
  const t=`Cannot complete request ${e} - no tasks found. Create tasks for this request before attempting completion.`
@@ -1910,7 +1920,7 @@ d.info("Generating journal for request",{requestId:c})
1910
1920
  const h=t.projectId
1911
1921
  if(!h)throw(0,n.createValidationError)("Project ID is required. Make sure you are in a project context.")
1912
1922
  o.setProjectId(h),d.info("Fetching request data, tasks, and file history in parallel")
1913
- const g=o.getRequestClient(),p=o.getTaskClient(),f=o.getToolRecordClient(),[m,y,w]=await Promise.all([g.getRequest(c),p.listTasks({requestId:c}),f.getToolRecordsByRequestId(c).catch((e=>(d.warn("Failed to fetch tool records",{error:e+""}),[])))]),k=(0,s.extractDataFromResponse)(m,{logger:d,operationName:"getRequest",throwOnNoData:!0}),b="data"in k?k.data:k,I={id:b.id||c,title:b.title||"Unknown Request",description:b.description||"No description available",status:b.status||"unknown",type:b.type||"unknown",acceptanceCriteria:b.acceptanceCriteria||[],createdAt:b.createdAt||(new Date).toISOString(),updatedAt:b.updatedAt||(new Date).toISOString(),completedAt:b.completedAt},v=(0,s.extractDataFromResponse)(y,{logger:d,operationName:"listTasks",throwOnNoData:!1}),C=(Array.isArray(v)?v:"data"in v?v.data:[]).map((e=>({id:e.id,title:e.title||"Untitled Task",description:e.description||"No description",status:e.status||"unknown",createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.metadata?.completedAt})))
1923
+ const g=o.getRequestClient(),f=o.getTaskClient(),p=o.getToolRecordClient(),[m,y,w]=await Promise.all([g.getRequest(c),f.listTasks({requestId:c}),p.getToolRecordsByRequestId(c).catch((e=>(d.warn("Failed to fetch tool records",{error:e+""}),[])))]),k=(0,s.extractDataFromResponse)(m,{logger:d,operationName:"getRequest",throwOnNoData:!0}),b="data"in k?k.data:k,I={id:b.id||c,title:b.title||"Unknown Request",description:b.description||"No description available",status:b.status||"unknown",type:b.type||"unknown",acceptanceCriteria:b.acceptanceCriteria||[],createdAt:b.createdAt||(new Date).toISOString(),updatedAt:b.updatedAt||(new Date).toISOString(),completedAt:b.completedAt},v=(0,s.extractDataFromResponse)(y,{logger:d,operationName:"listTasks",throwOnNoData:!1}),C=(Array.isArray(v)?v:"data"in v?v.data:[]).map((e=>({id:e.id,title:e.title||"Untitled Task",description:e.description||"No description",status:e.status||"unknown",createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.metadata?.completedAt})))
1914
1924
  d.info(`Fetched request, ${C.length} tasks, ${w.length} tool records`)
1915
1925
  const _=await async function(e){const t=new Map,n=[],o=e.filter((e=>["write-file","replace-in-files","move-files","delete-files","manage-files"].includes(e.type))).sort(((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()))
1916
1926
  for(const e of o){const o=r(e),s=e.metadata?.comment||e.metadata?.userComment||"No comment"
@@ -1944,14 +1954,14 @@ d.info("Successfully acquired request lock",{requestId:h,sessionTag:e,lockedAt:t
1944
1954
  const r=t instanceof Error?t.message:t+""
1945
1955
  return r.includes("already locked")?{content:[{type:"text",text:`\u274c Request ${h} is already locked by another agent. ${r}`}],isError:!0}:{content:[{type:"text",text:`\u274c Failed to acquire lock for request ${h}: ${r}`}],isError:!0}}}}catch(e){return d.error("Error checking/acquiring request lock",{requestId:h,error:(0,i.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c Failed to check request lock status: "+(0,i.getErrorMessage)(e)}],isError:!0}}}else d.debug("Single-agent mode: skipping request locking",{requestId:h})
1946
1956
  d.info("Using unified workspace switching",{requestId:h})
1947
- const p=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status})
1948
- if(!p.success){if(t.multiAgentMode)try{const{sessionTag:e}=(0,s.getGlobalClientInfo)()
1949
- d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:p.message}),await a.unlockRequest(h,e),d.info("Successfully released lock after workspace switch failure",{requestId:h})}catch(e){d.error("Failed to release lock after workspace switch failure",{requestId:h,unlockError:e instanceof Error?e.message:e+""})}const e=p.message||"Unknown error"
1957
+ const f=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status})
1958
+ if(!f.success){if(t.multiAgentMode)try{const{sessionTag:e}=(0,s.getGlobalClientInfo)()
1959
+ d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:f.message}),await a.unlockRequest(h,e),d.info("Successfully released lock after workspace switch failure",{requestId:h})}catch(e){d.error("Failed to release lock after workspace switch failure",{requestId:h,unlockError:e instanceof Error?e.message:e+""})}const e=f.message||"Unknown error"
1950
1960
  if(e.includes("does not exist")||e.includes("Branch for request"))return{content:[{type:"text",text:`\u274c Branch for request ${h} does not exist. This can happen if:\n- Request was reverted (branch deleted during revert)\n- Request was completed and branch was cleaned up\n- Branch was manually deleted\n\nUse 'get-request-information' to check the request status.`}],isError:!0}
1951
- throw(0,o.createServiceError)(`Failed to switch to request ${h}: ${e}`,{requestId:h,error:e})}const f=Date.now()-u
1952
- l.recordValue("switch_to_request_branch_time",f),l.incrementCounter("switch_to_request_branch_success",1)
1953
- const m=["Successfully switched to branch: "+(p.newContext?.branchName||"unknown"),"**Previous branch:** "+(p.previousContext?.branchName||"unknown")]
1954
- return t.multiAgentMode&&m.push("\u{1f512} **Locked request:** "+h),d.info("Successfully switched to request workspace",{requestId:h,mode:p.newContext?.mode,branch:p.newContext?.branchName,duration:f}),{content:[{type:"text",text:m.join("\n")}]}}catch(t){const r=Date.now()-u
1961
+ throw(0,o.createServiceError)(`Failed to switch to request ${h}: ${e}`,{requestId:h,error:e})}const p=Date.now()-u
1962
+ l.recordValue("switch_to_request_branch_time",p),l.incrementCounter("switch_to_request_branch_success",1)
1963
+ const m=["Successfully switched to branch: "+(f.newContext?.branchName||"unknown"),"**Previous branch:** "+(f.previousContext?.branchName||"unknown")]
1964
+ return t.multiAgentMode&&m.push("\u{1f512} **Locked request:** "+h),d.info("Successfully switched to request workspace",{requestId:h,mode:f.newContext?.mode,branch:f.newContext?.branchName,duration:p}),{content:[{type:"text",text:m.join("\n")}]}}catch(t){const r=Date.now()-u
1955
1965
  if(l.recordValue("switch_to_request_branch_time",r),l.incrementCounter("switch_to_request_branch_error",1),d.error("Failed to switch to request branch",{requestId:e.requestId,error:(0,i.getErrorMessage)(t),duration:r}),t instanceof o.ValidationError||t instanceof o.NotFoundError)return{content:[{type:"text",text:"\u274c "+t.message}],isError:!0}
1956
1966
  throw t}}
1957
1967
  const n=t(6183),o=t(9860),s=t(5172),i=t(8824)},3217(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.MultiAgentWorkspaceManager=exports.SingleAgentWorkspaceManager=void 0,exports.createWorkspaceManager=function(e,t,o,s,i,a){return t?new n.MultiAgentWorkspaceManager(e,o,s,i,a):new r.SingleAgentWorkspaceManager(e,o,s,i)}
@@ -2034,7 +2044,7 @@ T.push({type:"file",path:r,fullPath:n,replacements:e.replacements,mode:e.mode||"
2034
2044
  if(S.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
2035
2045
  for(const e of S)M.push({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode||"unique"})
2036
2046
  if(M.length>0&&t.apiClient){const e=M.map((e=>e.documentId))
2037
- try{await(0,f.ensureDocumentsNotLocked)(e,t.apiClient,y,a,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2047
+ try{await(0,p.ensureDocumentsNotLocked)(e,t.apiClient,y,a,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2038
2048
  throw e}}I=u.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_strings_phase",1,{phase:I})
2039
2049
  const R=T.length>0?T[0].path:"document-operation",P=await u.validateTaskId(C,R,r,y,a,v.metricsPrefix),x=P?.requestId
2040
2050
  let O=null
@@ -2047,9 +2057,9 @@ throw Error($.error)}if(T.length>0){y.debug("Re-validating file paths with corre
2047
2057
  for(let e=0;e<T.length;e++){const r=T[e],n=q[e],{normalizedPath:o,fullPath:s}=u.validateAndNormalizePath(n.path,t)
2048
2058
  T[e]={...r,path:o,fullPath:s}}}if(M.length>0&&x)try{await(0,g.validateRequestStatusForDocumentOperation)(x,s,y,a,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2049
2059
  throw e}I=u.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_strings_phase",1,{phase:I})
2050
- const A=[...T.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:D}=await u.createFileOperationRecords(C,x,t.projectId,v.recordType,R,{operationCount:_.length,fileOperations:T.length,documentOperations:M.length,operations:A,userComment:E},r,o,y,a,v.metricsPrefix,c)
2051
- if(k=D,b=D,I=v.fileOperationPhase,a.incrementCounter("replace_strings_phase",1,{phase:I}),T.length>0&&t.git)try{y.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
2052
- const e=await(0,p.commitUserChangesBeforeToolOperation)(t.git,"replace-strings",{requestId:x,taskId:C,workspaceManager:t.workspaceManager},y,a)
2060
+ const D=[...T.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:A}=await u.createFileOperationRecords(C,x,t.projectId,v.recordType,R,{operationCount:_.length,fileOperations:T.length,documentOperations:M.length,operations:D,userComment:E},r,o,y,a,v.metricsPrefix,c)
2061
+ if(k=A,b=A,I=v.fileOperationPhase,a.incrementCounter("replace_strings_phase",1,{phase:I}),T.length>0&&t.git)try{y.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
2062
+ const e=await(0,f.commitUserChangesBeforeToolOperation)(t.git,"replace-strings",{requestId:x,taskId:C,workspaceManager:t.workspaceManager},y,a)
2053
2063
  e.userChangesCommitted&&(y.debug("[REPLACE-STRINGS] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before replace-strings operation",{taskId:C,fileOperationsCount:T.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){y.debug("[REPLACE-STRINGS] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:C,fileOperationsCount:T.length,error:e instanceof Error?e.message:e+""})}y.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:T.length})
2054
2064
  const F=[]
2055
2065
  let N=0,L=0
@@ -2061,18 +2071,18 @@ try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.docu
2061
2071
  r.filename=s?.filename
2062
2072
  const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
2063
2073
  r.replacements=c,r.successfulReplacements=c.filter((e=>e.success)).length,r.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),r.success=!0,L++,y.info("Document updated successfully",{documentId:e.documentId,filename:r.filename,successfulReplacements:r.successfulReplacements,failedReplacements:r.failedReplacements})):0===r.failedReplacements&&(r.success=!0),N+=r.failedReplacements}catch(t){r.error=(0,m.getErrorMessage)(t),r.failedReplacements=e.replacements.length,N+=r.failedReplacements,y.error("Document operation failed",{documentId:e.documentId,error:r.error})}F.push(r)}if(M.length>0)try{for(const e of M){const r=F.find((t=>t.documentId===e.documentId))
2064
- r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const z=await u.handleMultiFileGitCommit(C,T,F,L,{operationType:"Replace strings",toolRecordId:b,successField:"successfulReplacements",logger:y,metrics:a,metricsPrefix:"replace_strings"},t),B=u.processMultiFileOperationResults(F,"successfulReplacements"),{successfulOperations:H,failedOperations:U,totalSuccessfulChanges:W,overallSuccess:G,successfulFiles:V,failedFiles:J}=B
2065
- try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:G?"completed":"failed",error:G?void 0:U+" operations failed",totalOperations:F.length,successfulFiles:V,failedFiles:J,operations:A,totalSuccessfulReplacements:W,totalFailedReplacements:N,operationsWithChanges:L,processingTime:Date.now()-w,userComment:E,...T.length>0&&z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}},note:G?`String replacement completed: ${H}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`String replacement partially failed: ${U}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:H,failedOperations:U,totalSuccessfulChanges:W,overallSuccess:G,successfulFiles:V,failedFiles:J},z,$)
2074
+ r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const z=await u.handleMultiFileGitCommit(C,T,F,L,{operationType:"Replace strings",toolRecordId:b,successField:"successfulReplacements",logger:y,metrics:a,metricsPrefix:"replace_strings"},t),B=u.processMultiFileOperationResults(F,"successfulReplacements"),{successfulOperations:H,failedOperations:W,totalSuccessfulChanges:U,overallSuccess:G,successfulFiles:V,failedFiles:J}=B
2075
+ try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:G?"completed":"failed",error:G?void 0:W+" operations failed",totalOperations:F.length,successfulFiles:V,failedFiles:J,operations:D,totalSuccessfulReplacements:U,totalFailedReplacements:N,operationsWithChanges:L,processingTime:Date.now()-w,userComment:E,...T.length>0&&z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}},note:G?`String replacement completed: ${H}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`String replacement partially failed: ${W}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:H,failedOperations:W,totalSuccessfulChanges:U,overallSuccess:G,successfulFiles:V,failedFiles:J},z,$)
2066
2076
  let K="## String Replacement Results\n\n"
2067
- if(t.workspaceManager&&(K+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),K+="**Summary:**\n",K+=`- **Files processed:** ${H+U}\n`,K+=`- **Successful operations:** ${H}\n`,K+=`- **Failed operations:** ${U}\n`,K+=`- **Total replacements:** ${W} successful, ${N} failed\n\n`,z.success&&z.commitHash&&(K+="**Git Commit:**\n",K+=`- **Commit Hash:** ${z.commitHash.substring(0,8)}\n`,K+=`- **Files Committed:** ${z.filesCommitted.length}\n`,z.previousCommitHash&&(K+=`- **Previous Commit:** ${z.previousCommitHash.substring(0,8)}\n`),K+="\n"),$.lockAcquired&&$.lockedRequestId&&(K+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===F.length){const e=F[0]
2077
+ if(t.workspaceManager&&(K+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),K+="**Summary:**\n",K+=`- **Files processed:** ${H+W}\n`,K+=`- **Successful operations:** ${H}\n`,K+=`- **Failed operations:** ${W}\n`,K+=`- **Total replacements:** ${U} successful, ${N} failed\n\n`,z.success&&z.commitHash&&(K+="**Git Commit:**\n",K+=`- **Commit Hash:** ${z.commitHash.substring(0,8)}\n`,K+=`- **Files Committed:** ${z.filesCommitted.length}\n`,z.previousCommitHash&&(K+=`- **Previous Commit:** ${z.previousCommitHash.substring(0,8)}\n`),K+="\n"),$.lockAcquired&&$.lockedRequestId&&(K+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===F.length){const e=F[0]
2068
2078
  if(K+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?K+=`**File:** ${e.path}\n`:(K+="**Document:** "+e.documentId,e.filename&&(K+=` (${e.filename})`),K+="\n"),e.error?K+=`**Error:** ${e.error}\n`:(K+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(K+=`, ${e.failedReplacements} failed`),K+="\n"),e.replacements.some((e=>!e.success))){K+="**Failed Replacement Details:**\n"
2069
- for(const t of e.replacements.filter((e=>!e.success)))K+=`- "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}}else{K+="**Summary:**\n",K+=`- **Total Operations:** ${F.length}\n`,K+=`- **Successful:** ${H}\n`,K+=`- **Failed:** ${U}\n`,K+=`- **Total Replacements:** ${W} successful, ${N} failed\n\n`,K+="**Detailed Results:**\n\n"
2079
+ for(const t of e.replacements.filter((e=>!e.success)))K+=`- "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}}else{K+="**Summary:**\n",K+=`- **Total Operations:** ${F.length}\n`,K+=`- **Successful:** ${H}\n`,K+=`- **Failed:** ${W}\n`,K+=`- **Total Replacements:** ${U} successful, ${N} failed\n\n`,K+="**Detailed Results:**\n\n"
2070
2080
  for(const e of F){if("file"===e.type?K+=`### File: ${e.path}\n`:(K+="### Document: "+e.documentId,e.filename&&(K+=` (${e.filename})`),K+="\n"),K+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?K+=`- **Error:** ${e.error}\n`:(K+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(K+=`, ${e.failedReplacements} failed`),K+="\n"),e.replacements.some((e=>!e.success))){K+="- **Failed Replacement Details:**\n"
2071
2081
  for(const t of e.replacements.filter((e=>!e.success)))K+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}K+="\n"}}M.length>0&&(K+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
2072
2082
  const Y=Date.now()-w
2073
- return y.info("Replace strings operation completed",{duration:Y,success:G,totalOperations:F.length,successfulOperations:H,failedOperations:U}),a.incrementCounter("replace_strings_total",1,{success:G}),{content:[{type:"text",text:K}],isError:!G}}catch(t){const r=Date.now()-w
2083
+ return y.info("Replace strings operation completed",{duration:Y,success:G,totalOperations:F.length,successfulOperations:H,failedOperations:W}),a.incrementCounter("replace_strings_total",1,{success:G}),{content:[{type:"text",text:K}],isError:!G}}catch(t){const r=Date.now()-w
2074
2084
  if(y.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:I}),b)try{await o.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:I,duration:r,userComment:e?.comment},note:"String replacement failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("replace_strings_errors",1,{phase:I}),{content:[{type:"text",text:"\u274c **Replace Strings Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
2075
- const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),p=t(7478),f=t(9949),m=t(8824)},3322(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
2085
+ const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),f=t(7478),p=t(9949),m=t(8824)},3322(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
2076
2086
  var o=Object.getOwnPropertyDescriptor(t,r)
2077
2087
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
2078
2088
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -2106,10 +2116,10 @@ var h=t(4192)
2106
2116
  Object.defineProperty(exports,"BaseApiClient",{enumerable:!0,get(){return h.BaseApiClient}})
2107
2117
  var g=t(1599)
2108
2118
  Object.defineProperty(exports,"SessionRequestAssociationClient",{enumerable:!0,get(){return g.SessionRequestAssociationClient}})
2109
- var p=t(4465)
2110
- Object.defineProperty(exports,"SessionTagMappingClient",{enumerable:!0,get(){return p.SessionTagMappingClient}})
2111
- var f=t(5187)
2112
- Object.defineProperty(exports,"CLISessionClient",{enumerable:!0,get(){return f.CLISessionClient}})
2119
+ var f=t(4465)
2120
+ Object.defineProperty(exports,"SessionTagMappingClient",{enumerable:!0,get(){return f.SessionTagMappingClient}})
2121
+ var p=t(5187)
2122
+ Object.defineProperty(exports,"CLISessionClient",{enumerable:!0,get(){return p.CLISessionClient}})
2113
2123
  var m=t(6539)
2114
2124
  Object.defineProperty(exports,"ClientFactory",{enumerable:!0,get(){return m.ClientFactory}})
2115
2125
  const y=t(6539)
@@ -2134,12 +2144,12 @@ const n=e
2134
2144
  "metadata"in t&&t.metadata&&(n.metadata=t.metadata),h=n}else h={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:a,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
2135
2145
  l.info("Retrieved task information",{taskId:r,title:h.title,status:h.status})}catch(e){throw new o.NotFoundError(`Task ${r} not found in project ${a}. Please provide a valid task ID.`,{taskId:r,projectId:a,originalError:e})}let g=null
2136
2146
  if(h.requestId)try{const e=i.getRequestClient()
2137
- g=await e.getRequest(h.requestId),l.info("Retrieved parent request information",{taskId:r,requestId:h.requestId})}catch(e){l.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:h.requestId})}const p=e=>{if(!e)return"Unknown date"
2147
+ g=await e.getRequest(h.requestId),l.info("Retrieved parent request information",{taskId:r,requestId:h.requestId})}catch(e){l.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:h.requestId})}const f=e=>{if(!e)return"Unknown date"
2138
2148
  try{const t=new Date(e)
2139
- return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return l.warn("Invalid date format: "+e),"Unknown date"}},f=p(h.createdAt),m=p(h.updatedAt)
2149
+ return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return l.warn("Invalid date format: "+e),"Unknown date"}},p=f(h.createdAt),m=f(h.updatedAt)
2140
2150
  let y=`# Task: ${h.title} (${r})\n\n`
2141
- if(y+=`**Status**: ${h.status}\n`,y+=`**Created**: ${f}\n`,y+=`**Updated**: ${m}\n`,h.requestId&&(y+="**Parent Request**: "+h.requestId,y+=g?` (${g.title})\n`:"\n"),h.metadata){const e=h.metadata
2142
- y+="\n## Metadata\n\n",e.lastCommit&&(y+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(y+=`**Completed At**: ${p(e.completedAt)}\n`),e.completionSummary&&(y+=`**Completion Summary**: ${e.completionSummary}\n`)
2151
+ if(y+=`**Status**: ${h.status}\n`,y+=`**Created**: ${p}\n`,y+=`**Updated**: ${m}\n`,h.requestId&&(y+="**Parent Request**: "+h.requestId,y+=g?` (${g.title})\n`:"\n"),h.metadata){const e=h.metadata
2152
+ y+="\n## Metadata\n\n",e.lastCommit&&(y+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(y+=`**Completed At**: ${f(e.completedAt)}\n`),e.completionSummary&&(y+=`**Completion Summary**: ${e.completionSummary}\n`)
2143
2153
  const t=["lastCommit","completedAt","completionSummary"]
2144
2154
  Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{y+=`**${e}**: ${t}\n`}))}return y+="\n## Description\n\n",h.description&&h.description.trim().length>0?y+=h.description:y+="No description provided.",d({success:!0}),{content:[{type:"text",text:y}]}}catch(n){l.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
2145
2155
  try{const o=i.getToolRecordClient()
@@ -2155,31 +2165,7 @@ exports.defaultLogger=o.default
2155
2165
  const s=t(6540)
2156
2166
  Object.defineProperty(exports,"LogLevel",{enumerable:!0,get(){return s.LogLevel}}),exports.default=o.default},3556(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
2157
2167
  const r=t(6183),n=t(8317)
2158
- exports.def={name:"request_file_history",description:"Get file change history for an entire request. Supports summary mode (net diffs) or detailed mode (chronological operations). Can be filtered to specific task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Request File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleRequestFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},3596(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFinalizeRequest=async function(e,t,a,c,l){const d=c.child({tool:"finalize_request"}),u=l.startTimer("tool_execution_time")
2159
- try{const{requestId:n}=e
2160
- if(!n)throw(0,r.createValidationError)("Request ID is required")
2161
- let o,c
2162
- d.info("Starting request finalization",{requestId:n})
2163
- try{const e=await a.proxyPost(`/api/projects/${t.projectId}/requests/${n}/validate-completion`,{})
2164
- o=e?.data||e}catch(e){const t=(0,i.getErrorMessage)(e)
2165
- return d.error("Server validation failed",{requestId:n,error:t}),u({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate finalization: "+t}],isError:!0}}if(!o.canComplete){let e=`Cannot finalize request ${n}: ${o.reason}\n`
2166
- return o.blockedByTasks?.length&&(e+="\n**Tasks that must be completed first:**\n",o.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (${t.status})\n`}))),u({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if(!t.workspaceManager)throw Error("WorkspaceManager not available for request finalization")
2167
- let l="workspace-manager"
2168
- try{const e=a.getRequestClient(),r=await e.getRequest(n),o=r?.title||"Request "+n
2169
- if("conflicted"===r?.status){d.info("Request is conflicted, attempting fast-path merge",{requestId:n})
2170
- const e=t.workspaceManager.getCurrentContext()
2171
- let r=e?.basePath||process.cwd()
2172
- if("multi-agent"===e?.mode)try{const e=await t.workspaceManager.getWorktreeInfo(n)
2173
- e?.worktreePath&&(r=e.worktreePath)}catch{}const i=(0,s.createConflictResolutionManager)(d,a,r,t.git),h=await i.validateMarkersRemoved(n)
2174
- if(!h.resolved)return u({success:!1,reason:"conflicts_unresolved"}),{content:[{type:"text",text:`## \u26a0\ufe0f Conflicts Still Need Resolution\n\nConflict markers still exist in:\n\n${h.remainingConflicts.map((e=>`- \`${e}\``)).join("\n")}\n\nRemove all conflict markers and try again.`}]}
2175
- const g=await i.hasMainBranchChanged(n)
2176
- g.hasChanged&&g.canDetermine?(d.info("Main branch changed since conflict detection, using full merge",{requestId:n,originalHash:g.originalHash?.substring(0,8),currentHash:g.currentHash?.substring(0,8)}),c=await t.workspaceManager.completeRequest(n,o),l=c.autoMergeInfo?.strategy||"main-changed-remerge"):(c=await t.workspaceManager.completeRequest(n,o,{skipConflictDetection:!0}),l="conflict-fast-path",d.info("Conflict fast-path merge completed",{requestId:n,mergeCommitHash:c.mergeCommitHash}))}else c=await t.workspaceManager.completeRequest(n,o),l=c.autoMergeInfo?.strategy||"workspace-manager",d.info("Merge completed",{requestId:n,mergeCommitHash:c.mergeCommitHash,cleanedUp:c.cleanedUp})}catch(e){if(e.conflictInfo){const r=e.conflictInfo,n=r.workingDirectory||t.workspaceManager?.getCurrentContext()?.basePath||process.cwd(),o=(0,s.createConflictResolutionManager)(d,a,n,t.git),i=await o.handleConflicts(r)
2177
- return u({success:!1,reason:"merge_conflicts"}),{content:[{type:"text",text:i.userMessage}],isError:!1}}const r=(0,i.getErrorMessage)(e)
2178
- return u({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Request finalization failed during merge: "+r}],isError:!0}}try{await a.proxyPost(`/api/projects/${t.projectId}/requests/${n}/finalize-completion`,{summary:"Finalized request "+n,acceptanceEvidence:[{evidence:"Finalized after review"}],mergeResult:{mergeCommitHash:c.mergeCommitHash,mergedFiles:c.mergedFiles,cleanedUp:c.cleanedUp,method:l}})}catch(e){const t=(0,i.getErrorMessage)(e)
2179
- return d.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:n,mergeCommitHash:c.mergeCommitHash,error:t}),u({success:!1,error:"api_update_failed"}),{content:[{type:"text",text:`CRITICAL: Code was merged (commit: ${c.mergeCommitHash.substring(0,8)}) but failed to update server state: ${t}`}],isError:!0}}return u({success:!0}),{content:[{type:"text",text:"Request finalized: "+n}]}}catch(r){let s="An unexpected error occurred"
2180
- r instanceof n.ZodError?s=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", "):r instanceof Error&&(s=r.message),d.error("Finalize request failed",{error:s})
2181
- try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,requestId:e?.requestId},a.getToolRecordClient(),d,l,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to finalize request"})}catch{}return u({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+s}],isError:!0}}}
2182
- const r=t(9860),n=t(1569),o=t(8616),s=t(1651),i=t(8824)},3626(e,exports,t){function r(e){if(!e)return!1
2168
+ exports.def={name:"request_file_history",description:"Get file change history for an entire request. Supports summary mode (net diffs) or detailed mode (chronological operations). Can be filtered to specific task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Request File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleRequestFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},3626(e,exports,t){function r(e){if(!e)return!1
2183
2169
  const t=e.toLowerCase().replace(/^\./,"")
2184
2170
  return u.has(t)}function n(e,t){if(r(t)){const t=e.match(/^([ \t]*)(.*?)\s*$/)
2185
2171
  if(!t)return e
@@ -2218,30 +2204,30 @@ if(i.length>h)break
2218
2204
  if(i===l){c.push({line:s+1,actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t})
2219
2205
  break}}}o+=i.length+1}return c}const g=t.trim()[0]
2220
2206
  if(!g)return c
2221
- let p=0,f=0
2222
- for(;;){if(f%100==0&&Date.now()-d>o){const r=Date.now()-d
2223
- throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${o}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}f++
2224
- const r=e.indexOf(g,p)
2207
+ let f=0,p=0
2208
+ for(;;){if(p%100==0&&Date.now()-d>o){const r=Date.now()-d
2209
+ throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${o}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}p++
2210
+ const r=e.indexOf(g,f)
2225
2211
  if(-1===r)break
2226
2212
  let i=r+t.length
2227
2213
  const u=Math.min(Math.floor(.5*t.length),200),h=Math.min(r+t.length+u,e.length),m=l.length
2228
2214
  let y=!1
2229
2215
  for(let t=i;h>=t;t++){const o=e.substring(r,t),i=n(o,a)
2230
2216
  if(i.length>m)break
2231
- if(i===l){c.push({line:s(e,r),actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t}),p=t,y=!0
2232
- break}}y||(p=r+1)}return c}(e,t,c,u),h.length>0)return h}catch(e){if(e instanceof Error&&e.message.includes("timed out"))throw e}return h=function(e,t,n=100,a){if(r(a))return[]
2217
+ if(i===l){c.push({line:s(e,r),actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t}),f=t,y=!0
2218
+ break}}y||(f=r+1)}return c}(e,t,c,u),h.length>0)return h}catch(e){if(e instanceof Error&&e.message.includes("timed out"))throw e}return h=function(e,t,n=100,a){if(r(a))return[]
2233
2219
  const c=[],l=o(t),d=Date.now()
2234
2220
  if(t.length>500)return i(e,t)
2235
2221
  if(!l)return c
2236
2222
  const u=t.replace(/\s/g,"")[0],h=l.length
2237
- let g=0,p=0
2238
- for(;;){if(p%100==0&&Date.now()-d>n){const r=Date.now()-d
2239
- throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${n}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}p++
2223
+ let g=0,f=0
2224
+ for(;;){if(f%100==0&&Date.now()-d>n){const r=Date.now()-d
2225
+ throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${n}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}f++
2240
2226
  const r=e.indexOf(u,g)
2241
2227
  if(-1===r)break
2242
- const i=r+h,a=Math.min(t.length,300),f=Math.min(r+h+a,e.length)
2228
+ const i=r+h,a=Math.min(t.length,300),p=Math.min(r+h+a,e.length)
2243
2229
  let m=!1
2244
- for(let t=i;f>=t;t++){const n=e.substring(r,t),i=o(n)
2230
+ for(let t=i;p>=t;t++){const n=e.substring(r,t),i=o(n)
2245
2231
  if(i.length>h)break
2246
2232
  if(i===l){c.push({line:s(e,r),actuallyMatched:n,matchType:"whitespace_agnostic",startPos:r,endPos:t}),g=t,m=!0
2247
2233
  break}}m||(g=r+1)}return c}(e,t,c,u),h},exports.replaceMatch=a,exports.replaceMatches=function(e,t,r){const n=[...t].sort(((e,t)=>t.startPos-e.startPos))
@@ -2268,45 +2254,46 @@ let i=u.FileOperationPhase.VALIDATION
2268
2254
  const a={toolName:"get-file-info",operationName:"read",fileOperationPhase:u.FileOperationPhase.FILE_WRITE,recordType:"write",metricsPrefix:"get_file_info",successMessage:"Successfully retrieved info for {path}",failureMessage:"Failed to retrieve info for {path}"}
2269
2255
  try{const a=u.validateArgs(e,d.GetFileInfoSchema),{path:h}=a
2270
2256
  n.info("Getting file info: "+h)
2271
- const{normalizedPath:f,fullPath:m}=u.validateAndNormalizePath(h,t)
2257
+ const{normalizedPath:p,fullPath:m}=u.validateAndNormalizePath(h,t)
2272
2258
  i=u.FileOperationPhase.FILE_WRITE
2273
- try{await c.default.access(m)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(m),w=y.isFile()?l.default.extname(m).slice(1):"",k={path:f,type:y.isDirectory()?"directory":"file",size:y.size,sizeFormatted:(p=y.size,u.formatFileSize(p)),created:r(y.birthtime),modified:r(y.mtime),accessed:r(y.atime),permissions:(g=y.mode,(511&g).toString(8)),isDirectory:y.isDirectory(),isFile:y.isFile(),isSymbolicLink:y.isSymbolicLink(),extension:w},b=["File Information for: "+f,"Type: "+k.type,`Size: ${k.sizeFormatted} (${k.size} bytes)`,"Created: "+k.created,"Modified: "+k.modified,"Accessed: "+k.accessed,"Permissions: "+k.permissions,"Is Directory: "+k.isDirectory,"Is File: "+k.isFile,"Is Symbolic Link: "+k.isSymbolicLink]
2259
+ try{await c.default.access(m)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(m),w=y.isFile()?l.default.extname(m).slice(1):"",k={path:p,type:y.isDirectory()?"directory":"file",size:y.size,sizeFormatted:(f=y.size,u.formatFileSize(f)),created:r(y.birthtime),modified:r(y.mtime),accessed:r(y.atime),permissions:(g=y.mode,(511&g).toString(8)),isDirectory:y.isDirectory(),isFile:y.isFile(),isSymbolicLink:y.isSymbolicLink(),extension:w},b=["File Information for: "+p,"Type: "+k.type,`Size: ${k.sizeFormatted} (${k.size} bytes)`,"Created: "+k.created,"Modified: "+k.modified,"Accessed: "+k.accessed,"Permissions: "+k.permissions,"Is Directory: "+k.isDirectory,"Is File: "+k.isFile,"Is Symbolic Link: "+k.isSymbolicLink]
2274
2260
  k.isFile&&w&&b.push("Extension: "+w)
2275
2261
  const I=Date.now()-s
2276
- return o.recordValue("get_file_info_time",I),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+f,{type:k.type,size:k.size,time:I}),{content:[{type:"text",text:b.join("\n")}]}}catch(t){const r=Date.now()-s
2277
- return o.recordValue("get_file_info_time",r),o.incrementCounter("get_file_info_errors",1),n.error("Error getting file info:",{error:(0,h.getErrorMessage)(t),time:r}),u.handleFileOperationError(t,i,n,o,e,a)}var g,p}
2278
- const c=a(t(1943)),l=a(t(6928)),d=t(6183),u=i(t(5967)),h=t(8824)},3707(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,p){const f=h.child({tool:"quick_edit"}),m=Date.now()
2262
+ return o.recordValue("get_file_info_time",I),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+p,{type:k.type,size:k.size,time:I}),{content:[{type:"text",text:b.join("\n")}]}}catch(t){const r=Date.now()-s
2263
+ return o.recordValue("get_file_info_time",r),o.incrementCounter("get_file_info_errors",1),n.error("Error getting file info:",{error:(0,h.getErrorMessage)(t),time:r}),u.handleFileOperationError(t,i,n,o,e,a)}var g,f}
2264
+ const c=a(t(1943)),l=a(t(6928)),d=t(6183),u=i(t(5967)),h=t(8824)},3707(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,f){const p=h.child({tool:"quick_edit"}),m=Date.now()
2279
2265
  try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),b=u.getToolRecordClient(),{title:I,description:v,...C}=e,_=e.comment||I
2280
- f.info("Starting quick_edit workflow",{title:I,operationType:t})
2266
+ p.info("Starting quick_edit workflow",{title:I,operationType:t})
2281
2267
  let E=!1
2282
2268
  try{const e=await y.listRequests({limit:2,sortBy:"created_at",sortDirection:"desc"})
2283
- e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,f.info("Detected two consecutive quick-edits, will recommend normal request"))}catch(e){f.warn("Could not check recent requests for recommendation",{error:e})}f.debug("Creating quick_edit request")
2269
+ e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,p.info("Detected two consecutive quick-edits, will recommend normal request"))}catch(e){p.warn("Could not check recent requests for recommendation",{error:e})}p.debug("Creating quick_edit request")
2284
2270
  const q=await y.createRequest({title:I,description:v,type:"quick-edit",acceptanceCriteria:["Quick change completed successfully"]})
2285
2271
  if(!q||!q.id)throw Error("Failed to create request")
2286
2272
  const S=q.id
2287
2273
  let T
2288
- f.info("Created request",{requestId:S})
2289
- try{if(f.debug("Checking for uncommitted user changes before quick-edit branch creation"),d.git)try{const e=await(0,c.commitUserChangesBeforeToolOperation)(d.git,"quick-fix",{requestId:S,taskId:void 0,workspaceManager:d.workspaceManager},h,g)
2290
- e.userChangesCommitted?f.info("Committed user changes to main before quick-edit branch creation",{requestId:S,commitHash:e.commitHash?.substring(0,8)}):f.debug("No uncommitted changes found, proceeding with quick-edit")}catch(e){f.warn("Failed to commit user changes before quick-edit, proceeding anyway",{requestId:S,error:e instanceof Error?e.message:e+""})}else f.debug("No git instance available, skipping uncommitted changes check")
2291
- f.debug("Creating task")
2274
+ p.info("Created request",{requestId:S})
2275
+ try{if(p.debug("Checking for uncommitted user changes before quick-edit branch creation"),d.git)try{const e=await(0,c.commitUserChangesBeforeToolOperation)(d.git,"quick-fix",{requestId:S,taskId:void 0,workspaceManager:d.workspaceManager},h,g)
2276
+ e.userChangesCommitted?p.info("Committed user changes to main before quick-edit branch creation",{requestId:S,commitHash:e.commitHash?.substring(0,8)}):p.debug("No uncommitted changes found, proceeding with quick-edit")}catch(e){p.warn("Failed to commit user changes before quick-edit, proceeding anyway",{requestId:S,error:e instanceof Error?e.message:e+""})}else p.debug("No git instance available, skipping uncommitted changes check")
2277
+ p.debug("Creating task")
2292
2278
  const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+I})
2293
2279
  if(!e||!e.id)throw Error("Failed to create task")
2294
- let l
2295
- if(T=e.id,f.info("Created task",{taskId:T}),f.debug("Executing file operation",{operationType:t}),"write"===t)l=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,b,y,h,g,p)
2296
- else if("replace"===t)l=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,b,y,h,g,p)
2280
+ let v
2281
+ if(T=e.id,p.info("Created task",{taskId:T}),p.debug("Executing file operation",{operationType:t}),"write"===t)v=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,b,y,h,g,f)
2282
+ else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,b,y,h,g,f)
2297
2283
  else{if("manage"!==t)throw new r.ValidationError("Unsupported operation type: "+t)
2298
- l=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||I},d,w,b,y,u,h,g,p)}if(l.isError){f.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
2299
- try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after operation failure",{taskId:T})}catch(e){f.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),f.info("Canceled request after operation failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),f.info("Cleaned up branch/worktree after operation failure",{requestId:S}))}catch(e){f.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}return{content:[{type:"text",text:`\u274c Quick change failed during ${t} operation:\n\n${l.content[0].text}\n\nThe request (${S}) and task have been canceled and cleaned up.`}],isError:!0}}const v=l.content[0].text,q=v.includes("\u26a0\ufe0f Partial Success")||v.includes("\u274c Failed")||v.includes("\u274c 0 successful")
2300
- q?f.warn("File operation completed with partial failures",{requestId:S}):f.info("File operation completed successfully"),f.debug("Completing task")
2301
- try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${I}${q?" (partial success)":""}`},d,u,h,g),f.info("Task completed successfully",{taskId:T})}catch(e){f.error("Task completion via handleCompleteTask failed, attempting direct status update",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0})
2302
- try{await w.updateTaskStatus(T,"completed"),f.info("Task completed via direct updateTaskStatus call",{taskId:T})}catch(e){return f.error("Direct task completion ALSO failed - task may be stuck in in_progress",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0,operationType:t,isDocumentOperation:!!C.documentId}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but task completion failed.\n\n**Request:** ${S}\n**Task:** ${T}\n**Issue:** Could not mark task as completed - it remains in 'in_progress' state\n\nThe ${t} operation was successful, but we couldn't automatically complete the task. Please use the complete-task tool manually with taskId: ${T}\n\nError: `+(e instanceof Error?e.message:e+"")}],isError:!0}}}f.debug("Completing request")
2303
- const M=q?`Quick change completed with partial success: ${I}. Some replacements failed - see details below.`:"Quick change completed: "+I,R=q?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
2304
- let P=!1
2305
- try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:M,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,p)
2306
- e.isError?f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text}):(P=!0,f.info("Request completed successfully via handleCompleteRequest",{requestId:S}))}catch(e){f.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!P)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:M}),P=!0,f.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return f.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const x=Date.now()-m
2307
- let O
2308
- return f.info("Quick fix completed",{requestId:S,duration:x,hasPartialFailure:q}),O=q?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${x}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+v:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${x}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(v.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+v.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(O+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:O}]}}catch(e){if(f.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after workflow failure",{taskId:T})}catch(e){f.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),f.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),f.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){f.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-m
2309
- return f.error("Quick change failed",{error:(0,l.getErrorMessage)(e),duration:t}),e instanceof r.ValidationError?{content:[{type:"text",text:"\u274c "+e.message}],isError:!0}:{content:[{type:"text",text:"\u274c Quick change failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
2284
+ v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||I},d,w,b,y,u,h,g,f)}if(v.isError){p.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
2285
+ try{await w.updateTaskStatus(T,"canceled"),p.info("Canceled task after operation failure",{taskId:T})}catch(e){p.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),p.info("Canceled request after operation failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),p.info("Cleaned up branch/worktree after operation failure",{requestId:S}))}catch(e){p.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}return{content:[{type:"text",text:`\u274c Quick change failed during ${t} operation:\n\n${v.content[0].text}\n\nThe request (${S}) and task have been canceled and cleaned up.`}],isError:!0}}const q=v.content[0].text,M=q.includes("\u26a0\ufe0f Partial Success")||q.includes("\u274c Failed")||q.includes("\u274c 0 successful")
2286
+ M?p.warn("File operation completed with partial failures",{requestId:S}):p.info("File operation completed successfully"),p.debug("Completing task")
2287
+ try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${I}${M?" (partial success)":""}`},d,u,h,g),p.info("Task completed successfully",{taskId:T})}catch(e){p.error("Task completion via handleCompleteTask failed, attempting direct status update",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0})
2288
+ try{await w.updateTaskStatus(T,"completed"),p.info("Task completed via direct updateTaskStatus call",{taskId:T})}catch(e){return p.error("Direct task completion ALSO failed - task may be stuck in in_progress",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0,operationType:t,isDocumentOperation:!!C.documentId}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but task completion failed.\n\n**Request:** ${S}\n**Task:** ${T}\n**Issue:** Could not mark task as completed - it remains in 'in_progress' state\n\nThe ${t} operation was successful, but we couldn't automatically complete the task. Please use the complete-task tool manually with taskId: ${T}\n\nError: `+(e instanceof Error?e.message:e+"")}],isError:!0}}}p.debug("Completing request")
2289
+ const R=M?`Quick change completed with partial success: ${I}. Some replacements failed - see details below.`:"Quick change completed: "+I,P=M?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
2290
+ let x=!1
2291
+ try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:R,acceptanceEvidence:[{evidence:P}],testVerification:void 0},d,u,h,g,f)
2292
+ if(e.isError)p.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
2293
+ else{try{await y.updateRequest(S,{status:"completed",completionSummary:R}),p.info("Request finalized to completed",{requestId:S})}catch(e){p.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}x=!0,p.info("Request completed successfully",{requestId:S})}}catch(e){p.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!x)try{p.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:R}),x=!0,p.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return p.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const O=Date.now()-m
2294
+ let j
2295
+ return p.info("Quick fix completed",{requestId:S,duration:O,hasPartialFailure:M}),j=M?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${O}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${O}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(q.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+q.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(j+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:j}]}}catch(e){if(p.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),p.info("Canceled task after workflow failure",{taskId:T})}catch(e){p.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),p.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),p.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){p.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-m
2296
+ return p.error("Quick change failed",{error:(0,l.getErrorMessage)(e),duration:t}),e instanceof r.ValidationError?{content:[{type:"text",text:"\u274c "+e.message}],isError:!0}:{content:[{type:"text",text:"\u274c Quick change failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
2310
2297
  const r=t(9860),n=t(4079),o=t(9442),s=t(7684),i=t(355),a=t(5715),c=t(7478),l=t(8824)},3807(module){module.exports=require("simple-git")},3895(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.AuthenticationManager=void 0
2311
2298
  const r=t(6848)
2312
2299
  exports.AuthenticationManager=class{constructor(e,t,n){this.cachedToken=null,this.tokenRefreshPromise=null,this.tokenManager=e,this.logger=t.child({component:"auth-manager"}),this.tokenSynchronizer=n||new r.ClientTokenSynchronizer(t)}async setToken(e){try{this.logger.info("Storing authentication token",{username:e.username,expiresAt:e.expiresAt,userId:e.userId}),await this.tokenManager.storeToken(e),this.cachedToken=e,this.tokenSynchronizer.updateToken(e.token),this.logger.info("Authentication token stored and synchronized to all clients")}catch(e){throw this.logger.error("Failed to store authentication token",{error:e instanceof Error?e.stack:e+""}),Error("Failed to store authentication token")}}async setTokenString(e){try{this.logger.info("Setting token string directly")
@@ -2368,47 +2355,47 @@ return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModu
2368
2355
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,t,r,n,o,s,i,m,y){const w=i.child({tool:"write_file"}),k=m.startTimer("tool_execution_time"),b=Date.now()
2369
2356
  let I,v,C=d.FileOperationPhase.VALIDATION
2370
2357
  const _={toolName:"write_file",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"write-file",metricsPrefix:"write_file",successMessage:"Successfully wrote content",failureMessage:"Failed to write content"}
2371
- try{const r=d.validateArgs(e,l.WriteFileSchema),{taskId:i,path:f,documentId:E,content:q,format:S,append:T,comment:M}=r,R=!!E,P=!!f
2372
- w.info("Writing content to "+(R?"document":"file"),{taskId:i,filePath:P?f:void 0,documentId:R?E:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S,append:T,comment:M})
2373
- let x,O,j,$="",A=!1,D=!1
2374
- const F=P?f:void 0
2375
- if(R){if(t.apiClient)try{await(0,p.ensureDocumentNotLocked)(E,t.apiClient,w,m,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2358
+ try{const r=d.validateArgs(e,l.WriteFileSchema),{taskId:i,path:p,documentId:E,content:q,format:S,append:T,comment:M}=r,R=!!E,P=!!p
2359
+ w.info("Writing content to "+(R?"document":"file"),{taskId:i,filePath:P?p:void 0,documentId:R?E:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S,append:T,comment:M})
2360
+ let x,O,j,$="",D=!1,A=!1
2361
+ const F=P?p:void 0
2362
+ if(R){if(t.apiClient)try{await(0,f.ensureDocumentNotLocked)(E,t.apiClient,w,m,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2376
2363
  throw e}if(!t.documentFileManager)throw Error("Document file manager not available")
2377
2364
  $=await t.documentFileManager.getDocumentAsFile(E)
2378
2365
  const e=t.documentFileManager.getCachedDocumentInfo(E)
2379
- j=e?.filename,D=!0,A=!1}C=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("write_file_phase",1,{phase:C})
2366
+ j=e?.filename,A=!0,D=!1}C=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("write_file_phase",1,{phase:C})
2380
2367
  const N=P?F:"document:"+E,L=await d.validateTaskId(i,N,n,w,m,_.metricsPrefix),z=L?.requestId
2381
2368
  let B=null
2382
2369
  P&&z&&(B=await d.validateWorkItemStates(i,N,n,s,t,w,m,_.metricsPrefix))
2383
2370
  let H={taskPromoted:!1,requestPromoted:!1}
2384
2371
  P&&z&&B&&(H=await d.autoPromoteTaskStatus(i,L.status,z,B.request?.status,N,n,s,w,m,_.metricsPrefix),H.taskPromoted&&w.info("Auto-promoted task to in_progress for file operation",{taskId:i,requestId:z,previousStatus:L.status,newStatus:H.newTaskStatus,triggeringOperation:"write_file"}))
2385
- const U=await d.ensureCorrectWorkspaceContext({taskPromoted:H.taskPromoted,requestId:z,context:t,operation:"write_file",logger:w,metrics:m,metricsPrefix:_.metricsPrefix,requireRequestContext:P})
2386
- if(!U.success){if(U.isLockConflict)return{content:[{type:"text",text:"\u274c "+U.error}],isError:!0}
2387
- throw Error(U.error)}if(U.switched&&w.info("Workspace context successfully established",{requestId:z,branchName:U.branchName,operation:"write_file"}),P&&F){const e=d.validateAndNormalizePath(F,t)
2372
+ const W=await d.ensureCorrectWorkspaceContext({taskPromoted:H.taskPromoted,requestId:z,context:t,operation:"write_file",logger:w,metrics:m,metricsPrefix:_.metricsPrefix,requireRequestContext:P})
2373
+ if(!W.success){if(W.isLockConflict)return{content:[{type:"text",text:"\u274c "+W.error}],isError:!0}
2374
+ throw Error(W.error)}if(W.switched&&w.info("Workspace context successfully established",{requestId:z,branchName:W.branchName,operation:"write_file"}),P&&F){const e=d.validateAndNormalizePath(F,t)
2388
2375
  x=e.normalizedPath,O=e.fullPath,$=O
2389
- try{await c.default.access(O),D=!0}catch{D=!1,A=!0}w.debug("Path validated with correct workspace context",{rawPath:F,normalizedPath:x,fullPath:O,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})}if(R&&z)try{await(0,h.validateRequestStatusForDocumentOperation)(z,s,w,m,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2376
+ try{await c.default.access(O),A=!0}catch{A=!1,D=!0}w.debug("Path validated with correct workspace context",{rawPath:F,normalizedPath:x,fullPath:O,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})}if(R&&z)try{await(0,h.validateRequestStatusForDocumentOperation)(z,s,w,m,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2390
2377
  throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("write_file_phase",1,{phase:C})
2391
- const{toolRecordId:W}=await d.createFileOperationRecords(i,z,t.projectId,_.recordType,N,{operationType:R?"document":"file",documentId:R?E:void 0,documentFilename:j,filePath:P?x:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S||"text",append:T||!1,wasFileCreated:!D,userComment:M},n,o,w,m,_.metricsPrefix,y)
2378
+ const{toolRecordId:U}=await d.createFileOperationRecords(i,z,t.projectId,_.recordType,N,{operationType:R?"document":"file",documentId:R?E:void 0,documentFilename:j,filePath:P?x:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S||"text",append:T||!1,wasFileCreated:!A,userComment:M},n,o,w,m,_.metricsPrefix,y)
2392
2379
  let G
2393
- if(I=W,v=W,C=_.fileOperationPhase,m.incrementCounter("write_file_phase",1,{phase:C}),"json"===S)if("string"==typeof q)try{JSON.parse(q),G=q}catch(e){throw new u.ValidationError("Content is not valid JSON")}else G=JSON.stringify(q,null,2)
2380
+ if(I=U,v=U,C=_.fileOperationPhase,m.incrementCounter("write_file_phase",1,{phase:C}),"json"===S)if("string"==typeof q)try{JSON.parse(q),G=q}catch(e){throw new u.ValidationError("Content is not valid JSON")}else G=JSON.stringify(q,null,2)
2394
2381
  else G="string"==typeof q?q:JSON.stringify(q,null,2)
2395
2382
  let V=G
2396
2383
  if(P&&t.git)try{w.debug("[WRITE-FILE] Checking for user changes before write operation")
2397
2384
  const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"write_file",{requestId:t.workspaceManager?.getCurrentContext()?.requestId,taskId:i},w,m)
2398
2385
  e.userChangesCommitted&&(w.debug("[WRITE-FILE] User changes committed before write operation",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before write-file operation",{taskId:i,path:x,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[WRITE-FILE] Pre-tool commit failed, continuing with write",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with write operation",{taskId:i,path:x,error:e instanceof Error?e.message:e+""})}if(!$)throw Error("Target path not properly initialized")
2399
- if(w.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:$}),T&&D)try{V=await c.default.readFile($,"utf8")+G}catch(e){w.warn("Failed to read existing content for append",{error:e})}const J=a.default.dirname($)
2400
- if(await c.default.mkdir(J,{recursive:!0}),await c.default.writeFile($,V,"utf8"),w.info("Content written successfully",{path:P?x:"document:"+E,finalLength:V.length,append:T,wasCreated:A}),R){t.documentFileManager.markForSync(E)
2386
+ if(w.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:$}),T&&A)try{V=await c.default.readFile($,"utf8")+G}catch(e){w.warn("Failed to read existing content for append",{error:e})}const J=a.default.dirname($)
2387
+ if(await c.default.mkdir(J,{recursive:!0}),await c.default.writeFile($,V,"utf8"),w.info("Content written successfully",{path:P?x:"document:"+E,finalLength:V.length,append:T,wasCreated:D}),R){t.documentFileManager.markForSync(E)
2401
2388
  try{await t.documentFileManager.syncDocument(E),w.info("Document synced successfully",{documentId:E})}catch(e){w.warn("Failed to sync document immediately",{documentId:E,error:e})}}let K,Y,Q=null
2402
2389
  if(P){if(C=d.FileOperationPhase.GIT_COMMIT,m.incrementCounter("write_file_phase",1,{phase:C}),t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
2403
- Y=e.branchName,w.debug("Retrieved branch name from workspace manager",{branchName:Y,requestId:e.requestId,mode:e.mode,isMainBranch:e.isMainBranch})}try{const e=`${A?"Create":T?"Append to":"Update"} ${x} (${v})`,r=await d.commitToGit(i,x,v,v,e,t,w,m,_.metricsPrefix)
2404
- K=r.commitHash,Q=r.previousCommitHash,w.info("Changes committed to git via shared utility",{path:x,commitMessage:e,commitHash:K?.substring(0,8),previousCommitHash:Q?.substring(0,8),branchName:Y,toolRecordId:v})}catch(e){w.warn("Git operations failed via shared utility",{error:e})}}try{await o.updateToolRecord(v,{metadata:{path:P?x:"document:"+E,status:"completed",finalContentLength:V.length,wasFileCreated:A,wasAppended:T&&D,operationType:R?"document":"file",processingTime:Date.now()-b,userComment:M,...P&&K&&{commitHash:K,previousCommitHash:Q||void 0}},note:"Write operation completed successfully"+(R?" (document synced)":" (committed to git)")})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z=`**${A?"Created":T?"Appended to":"Updated"} ${R?`document ${E}${j?` (${j})`:""}`:"file "+x}**\n`
2405
- Z+=`**Content Length:** ${V.length} characters\n`,P&&Y&&(Z+=`**Branch:** ${Y}\n`),U.lockAcquired&&U.lockedRequestId&&(Z+=`**Locked request:** ${U.lockedRequestId}\n`),P&&K&&(Z+=`**Commit Hash:** ${K.substring(0,8)}\n`,Q&&(Z+=`**Previous Commit:** ${Q.substring(0,8)}\n`)),v&&(Z+=`[RECORD:${v}]\n`),R&&(Z+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${E}\`.`)
2390
+ Y=e.branchName,w.debug("Retrieved branch name from workspace manager",{branchName:Y,requestId:e.requestId,mode:e.mode,isMainBranch:e.isMainBranch})}try{const e=`${D?"Create":T?"Append to":"Update"} ${x} (${v})`,r=await d.commitToGit(i,x,v,v,e,t,w,m,_.metricsPrefix)
2391
+ K=r.commitHash,Q=r.previousCommitHash,w.info("Changes committed to git via shared utility",{path:x,commitMessage:e,commitHash:K?.substring(0,8),previousCommitHash:Q?.substring(0,8),branchName:Y,toolRecordId:v})}catch(e){w.warn("Git operations failed via shared utility",{error:e})}}try{await o.updateToolRecord(v,{metadata:{path:P?x:"document:"+E,status:"completed",finalContentLength:V.length,wasFileCreated:D,wasAppended:T&&A,operationType:R?"document":"file",processingTime:Date.now()-b,userComment:M,...P&&K&&{commitHash:K,previousCommitHash:Q||void 0}},note:"Write operation completed successfully"+(R?" (document synced)":" (committed to git)")})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z=`**${D?"Created":T?"Appended to":"Updated"} ${R?`document ${E}${j?` (${j})`:""}`:"file "+x}**\n`
2392
+ Z+=`**Content Length:** ${V.length} characters\n`,P&&Y&&(Z+=`**Branch:** ${Y}\n`),W.lockAcquired&&W.lockedRequestId&&(Z+=`**Locked request:** ${W.lockedRequestId}\n`),P&&K&&(Z+=`**Commit Hash:** ${K.substring(0,8)}\n`,Q&&(Z+=`**Previous Commit:** ${Q.substring(0,8)}\n`)),v&&(Z+=`[RECORD:${v}]\n`),R&&(Z+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${E}\`.`)
2406
2393
  const X=Date.now()
2407
- return w.info("Write operation completed successfully",{duration:X-b,path:P?x:"document:"+E,contentLength:V.length,wasCreated:A}),k({tool:"write_file",success:!0}),m.incrementCounter("write_file_total",1,{success:!0}),t.workspaceManager?.largeFileWarning&&(Z+=t.workspaceManager.largeFileWarning,t.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:Z}]}}catch(t){const r=Date.now()-b
2408
- if(w.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await o.updateToolRecord(v,{metadata:{path:e?.path,status:"failed",error:(0,f.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return k({tool:"write_file",success:!1}),m.incrementCounter("write_file_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
2409
- const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824)},4139(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ALCHEMY_DIR_NAME=exports.TOKEN_DIR_NAME=void 0,exports.TOKEN_DIR_NAME="alchemy-key",exports.ALCHEMY_DIR_NAME=".alchemy_lab"},4165(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
2394
+ return w.info("Write operation completed successfully",{duration:X-b,path:P?x:"document:"+E,contentLength:V.length,wasCreated:D}),k({tool:"write_file",success:!0}),m.incrementCounter("write_file_total",1,{success:!0}),t.workspaceManager?.largeFileWarning&&(Z+=t.workspaceManager.largeFileWarning,t.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:Z}]}}catch(t){const r=Date.now()-b
2395
+ if(w.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await o.updateToolRecord(v,{metadata:{path:e?.path,status:"failed",error:(0,p.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,p.getErrorMessage)(t)})}catch(e){}return k({tool:"write_file",success:!1}),m.incrementCounter("write_file_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,p.getErrorMessage)(t)}],isError:!0}}}
2396
+ const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),f=t(9949),p=t(8824)},4139(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ALCHEMY_DIR_NAME=exports.TOKEN_DIR_NAME=void 0,exports.TOKEN_DIR_NAME="alchemy-key",exports.ALCHEMY_DIR_NAME=".alchemy_lab"},4165(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
2410
2397
  const r=t(6183),n=t(4648)
2411
- exports.def={name:"request_operations",description:"Perform operations on existing requests.\n\nOperations:\n\u2022 complete - Mark request as complete with summary and acceptance evidence\n\u2022 finalize - Approve and merge a request that is ready for review\n\u2022 approve - Approve a pending request so work can begin\n\u2022 revert - Completely revert a completed request, undoing all changes\n\u2022 get-info - Get comprehensive request information\n\u2022 list - List and filter requests\n\nNote: To create a new request, use the separate create-request tool.",schema:r.RequestOperationsSchema,annotations:{title:"Request Operations",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleRequestOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},4192(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseApiClient=void 0
2398
+ exports.def={name:"request_operations",description:"Perform operations on existing requests.\n\nOperations:\n\u2022 complete - Begin completion: provide summary, get criteria keys for verification\n\u2022 verify-criteria - Verify acceptance criteria with evidence per key (triggers merge when all verified)\n\u2022 finalize - Approve and merge a request that is ready for review\n\u2022 approve - Approve a pending request so work can begin\n\u2022 revert - Completely revert a completed request, undoing all changes\n\u2022 get-info - Get comprehensive request information\n\u2022 list - List and filter requests\n\nCompletion is two-phase: first call complete with a summary, then call verify-criteria with evidence for each criterion key.\n\nNote: To create a new request, use the separate create-request tool.",schema:r.RequestOperationsSchema,annotations:{title:"Request Operations",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleRequestOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},4192(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseApiClient=void 0
2412
2399
  const r=t(7163)
2413
2400
  exports.BaseApiClient=class{constructor(e,t,n,o,s){this.failureCount=0,this.circuitState="closed",this.circuitResetTimeout=null,this.baseUrl=e,this.logger=t,this.metrics=n,this.authToken=o,this.options={retryAttempts:3,retryDelay:1e3,timeout:1e4,circuitBreakerThreshold:5,circuitBreakerResetTime:3e4,...s},this.logger.debug("BaseApiClient constructor options:",{providedOptions:s?JSON.stringify(s):"undefined",mergedOptions:JSON.stringify(this.options)})
2414
2401
  try{(0,r.debugTokenAccess)(this,"BaseApiClient constructor")}catch(e){}}setAuthToken(e){this.authToken=e||void 0,this.logger.debug("Auth token updated",{hasToken:!!e,tokenLength:e?e.length:0})}getAuthToken(){return this.authToken}async requestWithRetry(e,t,r,n,o){if("open"===this.circuitState)throw this.logger.warn(`Circuit breaker open - rejecting request to ${e} ${t}`),Error("Service unavailable - circuit breaker open")
@@ -2467,9 +2454,28 @@ if(!c.startsWith(s+a.sep))return{content:[{type:"text",text:"\u274c Invalid file
2467
2454
  try{await i.access(c)}catch{return{content:[{type:"text",text:"\u274c Asset not found: "+r}],isError:!0}}const u=a.extname(r).toLowerCase().slice(1),h=d[u]
2468
2455
  if(!h)return{content:[{type:"text",text:"\u274c Unsupported image type: ."+u}],isError:!0}
2469
2456
  if("svg"===u)return{content:[{type:"text",text:`**Asset: ${r}**\n\n\`\`\`svg\n${await i.readFile(c,"utf-8")}\n\`\`\``}]}
2470
- const g=await i.readFile(c),p=g.toString("base64")
2471
- return o.info("Asset viewed",{filename:r,size:g.length}),{content:[{type:"text",text:`**Asset: ${r}** (${(g.length/1024).toFixed(1)} KB)`},{type:"image",data:p,mimeType:h}]}}catch(e){return o.error("Failed to view asset",{error:(0,c.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c **Failed to view asset:** "+(0,c.getErrorMessage)(e)}],isError:!0}}}
2472
- const i=s(t(1943)),a=s(t(6928)),c=t(8824),l=t(4139),d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"}},4394(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOrCreateHealthCheckManager=function(e,t,o,s={}){const i=e.endsWith("/")?e.slice(0,-1):e,a=n.get(i)
2457
+ const g=await i.readFile(c),f=g.toString("base64")
2458
+ return o.info("Asset viewed",{filename:r,size:g.length}),{content:[{type:"text",text:`**Asset: ${r}** (${(g.length/1024).toFixed(1)} KB)`},{type:"image",data:f,mimeType:h}]}}catch(e){return o.error("Failed to view asset",{error:(0,c.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c **Failed to view asset:** "+(0,c.getErrorMessage)(e)}],isError:!0}}}
2459
+ const i=s(t(1943)),a=s(t(6928)),c=t(8824),l=t(4139),d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"}},4306(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMergeRequest=async function(e,t,i,a,c){const l=a.child({tool:"merge_request"}),d=c.startTimer("tool_execution_time"),{requestId:u,verifications:h}=e
2460
+ try{if(!u)throw(0,r.createValidationError)("requestId is required")
2461
+ l.info("Starting merge request",{requestId:u,verificationCount:h.length})
2462
+ const e=i.getRequestClient(),o=await e.getRequest(u)
2463
+ if("ready_for_review"===o?.status)return d({success:!1,reason:"testing_in_progress"}),{content:[{type:"text",text:`STOP: Cannot merge request ${u} \u2014 testing is in progress. Wait for tests to complete. The request will be moved to ready_for_merge when tests pass.`}],isError:!0}
2464
+ if(h.length>0)try{await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/verify-criteria`,{verifications:h}),l.info("Criteria verified",{requestId:u,count:h.length})}catch(e){const t=(0,s.getErrorMessage)(e)
2465
+ l.warn("Criteria verification failed, continuing with merge",{requestId:u,error:t})}let a,c
2466
+ try{const e=await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/validate-completion`,{})
2467
+ a=e?.data||e}catch(e){const t=(0,s.getErrorMessage)(e)
2468
+ return d({success:!1,error:"validation_failed"}),{content:[{type:"text",text:"Failed to validate merge: "+t}],isError:!0}}if(!a.canComplete){let e=`Cannot merge request ${u}: ${a.reason}\n`
2469
+ return a.blockedByTasks?.length&&(e+="\n**Tasks that must be completed first:**\n",a.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (${t.status})\n`}))),d({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if(!t.workspaceManager)throw Error("WorkspaceManager not available")
2470
+ let g="workspace-manager"
2471
+ const f=await e.getRequest(u),p=f?.title||"Request "+u,m="resolving_conflicts"===f?.status
2472
+ try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,p,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,p),g=c.autoMergeInfo?.strategy||"workspace-manager"),l.info("Merge completed",{requestId:u,mergeCommitHash:c.mergeCommitHash,mergeMethod:g})}catch(r){if(r.conflictInfo){const o=r.conflictInfo,a=o.workingDirectory||t.workspaceManager?.getCurrentContext()?.basePath||process.cwd(),c=(0,n.createConflictResolutionManager)(l,i,a,t.git),h=await c.handleConflicts(o)
2473
+ try{await e.updateRequest(u,{status:"resolving_conflicts"}),l.info("Set status to resolving_conflicts",{requestId:u})}catch(e){l.error("Failed to set resolving_conflicts status",{requestId:u,error:(0,s.getErrorMessage)(e)})}return d({success:!1,reason:"merge_conflicts"}),{content:[{type:"text",text:h.userMessage}],isError:!1}}const o=(0,s.getErrorMessage)(r)
2474
+ return d({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Merge failed: "+o}],isError:!0}}try{await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/finalize-completion`,{summary:f?.completionSummary||"Merged request "+u,acceptanceEvidence:h.map((e=>({evidence:e.evidence}))),mergeResult:{mergeCommitHash:c.mergeCommitHash,mergedFiles:c.mergedFiles,cleanedUp:c.cleanedUp,method:g}})}catch(e){const t=(0,s.getErrorMessage)(e)
2475
+ return l.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:u,mergeCommitHash:c.mergeCommitHash,error:t}),d({success:!1,error:"api_update_failed"}),{content:[{type:"text",text:`CRITICAL: Code was merged (commit: ${c.mergeCommitHash.substring(0,8)}) but failed to update server: ${t}`}],isError:!0}}return d({success:!0}),{content:[{type:"text",text:`Request ${u} merged successfully.\nCommit: ${c.mergeCommitHash.substring(0,8)}`}]}}catch(e){const r=(0,s.getErrorMessage)(e)
2476
+ l.error("Merge request failed",{error:r})
2477
+ try{await(0,o.createFailureToolRecord)("merge-request",e,{error:r,requestId:u},i.getToolRecordClient(),l,c,{requestId:u,projectId:t.projectId,note:"Failed to merge request"})}catch{}return d({success:!1,error:e instanceof Error?e.name:"unknown"}),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
2478
+ const r=t(9860),n=t(1651),o=t(8616),s=t(8824)},4394(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOrCreateHealthCheckManager=function(e,t,o,s={}){const i=e.endsWith("/")?e.slice(0,-1):e,a=n.get(i)
2473
2479
  if(a)return t.debug("Reusing existing HealthCheckManager instance",{baseUrl:i,totalInstances:n.size}),a
2474
2480
  t.info("Creating new HealthCheckManager instance",{baseUrl:i,totalInstancesBefore:n.size})
2475
2481
  const c=new r.HealthCheckManager(i,t,o,{checkIntervalMs:s.checkIntervalMs||3e4,timeoutMs:s.timeoutMs||5e3,retryCount:s.retryCount||2,onOfflineCallback:s.onOfflineCallback,onOnlineCallback:s.onOnlineCallback})
@@ -2509,10 +2515,10 @@ var t={}
2509
2515
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2510
2516
  return o(t,e),t})
2511
2517
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlannerOps=async function(e,t,r,n,o,s){const h=r.child({tool:"planner_ops"}),g=n.startTimer("tool_execution_time")
2512
- try{"request"===e?.operation&&e?.prompt&&!e?.request&&(e.request={prompt:e.prompt,description:e.description||e.prompt.slice(0,60)},delete e.prompt,delete e.description)
2513
- const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:p,sessionId:f}=r
2518
+ try{if(e?.request&&"string"==typeof e.request)try{e.request=JSON.parse(e.request)}catch{}"request"===e?.operation&&e?.prompt&&!e?.request&&(e.request={prompt:e.prompt,description:e.description||e.prompt.slice(0,60)},delete e.prompt,delete e.description)
2519
+ const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:f,sessionId:p}=r
2514
2520
  let m
2515
- switch(h.info("Processing planner_ops",{operation:p,sessionId:f}),p){case"request":{const e=await async function(e,t,r){if(!e)return"ask"
2521
+ switch(h.info("Processing planner_ops",{operation:f,sessionId:p}),f){case"request":{const e=await async function(e,t,r){if(!e)return"ask"
2516
2522
  try{const n=r?.sessionId||d.sessionIdentity.getIdentity()?.sessionId
2517
2523
  if(!n)return"ask"
2518
2524
  const o=e.getCLISessionClient()
@@ -2531,13 +2537,13 @@ if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.request.d
2531
2537
  await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.request.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}m={content:[{type:"text",text:"Planning request submitted. The user will choose the planning approach. This is non-blocking \u2014 continue with your other work.\nPLANNER_CHOICE_PENDING|"+JSON.stringify({prompt:r.request.prompt,description:r.request.description})}]}
2532
2538
  break}const n="auto-planner"
2533
2539
  if(h.info("Spawning planner",{planningMode:e,agent:n}),m=await(0,u.handleSpawn)({agent:n,prompt:r.request.prompt,title:r.request.description},t,h,o),!m.isError&&m.content.length>0){const t=m.content[0].text
2534
- m.content[0].text=`Planning mode: ${e} (agent: ${n}). Planning is running in the background \u2014 continue with your other work.\n${t}`}break}case"check-status":m=await(0,u.handleCheckStatus)(f,t,h,o)
2540
+ m.content[0].text=`Planning mode: ${e} (agent: ${n}). Planning is running in the background \u2014 continue with your other work.\n${t}`}break}case"check-status":m=await(0,u.handleCheckStatus)(p,t,h,o)
2535
2541
  break
2536
2542
  case"list":const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,[n,a]=await Promise.all([(0,u.handleListSessions)(t,h,o,{activeOnly:r.list?.activeOnly,limit:r.list?.limit,agentType:"auto-planner",parentSessionId:e}),(0,u.handleListSessions)(t,h,o,{activeOnly:r.list?.activeOnly,limit:r.list?.limit,agentType:"planner",parentSessionId:e})]),c=n.content[0]?.text??"",g=a.content[0]?.text??""
2537
2543
  if(c.trim()||g.trim()){const e=[]
2538
2544
  c.trim()&&e.push("## Auto-planner sessions\n"+c),g.trim()&&e.push("## Interactive plan sessions\n"+g),m={content:[{type:"text",text:e.join("\n\n")}]}}else m={content:[{type:"text",text:"No planning sessions found."}]}
2539
2545
  break
2540
- default:throw new i.ValidationError("Unknown operation: "+p)}return g({success:!0}),n.incrementCounter(`planner_ops_${p}_success`,1),m}catch(e){return h.error("Planner ops failed",{error:e instanceof Error?e.stack:e+""}),g({success:!1}),n.incrementCounter("planner_ops_errors",1),{content:[{type:"text",text:"Planner operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
2546
+ default:throw new i.ValidationError("Unknown operation: "+f)}return g({success:!0}),n.incrementCounter(`planner_ops_${f}_success`,1),m}catch(e){return h.error("Planner ops failed",{error:e instanceof Error?e.stack:e+""}),g({success:!1}),n.incrementCounter("planner_ops_errors",1),{content:[{type:"text",text:"Planner operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
2541
2547
  const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(6688),u=t(1725)},4600(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.execAsync=async function(e,t={}){return new Promise(((n,o)=>{const[s,...i]=e.split(" "),a=(0,r.spawn)(s,i,{cwd:t.cwd||process.cwd(),stdio:["pipe","pipe","pipe"]})
2542
2548
  let c="",l=""
2543
2549
  a.stdout?.on("data",(e=>{c+=e.toString()})),a.stderr?.on("data",(e=>{l+=e.toString()})),a.on("close",(e=>{n({stdout:c,stderr:l,exitCode:e||0})})),a.on("error",(t=>{o(Error(`Command failed: ${e}\nError: ${t.message}`))})),t.timeout&&setTimeout((()=>{a.kill(),o(Error("Command timed out: "+e))}),t.timeout)}))}
@@ -2551,12 +2557,12 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
2551
2557
  var t={}
2552
2558
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2553
2559
  return o(t,e),t})
2554
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,t,r,n,o,s,g){const p=o.child({tool:"file_recover"}),f=s.startTimer("tool_execution_time"),m=Date.now()
2560
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,t,r,n,o,s,g){const f=o.child({tool:"file_recover"}),p=s.startTimer("tool_execution_time"),m=Date.now()
2555
2561
  try{let o
2556
2562
  try{o=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
2557
- return p.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{taskId:f,path:y,commitHash:w,createBackup:k}=o
2558
- return p.info("Recovering file to previous version",{taskId:f,filePath:y,commitHash:w,createBackup:k}),await async function(e,t,r,n,o,s,i,a,g,p,f){let m
2559
- try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:b}=await d.createFileOperationRecords(e,k?.requestId,o.projectId,"file-recover",y,{operationType:"file",filePath:y,commitHash:r,createBackup:n},s.getTaskClient(),i,a,g,"file-recover",f)
2563
+ return f.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{taskId:p,path:y,commitHash:w,createBackup:k}=o
2564
+ return f.info("Recovering file to previous version",{taskId:p,filePath:y,commitHash:w,createBackup:k}),await async function(e,t,r,n,o,s,i,a,g,f,p){let m
2565
+ try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:b}=await d.createFileOperationRecords(e,k?.requestId,o.projectId,"file-recover",y,{operationType:"file",filePath:y,commitHash:r,createBackup:n},s.getTaskClient(),i,a,g,"file-recover",p)
2560
2566
  m=b
2561
2567
  let I,v=!1
2562
2568
  try{await l.access(w),v=!0,n&&(I=`${w}.backup-${(new Date).toISOString().replace(/[:.]/g,"-")}`,await l.copyFile(w,I),a.info("Created backup",{originalPath:w,backupPath:I}))}catch{v=!1}const C=o.git
@@ -2568,32 +2574,29 @@ if(t.includes("does not exist")||t.includes("not found")||t.includes("Path"))thr
2568
2574
  throw Error(`Failed to retrieve file '${y}' from commit '${r}': ${t}`)}await l.writeFile(w,_,"utf8")
2569
2575
  let E={}
2570
2576
  try{const t=`Recover ${y} from ${r.substring(0,8)}`
2571
- E=await d.commitToGit(e,y,m,m,t,o,a,g,"file-recover"),a.info("Recovery committed via shared utility",{path:y,sourceCommitHash:r,newCommitHash:E.commitHash?.substring(0,8),commitMessage:t})}catch(e){a.warn("Failed to commit recovery via shared utility",{error:e})}if(m)try{await i.updateToolRecord(m,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:I,wasFileCreated:!v,processingTime:Date.now()-p,...E.commitHash&&{commitHash:E.commitHash,previousCommitHash:E.previousCommitHash||void 0}},note:"File recovered successfully from "+r.substring(0,8)})}catch(e){a.warn("Failed to update tool record",{recordError:e})}const q=v?"recovered":"created from recovery"
2577
+ E=await d.commitToGit(e,y,m,m,t,o,a,g,"file-recover"),a.info("Recovery committed via shared utility",{path:y,sourceCommitHash:r,newCommitHash:E.commitHash?.substring(0,8),commitMessage:t})}catch(e){a.warn("Failed to commit recovery via shared utility",{error:e})}if(m)try{await i.updateToolRecord(m,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:I,wasFileCreated:!v,processingTime:Date.now()-f,...E.commitHash&&{commitHash:E.commitHash,previousCommitHash:E.previousCommitHash||void 0}},note:"File recovered successfully from "+r.substring(0,8)})}catch(e){a.warn("Failed to update tool record",{recordError:e})}const q=v?"recovered":"created from recovery"
2572
2578
  let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
2573
- return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&I&&(S+=`**Backup created:** ${c.basename(I)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(f,y,w,k,t,r,n,p,s,m,g)}catch(e){const t=Date.now()-m
2574
- return p.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),f({tool:"file_recover",success:!1}),s.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
2575
- const i=t(6183),a=t(1569),c=s(t(6928)),l=s(t(1943)),d=s(t(5967)),u=t(3922),h=t(8824)},4648(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,t,u,h,g,p){const f=h.child({tool:"request_operations"})
2576
- try{"complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary,acceptanceEvidence:e.acceptanceEvidence||[],testVerification:e.testVerification},delete e.summary,delete e.acceptanceEvidence,delete e.testVerification),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters)
2577
- const d=e?.complete?.acceptanceEvidence
2578
- Array.isArray(d)&&(e.complete.acceptanceEvidence=d.map((e=>"object"==typeof e&&e.evidence?e.evidence:e)))
2579
- const m=r.RequestOperationsSchema.parse(e),{requestId:y,operation:w}=m
2580
- switch(f.info("Processing request operation",{requestId:y,operation:w}),w){case"complete":{f.info("Routing to complete-request handler")
2581
- const e={requestId:y,summary:m.complete.summary,acceptanceEvidence:m.complete.acceptanceEvidence.map((e=>"string"==typeof e?{evidence:e}:e)),testVerification:m.complete.testVerification}
2582
- return await(0,n.handleCompleteRequest)(e,t,u,h,g,p)}case"finalize":{f.info("Routing to finalize-request handler")
2583
- const e={requestId:y}
2584
- return await(0,c.handleFinalizeRequest)(e,t,u,h,g,p)}case"approve":{f.info("Routing to approve-request handler")
2585
- const e={requestId:y}
2586
- return await(0,l.handleApproveRequest)(e,t,u,h,g,p)}case"revert":{f.info("Routing to revert-request handler")
2587
- const e={requestId:y,reason:m.revert.reason,confirmDestructive:m.revert.confirmDestructive}
2588
- return await(0,o.handleRevertRequest)(e,t,u,h,g)}case"get-info":{f.info("Routing to get-request-information handler")
2589
- const e={requestId:y}
2590
- return await(0,s.handleGetRequestInformation)(e,t,u,h,g)}case"list":{f.info("Routing to list-requests handler")
2591
- const e={filters:m.list?.filters}
2592
- return await(0,i.handleListRequests)(e,t,u,h,g)}case"search":{f.info("Routing to search-requests handler")
2593
- const e={search:m.search}
2594
- return await(0,a.handleSearchRequests)(e,t,u,h,g)}default:{const e="Unknown operation type: "+w
2595
- return f.error(e),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+e}],isError:!0}}}}catch(e){return f.error("Request operations failed",{error:e instanceof Error?e.stack:e+""}),g.incrementCounter("request_operations_errors",1),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
2596
- const r=t(6183),n=t(5715),o=t(6416),s=t(5434),i=t(8037),a=t(233),c=t(3596),l=t(1537),d=t(8824)},4710(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2579
+ return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&I&&(S+=`**Backup created:** ${c.basename(I)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-f}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(p,y,w,k,t,r,n,f,s,m,g)}catch(e){const t=Date.now()-m
2580
+ return f.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),p({tool:"file_recover",success:!1}),s.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
2581
+ const i=t(6183),a=t(1569),c=s(t(6928)),l=s(t(1943)),d=s(t(5967)),u=t(3922),h=t(8824)},4648(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,t,u,h,g,f){const p=h.child({tool:"request_operations"})
2582
+ try{for(const t of["complete","verifyCriteria","merge","revert","search","list"])if(e&&"string"==typeof e[t])try{e[t]=JSON.parse(e[t])}catch{}"complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary},delete e.summary),"complete"!==e?.operation||e?.complete||e?.summary||(e.complete={summary:""}),"merge"===e?.operation&&e?.verifications&&!e?.merge&&(e.merge={verifications:e.verifications},delete e.verifications),e?.merge&&Array.isArray(e.merge)&&(e.merge={verifications:e.merge}),"verify-criteria"===e?.operation&&(e.operation="merge",e.verifyCriteria&&!e.merge&&(e.merge=e.verifyCriteria,delete e.verifyCriteria)),"finalize"===e?.operation&&(e.operation="merge",e.merge||(e.merge={verifications:[]})),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters)
2583
+ const d=r.RequestOperationsSchema.parse(e),{requestId:m,operation:y}=d
2584
+ switch(p.info("Processing request operation",{requestId:m,operation:y}),y){case"complete":{p.info("Routing to complete-request handler")
2585
+ const e={requestId:m,summary:d.complete.summary}
2586
+ return await(0,n.handleCompleteRequest)(e,t,u,h,g,f)}case"merge":return p.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:m,verifications:d.merge?.verifications||[]},t,u,h,g,f)
2587
+ case"approve":{p.info("Routing to approve-request handler")
2588
+ const e={requestId:m}
2589
+ return await(0,c.handleApproveRequest)(e,t,u,h,g,f)}case"revert":{p.info("Routing to revert-request handler")
2590
+ const e={requestId:m,reason:d.revert.reason,confirmDestructive:d.revert.confirmDestructive}
2591
+ return await(0,o.handleRevertRequest)(e,t,u,h,g)}case"get-info":{p.info("Routing to get-request-information handler")
2592
+ const e={requestId:m}
2593
+ return await(0,s.handleGetRequestInformation)(e,t,u,h,g)}case"list":{p.info("Routing to list-requests handler")
2594
+ const e={filters:d.list?.filters}
2595
+ return await(0,i.handleListRequests)(e,t,u,h,g)}case"search":{p.info("Routing to search-requests handler")
2596
+ const e={search:d.search}
2597
+ return await(0,a.handleSearchRequests)(e,t,u,h,g)}default:{const e="Unknown operation type: "+y
2598
+ return p.error(e),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+e}],isError:!0}}}}catch(e){return p.error("Request operations failed",{error:e instanceof Error?e.stack:e+""}),g.incrementCounter("request_operations_errors",1),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
2599
+ const r=t(6183),n=t(5715),o=t(6416),s=t(5434),i=t(8037),a=t(233),c=t(1537),l=t(4306),d=t(8824)},4710(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2597
2600
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClient=void 0
2598
2601
  const n=r(t(9896)),o=r(t(6928)),s=t(7645),i=t(2161),a=t(1058),c=t(8824)
2599
2602
  class l extends s.ConnectionAwareClient{isOffline(){return!!this.connectionStatusManager&&this.connectionStatusManager.isOffline()}isOnline(){return!this.isOffline()}setProjectSynchronizer(e){this.logger.info("Setting ProjectSynchronizer on ProjectClient"),this.projectSynchronizer=e}getProjectSynchronizer(){return this.projectSynchronizer}async fetchProject(e){return this.getProject(e)}async pingDetailed(){this.logger.debug("Pinging remote server")
@@ -2713,17 +2716,17 @@ var t={}
2713
2716
  if(null!=e)for(var r=s(e),n=0;n<r.length;n++)"default"!==r[n]&&i(t,e,r[n])
2714
2717
  return a(t,e),t})
2715
2718
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileBlame=async function(e,t,s,i,a){const c=i.child({tool:"file_blame"}),g=Date.now()
2716
- try{const{path:i,lines:p,branch:f}=e
2717
- c.info("Processing blame request",{filePath:i,lines:p,branch:f})
2719
+ try{const{path:i,lines:f,branch:p}=e
2720
+ c.info("Processing blame request",{filePath:i,lines:f,branch:p})
2718
2721
  const m=t.basePath,y=d.isAbsolute(i)?i:d.join(m,i),w=d.relative(m,y)
2719
2722
  try{await u.access(y)}catch{return{content:[{type:"text",text:"\u274c File not found: "+w}],isError:!0}}const k=function(e){if(!e)return null
2720
2723
  if(/^\d+$/.test(e)){const t=parseInt(e,10)
2721
2724
  return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
2722
2725
  if(t)return{start:parseInt(t[1],10),end:parseInt(t[2],10)}
2723
2726
  if(e.match(/^(\d+(?:,\d+)+)$/)){const t=e.split(",").map((e=>parseInt(e,10)))
2724
- return{start:Math.min(...t),end:Math.max(...t)}}return null}(p),b=["blame","--porcelain"]
2727
+ return{start:Math.min(...t),end:Math.max(...t)}}return null}(f),b=["blame","--porcelain"]
2725
2728
  let I
2726
- k&&b.push(`-L${k.start},${k.end}`),f&&b.push(f),b.push("--",w),c.debug("Executing git blame",{args:b})
2729
+ k&&b.push(`-L${k.start},${k.end}`),p&&b.push(p),b.push("--",w),c.debug("Executing git blame",{args:b})
2727
2730
  try{if(!t.git)throw Error("Git context not available")
2728
2731
  I=await t.git.raw(b)}catch(e){const t=(0,h.getErrorMessage)(e)
2729
2732
  return c.error("Git blame failed",{error:t}),{content:[{type:"text",text:"\u274c Git blame failed: "+t}],isError:!0}}const v=function(e){const t=[],r=e.split("\n")
@@ -2798,7 +2801,7 @@ const r=t(6183),n=t(4592)
2798
2801
  exports.def={name:"planner_ops",description:"Request a planning session and check on planner progress.\n\nOperations:\n\u2022 request - Start a planning session for a feature or architecture question\n\u2022 check-status - Check if a planner is busy or idle\n\u2022 list - List planning sessions",schema:r.PlannerOpsSchema,annotations:{title:"Planner Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handlePlannerOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5003(e,exports,t){async function r(e,t,r,s,i){const a=r.child({requestId:e,operation:"request-status-validation"})
2799
2802
  try{a.info("Validating request status for document operation",{requestId:e})
2800
2803
  const r=await t.getRequest(e)
2801
- if(a.info("Request status retrieved",{requestId:e,status:r.status}),"completed"===r.status||"canceled"===r.status||"pending_approval"===r.status){const t="pending_approval"===r.status?"pending approval":"completed"===r.status?"completed":"canceled",o=`\u274c **Document operations are not allowed on ${t} requests.**\n\n**Request:** ${e}\n**Status:** ${r.status}\n\n**Reason:** Once a request is ${t}, its associated documents become read-only to maintain audit trail integrity.\n\n**What you can do:**\n- Create a new request for additional changes\n- Use the revert-request tool if you need to make corrections\n- Contact your administrator if you believe this is an error`
2804
+ if(a.info("Request status retrieved",{requestId:e,status:r.status}),["completed","canceled","pending_approval","ready_for_review","ready_for_merge","reverted"].includes(r.status)){const t=r.status.replace(/_/g," "),o=`\u274c **Document operations are not allowed on ${t} requests.**\n\n**Request:** ${e}\n**Status:** ${r.status}\n\n**Reason:** Once a request is ${t}, its associated documents become read-only to maintain audit trail integrity.\n\n**What you can do:**\n- Create a new request for additional changes\n- Use the revert-request tool if you need to make corrections\n- Contact your administrator if you believe this is an error`
2802
2805
  a.warn("Document operation blocked on terminal request",{requestId:e,requestStatus:r.status,reason:"completed"===r.status?"request_completed":"request_canceled"})
2803
2806
  const c="completed"===r.status?i+"_blocked_completed_request":i+"_blocked_canceled_request"
2804
2807
  throw s.incrementCounter(c,1),new n.ValidationError(o,{requestId:e,requestStatus:r.status,reason:"request_completed"})}return a.info("Request status validation passed",{requestId:e,status:r.status}),r}catch(t){if(t instanceof n.ValidationError)throw t
@@ -2928,48 +2931,57 @@ var t={}
2928
2931
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2929
2932
  return o(t,e),t})
2930
2933
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlanRead=async function(e,t,r,n,o){const s=n.child({tool:"plan_read"})
2931
- try{const n=a.validateArgs(e,i.PlanReadSchema),{operation:d}=n
2932
- switch(s.info("Processing plan_read",{operation:d}),d){case"get":{const e=await(0,c.handleGetPlan)(n.get,t,r,s,o)
2933
- return o.incrementCounter("plan_read_total",1,{operation:"get",success:!e.isError}),e}case"list":{const e=await(0,l.handleListPlans)(n.list,t,r,s,o)
2934
- return o.incrementCounter("plan_read_total",1,{operation:"list",success:!e.isError}),e}case"get-history":{const{planId:e}=n.getHistory,t=r.getDocumentClient(),s=await t.getVersionHistory(e)
2934
+ try{e?.get?.planId&&!e.planId&&(e.planId=e.get.planId,delete e.get),e?.getHistory?.planId&&!e.planId&&(e.planId=e.getHistory.planId,delete e.getHistory),e?.getRequests?.planId&&!e.planId&&(e.planId=e.getRequests.planId,delete e.getRequests),e?.list&&!e.searchQuery&&(Object.assign(e,e.list),delete e.list)
2935
+ const n=a.validateArgs(e,i.PlanReadSchema),{operation:d,planId:u}=n
2936
+ switch(s.info("Processing plan_read",{operation:d}),d){case"get":{const e=await(0,c.handleGetPlan)({planId:u},t,r,s,o)
2937
+ return o.incrementCounter("plan_read_total",1,{operation:"get",success:!e.isError}),e}case"list":{const e=await(0,l.handleListPlans)({searchQuery:n.searchQuery,limit:n.limit,offset:n.offset,sortBy:n.sortBy,sortDirection:n.sortDirection},t,r,s,o)
2938
+ return o.incrementCounter("plan_read_total",1,{operation:"list",success:!e.isError}),e}case"get-history":{const e=r.getDocumentClient(),t=await e.getVersionHistory(u)
2935
2939
  o.incrementCounter("plan_read_total",1,{operation:"get-history",success:!0})
2936
- let i=""
2937
- s.snapshots&&s.snapshots.length>0?(i="### Version Snapshots\n\n",s.snapshots.forEach((e=>{i+=`**Version ${e.versionNumber}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.versionLabel&&(i+=` Label: ${e.versionLabel}\n`),e.changeSummary&&(i+=` Summary: ${e.changeSummary}\n`),i+="\n"}))):i="### Version Snapshots\n\nNo version snapshots created yet.\n\n"
2938
- let a=""
2939
- return s.changeHistory&&s.changeHistory.length>0?(a="### Recent Changes\n\n",s.changeHistory.slice(0,10).forEach((e=>{a+=`**${e.toolName}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.createdBy&&(a+=` By: ${e.createdBy}\n`),a+="\n"}))):a="### Recent Changes\n\nNo changes recorded.\n",{content:[{type:"text",text:`## Version History for ${e}\n\n${i}${a}`}]}}case"get-active":{const e=r.getProjectClient(),n=t.projectId
2940
+ let n=""
2941
+ t.snapshots&&t.snapshots.length>0?(n="### Version Snapshots\n\n",t.snapshots.forEach((e=>{n+=`**Version ${e.versionNumber}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.versionLabel&&(n+=` Label: ${e.versionLabel}\n`),e.changeSummary&&(n+=` Summary: ${e.changeSummary}\n`),n+="\n"}))):n="### Version Snapshots\n\nNo version snapshots created yet.\n\n"
2942
+ let s=""
2943
+ return t.changeHistory&&t.changeHistory.length>0?(s="### Recent Changes\n\n",t.changeHistory.slice(0,10).forEach((e=>{s+=`**${e.toolName}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.createdBy&&(s+=` By: ${e.createdBy}\n`),s+="\n"}))):s="### Recent Changes\n\nNo changes recorded.\n",{content:[{type:"text",text:`## Version History for ${u}\n\n${n}${s}`}]}}case"get-active":{const e=r.getProjectClient(),n=t.projectId
2940
2944
  if(!n)return{content:[{type:"text",text:"\u274c No project context available."}],isError:!0}
2941
2945
  const i=await e.getProject(n)
2942
2946
  if(!i||!i.activePlanId)return o.incrementCounter("plan_read_total",1,{operation:"get-active",success:!0}),{content:[{type:"text",text:"No active plan set for this project. Use `plan_write` with `set-active` to designate one, or create a new plan."}]}
2943
2947
  const a=await(0,c.handleGetPlan)({planId:i.activePlanId},t,r,s,o)
2944
- return o.incrementCounter("plan_read_total",1,{operation:"get-active",success:!a.isError}),!a.isError&&a.content.length>0&&(a.content[0].text="\u{1f4cc} **Active Project Plan**\n\n"+a.content[0].text),a}case"get-requests":{const{planId:e}=n.getRequests,t=r.getRequestClient(),s=await t.listRequests({planDocumentId:e})
2945
- if(o.incrementCounter("plan_read_total",1,{operation:"get-requests",success:!0}),!s||0===s.length)return{content:[{type:"text",text:`No requests linked to plan ${e}.`}]}
2946
- let i=`## Requests Linked to ${e} (${s.length})\n\n`
2947
- for(const e of s)i+=`**${e.localId||e.id}** \u2014 ${e.title}\n`,i+=` Status: ${e.status} | Type: ${e.type}\n`,i+=` Updated: ${new Date(e.updatedAt).toLocaleString()}\n\n`
2948
- return{content:[{type:"text",text:i}]}}default:throw Error("Unknown plan_read operation: "+d)}}catch(e){return s.error("plan_read failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("plan_read_errors",1),{content:[{type:"text",text:"\u274c **Plan Read Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
2949
- const i=t(6183),a=s(t(5967)),c=t(8800),l=t(8391),d=t(8824)},5317(module){module.exports=require("child_process")},5434(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetRequestInformation=async function(e,t,i,a,c){const l=a.child({tool:"get_request_information"}),d=c.startTimer("tool_execution_time")
2948
+ return o.incrementCounter("plan_read_total",1,{operation:"get-active",success:!a.isError}),!a.isError&&a.content.length>0&&(a.content[0].text="\u{1f4cc} **Active Project Plan**\n\n"+a.content[0].text),a}case"get-requests":{const e=r.getRequestClient(),t=await e.listRequests({planDocumentId:u})
2949
+ if(o.incrementCounter("plan_read_total",1,{operation:"get-requests",success:!0}),!t||0===t.length)return{content:[{type:"text",text:`No requests linked to plan ${u}.`}]}
2950
+ let n=`## Requests Linked to ${u} (${t.length})\n\n`
2951
+ for(const e of t)n+=`**${e.localId||e.id}** \u2014 ${e.title}\n`,n+=` Status: ${e.status} | Type: ${e.type}\n`,n+=` Updated: ${new Date(e.updatedAt).toLocaleString()}\n\n`
2952
+ return{content:[{type:"text",text:n}]}}default:throw Error("Unknown plan_read operation: "+d)}}catch(e){return s.error("plan_read failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("plan_read_errors",1),{content:[{type:"text",text:"\u274c **Plan Read Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
2953
+ const i=t(6183),a=s(t(5967)),c=t(8800),l=t(8391),d=t(8824)},5317(module){module.exports=require("child_process")},5434(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetRequestInformation=async function(e,t,a,c,l){const d=c.child({tool:"get_request_information"}),u=l.startTimer("tool_execution_time")
2950
2954
  try{const{requestId:t}=e
2951
2955
  if(!t)throw new r.ValidationError("Request ID is required")
2952
2956
  if(!/^req\d{6}$/.test(t))throw new r.ValidationError(`Invalid request ID format: ${t}. Expected format: req######`)
2953
- l.info("Getting information for request "+t)
2954
- const n=i.getRequestClient(),s=i.getTaskClient(),[a,c]=await Promise.all([n.getRequest(t),s.listTasks({requestId:t})])
2955
- l.info("Raw request response data",{responseData:JSON.stringify(a)}),l.debug("Request response structure",{type:typeof a,isArray:Array.isArray(a),hasData:null!=a,properties:a?Object.keys(a):[],dataPreview:a?JSON.stringify(a).substring(0,200)+"...":"null"})
2956
- const u=(0,o.extractDataFromResponse)(a,{logger:l,operationName:"getRequestInformation",throwOnNoData:!0}),h="data"in u?u.data:u
2957
- l.info("Successfully extracted request data using data extraction utility"),l.info("Raw tasks response data",{responseData:JSON.stringify(c)}),l.debug("Tasks response structure",{type:typeof c,isArray:Array.isArray(c),hasData:null!=c,properties:c?Object.keys(c):[],dataPreview:c?JSON.stringify(c).substring(0,200)+"...":"null"})
2958
- const g=(0,o.extractArrayFromResponse)(c,{logger:l,operationName:"listTasksForRequest",defaultValue:[]})
2959
- l.info(`Successfully extracted ${g.length} tasks using data extraction utility`)
2960
- const p={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:g.length}
2961
- g.forEach((e=>{const t=e.status
2957
+ d.info("Getting information for request "+t)
2958
+ const n=a.getRequestClient(),s=a.getTaskClient(),[c,l]=await Promise.all([n.getRequest(t),s.listTasks({requestId:t})])
2959
+ d.info("Raw request response data",{responseData:JSON.stringify(c)}),d.debug("Request response structure",{type:typeof c,isArray:Array.isArray(c),hasData:null!=c,properties:c?Object.keys(c):[],dataPreview:c?JSON.stringify(c).substring(0,200)+"...":"null"})
2960
+ const h=(0,o.extractDataFromResponse)(c,{logger:d,operationName:"getRequestInformation",throwOnNoData:!0}),g="data"in h?h.data:h
2961
+ d.info("Successfully extracted request data using data extraction utility"),d.info("Raw tasks response data",{responseData:JSON.stringify(l)}),d.debug("Tasks response structure",{type:typeof l,isArray:Array.isArray(l),hasData:null!=l,properties:l?Object.keys(l):[],dataPreview:l?JSON.stringify(l).substring(0,200)+"...":"null"})
2962
+ const f=(0,o.extractArrayFromResponse)(l,{logger:d,operationName:"listTasksForRequest",defaultValue:[]})
2963
+ d.info(`Successfully extracted ${f.length} tasks using data extraction utility`)
2964
+ const p={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:f.length}
2965
+ f.forEach((e=>{const t=e.status
2962
2966
  t in p&&p[t]++}))
2963
- const f=h.acceptanceCriteria||[],m={unverified:0,partial:0,verified:0,partially_verified:0,total:f.length}
2964
- f.forEach((e=>{const t=e.status||"unverified"
2965
- t in m&&m[t]++}))
2966
- let y=h.testVerification||null
2967
- const w=h.title,k=h.type
2968
- let b=`# ${"feature"===k?"Feature":"quick-edit"===k?"Quick Edit":"Bug Fix"} Request: ${w} (${t})\nStatus: ${h.status}\nCreated: ${new Date(h.createdAt).toLocaleString()}\nUpdated: ${new Date(h.updatedAt).toLocaleString()}\n\n## Description\n${h.description||"_No description provided._"}\n\n## Progress Summary\n- Tasks: ${p.completed}/${p.total} completed (${Math.round(p.completed/p.total*100)||0}%)\n- Acceptance Criteria: ${m.verified}/${m.total} verified (${Math.round(m.verified/m.total*100)||0}%)\n`
2969
- return b+=`\n## Task Status\n- Pending: ${p.pending}\n- In Progress: ${p.in_progress}\n- Blocked: ${p.blocked}\n- Ready for Review: ${p.ready_for_review}\n- Completed: ${p.completed}\n- Reverted: ${p.reverted}\n`,b+="\n## Tasks\n",0===g.length?b+="No tasks found for this request.\n":g.forEach((e=>{b+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),l.info(`Added task listing with ${g.length} tasks`),b+="\n## Acceptance Criteria\n",0===f.length?b+="No acceptance criteria defined.\n":f.forEach(((e,t)=>{const r=e.status||"unverified"
2970
- b+=`${t}. [${r.toUpperCase()}] ${e.description}\n`})),y&&(b+=`\n## Test Coverage\n- Test Cases: ${y.totalTestCases||0}\n- Criteria Tested: ${y.criteriaTestedCount||0}/${m.total}\n`,y.criterionCoverage&&Array.isArray(y.criterionCoverage)&&(b+="\n### Detailed Test Coverage:\n",y.criterionCoverage.forEach((e=>{b+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),h.recentActivity&&Array.isArray(h.recentActivity)&&(b+="\n## Recent Activity\n",h.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
2971
- b+=`- ${t}: ${e.description}\n`}))),d({success:!0}),{content:[{type:"text",text:b}]}}catch(t){return l.error("Error getting request information",{args:e,error:t instanceof Error?t.stack:t+""}),d({success:!1,error:t instanceof Error?t.name:"unknown"}),t instanceof n.ConnectionError?{content:[{type:"text",text:"Unable to get request information: Connection to the server failed. Please check your network connection and try again."}],isError:!0}:{content:[{type:"text",text:"Error getting request information: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
2972
- const r=t(9860),n=t(5674),o=t(2960),s=t(8824)},5459(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
2967
+ const m=g.acceptanceCriteria||[],y={unverified:0,partial:0,verified:0,partially_verified:0,total:m.length}
2968
+ m.forEach((e=>{const t=e.status||"unverified"
2969
+ t in y&&y[t]++}))
2970
+ let w=g.testVerification||null
2971
+ const k=g.title,b=g.type
2972
+ let I=`# ${"feature"===b?"Feature":"quick-edit"===b?"Quick Edit":"Bug Fix"} Request: ${k} (${t})\nStatus: ${g.status}\nCreated: ${new Date(g.createdAt).toLocaleString()}\nUpdated: ${new Date(g.updatedAt).toLocaleString()}\n\n## Description\n${g.description||"_No description provided._"}\n\n## Progress Summary\n- Tasks: ${p.completed}/${p.total} completed (${Math.round(p.completed/p.total*100)||0}%)\n- Acceptance Criteria: ${y.verified}/${y.total} verified (${Math.round(y.verified/y.total*100)||0}%)\n`
2973
+ return I+=`\n## Task Status\n- Pending: ${p.pending}\n- In Progress: ${p.in_progress}\n- Blocked: ${p.blocked}\n- Ready for Review: ${p.ready_for_review}\n- Completed: ${p.completed}\n- Reverted: ${p.reverted}\n`,I+="\n## Tasks\n",0===f.length?I+="No tasks found for this request.\n":f.forEach((e=>{I+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),d.info(`Added task listing with ${f.length} tasks`),I+="\n## Acceptance Criteria\n",I+=(0,i.formatCriteriaWithHashes)(m)+"\n","ready_for_review"===g.status&&m.some((e=>"verified"!==e.status))&&(I+="\n> **Status: ready_for_review** \u2014 Use the merge operation to verify criteria and merge to main.\n"),w&&(I+=`\n## Test Coverage\n- Test Cases: ${w.totalTestCases||0}\n- Criteria Tested: ${w.criteriaTestedCount||0}/${y.total}\n`,w.criterionCoverage&&Array.isArray(w.criterionCoverage)&&(I+="\n### Detailed Test Coverage:\n",w.criterionCoverage.forEach((e=>{I+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),g.recentActivity&&Array.isArray(g.recentActivity)&&(I+="\n## Recent Activity\n",g.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
2974
+ I+=`- ${t}: ${e.description}\n`}))),u({success:!0}),{content:[{type:"text",text:I}]}}catch(t){return d.error("Error getting request information",{args:e,error:t instanceof Error?t.stack:t+""}),u({success:!1,error:t instanceof Error?t.name:"unknown"}),t instanceof n.ConnectionError?{content:[{type:"text",text:"Unable to get request information: Connection to the server failed. Please check your network connection and try again."}],isError:!0}:{content:[{type:"text",text:"Error getting request information: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
2975
+ const r=t(9860),n=t(5674),o=t(2960),s=t(8824),i=t(5454)},5454(e,exports){function t(e,t){let r=0
2976
+ for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t)|0
2977
+ return`${t+1}${String.fromCharCode(97+Math.abs(r)%26)}`}function r(e){const r=new Map
2978
+ for(let n=0;n<e.length;n++){const o=t(e[n].id,n)
2979
+ r.set(o,e[n])}return r}function n(e){if(0===e.length)return"No acceptance criteria defined."
2980
+ const t=r(e),n=[]
2981
+ for(const[e,r]of t){const t=(r.status||"unverified").toUpperCase()
2982
+ n.push(`[${e}] [${t}] ${r.description}`)}return n.join("\n")}function o(e){const t=r(e),o=[]
2983
+ for(const[e,r]of t)o.push(` {"key": "${e}", "evidence": "<your evidence for: ${r.description}>"}`)
2984
+ return`Use the merge operation with evidence for each criterion:\n\n${n(e)}\n\nExample call:\n{\n "operation": "merge",\n "requestId": "<requestId>",\n "merge": {\n "verifications": [\n${o.join(",\n")}\n ]\n }\n}`}Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatEvidenceInstructions=exports.formatCriteriaWithHashes=exports.buildCriteriaHashMap=exports.criterionHash=void 0,exports.criterionShortKey=t,exports.buildCriteriaKeyMap=r,exports.formatCriteriaWithKeys=n,exports.formatVerifyInstructions=o,exports.criterionHash=t,exports.buildCriteriaHashMap=r,exports.formatCriteriaWithHashes=n,exports.formatEvidenceInstructions=o},5459(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
2973
2985
  const r=t(6183),n=t(2414)
2974
2986
  exports.def={name:"move_files",description:"Move or rename multiple files and directories in a single operation. Requires a taskId and a comment explaining the purpose of the modifications. All operations are processed sequentially and committed together. If any operation fails, the tool reports which operations succeeded and which failed.",schema:r.MoveFilesSchema,annotations:{title:"Move or Rename Multiple Files",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,createsRecords:!0,handler(e,t){return(0,n.handleMoveFiles)(e,t.context,t.apiClient.getTaskClient(),t.apiClient.getToolRecordClient(),t.apiClient.getRequestClient(),t.logger,t.metrics,t.mcpServer)}}},5626(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
2975
2987
  var o=Object.getOwnPropertyDescriptor(t,r)
@@ -2980,35 +2992,37 @@ var t={}
2980
2992
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2981
2993
  return o(t,e),t})
2982
2994
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDocumentOperations=async function(e,t,r,n,o,s,u){const h=n.child({tool:"document_operations"})
2983
- try{const n=a.validateArgs(e,i.DocumentOperationsSchema),{operation:d}=n
2984
- switch(h.info("Processing document_operations",{operation:d}),d){case"create":{h.info("Routing to create-document handler")
2985
- const e=await(0,c.handleCreateDocument)(n.create,t,r,h,o,s,u)
2995
+ try{const n=["create","search","createSnapshot","getHistory","getVersion","restoreVersion","listAnnotations","createAnnotation","replyToAnnotation","resolveAnnotation"]
2996
+ for(const t of n)e?.[t]&&"object"==typeof e[t]&&(Object.assign(e,e[t]),delete e[t])
2997
+ const d=a.validateArgs(e,i.DocumentOperationsSchema),{operation:g}=d,f=d.documentId
2998
+ switch(h.info("Processing document_operations",{operation:g}),g){case"create":{h.info("Routing to create-document handler")
2999
+ const e=await(0,c.handleCreateDocument)({requestId:d.requestId,filename:d.filename,content:d.content,type:d.type,comment:d.comment},t,r,h,o,s,u)
2986
3000
  return o.incrementCounter("document_operations_total",1,{operation:"create",success:!e.isError}),e}case"search":{h.info("Routing to search-documents handler")
2987
- const e=await(0,l.handleSearchDocuments)(n.search,t,r,h,o,s)
3001
+ const e=await(0,l.handleSearchDocuments)({query:d.query,type:d.type,requestId:d.requestId,includeArchived:d.includeArchived,maxResults:d.maxResults,dateFrom:d.dateFrom,dateTo:d.dateTo,searchIn:d.searchIn},t,r,h,o,s)
2988
3002
  return o.incrementCounter("document_operations_total",1,{operation:"search",success:!e.isError}),e}case"create-snapshot":{h.info("Creating version snapshot")
2989
- const{documentId:e,versionLabel:t,changeSummary:s}=n.createSnapshot,i=r.getDocumentClient(),a=await i.createVersionSnapshot(e,t,s)
2990
- return o.incrementCounter("document_operations_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Version Snapshot Created**\n\n**Document:** ${e}\n**Version:** ${a.versionNumber}\n**Label:** ${t||"None"}\n**Summary:** ${s||"None"}\n**Created:** `+new Date(a.createdAt).toLocaleString()}]}}case"get-history":{h.info("Retrieving version history")
2991
- const{documentId:e}=n.getHistory,t=r.getDocumentClient(),s=await t.getVersionHistory(e)
2992
- h.info("Version history data received",{hasSnapshots:!!s.snapshots,snapshotCount:s.snapshots?.length||0,hasChangeHistory:!!s.changeHistory,changeCount:s.changeHistory?.length||0,keys:Object.keys(s)}),o.incrementCounter("document_operations_total",1,{operation:"get-history",success:!0})
2993
- let i=""
2994
- s.snapshots&&s.snapshots.length>0?(i="### \u{1f4da} Version Snapshots\n\n",s.snapshots.forEach((e=>{i+=`**Version ${e.versionNumber}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.versionLabel&&(i+=` Label: ${e.versionLabel}\n`),e.changeSummary&&(i+=` Summary: ${e.changeSummary}\n`),i+="\n"}))):i="### \u{1f4da} Version Snapshots\n\nNo version snapshots created yet.\n\n"
2995
- let a=""
2996
- return s.changeHistory&&s.changeHistory.length>0?(a="### \u{1f4dd} Recent Changes\n\n",s.changeHistory.slice(0,10).forEach((e=>{a+=`**${e.toolName}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.createdBy&&(a+=` By: ${e.createdBy}\n`),a+="\n"}))):a="### \u{1f4dd} Recent Changes\n\nNo changes recorded.\n",{content:[{type:"text",text:`## Version History for ${e}\n\n${i}${a}`}]}}case"get-version":{h.info("Retrieving specific version")
2997
- const{documentId:e,versionNumber:t}=n.getVersion,s=r.getDocumentClient(),i=await s.getVersion(e,t)
2998
- return o.incrementCounter("document_operations_total",1,{operation:"get-version",success:!0}),{content:[{type:"text",text:`## Version ${t} of ${e}\n\n**Created:** ${new Date(i.createdAt).toLocaleString()}\n**Label:** ${i.versionLabel||"None"}\n**Summary:** ${i.changeSummary||"None"}\n\n### Content:\n\n\`\`\`\n${i.content}\n\`\`\``}]}}case"restore-version":{h.info("Restoring to version")
2999
- const{documentId:e,versionNumber:t}=n.restoreVersion,s=r.getDocumentClient(),i=await s.restoreToVersion(e,t)
3000
- return o.incrementCounter("document_operations_total",1,{operation:"restore-version",success:!0}),{content:[{type:"text",text:`\u2705 **Document Restored**\n\n**Document:** ${e}\n**Restored to Version:** ${t}\n**Filename:** ${i.filename}\n\nThe document has been successfully restored to version ${t}.`}]}}case"list-annotations":{h.info("Listing annotations")
3001
- const{documentId:e}=n.listAnnotations,t=r.getDocumentClient(),s=await t.listAnnotations(e)
3002
- if(o.incrementCounter("document_operations_total",1,{operation:"list-annotations",success:!0}),!s||0===s.length)return{content:[{type:"text",text:`No annotations found on document ${e}.`}]}
3003
- let i=`## Annotations on ${e} (${s.length})\n\n`
3004
- for(const e of s){if(i+=`### ${"resolved"===e.status?"\u2705":"\u{1f4ac}"} ${e.id} [${e.status}]\n`,i+=`> "${e.anchor?.selectedText?.substring(0,80)||""}"\n\n`,i+=e.body+"\n",e.createdByAgent&&(i+=`*By agent: ${e.createdByAgent}*\n`),e.replies&&e.replies.length>0){i+=`\n**Replies (${e.replies.length}):**\n`
3005
- for(const t of e.replies)i+="- "+t.body,t.createdByAgent&&(i+=` *(${t.createdByAgent})*`),i+="\n"}i+="\n---\n\n"}return{content:[{type:"text",text:i}]}}case"create-annotation":{h.info("Creating annotation")
3006
- const{documentId:e,selectedText:t,prefixContext:s,suffixContext:i,lineHint:a,body:c}=n.createAnnotation,l=r.getDocumentClient(),d=u?"agent":void 0,g=u?.sessionId,p=await l.createAnnotation(e,{selectedText:t,prefixContext:s,suffixContext:i,lineHint:a,body:c,createdByAgent:d,createdBySessionId:g})
3007
- return o.incrementCounter("document_operations_total",1,{operation:"create-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Created**\n\n**ID:** ${p.id}\n**Document:** ${e}\n**Selected text:** "${t.substring(0,60)}"\n**Comment:** `+c}]}}case"reply-to-annotation":{h.info("Replying to annotation")
3008
- const{documentId:e,annotationId:t,body:s}=n.replyToAnnotation,i=r.getDocumentClient(),a=await i.replyToAnnotation(e,t,{body:s,createdByAgent:u?"agent":void 0,createdBySessionId:u?.sessionId})
3009
- return o.incrementCounter("document_operations_total",1,{operation:"reply-to-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Reply Added**\n\n**Reply ID:** ${a.id}\n**Annotation:** ${t}\n**Body:** `+s}]}}case"resolve-annotation":{h.info("Resolving annotation")
3010
- const{documentId:e,annotationId:t}=n.resolveAnnotation,s=r.getDocumentClient()
3011
- return await s.resolveAnnotation(e,t,u?"agent":void 0),o.incrementCounter("document_operations_total",1,{operation:"resolve-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Resolved**\n\n**Annotation:** ${t}\n**Status:** resolved`}]}}default:throw Error("Unknown operation type: "+d)}}catch(e){return h.error("document_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("document_operations_errors",1),{content:[{type:"text",text:"\u274c **Document Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
3003
+ const{versionLabel:e,changeSummary:t}=d,n=r.getDocumentClient(),s=await n.createVersionSnapshot(f,e,t)
3004
+ return o.incrementCounter("document_operations_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Version Snapshot Created**\n\n**Document:** ${f}\n**Version:** ${s.versionNumber}\n**Label:** ${e||"None"}\n**Summary:** ${t||"None"}\n**Created:** `+new Date(s.createdAt).toLocaleString()}]}}case"get-history":{h.info("Retrieving version history")
3005
+ const e=r.getDocumentClient(),t=await e.getVersionHistory(f)
3006
+ h.info("Version history data received",{hasSnapshots:!!t.snapshots,snapshotCount:t.snapshots?.length||0,hasChangeHistory:!!t.changeHistory,changeCount:t.changeHistory?.length||0,keys:Object.keys(t)}),o.incrementCounter("document_operations_total",1,{operation:"get-history",success:!0})
3007
+ let n=""
3008
+ t.snapshots&&t.snapshots.length>0?(n="### \u{1f4da} Version Snapshots\n\n",t.snapshots.forEach((e=>{n+=`**Version ${e.versionNumber}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.versionLabel&&(n+=` Label: ${e.versionLabel}\n`),e.changeSummary&&(n+=` Summary: ${e.changeSummary}\n`),n+="\n"}))):n="### \u{1f4da} Version Snapshots\n\nNo version snapshots created yet.\n\n"
3009
+ let s=""
3010
+ return t.changeHistory&&t.changeHistory.length>0?(s="### \u{1f4dd} Recent Changes\n\n",t.changeHistory.slice(0,10).forEach((e=>{s+=`**${e.toolName}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.createdBy&&(s+=` By: ${e.createdBy}\n`),s+="\n"}))):s="### \u{1f4dd} Recent Changes\n\nNo changes recorded.\n",{content:[{type:"text",text:`## Version History for ${f}\n\n${n}${s}`}]}}case"get-version":{h.info("Retrieving specific version")
3011
+ const e=r.getDocumentClient(),t=await e.getVersion(f,d.versionNumber)
3012
+ return o.incrementCounter("document_operations_total",1,{operation:"get-version",success:!0}),{content:[{type:"text",text:`## Version ${d.versionNumber} of ${f}\n\n**Created:** ${new Date(t.createdAt).toLocaleString()}\n**Label:** ${t.versionLabel||"None"}\n**Summary:** ${t.changeSummary||"None"}\n\n### Content:\n\n\`\`\`\n${t.content}\n\`\`\``}]}}case"restore-version":{h.info("Restoring to version")
3013
+ const e=r.getDocumentClient(),t=await e.restoreToVersion(f,d.versionNumber)
3014
+ return o.incrementCounter("document_operations_total",1,{operation:"restore-version",success:!0}),{content:[{type:"text",text:`\u2705 **Document Restored**\n\n**Document:** ${f}\n**Restored to Version:** ${d.versionNumber}\n**Filename:** ${t.filename}\n\nThe document has been successfully restored to version ${d.versionNumber}.`}]}}case"list-annotations":{h.info("Listing annotations")
3015
+ const e=r.getDocumentClient(),t=await e.listAnnotations(f)
3016
+ if(o.incrementCounter("document_operations_total",1,{operation:"list-annotations",success:!0}),!t||0===t.length)return{content:[{type:"text",text:`No annotations found on document ${f}.`}]}
3017
+ let n=`## Annotations on ${f} (${t.length})\n\n`
3018
+ for(const e of t){if(n+=`### ${"resolved"===e.status?"\u2705":"\u{1f4ac}"} ${e.id} [${e.status}]\n`,n+=`> "${e.anchor?.selectedText?.substring(0,80)||""}"\n\n`,n+=e.body+"\n",e.createdByAgent&&(n+=`*By agent: ${e.createdByAgent}*\n`),e.replies&&e.replies.length>0){n+=`\n**Replies (${e.replies.length}):**\n`
3019
+ for(const t of e.replies)n+="- "+t.body,t.createdByAgent&&(n+=` *(${t.createdByAgent})*`),n+="\n"}n+="\n---\n\n"}return{content:[{type:"text",text:n}]}}case"create-annotation":{h.info("Creating annotation")
3020
+ const e=d.selectedText,t=d.body,{prefixContext:n,suffixContext:s,lineHint:i}=d,a=r.getDocumentClient(),c=u?"agent":void 0,l=u?.sessionId,g=await a.createAnnotation(f,{selectedText:e,prefixContext:n,suffixContext:s,lineHint:i,body:t,createdByAgent:c,createdBySessionId:l})
3021
+ return o.incrementCounter("document_operations_total",1,{operation:"create-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Created**\n\n**ID:** ${g.id}\n**Document:** ${f}\n**Selected text:** "${e.substring(0,60)}"\n**Comment:** `+t}]}}case"reply-to-annotation":{h.info("Replying to annotation")
3022
+ const e=d.annotationId,t=d.body,n=r.getDocumentClient(),s=await n.replyToAnnotation(f,e,{body:t,createdByAgent:u?"agent":void 0,createdBySessionId:u?.sessionId})
3023
+ return o.incrementCounter("document_operations_total",1,{operation:"reply-to-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Reply Added**\n\n**Reply ID:** ${s.id}\n**Annotation:** ${e}\n**Body:** `+t}]}}case"resolve-annotation":{h.info("Resolving annotation")
3024
+ const e=d.annotationId,t=r.getDocumentClient()
3025
+ return await t.resolveAnnotation(f,e,u?"agent":void 0),o.incrementCounter("document_operations_total",1,{operation:"resolve-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Resolved**\n\n**Annotation:** ${e}\n**Status:** resolved`}]}}default:throw Error("Unknown operation type: "+g)}}catch(e){return h.error("document_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("document_operations_errors",1),{content:[{type:"text",text:"\u274c **Document Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
3012
3026
  const i=t(6183),a=s(t(5967)),c=t(1572),l=t(1483),d=t(8824)},5671(e,exports,t){function r(e){const[t,...r]=e.split("/")
3013
3027
  return{provider:t||"anthropic",modelId:r.join("/")||e}}function n(e){const t={anthropic:!1,openai:!1}
3014
3028
  try{const n=(0,a.join)(e,"opencode.json")
@@ -3029,10 +3043,10 @@ let h,g=0
3029
3043
  if("one_down"===n&&(g=1),"two_down"===n&&(g=2),i===s.provider)h=u+g
3030
3044
  else{const e=l.length>1?u/(l.length-1):0
3031
3045
  h=Math.round(e*(d.length-1))+g}h=Math.min(h,d.length-1),h=Math.max(h,0)
3032
- const p=d[h]
3033
- let f
3046
+ const f=d[h]
3047
+ let p
3034
3048
  var m,y
3035
- return i===s.provider?(m=a,y=p,f=s.modelId.replace(m,y)):f=p,{provider:i,modelId:f,fullModel:`${i}/${f}`,resolved:!0}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseModelString=r,exports.getAvailableProviders=n,exports.getMainSessionModel=o,exports.resolveModelTier=s,exports.resolveAgentModel=function(e,t="inherit",i="same"){const a=o(e)
3049
+ return i===s.provider?(m=a,y=f,p=s.modelId.replace(m,y)):p=f,{provider:i,modelId:p,fullModel:`${i}/${p}`,resolved:!0}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseModelString=r,exports.getAvailableProviders=n,exports.getMainSessionModel=o,exports.resolveModelTier=s,exports.resolveAgentModel=function(e,t="inherit",i="same"){const a=o(e)
3036
3050
  if(!a)return{provider:"anthropic",modelId:"claude-sonnet-4-5",fullModel:"anthropic/claude-sonnet-4-5",resolved:!1,reason:"Could not determine main session model, using default"}
3037
3051
  if("inherit"===t&&"same"===i){const e=r(a)
3038
3052
  return{provider:e.provider,modelId:e.modelId,fullModel:a,resolved:!0}}return s(a,t,i,n(e))}
@@ -3055,55 +3069,25 @@ if(t){const e=Date.now()-t
3055
3069
  try{this.metrics.observeHistogram("offline_duration_ms",e,{reconnection_type:"manual"}),this.logger.info(`System was offline for ${Math.round(e/1e3)} seconds before manual reconnection`)}catch(e){this.logger.warn("Error observing histogram for offline duration on manual reconnection",{error:e instanceof Error?e.message:e+""})}}}}catch(e){this.logger.warn("Error calculating offline duration during manual mode change",{error:(0,s.getErrorMessage)(e)})}this.notifyOnlineStatus()}else!t&&e&&(this.logger.info("Manually setting connection mode to OFFLINE"),this.safeSetGauge("connection_status",0),this.safeSetGauge("last_connection_failure_timestamp",Date.now()),this.safeIncrementCounter("manual_disconnections",1),process.nextTick((()=>{exports.eventBus.emit(exports.EVENTS.OFFLINE,{timestamp:(new Date).toISOString()})})))}isOffline(){return this.isInOfflineMode()}async checkConnectivity(){return this.logger.debug("Explicit connectivity check requested"),this.healthCheckManager.requestHealthCheck()}getHealthCheckStats(){const e=this.healthCheckManager.getStats()
3056
3070
  return{isOffline:this.isInOfflineMode(),consecutiveFailures:e.consecutiveFailures,currentBackoffMs:e.currentBackoffMs,lastCheckTime:e.lastCheckTime}}cleanup(){this.logger.debug("Cleaning up connection status manager resources"),this.healthCheckManager.stopHealthChecks(),exports.eventBus.removeAllListeners(exports.EVENTS.ONLINE),exports.eventBus.removeAllListeners(exports.EVENTS.OFFLINE)}}},5692(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3057
3071
  const r=t(6183),n=t(2965)
3058
- exports.def={name:"read_files",description:'Read the contents of multiple files and documents with flexible line selection.\n\nLINE SELECTION (string format):\n- Single line: "lines": "5"\n- Multiple lines: "lines": "1,3,7,10"\n- Range: "lines": "5-15"\n- Entire file: omit "lines" parameter\n\nEXAMPLES:\n- Read first 10 lines: {"path": "file.txt", "lines": "1-10"}\n- Read specific lines: {"path": "file.txt", "lines": "1,5,25"}\n- Read line 42 only: {"path": "file.txt", "lines": "42"}\n- Read entire file: {"path": "file.txt"}\n\nSupports both filesystem files (using \'path\') and tracked documents (using \'documentId\'). More efficient than reading files one by one. Failed reads won\'t stop the entire operation.',schema:r.ReadFilesSchema,annotations:{title:"Read Files/Documents",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handleReadFiles)(e,t.context,t.logger,t.metrics)}}},5715(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteRequest=async function(e,t,l,d,u,h,g){const p=d.child({tool:"complete_request"}),f=u.startTimer("tool_execution_time")
3059
- try{const{requestId:o,summary:s,acceptanceEvidence:d}=e
3072
+ exports.def={name:"read_files",description:'Read the contents of multiple files and documents with flexible line selection.\n\nLINE SELECTION (string format):\n- Single line: "lines": "5"\n- Multiple lines: "lines": "1,3,7,10"\n- Range: "lines": "5-15"\n- Entire file: omit "lines" parameter\n\nEXAMPLES:\n- Read first 10 lines: {"path": "file.txt", "lines": "1-10"}\n- Read specific lines: {"path": "file.txt", "lines": "1,5,25"}\n- Read line 42 only: {"path": "file.txt", "lines": "42"}\n- Read entire file: {"path": "file.txt"}\n\nSupports both filesystem files (using \'path\') and tracked documents (using \'documentId\'). More efficient than reading files one by one. Failed reads won\'t stop the entire operation.',schema:r.ReadFilesSchema,annotations:{title:"Read Files/Documents",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handleReadFiles)(e,t.context,t.logger,t.metrics)}}},5715(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteRequest=async function(e,t,c,l,d,u,h){const g=l.child({tool:"complete_request"}),f=d.startTimer("tool_execution_time")
3073
+ try{const{requestId:o,summary:s}=e
3060
3074
  if(!o)throw(0,r.createValidationError)("Request ID is required")
3061
3075
  if(!s)throw(0,r.createValidationError)("Summary is required")
3062
- if(!d||!Array.isArray(d)||0===d.length)throw(0,r.createValidationError)("Acceptance evidence is required and must be a non-empty array")
3063
- const h=d.map((e=>{if("object"!=typeof e||!e.evidence)throw(0,r.createValidationError)('Each evidence item must have an "evidence" property')
3064
- return e.evidence}))
3065
- p.info("Starting request completion",{requestId:o,evidenceCount:h.length})
3066
- const m=g?.sessionId||(0,n.getCachedSession)()?.sessionId
3067
- let y,w
3068
- try{const e=await l.proxyPost(`/api/projects/${t.projectId}/requests/${o}/validate-completion`,{sessionId:m})
3069
- y=e?.data||e}catch(e){const t=(0,c.getErrorMessage)(e)
3070
- return p.error("Server validation failed",{requestId:o,error:t}),f({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate completion: "+t}],isError:!0}}if(p.info("Server validation result",{requestId:o,canComplete:y.canComplete,completionMode:y.completionMode,mergeStrategy:y.mergeStrategy,reason:y.reason}),!y.canComplete){let e=`Cannot complete request ${o}: ${y.reason}\n`
3071
- return y.blockedByTasks&&y.blockedByTasks.length>0&&(e+="\n**Tasks that must be completed or canceled first:**\n",y.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (Status: ${t.status})\n`}))),y.lifoViolation&&(e+="\n**Requests that must be re-completed first (LIFO order):**\n",y.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (Status: ${t.status})\n`}))),f({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if("auto-merge"!==y.completionMode){p.info("Non-auto-merge mode: setting request to ready_for_review",{requestId:o,completionMode:y.completionMode})
3072
- try{const e=l.getRequestClient()
3073
- let t
3074
- return await e.updateRequest(o,{status:"ready_for_review",completionSummary:s,acceptanceEvidence:d}),f({success:!0}),t="manual-review"===y.completionMode?"Use the GUI or the `finalize` operation to approve and merge.":"ask"===y.testingMode?"Testing mode is set to **Ask Me**. The user has been notified and will decide how to proceed.\n\n**Do NOT run tests or call finalize yourself.** Wait for the user to make their choice.":`## Next Steps (REQUIRED)\n1. Run the project build/tests to verify this request.\n2. If the build and tests PASS: call request_operations with { "operation": "finalize", "requestId": "${o}" } to merge.\n3. If the build or tests FAIL: report the failure. Do NOT call finalize.`,{content:[{type:"text",text:`Request ${o} submitted for review.\n\n**Summary:** ${s}\n\n**Status:** \u2705 Ready for Review\n\n**Evidence:** ${h.length} acceptance criteria verified\n\n**Mode:** ${y.completionMode}\n\n${t}`}]}}catch(e){const t=(0,c.getErrorMessage)(e)
3075
- return f({success:!1,error:"review_submission_failure"}),{content:[{type:"text",text:"Failed to submit request for review: "+t}],isError:!0}}}if("skip"===y.mergeStrategy){p.info("No tasks to merge \u2014 completing directly via server",{requestId:o})
3076
- try{return await l.proxyPost(`/api/projects/${t.projectId}/requests/${o}/finalize-completion`,{summary:s,acceptanceEvidence:d,mergeResult:{mergeCommitHash:"none",method:"skip-no-tasks"}}),f({success:!0}),{content:[{type:"text",text:`Request ${o} completed successfully.\n\n**Summary:** ${s}\n\n**Status:** \u2705 Completed (no tasks to merge)\n\n**Evidence:** ${h.length} acceptance criteria verified`}]}}catch(e){const t=(0,c.getErrorMessage)(e)
3077
- return f({success:!1,error:"no_tasks_completion_failure"}),{content:[{type:"text",text:"Failed to complete request with no tasks: "+t}],isError:!0}}}let k={merged:!1,deleted:!1,method:"",message:""}
3078
- if("revert-removal"===y.mergeStrategy&&y.revertInfo){if(p.info("Using revert removal strategy",{requestId:o,revertCommitHash:y.revertInfo.revertCommitHash.substring(0,8)}),t.git&&y.revertInfo.revertCommitHash){const e=await(0,a.hasMainChangedSinceRevert)(t.git,y.revertInfo.revertCommitHash,p,u)
3079
- if(e.hasChanged)return f({success:!1,reason:"main_changed_since_revert"}),{content:[{type:"text",text:`Cannot re-complete reverted request: Main branch has changed since revert\n\n${e.message}\n\nCreate a new request to implement the desired changes.`}],isError:!0}}try{const e=(await t.git.raw(["rev-parse",y.revertInfo.revertCommitHash+"^"])).trim()
3080
- await t.git.reset(["--hard",e])
3081
- const r=await t.git.revparse(["HEAD"])
3082
- if(r.trim()!==e)throw Error(`Git reset verification failed: expected ${e.substring(0,8)}, got ${r.substring(0,8)}`)
3083
- w={mergeCommitHash:r.trim(),mergedFiles:[],cleanedUp:!1},k={merged:!0,deleted:!1,method:"revert-removal",message:"Removed revert commit "+y.revertInfo.revertCommitHash.substring(0,8)},p.info("Revert removal succeeded",{requestId:o,newHead:r.trim().substring(0,8)})}catch(e){const t=(0,c.getErrorMessage)(e)
3084
- return f({success:!1,reason:"revert_removal_failed"}),{content:[{type:"text",text:"Failed to re-complete reverted request: "+t}],isError:!0}}}const b=l.getRequestClient(),I=await b.getRequest(o)
3085
- if(!w&&"conflicted"===I?.status){p.info("Request is conflicted, attempting fast-path merge",{requestId:o})
3086
- const e=t.workspaceManager?.getCurrentContext()
3087
- let r=e?.basePath||process.cwd()
3088
- if("multi-agent"===e?.mode&&t.workspaceManager)try{const e=await t.workspaceManager.getWorktreeInfo(o)
3089
- e?.worktreePath&&(r=e.worktreePath)}catch{}const n=(0,i.createConflictResolutionManager)(p,l,r,t.git),s=await n.validateMarkersRemoved(o)
3090
- if(!s.resolved)return{content:[{type:"text",text:`## \u26a0\ufe0f Conflicts Still Need Resolution\n\nConflict markers still exist in:\n\n${s.remainingConflicts.map((e=>`- \`${e}\``)).join("\n")}\n\nRemove all conflict markers and try again.`}]}
3091
- const a=await n.hasMainBranchChanged(o)
3092
- if(a.hasChanged&&a.canDetermine)p.info("Main branch changed since conflict detection, skipping fast-path",{requestId:o,originalHash:a.originalHash?.substring(0,8),currentHash:a.currentHash?.substring(0,8)})
3093
- else try{const e=await async function(e,t,r){r.info("Executing branch-version merge for resolved conflicts",{requestId:e})
3094
- try{return await t.completeRequest(e,"Request "+e,{skipConflictDetection:!0})}catch(t){throw r.warn("Branch-version merge failed",{requestId:e,error:(0,c.getErrorMessage)(t)}),t}}(o,t.workspaceManager,p)
3095
- w=e,k={merged:!0,deleted:e.cleanedUp,method:"conflict-fast-path",message:"Fast-path branch-version merge after conflict resolution"}}catch(e){const t=(0,c.getErrorMessage)(e)
3096
- return f({success:!1,reason:"conflict_fast_path_failed"}),{content:[{type:"text",text:"Fast-path merge failed: "+t}],isError:!0}}}if(!w){if(p.info("Normal merge via WorkspaceManager",{requestId:o}),!t.workspaceManager)return f({success:!1,error:"no_workspace_manager"}),{content:[{type:"text",text:"WorkspaceManager not available for request completion"}],isError:!0}
3097
- const e=t.workspaceManager.getCurrentContext()
3098
- if(!e.requestId||e.requestId!==o)try{await t.workspaceManager.ensureWorkspaceReady(o)}catch(e){return f({success:!1,error:"workspace_switch_failed"}),{content:[{type:"text",text:`Cannot complete request ${o}: ${(0,c.getErrorMessage)(e)}`}],isError:!0}}try{w=await t.workspaceManager.completeRequest(o,"Request "+o),k={merged:!0,deleted:w.cleanedUp,method:w.autoMergeInfo?.strategy||"workspace-manager",message:w.autoMergeInfo?.wasAutoMerged?"Auto-merged using "+w.autoMergeInfo.strategy:"Merged via WorkspaceManager"}}catch(e){if(e.conflictInfo){const r=e.conflictInfo,n=r.workingDirectory||t.workspaceManager.getCurrentContext()?.basePath||process.cwd(),s=(0,i.createConflictResolutionManager)(p,l,n,t.git)
3099
- let a
3100
- if("conflicted"===I?.status)try{a=await s.updateConflictResolution(o,r)}catch{a=await s.handleConflicts(r)}else a=await s.handleConflicts(r)
3101
- return f({success:!1,reason:"merge_conflicts_handled"}),{content:[{type:"text",text:a.userMessage}],isError:!1}}const r=(0,c.getErrorMessage)(e)
3102
- return f({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Request completion failed during merge: "+r}],isError:!0}}}try{await l.proxyPost(`/api/projects/${t.projectId}/requests/${o}/finalize-completion`,{summary:s,acceptanceEvidence:d,mergeResult:{mergeCommitHash:w.mergeCommitHash,mergedFiles:w.mergedFiles,cleanedUp:w.cleanedUp,method:k.method}})}catch(e){const t=(0,c.getErrorMessage)(e)
3103
- return p.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:o,mergeCommitHash:w.mergeCommitHash,error:t}),f({success:!1,error:"api_update_failed"}),{content:[{type:"text",text:`CRITICAL: Code was successfully merged (commit: ${w.mergeCommitHash.substring(0,8)}) but failed to update request status: ${t}`}],isError:!0}}return f({success:!0}),{content:[{type:"text",text:"Request completed: "+o}]}}catch(r){let n="An unexpected error occurred",i=""
3104
- r instanceof o.ZodError?(n="Validation error",i=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")):r instanceof Error?(n=r.message,i=r.stack||""):i=r+"",p.error("Complete request failed",{error:n,details:i})
3105
- try{await(0,s.createFailureToolRecord)("complete-request",r,{error:n,details:i,requestId:e?.requestId},l.getToolRecordClient(),p,u,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to complete request"})}catch{}return f({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+n}],isError:!0}}}
3106
- const r=t(9860),n=t(715),o=t(1569),s=t(8616),i=t(1651),a=t(7478),c=t(8824)},5767(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3076
+ g.info("Starting request completion",{requestId:o})
3077
+ const l=h?.sessionId||(0,n.getCachedSession)()?.sessionId
3078
+ let d
3079
+ try{const e=await c.proxyPost(`/api/projects/${t.projectId}/requests/${o}/validate-completion`,{sessionId:l})
3080
+ d=e?.data||e}catch(e){const t=(0,i.getErrorMessage)(e)
3081
+ return g.error("Server validation failed",{requestId:o,error:t}),f({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate completion: "+t}],isError:!0}}if(!d.canComplete){let e=`Cannot complete request ${o}: ${d.reason}\n`
3082
+ return d.blockedByTasks&&d.blockedByTasks.length>0&&(e+="\n**Tasks that must be completed or canceled first:**\n",d.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (Status: ${t.status})\n`}))),d.lifoViolation&&(e+="\n**Requests that must be re-completed first (LIFO order):**\n",d.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (Status: ${t.status})\n`}))),f({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}const u=c.getRequestClient(),p="auto-test-then-merge"===d.completionMode,m=p?"ready_for_review":"ready_for_merge"
3083
+ try{await u.updateRequest(o,{status:m,completionSummary:s})}catch(e){const t=(0,i.getErrorMessage)(e)
3084
+ return f({success:!1,error:"status_transition_failed"}),{content:[{type:"text",text:"Failed to transition request: "+t}],isError:!0}}let y
3085
+ try{y=await u.getRequest(o)}catch(e){const t=(0,i.getErrorMessage)(e)
3086
+ return f({success:!1,error:"fetch_request_failed"}),{content:[{type:"text",text:"Failed to fetch request criteria: "+t}],isError:!0}}const w=y?.acceptanceCriteria||[]
3087
+ return f({success:!0}),p?{content:[{type:"text",text:`Request ${o} moved to ready_for_review. Testing is active \u2014 a notification has been created for the user to choose testing mode. Do NOT call merge or any other tool. Your work is done. Stop here and wait.`}]}:0===w.length?{content:[{type:"text",text:`Request ${o} is ready. No acceptance criteria defined \u2014 call merge directly.`}]}:{content:[{type:"text",text:`Request ${o} completion started (${m}).\n\n## Next Step: Verify & Merge\n\n${(0,a.formatVerifyInstructions)(w)}\n\nUse the merge operation with your verification evidence to merge to main.`}]}}catch(r){let n="An unexpected error occurred",i=""
3088
+ r instanceof o.ZodError?(n="Validation error",i=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")):r instanceof Error?(n=r.message,i=r.stack||""):i=r+"",g.error("Complete request failed",{error:n,details:i})
3089
+ try{await(0,s.createFailureToolRecord)("complete-request",r,{error:n,details:i,requestId:e?.requestId},c.getToolRecordClient(),g,d,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to complete request"})}catch{}return d.startTimer("tool_execution_time")({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+n}],isError:!0}}}
3090
+ const r=t(9860),n=t(715),o=t(1569),s=t(8616),i=t(8824),a=t(5454)},5767(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3107
3091
  const r=t(6183),n=t(6285)
3108
3092
  exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nOperations:\n\u2022 delegate - Spawn a new specialist (include specialization). Abort an idle specialist first if pool is full.\n\u2022 follow-up - Send follow-up instructions to an existing specialist (can update specialization)\n\u2022 check-status - Check if a specialist is busy or idle\n\u2022 list - List specialist sessions with specializations\n\u2022 abort - Cancel a stuck specialist",schema:r.SpecialistOpsSchema,annotations:{title:"Specialist Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSpecialistOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5802(module){module.exports=require("@modelcontextprotocol/sdk/server/stdio.js")},5806(e,exports,t){function r(){const e=n.z.object({requestId:n.z.string(),summary:n.z.string(),acceptanceEvidence:n.z.array(n.z.object({evidence:n.z.string()}))}),t=n.z.object({testRecords:n.z.array(n.z.string()),coverage:n.z.object({criteriaTestedCount:n.z.number(),totalTestCases:n.z.number()}),criterionCoverage:n.z.array(n.z.object({coverage:n.z.enum(["none","partial","full"]),testRecords:n.z.array(n.z.string())}))})
3109
3093
  return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
@@ -3137,9 +3121,9 @@ i.info("Initial branch context",{initialBranch:P.branch,initialRequestId:P.reque
3137
3121
  const x=[]
3138
3122
  for(const e of T){const{normalizedPath:r,fullPath:n}=l.validateAndNormalizePath(e.target,t)
3139
3123
  x.push({normalized:r,full:n})}k=l.FileOperationPhase.TASK_VALIDATION,o.incrementCounter("delete_files_phase",1,{phase:k})
3140
- const O=x.length>0?x[0].normalized:"document_operations",j=await l.validateTaskId(C,O,n,i,o,b.metricsPrefix),$=j?.requestId,A=await l.validateWorkItemStates(C,O,n,I,t,i,o,b.metricsPrefix),D=await l.autoPromoteTaskStatus(C,j.status,$,A.request?.status,O,n,I,i,o,b.metricsPrefix)
3141
- D.taskPromoted&&i.info(`Auto-promoted task ${C} (${j.title||"Untitled"}) to in_progress for mixed operations`,{taskId:C,taskTitle:j.title,previousStatus:j.status,newStatus:D.newTaskStatus,totalOperations:S.length,fileOperations:T.length,documentOperations:M.length}),D.requestPromoted&&i.info(`Auto-promoted request ${$} to in_progress for file operations`,{requestId:$,previousStatus:A.request?.status,newStatus:D.newRequestStatus,triggeringTaskId:C})
3142
- const F=await l.ensureCorrectWorkspaceContext({taskPromoted:D.taskPromoted,requestId:$,context:t,operation:"delete-files",logger:i,metrics:o,metricsPrefix:b.metricsPrefix})
3124
+ const O=x.length>0?x[0].normalized:"document_operations",j=await l.validateTaskId(C,O,n,i,o,b.metricsPrefix),$=j?.requestId,D=await l.validateWorkItemStates(C,O,n,I,t,i,o,b.metricsPrefix),A=await l.autoPromoteTaskStatus(C,j.status,$,D.request?.status,O,n,I,i,o,b.metricsPrefix)
3125
+ A.taskPromoted&&i.info(`Auto-promoted task ${C} (${j.title||"Untitled"}) to in_progress for mixed operations`,{taskId:C,taskTitle:j.title,previousStatus:j.status,newStatus:A.newTaskStatus,totalOperations:S.length,fileOperations:T.length,documentOperations:M.length}),A.requestPromoted&&i.info(`Auto-promoted request ${$} to in_progress for file operations`,{requestId:$,previousStatus:D.request?.status,newStatus:A.newRequestStatus,triggeringTaskId:C})
3126
+ const F=await l.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:$,context:t,operation:"delete-files",logger:i,metrics:o,metricsPrefix:b.metricsPrefix})
3143
3127
  if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
3144
3128
  throw Error(F.error)}let N={hadUserMods:!1,userModsCommitHash:void 0}
3145
3129
  if(t.git)try{i.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
@@ -3152,14 +3136,14 @@ let H=0
3152
3136
  M.length>0&&r.setProjectId(t.projectId)
3153
3137
  for(let e=0;e<x.length;e++){const t=x[e],r={type:"file",path:t.normalized,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
3154
3138
  try{try{await a.default.access(t.full)}catch(e){throw Error("File not found: "+t.normalized)}if((await a.default.stat(t.full)).isDirectory())throw Error("Cannot 'delete' a directory: "+t.normalized)
3155
- await a.default.unlink(t.full),r.success=!0,H++,i.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,f.getErrorMessage)(e),i.warn("Failed to delete file "+t.normalized,{error:r.error})}B.push(r)}const U=M.length>0?r.getDocumentClient():null
3139
+ await a.default.unlink(t.full),r.success=!0,H++,i.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,p.getErrorMessage)(e),i.warn("Failed to delete file "+t.normalized,{error:r.error})}B.push(r)}const W=M.length>0?r.getDocumentClient():null
3156
3140
  for(const e of M){const t=e.target,n={type:"document",documentId:t,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
3157
3141
  try{let e
3158
- try{if(e=await U.getDocument(t),n.filename=e.filename,i.info("Document found for archival",{documentId:e.id,filename:e.filename,type:e.type,requestId:e.requestId}),e.requestId)try{await(0,g.validateRequestStatusForDocumentOperation)(e.requestId,I,i,o,"delete-document")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3159
- throw e}try{await(0,p.ensureDocumentNotLocked)(t,r,i,o,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3160
- throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,f.getErrorMessage)(e)}`)}const s=await U.archiveDocument(t)
3161
- n.success=!0,n.filename=s.filename,H++,i.info("Document archived successfully",{documentId:s.id,filename:s.filename,archivedAt:s.archived_at})}catch(e){n.error=(0,f.getErrorMessage)(e),i.warn("Failed to delete document "+t,{error:n.error})}B.push(n)}const W=Date.now()-m
3162
- o.recordValue("delete_files_time",W),o.incrementCounter("delete_files_operations_total",R),o.incrementCounter("delete_files_operations_success",H),o.incrementCounter("delete_files_operations_failed",R-H),o.incrementCounter("delete_files_file_operations",T.length),o.incrementCounter("delete_files_document_operations",M.length),H===R?o.incrementCounter("delete_files_success",1):H>0?o.incrementCounter("delete_files_partial_success",1):o.incrementCounter("delete_files_total_failure",1)
3142
+ try{if(e=await W.getDocument(t),n.filename=e.filename,i.info("Document found for archival",{documentId:e.id,filename:e.filename,type:e.type,requestId:e.requestId}),e.requestId)try{await(0,g.validateRequestStatusForDocumentOperation)(e.requestId,I,i,o,"delete-document")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3143
+ throw e}try{await(0,f.ensureDocumentNotLocked)(t,r,i,o,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3144
+ throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,p.getErrorMessage)(e)}`)}const s=await W.archiveDocument(t)
3145
+ n.success=!0,n.filename=s.filename,H++,i.info("Document archived successfully",{documentId:s.id,filename:s.filename,archivedAt:s.archived_at})}catch(e){n.error=(0,p.getErrorMessage)(e),i.warn("Failed to delete document "+t,{error:n.error})}B.push(n)}const U=Date.now()-m
3146
+ o.recordValue("delete_files_time",U),o.incrementCounter("delete_files_operations_total",R),o.incrementCounter("delete_files_operations_success",H),o.incrementCounter("delete_files_operations_failed",R-H),o.incrementCounter("delete_files_file_operations",T.length),o.incrementCounter("delete_files_document_operations",M.length),H===R?o.incrementCounter("delete_files_success",1):H>0?o.incrementCounter("delete_files_partial_success",1):o.incrementCounter("delete_files_total_failure",1)
3163
3147
  let G=null
3164
3148
  if(H>0){k=l.FileOperationPhase.GIT_COMMIT,o.incrementCounter("delete_files_phase",1,{phase:k})
3165
3149
  const e=B.filter((e=>e.success)),r=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
@@ -3174,11 +3158,11 @@ Y=e>0&&t>0?`Successfully deleted ${e} files and ${t} documents`:e>0?`Successfull
3174
3158
  return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations failed:\n"+B.map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
3175
3159
  return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
3176
3160
  return G?.commitHash&&(Y+="\nCommit: "+G.commitHash.substring(0,8)),K.requestId&&(Y+="\nBranch: "+K.requestId),F.lockAcquired&&F.lockedRequestId&&(Y+="\n\u{1f512} **Locked request:** "+F.lockedRequestId),{content:[{type:"text",text:Y}],isError:0===H}}catch(n){if(e.taskId&&r)try{const o=r.getToolRecordClient(),s=n instanceof d.NotFoundError||n instanceof d.ValidationError||n instanceof u.ZodError
3177
- await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:t.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,f.getErrorMessage)(n),errorDetails:n instanceof Error?n.stack:n+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,f.getErrorMessage)(n)})}catch(t){i.error("Failed to create failure record for delete-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0})}const s=Date.now()-m
3178
- if(o.recordValue("delete_files_time",s),o.incrementCounter("delete_files_errors",1),i.error("Error in delete-files operation:",{error:(0,f.getErrorMessage)(n),time:s}),(y||w)&&e.taskId){k=l.FileOperationPhase.RECORD_UPDATE_FAILURE
3161
+ await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:t.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,p.getErrorMessage)(n),errorDetails:n instanceof Error?n.stack:n+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,p.getErrorMessage)(n)})}catch(t){i.error("Failed to create failure record for delete-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0})}const s=Date.now()-m
3162
+ if(o.recordValue("delete_files_time",s),o.incrementCounter("delete_files_errors",1),i.error("Error in delete-files operation:",{error:(0,p.getErrorMessage)(n),time:s}),(y||w)&&e.taskId){k=l.FileOperationPhase.RECORD_UPDATE_FAILURE
3179
3163
  try{const t=r.getTaskClient(),s=r.getToolRecordClient()
3180
- await l.updateFileOperationRecords(e.taskId,y,w,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,f.getErrorMessage)(n),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment},"Failed to delete operations",t,s,i,o,b.metricsPrefix)}catch(t){i.error("Failed to update record with failure status",{taskId:e.taskId,recordId:y,error:t instanceof Error?t.message:t+""})}}return l.handleFileOperationError(n,k,i,o,e,b)}}
3181
- const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),p=t(9949),f=t(8824)},5997(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3164
+ await l.updateFileOperationRecords(e.taskId,y,w,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,p.getErrorMessage)(n),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment},"Failed to delete operations",t,s,i,o,b.metricsPrefix)}catch(t){i.error("Failed to update record with failure status",{taskId:e.taskId,recordId:y,error:t instanceof Error?t.message:t+""})}}return l.handleFileOperationError(n,k,i,o,e,b)}}
3165
+ const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),f=t(9949),p=t(8824)},5997(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3182
3166
  var o=Object.getOwnPropertyDescriptor(t,r)
3183
3167
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
3184
3168
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -3237,21 +3221,19 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
3237
3221
  if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
3238
3222
  const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
3239
3223
  return this.logger.info("Successfully recovered file "+e.path,{path:o.path,commitHash:o.commitHash,backupPath:o.backupPath}),o}catch(t){throw this.logger.error("Failed to recover file "+e.path,{path:e.path,commitHash:e.commitHash,error:t instanceof Error?t.stack:t+""}),t}}}exports.FileOperationsClient=a},6183(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=exports.SwitchToMainBranchSchema=void 0
3240
- const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!!e&&/^tas\d{6}$/.test(e)),{message:"Task ID must match format: tas###### (e.g. tas000001)"}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
3241
- exports.CompletionStatusEnum=r.z.enum(["complete","incomplete","partial"]),exports.TestCoverageTypeEnum=r.z.enum(["unit","e2e","integration","manual"]),exports.RequestTypeEnum=r.z.enum(["feature","bugfix","quick-edit"]),exports.TaskStatusEnum=r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]),exports.RequestStatusEnum=r.z.enum(["open","in_progress","ready_for_review","completed","canceled","reverted","conflicted"]),exports.CriterionStatusEnum=r.z.enum(["unverified","verified"]),exports.EvidenceTypeEnum=r.z.enum(["test","manual","other"]),exports.RecordTypeEnum=r.z.enum(["write","modify","blocker","resolution","discovery","test","delete"]),exports.AcceptanceCriterionSchema=r.z.object({description:r.z.string(),status:r.z.enum(["unverified","verified"]).default("unverified"),evidence:r.z.string().nullable().optional(),evidenceType:r.z.enum(["test","manual","other"]).nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.TestDefinitionSchema=r.z.object({id:r.z.string(),description:r.z.string(),status:exports.CompletionStatusEnum,coverageType:exports.TestCoverageTypeEnum,accepts:r.z.array(r.z.string())}),exports.TestVerificationSchema=r.z.object({criteria:r.z.array(r.z.string()),tests:r.z.array(r.z.string()),coverageType:exports.TestCoverageTypeEnum,coverageRatio:r.z.number(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.ExecutedTestSchema=r.z.object({id:r.z.string(),testId:r.z.string(),status:exports.CompletionStatusEnum,results:r.z.string(),coverage:r.z.array(r.z.string()),executedAt:r.z.string()}),exports.CompleteRequestSchema=r.z.object({status:exports.RequestStatusEnum,acceptanceCriteria:r.z.array(exports.AcceptanceCriterionSchema),testVerification:exports.TestVerificationSchema.optional(),completionSummary:r.z.string().optional()}),exports.CreateRequestSchema=r.z.object({title:r.z.string(),type:r.z.enum(["feature","bugfix"]),description:r.z.string(),acceptanceCriteria:r.z.array(r.z.string()),planDocumentId:r.z.string().optional()}),exports.CreateTaskSchema=r.z.object({requestId:s,title:r.z.string(),description:r.z.string()}),exports.UpdateTaskStatusSchema=r.z.object({taskId:o,status:exports.TaskStatusEnum,note:r.z.string()}),exports.WriteFileSchema=r.z.object({taskId:o,path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional(),comment:r.z.string()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}),exports.ViewAssetSchema=r.z.object({filename:r.z.string().describe("The asset filename (e.g., 01JMXYZ.png)")}),exports.ReadFilesSchema=r.z.object({paths:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),lines:r.z.string().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),encoding:r.z.enum(["utf8","utf-8","ascii","binary"]).optional()}),exports.ListDirectorySchema=r.z.object({path:r.z.string(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}),exports.GetFileInfoSchema=r.z.object({path:r.z.string()}),exports.CreateDirectorySchema=r.z.object({path:r.z.string(),taskId:o,comment:r.z.string().optional()}),exports.MoveFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()})),comment:r.z.string()}),exports.ReplaceStringSchema=r.z.object({taskId:o,path:r.z.string(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional(),comment:r.z.string()}),exports.ReplaceStringsSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceInFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1,"old string cannot be empty"),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1,"At least one replacement required"),fuzzy_match:r.z.boolean().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"Either path or documentId is required, but not both"})).min(1,"At least one operation required"),fuzzy_match:r.z.boolean().optional().default(!0),comment:r.z.string()}),exports.ReplaceInFileSchema=exports.ReplaceInFilesSchema,exports.DeleteFileSchema=r.z.object({taskId:o,path:r.z.string(),comment:r.z.string()}),exports.DeleteFilesSchema=r.z.object({taskId:o,paths:r.z.array(r.z.string()).optional(),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})).optional(),comment:r.z.string()}).refine((e=>e.paths&&!e.operations||!e.paths&&e.operations),{message:"paths or operations required"}).refine((e=>e.paths?.length||e.operations?.length),{message:"path/operation required"}),exports.FileHistorySchema=r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}),exports.FileRecoverSchema=r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string(),createBackup:r.z.boolean().default(!0)}),exports.QueryHistorySchema=r.z.object({queryType:r.z.enum(["file-history","request-file-history","recover","blame"],{errorMap(){return{message:"Invalid queryType. Valid options: file-history, request-file-history, recover, blame"}}}),fileHistory:r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}).optional(),requestHistory:r.z.object({requestId:s,detailLevel:r.z.enum(["summary","detailed"]).default("summary"),taskId:o.optional(),showDiff:r.z.boolean().optional(),fileFilter:r.z.string().optional()}).optional(),recover:r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string().optional(),createBackup:r.z.boolean().default(!0)}).optional(),blame:r.z.object({path:r.z.string(),lines:r.z.string().optional(),branch:r.z.string().optional()}).optional()}).refine((e=>"file-history"===e.queryType?e.fileHistory&&!e.requestHistory&&!e.recover:"request-file-history"===e.queryType?e.requestHistory&&!e.fileHistory&&!e.recover:"recover"===e.queryType?e.recover&&!e.fileHistory&&!e.requestHistory&&!e.blame:"blame"===e.queryType&&e.blame&&!e.fileHistory&&!e.requestHistory&&!e.recover),{message:"Invalid query data"}),exports.SearchSchema=r.z.object({needle:r.z.string().optional(),directory:r.z.string().optional(),options:r.z.object({caseSensitive:r.z.boolean().optional(),fileExtension:r.z.string().optional(),maxResults:r.z.number().optional(),useRegex:r.z.boolean().optional(),searchIn:r.z.enum(["content","filename","both"]).default("content").optional(),contextLines:r.z.number().min(0).max(10).optional(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}).optional()}),exports.ListTasksSchema=r.z.object({requestId:s,filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.ListRequestsSchema=r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["open","in_progress","ready_for_review","completed","canceled"]).optional(),planDocumentId:r.z.string().optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.GetRequestInformationSchema=r.z.object({requestId:s}),exports.GetTaskInformationSchema=r.z.object({taskId:o}),exports.CompleteTaskSchema=r.z.object({taskId:o,summary:r.z.string()}),exports.TaskOperationsSchema=r.z.object({taskId:o.optional(),requestId:s.optional(),operation:r.z.enum(["get-info","list"]),create:r.z.object({title:r.z.string(),description:r.z.string()}).optional(),complete:r.z.object({summary:r.z.string()}).optional(),list:r.z.object({filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional()}).refine((e=>{const t=!!e.list,r=!!e.taskId,n=!!e.requestId
3242
- return"get-info"===e.operation?!t&&r&&!n:"list"===e.operation&&!r&&n}),{message:"Invalid operation data"})
3224
+ const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!!e&&/^tas\d{6}$/.test(e)),{message:"Task ID must match format: tas###### (e.g. tas000001). If you don't have a task yet, create one first using task_operations with operation 'create'."}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
3225
+ exports.CompletionStatusEnum=r.z.enum(["complete","incomplete","partial"]),exports.TestCoverageTypeEnum=r.z.enum(["unit","e2e","integration","manual"]),exports.RequestTypeEnum=r.z.enum(["feature","bugfix","quick-edit"]),exports.TaskStatusEnum=r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]),exports.RequestStatusEnum=r.z.enum(["open","in_progress","ready_for_review","ready_for_merge","completed","canceled","reverted","conflicted"]),exports.CriterionStatusEnum=r.z.enum(["unverified","verified"]),exports.EvidenceTypeEnum=r.z.enum(["test","manual","other"]),exports.RecordTypeEnum=r.z.enum(["write","modify","blocker","resolution","discovery","test","delete"]),exports.AcceptanceCriterionSchema=r.z.object({description:r.z.string(),status:r.z.enum(["unverified","verified"]).default("unverified"),evidence:r.z.string().nullable().optional(),evidenceType:r.z.enum(["test","manual","other"]).nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.TestDefinitionSchema=r.z.object({id:r.z.string(),description:r.z.string(),status:exports.CompletionStatusEnum,coverageType:exports.TestCoverageTypeEnum,accepts:r.z.array(r.z.string())}),exports.TestVerificationSchema=r.z.object({criteria:r.z.array(r.z.string()),tests:r.z.array(r.z.string()),coverageType:exports.TestCoverageTypeEnum,coverageRatio:r.z.number(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.ExecutedTestSchema=r.z.object({id:r.z.string(),testId:r.z.string(),status:exports.CompletionStatusEnum,results:r.z.string(),coverage:r.z.array(r.z.string()),executedAt:r.z.string()}),exports.CompleteRequestSchema=r.z.object({status:exports.RequestStatusEnum,acceptanceCriteria:r.z.array(exports.AcceptanceCriterionSchema),testVerification:exports.TestVerificationSchema.optional(),completionSummary:r.z.string().optional()}),exports.CreateRequestSchema=r.z.object({title:r.z.string(),type:r.z.enum(["feature","bugfix"]),description:r.z.string(),acceptanceCriteria:r.z.array(r.z.string()),planDocumentId:r.z.string().optional()}),exports.CreateTaskSchema=r.z.object({requestId:s,title:r.z.string(),description:r.z.string()}),exports.UpdateTaskStatusSchema=r.z.object({taskId:o,status:exports.TaskStatusEnum,note:r.z.string()}),exports.WriteFileSchema=r.z.object({taskId:o,path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional(),comment:r.z.string()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}),exports.ViewAssetSchema=r.z.object({filename:r.z.string().describe("The asset filename (e.g., 01JMXYZ.png)")}),exports.ReadFilesSchema=r.z.object({paths:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),lines:r.z.string().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),encoding:r.z.enum(["utf8","utf-8","ascii","binary"]).optional()}),exports.ListDirectorySchema=r.z.object({path:r.z.string(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}),exports.GetFileInfoSchema=r.z.object({path:r.z.string()}),exports.CreateDirectorySchema=r.z.object({path:r.z.string(),taskId:o,comment:r.z.string().optional()}),exports.MoveFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()})),comment:r.z.string()}),exports.ReplaceStringSchema=r.z.object({taskId:o,path:r.z.string(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional(),comment:r.z.string()}),exports.ReplaceStringsSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceInFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1,"old string cannot be empty"),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1,"At least one replacement required"),fuzzy_match:r.z.boolean().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"Either path or documentId is required, but not both"})).min(1,"At least one operation required"),fuzzy_match:r.z.boolean().optional().default(!0),comment:r.z.string()}),exports.ReplaceInFileSchema=exports.ReplaceInFilesSchema,exports.DeleteFileSchema=r.z.object({taskId:o,path:r.z.string(),comment:r.z.string()}),exports.DeleteFilesSchema=r.z.object({taskId:o,paths:r.z.array(r.z.string()).optional(),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})).optional(),comment:r.z.string()}).refine((e=>e.paths&&!e.operations||!e.paths&&e.operations),{message:"paths or operations required"}).refine((e=>e.paths?.length||e.operations?.length),{message:"path/operation required"}),exports.FileHistorySchema=r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}),exports.FileRecoverSchema=r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string(),createBackup:r.z.boolean().default(!0)}),exports.QueryHistorySchema=r.z.object({queryType:r.z.enum(["file-history","request-file-history","recover","blame"],{errorMap(){return{message:"Invalid queryType. Valid options: file-history, request-file-history, recover, blame"}}}),fileHistory:r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}).optional(),requestHistory:r.z.object({requestId:s,detailLevel:r.z.enum(["summary","detailed"]).default("summary"),taskId:o.optional(),showDiff:r.z.boolean().optional(),fileFilter:r.z.string().optional()}).optional(),recover:r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string().optional(),createBackup:r.z.boolean().default(!0)}).optional(),blame:r.z.object({path:r.z.string(),lines:r.z.string().optional(),branch:r.z.string().optional()}).optional()}).refine((e=>"file-history"===e.queryType?e.fileHistory&&!e.requestHistory&&!e.recover:"request-file-history"===e.queryType?e.requestHistory&&!e.fileHistory&&!e.recover:"recover"===e.queryType?e.recover&&!e.fileHistory&&!e.requestHistory&&!e.blame:"blame"===e.queryType&&e.blame&&!e.fileHistory&&!e.requestHistory&&!e.recover),{message:"Invalid query data"}),exports.SearchSchema=r.z.object({needle:r.z.string().optional(),directory:r.z.string().optional(),options:r.z.object({caseSensitive:r.z.boolean().optional(),fileExtension:r.z.string().optional(),maxResults:r.z.number().optional(),useRegex:r.z.boolean().optional(),searchIn:r.z.enum(["content","filename","both"]).default("content").optional(),contextLines:r.z.number().min(0).max(10).optional(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}).optional()}),exports.ListTasksSchema=r.z.object({requestId:s,filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.ListRequestsSchema=r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["open","in_progress","ready_for_review","completed","canceled"]).optional(),planDocumentId:r.z.string().optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.GetRequestInformationSchema=r.z.object({requestId:s}),exports.GetTaskInformationSchema=r.z.object({taskId:o}),exports.CompleteTaskSchema=r.z.object({taskId:o,summary:r.z.string()}),exports.TaskOperationsSchema=r.z.object({operation:r.z.enum(["get-info","list"]),taskId:o.optional(),requestId:s.optional(),status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).superRefine(((e,t)=>{"get-info"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for get-info. Example: { "operation": "get-info", "taskId": "tas000001" }'}),"list"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for list. Example: { "operation": "list", "requestId": "req000001" }'})}))
3243
3226
  const a=r.z.string().min(1).describe("OpenCode session ID")
3244
3227
  exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),spawn:r.z.object({agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)"),prompt:r.z.string().min(1).describe("The task/prompt for the subagent to work on"),description:r.z.string().max(60).describe('Brief label for the UI, e.g. "Plan auth refactor" (max 60 chars)'),requestId:r.z.string().regex(/^req\d{6}$/).optional().describe("Optional request ID to associate with the work"),allowParallel:r.z.boolean().default(!1).optional().describe("Allow spawning even if request already has active workers (default: false, will block)"),useExistingSession:r.z.string().optional().describe("Optional existing session ID to send prompt to instead of creating new session")}).optional(),continue:r.z.object({prompt:r.z.string().min(1).describe("New instructions/feedback to send to the subagent")}).optional(),readMessages:r.z.object({limit:r.z.number().min(1).max(50).default(1).describe("Number of recent messages to fetch (default 10, max 50)")}).optional(),listSessions:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show sessions that are currently active/busy"),requestId:r.z.string().optional().describe("Find sessions that worked on a specific request"),limit:r.z.number().min(1).max(100).optional().describe("Only show N most recent sessions"),minTokens:r.z.number().min(0).optional().describe("Only show sessions with at least this many tokens"),maxTokens:r.z.number().min(0).optional().describe("Only show sessions with at most this many tokens"),maxAgeHours:r.z.number().min(0).optional().describe("Only show sessions newer than X hours")}).optional()}).refine((e=>{const t=!!e.sessionId,r=!!e.spawn,n=!!e.continue,o=!!e.readMessages
3245
3228
  return"spawn"===e.operation?r&&!n&&!o:"continue"===e.operation?n&&!r&&!o&&t:"check-status"===e.operation||"abort"===e.operation?!r&&!n&&!o&&t:"read-messages"===e.operation?!r&&!n&&t:"list-sessions"===e.operation&&!(r||n||o||t)}),{message:"Invalid operation data: spawn requires spawn object, continue/check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),delegate:r.z.object({prompt:r.z.string().min(1).describe("Detailed instructions for the specialist"),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars)"),requestId:r.z.string().regex(/^req\d{6}$/).describe("Request ID to associate with the work").optional(),specialization:r.z.string().max(100).describe('Domain description for the specialist (e.g. "Frontend UI components", "Database migrations")')}).optional(),followUp:r.z.object({prompt:r.z.string().min(1).describe("Follow-up instructions or feedback for the specialist"),specialization:r.z.string().max(100).describe("Update the specialist's domain description if their focus has shifted").optional()}).optional(),list:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show active/busy specialists"),requestId:r.z.string().optional().describe("Filter to specialists working on a specific request"),limit:r.z.number().min(1).max(100).optional().describe("Max sessions to return")}).optional()}).refine((e=>{const t=!!e.sessionId,r=!!e.delegate,n=!!e.followUp
3246
3229
  return"delegate"===e.operation?r&&!n&&!t:"follow-up"===e.operation?n&&!r&&t:"check-status"===e.operation||"abort"===e.operation?!r&&!n&&t:"list"===e.operation&&!r&&!n&&!t}),{message:"Invalid operation data: delegate requires delegate object, follow-up/check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),request:r.z.object({prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc."),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars)")}).optional(),sessionId:a.optional(),list:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show active/busy planning sessions"),limit:r.z.number().min(1).max(100).optional().describe("Max sessions to return")}).optional()}).refine((e=>{const t=!!e.request,r=!!e.sessionId
3247
- return"request"===e.operation?t&&!r:"check-status"===e.operation?!t&&r:"list"===e.operation&&!t&&!r}),{message:"Invalid operation data: request requires request object, check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),create:r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}).optional(),search:r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}).optional(),createSnapshot:r.z.object({documentId:i,versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional()}).optional(),getHistory:r.z.object({documentId:i}).optional(),getVersion:r.z.object({documentId:i,versionNumber:r.z.number().int().min(1)}).optional(),restoreVersion:r.z.object({documentId:i,versionNumber:r.z.number().int().min(1)}).optional(),listAnnotations:r.z.object({documentId:i}).optional(),createAnnotation:r.z.object({documentId:i,selectedText:r.z.string().min(1),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().min(1)}).optional(),replyToAnnotation:r.z.object({documentId:i,annotationId:r.z.string().min(1),body:r.z.string().min(1)}).optional(),resolveAnnotation:r.z.object({documentId:i,annotationId:r.z.string().min(1)}).optional()}).refine((e=>"create"===e.operation?e.create&&!e.search&&!e.createSnapshot&&!e.getHistory&&!e.getVersion&&!e.restoreVersion:"search"===e.operation?e.search&&!e.create&&!e.createSnapshot&&!e.getHistory&&!e.getVersion&&!e.restoreVersion:"create-snapshot"===e.operation?e.createSnapshot&&!e.create&&!e.search&&!e.getHistory&&!e.getVersion&&!e.restoreVersion:"get-history"===e.operation?e.getHistory&&!e.create&&!e.search&&!e.createSnapshot&&!e.getVersion&&!e.restoreVersion:"get-version"===e.operation?e.getVersion&&!e.create&&!e.search&&!e.createSnapshot&&!e.getHistory&&!e.restoreVersion:"restore-version"===e.operation?!!e.restoreVersion:"list-annotations"===e.operation?!!e.listAnnotations:"create-annotation"===e.operation?!!e.createAnnotation:"reply-to-annotation"===e.operation?!!e.replyToAnnotation:"resolve-annotation"===e.operation&&!!e.resolveAnnotation),{message:"Invalid operation data"})
3230
+ return"request"===e.operation?t&&!r:"check-status"===e.operation?!t&&r:"list"===e.operation&&!t&&!r}),{message:"Invalid operation data: request requires request object, check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
3248
3231
  const c=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^plan\d{6}$/.test(e))),{message:"Plan ID must match format: doc_[26 alphanumeric] (ULID) or plan###### (local ID)"})
3249
- exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list","get-history","get-requests"]),get:r.z.object({planId:c}).optional(),list:r.z.object({searchQuery:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["createdAt","updatedAt","filename"]).default("updatedAt"),sortDirection:r.z.enum(["ASC","DESC"]).default("DESC")}).optional(),getHistory:r.z.object({planId:c}).optional(),getRequests:r.z.object({planId:c}).optional()}).refine((e=>{const t={get:"get","get-active":null,list:"list","get-history":"getHistory","get-requests":"getRequests"}[e.operation],r=["get","list","getHistory","getRequests"].some((t=>void 0!==e[t]))
3250
- return null===t||"list"===e.operation?!r||"list"===e.operation&&void 0!==e.list:void 0!==e[t]}),{message:"Invalid operation data: ensure the correct sub-object is provided for the chosen operation"}),exports.PlanWriteSchema=r.z.object({operation:r.z.enum(["update","append","replace","create-snapshot","restore","set-active"]),setActive:r.z.object({planId:c}).optional(),update:r.z.object({planId:c,content:r.z.string(),name:r.z.string().optional().describe("Optional new name for the plan (omit to keep current name)")}).optional(),append:r.z.object({planId:c,content:r.z.string().describe("Content to append to the end of the plan"),name:r.z.string().optional().describe("Optional new name for the plan (omit to keep current name)")}).optional(),replace:r.z.object({planId:c,old:r.z.string().min(1).describe("Text to find in the plan"),new:r.z.string().describe("Replacement text"),name:r.z.string().optional().describe("Optional new name for the plan (omit to keep current name)")}).optional(),createSnapshot:r.z.object({planId:c,versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional()}).optional(),restore:r.z.object({planId:c,versionNumber:r.z.number().int().min(1)}).optional()}).refine((e=>{const t={update:"update",append:"append",replace:"replace","create-snapshot":"createSnapshot",restore:"restore","set-active":"setActive"}[e.operation]
3251
- if(!t)return!1
3252
- const r=["create","update","append","replace","createSnapshot","restore","setActive"].filter((e=>e!==t)).some((t=>void 0!==e[t]))
3253
- return void 0!==e[t]&&!r}),{message:"Invalid operation data: ensure the correct sub-object is provided for the chosen operation"}),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),operationType:r.z.enum(["replace-string","insert-lines","replace-lines","delete-string","delete-lines"]),replaceString:r.z.object({replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).optional(),insertLines:r.z.object({insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).optional(),replaceLines:r.z.object({replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).optional(),deleteString:r.z.object({patterns:r.z.array(r.z.string()),mode:r.z.enum(["all","unique"]).optional()}).optional(),deleteLines:r.z.object({lines:r.z.string()}).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}).refine((e=>"replace-string"===e.operationType?e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"insert-lines"===e.operationType?e.insertLines&&!e.replaceString&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"replace-lines"===e.operationType?e.replaceLines&&!e.replaceString&&!e.insertLines&&!e.deleteString&&!e.deleteLines:"delete-string"===e.operationType?e.deleteString&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteLines:"delete-lines"===e.operationType&&e.deleteLines&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString),{message:"Invalid operation data"})),comment:r.z.string()}),exports.ManageFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files","get-file-info"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}))}).optional(),getFileInfo:r.z.object({path:r.z.string()}).optional()}).refine((e=>"create-directory"===e.operationType?e.createDirectory&&!e.moveFiles&&!e.deleteFiles&&!e.getFileInfo:"move-files"===e.operationType?e.moveFiles&&!e.createDirectory&&!e.deleteFiles&&!e.getFileInfo:"delete-files"===e.operationType?e.deleteFiles&&!e.createDirectory&&!e.moveFiles&&!e.getFileInfo:"get-file-info"===e.operationType&&e.getFileInfo&&!e.createDirectory&&!e.moveFiles&&!e.deleteFiles),{message:"Invalid operation data"})),comment:r.z.string()}),exports.RequestOperationsSchema=r.z.object({requestId:s.optional(),operation:r.z.enum(["complete","finalize","approve","revert","get-info","list","search"]),complete:r.z.object({summary:r.z.string(),acceptanceEvidence:r.z.array(r.z.string()),testVerification:r.z.object({testRecords:r.z.array(r.z.string()),coverage:r.z.object({criteriaTestedCount:r.z.number(),totalTestCases:r.z.number()}),criterionCoverage:r.z.array(r.z.object({coverage:r.z.enum(["none","partial","full"]),testRecords:r.z.array(r.z.string())}))}).optional()}).optional(),revert:r.z.object({reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}).optional(),list:r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional(),search:r.z.object({query:r.z.string().min(1),searchIn:r.z.enum(["title","description","criteria","all"]).default("all"),filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0)}).optional()}).optional(),finalize:r.z.object({}).optional(),approve:r.z.object({}).optional()}).refine((e=>{const t=!!e.complete,r=!!e.finalize,n=!!e.approve,o=!!e.revert,s=!!e.list,i=!!e.search,a=!!e.requestId
3254
- return"complete"===e.operation?t&&!r&&!n&&!o&&!s&&!i&&a:"finalize"===e.operation?!t&&!n&&!o&&!s&&!i&&a:"approve"===e.operation?!t&&!r&&!o&&!s&&!i&&a:"revert"===e.operation?o&&!t&&!r&&!n&&!s&&!i&&a:"get-info"===e.operation?!t&&!r&&!n&&!o&&!s&&!i&&a:"list"===e.operation?!(t||r||n||o||i):"search"===e.operation&&i&&!t&&!r&&!n&&!o&&!s}),{message:"Invalid operation data"}),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
3232
+ exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list","get-history","get-requests"]),planId:c.optional(),searchQuery:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["createdAt","updatedAt","filename"]).default("updatedAt"),sortDirection:r.z.enum(["ASC","DESC"]).default("DESC")}).superRefine(((e,t)=>{["get","get-history","get-requests"].includes(e.operation)&&!e.planId&&t.addIssue({code:"custom",message:`planId is required for '${e.operation}'. Example: { "operation": "${e.operation}", "planId": "plan000001" }`})})),exports.PlanWriteSchema=r.z.object({operation:r.z.enum(["update","append","replace","create-snapshot","restore","set-active"]),planId:c,content:r.z.string().optional(),name:r.z.string().optional().describe("Optional new name for the plan"),old:r.z.string().optional().describe("Text to find in the plan (for replace)"),new:r.z.string().optional().describe("Replacement text (for replace)"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional()}).superRefine(((e,t)=>{const r=e.operation
3233
+ "update"!==r&&"append"!==r||e.content||t.addIssue({code:"custom",message:`content is required for '${r}'. Example: { "operation": "${r}", "planId": "plan000001", "content": "..." }`}),"replace"===r&&(e.old||t.addIssue({code:"custom",message:'old is required for replace. Example: { "operation": "replace", "planId": "plan000001", "old": "find this", "new": "replace with" }'}),void 0===e.new&&t.addIssue({code:"custom",message:"new is required for replace"})),"restore"!==r||e.versionNumber||t.addIssue({code:"custom",message:'versionNumber is required for restore. Example: { "operation": "restore", "planId": "plan000001", "versionNumber": 1 }'})})),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),operationType:r.z.enum(["replace-string","insert-lines","replace-lines","delete-string","delete-lines"]),replaceString:r.z.object({replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).optional(),insertLines:r.z.object({insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).optional(),replaceLines:r.z.object({replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).optional(),deleteString:r.z.object({patterns:r.z.array(r.z.string()),mode:r.z.enum(["all","unique"]).optional()}).optional(),deleteLines:r.z.object({lines:r.z.string()}).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}).refine((e=>"replace-string"===e.operationType?e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"insert-lines"===e.operationType?e.insertLines&&!e.replaceString&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"replace-lines"===e.operationType?e.replaceLines&&!e.replaceString&&!e.insertLines&&!e.deleteString&&!e.deleteLines:"delete-string"===e.operationType?e.deleteString&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteLines:"delete-lines"===e.operationType&&e.deleteLines&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString),{message:"Invalid operation data"})),comment:r.z.string()}),exports.ManageFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files","get-file-info"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}))}).optional(),getFileInfo:r.z.object({path:r.z.string()}).optional()}).refine((e=>"create-directory"===e.operationType?e.createDirectory&&!e.moveFiles&&!e.deleteFiles&&!e.getFileInfo:"move-files"===e.operationType?e.moveFiles&&!e.createDirectory&&!e.deleteFiles&&!e.getFileInfo:"delete-files"===e.operationType?e.deleteFiles&&!e.createDirectory&&!e.moveFiles&&!e.getFileInfo:"get-file-info"===e.operationType&&e.getFileInfo&&!e.createDirectory&&!e.moveFiles&&!e.deleteFiles),{message:"Invalid operation data"})),comment:r.z.string()}),exports.RequestOperationsSchema=r.z.object({requestId:s.optional(),operation:r.z.enum(["complete","merge","approve","revert","get-info","list","search"]),complete:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({summary:r.z.string()})).optional(),merge:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({verifications:r.z.array(r.z.object({key:r.z.string().min(2).max(4),evidence:r.z.string().min(1)})).min(1)})).optional(),revert:r.z.object({reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}).optional(),list:r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional(),search:r.z.object({query:r.z.string().min(1),searchIn:r.z.enum(["title","description","criteria","all"]).default("all"),filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0)}).optional()}).optional(),approve:r.z.object({}).optional()}).superRefine(((e,t)=>{const r=!!e.requestId,n=e.operation
3234
+ if(["complete","merge","approve","revert","get-info"].includes(n)&&!r)return void t.addIssue({code:"custom",message:`requestId is required for '${n}' operation`})
3235
+ const o={complete:{field:"complete",hint:'Provide: { complete: { summary: "..." } }'},merge:{field:"merge",hint:'Provide: { merge: { verifications: [{key: "1a", evidence: "..."}] } }'},revert:{field:"revert",hint:'Provide: { revert: { reason: "..." } }'},search:{field:"search",hint:'Provide: { search: { query: "..." } }'}}[n]
3236
+ o&&!e[o.field]&&t.addIssue({code:"custom",message:`'${n}' operation requires '${o.field}' data. ${o.hint}`})})),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
3255
3237
  const l=r.z.object({name:r.z.string().min(1).describe('Command name (e.g., "Build", "Unit Tests")'),command:r.z.string().min(1).describe('Shell command to run (e.g., "npm test")'),required:r.z.boolean().default(!0).describe("If true, failure blocks the request (default: true)"),timeout:r.z.number().int().min(10).max(3600).default(300).describe("Max execution time in seconds (default: 300)")})
3256
3238
  exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"})},6252(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3257
3239
  const r=t(6183),n=t(405)
@@ -3263,13 +3245,13 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
3263
3245
  var t={}
3264
3246
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3265
3247
  return o(t,e),t})
3266
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,f){const m=n.child({tool:"specialist_ops"}),y=o.startTimer("tool_execution_time")
3267
- try{if(!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),"string"==typeof e?.delegate){const t=e.delegate
3248
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const m=n.child({tool:"specialist_ops"}),y=o.startTimer("tool_execution_time")
3249
+ try{if(!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),e?.followUp&&"string"==typeof e.followUp)try{e.followUp=JSON.parse(e.followUp)}catch{}if(e?.delegate&&"string"==typeof e.delegate)try{e.delegate=JSON.parse(e.delegate)}catch{}if("string"==typeof e?.delegate){const t=e.delegate
3268
3250
  e.delegate={prompt:e.prompt||t,description:e.description||t.slice(0,60),specialization:e.specialization||"general",requestId:e.requestId},e.operation=e.operation||"delegate",delete e.prompt,delete e.description,delete e.specialization,delete e.requestId}"follow-up"===e?.operation&&e?.prompt&&!e?.followUp&&(e.followUp={prompt:e.prompt,specialization:e.specialization},delete e.prompt,e.specialization&&delete e.specialization),"delegate"===e?.operation&&e?.prompt&&!e?.delegate&&(e.delegate={prompt:e.prompt,description:e.description||e.prompt.slice(0,60),specialization:e.specialization||"general",requestId:e.requestId},delete e.prompt,delete e.description,delete e.specialization,delete e.requestId)
3269
3251
  const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:w,sessionId:k}=n
3270
3252
  let b
3271
3253
  switch(m.info("Processing specialist_ops",{operation:w,sessionId:k}),w){case"delegate":{const e=n.delegate,o=10
3272
- let i=f?.sessionId||p.sessionIdentity.getIdentity()?.sessionId
3254
+ let i=p?.sessionId||f.sessionIdentity.getIdentity()?.sessionId
3273
3255
  if(!i){const e=await(0,h.getServerUrl)(r,m)
3274
3256
  if(e)try{i=(0,g.getCachedSession)()?.sessionId||await(0,h.discoverParentSessionId)(e,m)}catch{}}if(i&&s){const e=await async function(e,t,r,n,o){n.info("enforcePoolLimit called",{parentSessionId:e,maxPoolSize:t})
3275
3257
  const s=await(0,h.getServerUrl)(r,n)
@@ -3295,23 +3277,23 @@ y(`siblings=${e.length}: ${e.join(", ")}`)
3295
3277
  const r=(0,d.pickSpecialistName)(e)
3296
3278
  a=r,y("picked name: "+r)}}else y("no serverUrl")}catch(e){y("error: "+(e instanceof Error?e.message:e+""))}else y("no parentId")
3297
3279
  const w=e.requestId,k=w?`Working on request ${w}.\n\n${e.prompt}`:e.prompt
3298
- b=await(0,u.handleSpawn)({agent:"specialist",prompt:k,title:a,specialization:e.specialization},r,m,s,f)
3280
+ b=await(0,u.handleSpawn)({agent:"specialist",prompt:k,title:a,specialization:e.specialization},r,m,s,p)
3299
3281
  break}case"follow-up":{const e=await(0,h.getServerUrl)(r,m)
3300
3282
  if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
3301
3283
  if(t.ok){const e=await t.json(),r=e[k]?.type
3302
3284
  if(r&&"idle"!==r&&"prompting"!==r){b={content:[{type:"text",text:`\u274c Specialist ${k} is currently busy (status: ${r}).\nUse \`delegate\` to spawn a new specialist instead.`}],isError:!0}
3303
- break}}}catch{}b=await(0,u.handleContinue)(k,n.followUp.prompt,r,m,s,"specialist",f)
3285
+ break}}}catch{}b=await(0,u.handleContinue)(k,n.followUp.prompt,r,m,s,"specialist",p)
3304
3286
  const t=n.followUp.specialization
3305
3287
  if(t&&s)try{const e=s.getCLISessionClient()
3306
3288
  e&&(await e.createOrUpdateSession({externalSessionId:k,specialization:t}),b.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":b=await(0,u.handleCheckStatus)(k,r,m,s)
3307
3289
  break
3308
3290
  case"abort":if(b=await(0,u.handleAbort)(k,r,m),!b.isError&&s)try{const e=s.getCLISessionClient()
3309
3291
  e&&await e.createOrUpdateSession({externalSessionId:k,status:"archived"})}catch{}break
3310
- case"list":{let e=f?.sessionId||p.sessionIdentity.getIdentity()?.sessionId
3292
+ case"list":{let e=p?.sessionId||f.sessionIdentity.getIdentity()?.sessionId
3311
3293
  if(!e){const t=await(0,h.getServerUrl)(r,m)
3312
3294
  if(t)try{e=(0,g.getCachedSession)()?.sessionId||await(0,h.discoverParentSessionId)(t,m)}catch{}}b=await(0,u.handleListSessions)(r,m,s,{activeOnly:n.list?.activeOnly,requestId:n.list?.requestId,limit:n.list?.limit,agentType:"specialist",parentSessionId:e})
3313
3295
  break}default:throw new i.ValidationError("Unknown operation: "+w)}return y({success:!0}),o.incrementCounter(`specialist_ops_${w}_success`,1),b}catch(e){return m.error("Specialist ops failed",{error:e instanceof Error?e.stack:e+""}),y({success:!1}),o.incrementCounter("specialist_ops_errors",1),{content:[{type:"text",text:"Specialist operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
3314
- const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(9089),u=t(1725),h=t(7617),g=t(715),p=t(6688)},6315(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3296
+ const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(9089),u=t(1725),h=t(7617),g=t(715),f=t(6688)},6315(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3315
3297
  const r=t(6183),n=t(2982)
3316
3298
  exports.def={name:"generate_request_journal",description:"Fetch comprehensive data about a request for writing a journal entry.\n\nReturns structured data including:\n\u2022 Request details (title, description, type, status, acceptance criteria)\n\u2022 All tasks with descriptions and status\n\u2022 File changes summary (files modified, operations performed)\n\u2022 Chronological operation history\n\nUse this data to write a narrative journal entry and save it as:\nJOURNAL-{requestId}.md using document-operations (create).",schema:r.GenerateRequestJournalSchema,annotations:{title:"Generate Request Journal",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0},readOnly:!0,hidden(){return"journal"!==process.env.ALCHEMY_MODE},handler(e,t){return(0,n.handleGenerateRequestJournal)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},6416(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3317
3299
  var o=Object.getOwnPropertyDescriptor(t,r)
@@ -3322,17 +3304,17 @@ var t={}
3322
3304
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3323
3305
  return o(t,e),t})
3324
3306
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRevertRequest=async function(e,t,r,n,o){const s=n.child({tool:"revert_request"}),h=o.startTimer("tool_execution_time")
3325
- try{const n=i.RevertRequestSchema.parse(e),{requestId:d,reason:g,confirmDestructive:p}=n
3326
- if(s.info("Starting revert/cancel process",{requestId:d,reason:g}),!p)return h({success:!1,reason:"confirmation_required"}),{content:[{type:"text",text:"Error: This operation requires confirmation. Set confirmDestructive: true to proceed.\n\nThis tool will:\n- **For open/in_progress requests:** Cancel the request (no git changes)\n- **For completed requests:** Revert using git (affects git history)\n\nBoth operations make the request read-only and block further tool use."}],isError:!0}
3327
- let f
3307
+ try{const n=i.RevertRequestSchema.parse(e),{requestId:d,reason:g,confirmDestructive:f}=n
3308
+ if(s.info("Starting revert/cancel process",{requestId:d,reason:g}),!f)return h({success:!1,reason:"confirmation_required"}),{content:[{type:"text",text:"Error: This operation requires confirmation. Set confirmDestructive: true to proceed.\n\nThis tool will:\n- **For open/in_progress requests:** Cancel the request (no git changes)\n- **For completed requests:** Revert using git (affects git history)\n\nBoth operations make the request read-only and block further tool use."}],isError:!0}
3309
+ let p
3328
3310
  try{const e=await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/validate-revert`,{})
3329
- f=e?.data||e}catch(e){const t=(0,u.getErrorMessage)(e)
3330
- return s.error("Server validation failed",{requestId:d,error:t}),h({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate revert: "+t}],isError:!0}}if(s.info("Server validation result",{requestId:d,canRevert:f.canRevert,operationType:f.operationType,mergeCommitHash:f.mergeCommitHash?.substring(0,8),reason:f.reason}),!f.canRevert){let e=`Cannot revert request ${d}: ${f.reason}\n`
3331
- return f.lifoViolation?.blockingRequests?.length&&(e+="\n**Requests that must be reverted first (in reverse order):**\n",f.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (${t.status})\n`})),e+="\n**Why:** Requests must be reverted in reverse order (LIFO) to maintain safe git history.\n",e+="Revert the above request(s) first, then retry this one."),h({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if("cancel"===f.operationType){s.info("Cancel operation \u2014 delegating to server",{requestId:d})
3332
- try{return await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/finalize-revert`,{reason:g,operationType:"cancel"}),h({success:!0}),{content:[{type:"text",text:`Successfully canceled request ${d}.\n\nOperation: Cancel (no git changes)\nTasks updated: ${f.tasksToUpdate.length} task(s) marked as canceled\nReason: ${g}`}]}}catch(e){const t=(0,u.getErrorMessage)(e)
3311
+ p=e?.data||e}catch(e){const t=(0,u.getErrorMessage)(e)
3312
+ return s.error("Server validation failed",{requestId:d,error:t}),h({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate revert: "+t}],isError:!0}}if(s.info("Server validation result",{requestId:d,canRevert:p.canRevert,operationType:p.operationType,mergeCommitHash:p.mergeCommitHash?.substring(0,8),reason:p.reason}),!p.canRevert){let e=`Cannot revert request ${d}: ${p.reason}\n`
3313
+ return p.lifoViolation?.blockingRequests?.length&&(e+="\n**Requests that must be reverted first (in reverse order):**\n",p.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (${t.status})\n`})),e+="\n**Why:** Requests must be reverted in reverse order (LIFO) to maintain safe git history.\n",e+="Revert the above request(s) first, then retry this one."),h({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if("cancel"===p.operationType){s.info("Cancel operation \u2014 delegating to server",{requestId:d})
3314
+ try{return await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/finalize-revert`,{reason:g,operationType:"cancel"}),h({success:!0}),{content:[{type:"text",text:`Successfully canceled request ${d}.\n\nOperation: Cancel (no git changes)\nTasks updated: ${p.tasksToUpdate.length} task(s) marked as canceled\nReason: ${g}`}]}}catch(e){const t=(0,u.getErrorMessage)(e)
3333
3315
  return h({success:!1,error:"cancel_finalization_failed"}),{content:[{type:"text",text:"Failed to cancel request: "+t}],isError:!0}}}if(s.info("Revert operation \u2014 performing git revert",{requestId:d}),!t.git)throw(0,a.createServiceError)("Git repository not available for revert",{requestId:d})
3334
3316
  t.syncBranchState&&await t.syncBranchState()
3335
- let m=f.mergeCommitHash
3317
+ let m=p.mergeCommitHash
3336
3318
  if(!m){s.info("No merge commit hash from server, searching git log",{requestId:d})
3337
3319
  const e=await async function(e,t,r){try{const r=t.workspaceManager.getMainGit(),n=await r.raw(["log","--merges","--format=%H %s","HEAD"]),o=n.trim()?n.trim().split("\n").map((e=>{const t=e.indexOf(" ")
3338
3320
  return-1===t?{hash:e,message:""}:{hash:e.substring(0,t),message:e.substring(t+1)}})):[],s=c.generateMergeMessagePatterns(e)
@@ -3348,7 +3330,7 @@ try{s.info("Executing git revert",{mergeCommitHash:m.substring(0,8)}),await y.ra
3348
3330
  const e=await(0,l.verifyGitStateConsistency)(y,k,s,`revert-request-${d}-verification`)
3349
3331
  e.consistent||s.error("Git state inconsistency after revert",{issues:e.issues}),s.info("Git revert completed",{requestId:d,originalMergeCommit:m.substring(0,8),revertCommitHash:k.substring(0,8)})}catch(e){const t=(0,u.getErrorMessage)(e)
3350
3332
  return s.error("Git revert failed",{requestId:d,error:t}),h({success:!1,error:"git_revert_failed"}),{content:[{type:"text",text:"Git revert failed: "+t}],isError:!0}}try{await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/finalize-revert`,{reason:g,operationType:"revert",revertCommitHash:k,originalMergeCommitHash:m})}catch(e){const t=(0,u.getErrorMessage)(e)
3351
- return s.error("CRITICAL: Git revert succeeded but server finalization failed",{requestId:d,revertCommitHash:k,error:t}),h({success:!1,error:"finalization_failed"}),{content:[{type:"text",text:`CRITICAL: Git revert succeeded (commit: ${k.substring(0,8)}) but failed to update server state: ${t}`}],isError:!0}}return h({success:!0}),{content:[{type:"text",text:`Successfully reverted request ${d}.\n\nOperation: Revert (git revert of merge commit)\nTasks updated: ${f.tasksToUpdate.length} task(s) marked as reverted\nReason: ${g}\n\nYou can re-complete the request if the revert was a mistake.`}]}}catch(n){if(n instanceof a.ValidationError||n instanceof a.NotFoundError)return s.warn("Revert validation failed",{error:n.message,requestId:e.requestId}),h({success:!1,error:"validation"}),{content:[{type:"text",text:"Error: "+n.message}],isError:!0}
3333
+ return s.error("CRITICAL: Git revert succeeded but server finalization failed",{requestId:d,revertCommitHash:k,error:t}),h({success:!1,error:"finalization_failed"}),{content:[{type:"text",text:`CRITICAL: Git revert succeeded (commit: ${k.substring(0,8)}) but failed to update server state: ${t}`}],isError:!0}}return h({success:!0}),{content:[{type:"text",text:`Successfully reverted request ${d}.\n\nOperation: Revert (git revert of merge commit)\nTasks updated: ${p.tasksToUpdate.length} task(s) marked as reverted\nReason: ${g}\n\nYou can re-complete the request if the revert was a mistake.`}]}}catch(n){if(n instanceof a.ValidationError||n instanceof a.NotFoundError)return s.warn("Revert validation failed",{error:n.message,requestId:e.requestId}),h({success:!1,error:"validation"}),{content:[{type:"text",text:"Error: "+n.message}],isError:!0}
3352
3334
  if(n instanceof d.ZodError)return h({success:!1,error:"zod_validation"}),{content:[{type:"text",text:"Validation error: "+n.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}],isError:!0}
3353
3335
  if(t.projectId&&e.requestId)try{const o=r.getToolRecordClient()
3354
3336
  await o.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"revert-request",metadata:{status:"failed",timestamp:(new Date).toISOString(),reason:e.reason,error:(0,u.getErrorMessage)(n)},note:"Failed to revert request: "+(0,u.getErrorMessage)(n)})}catch{}return s.error("Revert request failed",{error:(0,u.getErrorMessage)(n),requestId:e.requestId}),h({success:!1,error:n instanceof Error?n.name:"unknown"}),{content:[{type:"text",text:"Failed to revert request: "+(0,u.getErrorMessage)(n)}],isError:!0}}}
@@ -3369,7 +3351,7 @@ break
3369
3351
  case"between":if(void 0===e.afterLine||void 0===e.beforeLine)throw Error("Both afterLine and beforeLine are required for between insertion")
3370
3352
  n=(0,m.insertBetweenLines)(r,e.afterLine,e.beforeLine,e.content)
3371
3353
  break
3372
- default:throw Error("Unknown insertion type: "+e.type)}r=n.newContent,t.success=!0,t.linesAdded=n.linesAdded,t.insertionPoint=n.insertionPoint,o+=n.linesAdded}catch(e){t.error=(0,f.getErrorMessage)(e)}n.push(t)}return{newContent:r,results:n}}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3354
+ default:throw Error("Unknown insertion type: "+e.type)}r=n.newContent,t.success=!0,t.linesAdded=n.linesAdded,t.insertionPoint=n.insertionPoint,o+=n.linesAdded}catch(e){t.error=(0,p.getErrorMessage)(e)}n.push(t)}return{newContent:r,results:n}}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3373
3355
  var o=Object.getOwnPropertyDescriptor(t,r)
3374
3356
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[]
3375
3357
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -3390,7 +3372,7 @@ T.push({type:"file",path:r,fullPath:n,insertions:e.insertions})}const M=[]
3390
3372
  if(S.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
3391
3373
  for(const e of S)M.push({type:"document",documentId:e.documentId,insertions:e.insertions})
3392
3374
  if(M.length>0&&t.apiClient){const e=M.map((e=>e.documentId))
3393
- try{await(0,p.ensureDocumentsNotLocked)(e,t.apiClient,y,a,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3375
+ try{await(0,f.ensureDocumentsNotLocked)(e,t.apiClient,y,a,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3394
3376
  throw e}}I=d.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("insert_lines_phase",1,{phase:I})
3395
3377
  const R=T.length>0?T[0].path:"document-operation",P=await d.validateTaskId(C,R,n,y,a,v.metricsPrefix),x=P?.requestId
3396
3378
  let O=null
@@ -3403,8 +3385,8 @@ throw Error($.error)}if(T.length>0){y.debug("Re-validating file paths with corre
3403
3385
  for(let e=0;e<T.length;e++){const r=T[e],n=q[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(n.path,t)
3404
3386
  T[e]={...r,path:o,fullPath:s}}}if(M.length>0&&x)try{await(0,h.validateRequestStatusForDocumentOperation)(x,s,y,a,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3405
3387
  throw e}I=d.FileOperationPhase.RECORD_CREATION,a.incrementCounter("insert_lines_phase",1,{phase:I})
3406
- const A=[...T.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...M.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:D}=await d.createFileOperationRecords(C,x,t.projectId,v.recordType,R,{operationCount:_.length,fileOperations:T.length,documentOperations:M.length,operations:A,userComment:E},n,o,y,a,v.metricsPrefix,m)
3407
- if(k=D,b=D,I=v.fileOperationPhase,a.incrementCounter("insert_lines_phase",1,{phase:I}),T.length>0&&t.git)try{y.debug("[INSERT-LINES] Checking for user changes before insert operations")
3388
+ const D=[...T.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...M.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:A}=await d.createFileOperationRecords(C,x,t.projectId,v.recordType,R,{operationCount:_.length,fileOperations:T.length,documentOperations:M.length,operations:D,userComment:E},n,o,y,a,v.metricsPrefix,m)
3389
+ if(k=A,b=A,I=v.fileOperationPhase,a.incrementCounter("insert_lines_phase",1,{phase:I}),T.length>0&&t.git)try{y.debug("[INSERT-LINES] Checking for user changes before insert operations")
3408
3390
  const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"insert-lines",{requestId:x,taskId:C,workspaceManager:t.workspaceManager},y,a)
3409
3391
  e.userChangesCommitted&&(y.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before insert-lines operation",{taskId:C,fileOperationsCount:T.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){y.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:C,fileOperationsCount:T.length,error:e instanceof Error?e.message:e+""})}y.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:T.length})
3410
3392
  const F=[]
@@ -3412,31 +3394,31 @@ let N=0,L=0,z=0
3412
3394
  for(const e of T){const t={type:"file",path:e.path,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3413
3395
  try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
3414
3396
  const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.insertions)
3415
- t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,z++,y.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),N+=t.failedInsertions,L+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,N+=t.failedInsertions,y.error("File operation failed",{path:e.path,error:t.error})}F.push(t)}for(const e of M){const n={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3397
+ t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,z++,y.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),N+=t.failedInsertions,L+=t.totalLinesAdded}catch(r){t.error=(0,p.getErrorMessage)(r),t.failedInsertions=e.insertions.length,N+=t.failedInsertions,y.error("File operation failed",{path:e.path,error:t.error})}F.push(t)}for(const e of M){const n={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3416
3398
  try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
3417
3399
  n.filename=s?.filename
3418
3400
  const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
3419
- n.insertions=l,n.successfulInsertions=l.filter((e=>e.success)).length,n.failedInsertions=l.filter((e=>!e.success)).length,n.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&n.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),n.success=!0,z++,y.info("Document updated successfully",{documentId:e.documentId,filename:n.filename,successfulInsertions:n.successfulInsertions,failedInsertions:n.failedInsertions,linesAdded:n.totalLinesAdded})):0===n.failedInsertions&&(n.success=!0),N+=n.failedInsertions,L+=n.totalLinesAdded}catch(t){n.error=(0,f.getErrorMessage)(t),n.failedInsertions=e.insertions.length,N+=n.failedInsertions,y.error("Document operation failed",{documentId:e.documentId,error:n.error})}F.push(n)}if(M.length>0)try{for(const e of M){const r=F.find((t=>t.documentId===e.documentId))
3420
- r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const B=await d.handleMultiFileGitCommit(C,T,F,z,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:y,metrics:a,metricsPrefix:"insert_lines"},t),H=d.processMultiFileOperationResults(F,"successfulInsertions"),{successfulOperations:U,failedOperations:W,totalSuccessfulChanges:G,overallSuccess:V,successfulFiles:J,failedFiles:K}=H
3421
- try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:V?"completed":"failed",error:V?void 0:W+" operations failed",totalOperations:F.length,successfulFiles:J,failedFiles:K,operations:A,totalSuccessfulInsertions:G,totalFailedInsertions:N,totalLinesAdded:L,operationsWithChanges:z,processingTime:Date.now()-w,userComment:E,...T.length>0&&B.success&&B.commitHash&&{commitHash:B.commitHash,previousCommitHash:B.previousCommitHash||void 0}},note:V?`Line insertion completed: ${U}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${W}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}let Y="## Line Insertion Results\n\n"
3422
- if(t.workspaceManager&&(Y+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Y+="**Summary:**\n",Y+=`- **Files processed:** ${U+W}\n`,Y+=`- **Successful operations:** ${U}\n`,Y+=`- **Failed operations:** ${W}\n`,Y+=`- **Total insertions:** ${G} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n`,Y+="\n",B.success&&B.commitHash&&(Y+="**Git Commit:**\n",Y+=`- **Commit Hash:** ${B.commitHash.substring(0,8)}\n`,Y+=`- **Files Committed:** ${B.filesCommitted.length}\n`,B.previousCommitHash&&(Y+=`- **Previous Commit:** ${B.previousCommitHash.substring(0,8)}\n`),Y+="\n"),$.lockAcquired&&$.lockedRequestId&&(Y+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===F.length){const e=F[0]
3401
+ n.insertions=l,n.successfulInsertions=l.filter((e=>e.success)).length,n.failedInsertions=l.filter((e=>!e.success)).length,n.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&n.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),n.success=!0,z++,y.info("Document updated successfully",{documentId:e.documentId,filename:n.filename,successfulInsertions:n.successfulInsertions,failedInsertions:n.failedInsertions,linesAdded:n.totalLinesAdded})):0===n.failedInsertions&&(n.success=!0),N+=n.failedInsertions,L+=n.totalLinesAdded}catch(t){n.error=(0,p.getErrorMessage)(t),n.failedInsertions=e.insertions.length,N+=n.failedInsertions,y.error("Document operation failed",{documentId:e.documentId,error:n.error})}F.push(n)}if(M.length>0)try{for(const e of M){const r=F.find((t=>t.documentId===e.documentId))
3402
+ r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const B=await d.handleMultiFileGitCommit(C,T,F,z,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:y,metrics:a,metricsPrefix:"insert_lines"},t),H=d.processMultiFileOperationResults(F,"successfulInsertions"),{successfulOperations:W,failedOperations:U,totalSuccessfulChanges:G,overallSuccess:V,successfulFiles:J,failedFiles:K}=H
3403
+ try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:V?"completed":"failed",error:V?void 0:U+" operations failed",totalOperations:F.length,successfulFiles:J,failedFiles:K,operations:D,totalSuccessfulInsertions:G,totalFailedInsertions:N,totalLinesAdded:L,operationsWithChanges:z,processingTime:Date.now()-w,userComment:E,...T.length>0&&B.success&&B.commitHash&&{commitHash:B.commitHash,previousCommitHash:B.previousCommitHash||void 0}},note:V?`Line insertion completed: ${W}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${U}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}let Y="## Line Insertion Results\n\n"
3404
+ if(t.workspaceManager&&(Y+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Y+="**Summary:**\n",Y+=`- **Files processed:** ${W+U}\n`,Y+=`- **Successful operations:** ${W}\n`,Y+=`- **Failed operations:** ${U}\n`,Y+=`- **Total insertions:** ${G} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n`,Y+="\n",B.success&&B.commitHash&&(Y+="**Git Commit:**\n",Y+=`- **Commit Hash:** ${B.commitHash.substring(0,8)}\n`,Y+=`- **Files Committed:** ${B.filesCommitted.length}\n`,B.previousCommitHash&&(Y+=`- **Previous Commit:** ${B.previousCommitHash.substring(0,8)}\n`),Y+="\n"),$.lockAcquired&&$.lockedRequestId&&(Y+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===F.length){const e=F[0]
3423
3405
  if(Y+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?Y+=`**File:** ${e.path}\n`:(Y+="**Document:** "+e.documentId,e.filename&&(Y+=` (${e.filename})`),Y+="\n"),e.error?Y+=`**Error:** ${e.error}\n`:(Y+=`**Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(Y+=`, ${e.failedInsertions} failed`),Y+="\n",Y+=`**Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){Y+="**Failed Insertion Details:**\n"
3424
3406
  for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?`between lines ${t.afterLine} and ${t.beforeLine}`:`${t.type} line ${t.line}`
3425
- Y+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{Y+="**Summary:**\n",Y+=`- **Total Operations:** ${F.length}\n`,Y+=`- **Successful:** ${U}\n`,Y+=`- **Failed:** ${W}\n`,Y+=`- **Total Insertions:** ${G} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n\n`,Y+="**Detailed Results:**\n\n"
3407
+ Y+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{Y+="**Summary:**\n",Y+=`- **Total Operations:** ${F.length}\n`,Y+=`- **Successful:** ${W}\n`,Y+=`- **Failed:** ${U}\n`,Y+=`- **Total Insertions:** ${G} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n\n`,Y+="**Detailed Results:**\n\n"
3426
3408
  for(const e of F){if("file"===e.type?Y+=`### File: ${e.path}\n`:(Y+="### Document: "+e.documentId,e.filename&&(Y+=` (${e.filename})`),Y+="\n"),Y+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?Y+=`- **Error:** ${e.error}\n`:(Y+=`- **Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(Y+=`, ${e.failedInsertions} failed`),Y+="\n",Y+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){Y+="- **Failed Insertion Details:**\n"
3427
3409
  for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?`between lines ${t.afterLine} and ${t.beforeLine}`:`${t.type} line ${t.line}`
3428
3410
  Y+=` - ${t.type} insertion ${e}: ${t.error}\n`}}Y+="\n"}}M.length>0&&(Y+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
3429
3411
  const Q=Date.now()-w
3430
- return y.info("Insert lines operation completed",{duration:Q,success:V,totalOperations:F.length,successfulOperations:U,failedOperations:W}),a.incrementCounter("insert_lines_total",1,{success:V}),{content:[{type:"text",text:Y}],isError:!V}}catch(t){const r=Date.now()-w
3431
- if(y.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:I}),b)try{await o.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:I,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("insert_lines_errors",1,{phase:I}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
3432
- const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255)},6539(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
3433
- const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),p=t(2968),f=t(922)
3412
+ return y.info("Insert lines operation completed",{duration:Q,success:V,totalOperations:F.length,successfulOperations:W,failedOperations:U}),a.incrementCounter("insert_lines_total",1,{success:V}),{content:[{type:"text",text:Y}],isError:!V}}catch(t){const r=Date.now()-w
3413
+ if(y.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:I}),b)try{await o.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,p.getErrorMessage)(t),phase:I,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,p.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("insert_lines_errors",1,{phase:I}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,p.getErrorMessage)(t)}],isError:!0}}}
3414
+ const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),f=t(9949),p=t(8824),m=t(3255)},6539(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
3415
+ const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),f=t(2968),p=t(922)
3434
3416
  exports.ClientFactory=class{static async createClient(e,m,y,w={}){(m=m.child({component:"client-factory"})).info("Creating API client with components")
3435
3417
  const k=w.tokenManager||new r.TokenManager(m,w.workingDir||process.cwd())
3436
3418
  await k.initialize()
3437
3419
  const b=w.tokenSynchronizer||new i.ClientTokenSynchronizer(m),I=new s.AuthenticationManager(k,m,b),v=await I.getTokenString(),C=w.connectionStatusManager||new n.ConnectionStatusManager(e,m,y,{alchemyPath:w.alchemyPath,checkIntervalMs:w.offlineCheckIntervalMs,timeoutMs:w.timeout,retryCount:w.retryAttempts}),_=new c.ProjectClient(e,m,y,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3438
3420
  b.registerClient(_),w.alchemyPath&&_.setAlchemyPath(w.alchemyPath)
3439
- const E=new p.TaskClient(e,m,y,_,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3421
+ const E=new f.TaskClient(e,m,y,_,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3440
3422
  b.registerClient(E)
3441
3423
  const q=new a.FileOperationsClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3442
3424
  b.registerClient(q),m.info("RequestClient constructor received token: "+(v?"present":"missing"))
@@ -3444,7 +3426,7 @@ const S=new u.RequestClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts
3444
3426
  b.registerClient(S),m.info("RequestClient post-constructor token: "+(S.getAuthToken()?"present":"missing"))
3445
3427
  const T=new g.DocumentClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3446
3428
  b.registerClient(T)
3447
- const M=new f.ToolRecordClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3429
+ const M=new p.ToolRecordClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3448
3430
  b.registerClient(M)
3449
3431
  const R=new d.ProxyClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
3450
3432
  if(b.registerClient(R),!w.alchemyPath)throw Error("alchemyPath is required for ProjectSynchronizer creation. Cannot create API client without project synchronization capabilities.")
@@ -3462,7 +3444,7 @@ if(E)try{await E.connectStdio(),(0,a.isDebugToolsEnabled)()&&b.info("Connected s
3462
3444
  throw b.error("Failed to connect stdio transport",{errorDetails:t}),e}else b.error("No global server instance available to connect transport")
3463
3445
  return{transport:e,shutdownHandler:t}}var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
3464
3446
  Object.defineProperty(exports,"__esModule",{value:!0})
3465
- const o=t(5802),s=n(t(6928)),i=t(184),a=t(3444),c=t(1152),l=t(8851),d=t(8411),u=n(t(9896)),h=t(4139),g=t(5218),p=t(8824),f=t(9939),m=t(7960),y=process.argv.slice(2),w=y[0]||process.cwd(),k=s.default.resolve(w)
3447
+ const o=t(5802),s=n(t(6928)),i=t(184),a=t(3444),c=t(1152),l=t(8851),d=t(8411),u=n(t(9896)),h=t(4139),g=t(5218),f=t(8824),p=t(9939),m=t(7960),y=process.argv.slice(2),w=y[0]||process.cwd(),k=s.default.resolve(w)
3466
3448
  console.error("\n=== MCP STARTUP DIAGNOSTICS ==="),console.error("Script path (process.argv[1]):",process.argv[1]),console.error("Base directory:",k),console.error("ENABLE_DEBUG_TOOLS env:",process.env.ENABLE_DEBUG_TOOLS),console.error("DEBUG_LOGGING env:",process.env.DEBUG_LOGGING),console.error("isDevBuild():",(0,m.isDevBuild)()),console.error("isDebugToolsEnabled():",(0,a.isDebugToolsEnabled)()),console.error("===============================\n")
3467
3449
  const b=(0,a.createEnvLogger)({serviceName:"direct-mcp-server",console:!0,baseDir:k});(0,a.isDebugToolsEnabled)()?b.info("MCP Direct server initializing",{baseDir:k,debugLogging:process.env.DEBUG_LOGGING,debugLevel:process.env.DEBUG_LEVEL,pid:process.pid}):b.info("MCP Direct server starting"),console.log=function(...e){console.error("[LOG]",...e)},console.info=function(...e){console.error("[INFO]",...e)},console.warn=function(...e){console.error("[WARN]",...e)},process.on("uncaughtException",(e=>{if(b.error("UNCAUGHT EXCEPTION: "+e,{stack:e.stack||"No stack available"}),E)try{E.cleanupSSEConnection()}catch(e){b.error("Error during cleanup after uncaught exception: "+e)}setTimeout((()=>process.exit(1)),500)})),process.on("unhandledRejection",(e=>{b.error("UNHANDLED REJECTION: "+e,{stack:e instanceof Error?e.stack:"No stack available"})})),process.on("exit",(e=>{b.info("Process exiting with code: "+e)}))
3468
3450
  const I=process.stdout.write
@@ -3474,7 +3456,7 @@ const _=global.__serverInitialized
3474
3456
  void 0===_?(global.__serverInitialized=!1,(0,a.isDebugToolsEnabled)()&&b.info("FIRST RUN: Setting global.__serverInitialized to false")):(0,a.isDebugToolsEnabled)()&&b.info("REUSE: global.__serverInitialized is already "+global.__serverInitialized)
3475
3457
  let E=null
3476
3458
  const q=(0,g.isMultiAgentModeEnabled)(k)
3477
- try{(0,d.acquireProcessLock)(k,q)||(b.error(`Process lock acquisition failed for ${k}. Another instance may be running.`),b.error("This instance will exit to prevent duplicate initialization"),process.exit(1)),(0,a.isDebugToolsEnabled)()&&(q?b.info("Multi-agent mode enabled - allowing concurrent access to "+k):b.info("Successfully acquired process lock for "+k))}catch(e){b.error("Lock acquisition threw exception",{error:(0,p.getErrorMessage)(e),stack:e instanceof Error?e.stack:void 0}),b.error("Cannot continue without lock in single-agent mode"),process.exit(1)}(0,a.isDebugToolsEnabled)()&&(b.info("============================================================"),b.info(`PROCESS START: PID=${process.pid}, TIME=${(new Date).toISOString()}`),b.info("BASE DIR: "+k),b.info("ALCHEMY PATH: "+s.default.join(k,h.ALCHEMY_DIR_NAME)),b.info("PROJECT PATH: "+s.default.join(k,h.ALCHEMY_DIR_NAME+"/project.json")),b.info("MULTI-AGENT MODE: "+q),b.info("MCP client information will be captured during protocol initialization")),b.info("Starting MCP server"),(0,a.isDebugToolsEnabled)()&&(b.info("============================================================"),b.info("Base directory: "+k),b.info("Remote server URL: "+C),b.info("Node version: "+process.version),b.info("Current working directory: "+process.cwd()),b.info("ALLOWED_DIRECTORIES env var: not used (single working directory mode)"),b.info("Server already initialized: "+(_?"YES":"NO"))),_&&((0,a.isDebugToolsEnabled)()&&(b.info("Server already initialized globally, reusing existing server instance"),b.info("Reconnecting stdio to existing server...")),r().catch((e=>{const t=e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:e+""
3459
+ try{(0,d.acquireProcessLock)(k,q)||(b.error(`Process lock acquisition failed for ${k}. Another instance may be running.`),b.error("This instance will exit to prevent duplicate initialization"),process.exit(1)),(0,a.isDebugToolsEnabled)()&&(q?b.info("Multi-agent mode enabled - allowing concurrent access to "+k):b.info("Successfully acquired process lock for "+k))}catch(e){b.error("Lock acquisition threw exception",{error:(0,f.getErrorMessage)(e),stack:e instanceof Error?e.stack:void 0}),b.error("Cannot continue without lock in single-agent mode"),process.exit(1)}(0,a.isDebugToolsEnabled)()&&(b.info("============================================================"),b.info(`PROCESS START: PID=${process.pid}, TIME=${(new Date).toISOString()}`),b.info("BASE DIR: "+k),b.info("ALCHEMY PATH: "+s.default.join(k,h.ALCHEMY_DIR_NAME)),b.info("PROJECT PATH: "+s.default.join(k,h.ALCHEMY_DIR_NAME+"/project.json")),b.info("MULTI-AGENT MODE: "+q),b.info("MCP client information will be captured during protocol initialization")),b.info("Starting MCP server"),(0,a.isDebugToolsEnabled)()&&(b.info("============================================================"),b.info("Base directory: "+k),b.info("Remote server URL: "+C),b.info("Node version: "+process.version),b.info("Current working directory: "+process.cwd()),b.info("ALLOWED_DIRECTORIES env var: not used (single working directory mode)"),b.info("Server already initialized: "+(_?"YES":"NO"))),_&&((0,a.isDebugToolsEnabled)()&&(b.info("Server already initialized globally, reusing existing server instance"),b.info("Reconnecting stdio to existing server...")),r().catch((e=>{const t=e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:e+""
3478
3460
  b.error("Failed to connect stdio transport to existing server",{errorDetails:t}),process.exit(1)})))
3479
3461
  try{const e=u.default.existsSync(k)
3480
3462
  if((0,a.isDebugToolsEnabled)()&&b.info("Base directory exists: "+e),e&&(0,a.isDebugToolsEnabled)()){const e=u.default.statSync(k)
@@ -3482,7 +3464,7 @@ b.info(`Directory stats: isDirectory=${e.isDirectory()}, mode=${e.mode.toString(
3482
3464
  if(!u.default.existsSync(S))try{u.default.mkdirSync(S,{recursive:!0}),(0,a.isDebugToolsEnabled)()&&b.info("Created alchemy lab directory: "+S)}catch(e){b.error("Failed to create alchemy lab directory: "+e)}try{(async function(){try{C=await async function(){if(process.env.REMOTE_SERVER_URL)return process.env.REMOTE_SERVER_URL
3483
3465
  try{const{createConfigManager:e}=await Promise.resolve().then(t.t.bind(t,9060,23)),r=e(b),n=await r.getInstallationConfig()
3484
3466
  if(n.remoteServerUrl)return(0,a.isDebugToolsEnabled)()&&b.info("Loaded REMOTE_SERVER_URL from installation config",{remoteServerUrl:n.remoteServerUrl}),n.remoteServerUrl}catch(e){(0,a.isDebugToolsEnabled)()&&b.debug("Could not read REMOTE_SERVER_URL from installation config",{error:e instanceof Error?e.message:"Unknown error"})}return"https://api.alchemylabcode.com"}()
3485
- try{const e=await(0,f.syncPlugins)(k,(0,m.isDevBuild)(),b)
3467
+ try{const e=await(0,p.syncPlugins)(k,(0,m.isDevBuild)(),b)
3486
3468
  e.synced.length>0&&b.info("Synced plugins on startup",{synced:e.synced}),e.errors.length>0&&b.warn("Some plugins failed to sync",{errors:e.errors})}catch(e){b.warn("Plugin sync failed",{error:e instanceof Error?e.message:"Unknown error"})}(0,a.isDebugToolsEnabled)()&&(b.info("Creating MCP server with base dir: "+k),b.info("Using remote server URL: "+C))
3487
3469
  const e=await(0,i.createServer)(k,b,v,C,{multiAgentMode:(0,g.isMultiAgentModeEnabled)(k)})
3488
3470
  E=e,global.__serverInitialized=!0,(0,a.isDebugToolsEnabled)()&&b.info("MCP server created successfully")
@@ -3517,7 +3499,7 @@ const n=[],o=[...t].sort(((e,t)=>{const r=e=>"number"==typeof e?e:Array.isArray(
3517
3499
  return r(t.lines)-r(e.lines)}))
3518
3500
  for(const e of o){const t={lines:e.lines,success:!1}
3519
3501
  try{const n=(0,m.replaceLines)(r,e.lines,e.content)
3520
- r=n.newContent,t.success=!0,t.linesReplaced=n.linesReplaced,t.linesAdded=n.linesAdded,t.startLine=n.startLine,t.endLine=n.endLine}catch(e){t.error=(0,f.getErrorMessage)(e)}n.push(t)}return{newContent:r,results:n}}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3502
+ r=n.newContent,t.success=!0,t.linesReplaced=n.linesReplaced,t.linesAdded=n.linesAdded,t.startLine=n.startLine,t.endLine=n.endLine}catch(e){t.error=(0,p.getErrorMessage)(e)}n.push(t)}return{newContent:r,results:n}}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3521
3503
  var o=Object.getOwnPropertyDescriptor(t,r)
3522
3504
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[]
3523
3505
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -3538,20 +3520,20 @@ M.push({type:"file",path:r,fullPath:n,replacements:e.replacements.map((e=>({line
3538
3520
  if(T.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
3539
3521
  for(const e of T)R.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
3540
3522
  if(R.length>0&&t.apiClient){const e=R.map((e=>e.documentId))
3541
- try{await(0,p.ensureDocumentsNotLocked)(e,t.apiClient,w,a,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3523
+ try{await(0,f.ensureDocumentsNotLocked)(e,t.apiClient,w,a,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3542
3524
  throw e}}v=d.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_lines_phase",1,{phase:v})
3543
3525
  const P=M.length>0?M[0].path:"document-operation",x=await d.validateTaskId(_,P,n,w,a,C.metricsPrefix),O=x?.requestId
3544
3526
  let j=null
3545
3527
  M.length>0&&O&&(j=await d.validateWorkItemStates(_,M[0].path,n,s,t,w,a,C.metricsPrefix))
3546
3528
  let $={taskPromoted:!1,requestPromoted:!1}
3547
3529
  M.length>0&&O&&j&&($=await d.autoPromoteTaskStatus(_,x.status,O,j.request?.status,M[0].path,n,s,w,a,C.metricsPrefix),$.taskPromoted&&w.info("Auto-promoted task to in_progress for replace-lines operation",{taskId:_,requestId:O,previousStatus:x.status,newStatus:$.newTaskStatus,triggeringOperation:"replace-lines"}))
3548
- const A=await d.ensureCorrectWorkspaceContext({taskPromoted:$.taskPromoted,requestId:O,context:t,operation:"replace-lines",logger:w,metrics:a,metricsPrefix:C.metricsPrefix})
3549
- if(!A.success){if(A.isLockConflict)return{content:[{type:"text",text:"\u274c "+A.error}],isError:!0}
3550
- throw Error(A.error)}if(M.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:M.length,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})
3530
+ const D=await d.ensureCorrectWorkspaceContext({taskPromoted:$.taskPromoted,requestId:O,context:t,operation:"replace-lines",logger:w,metrics:a,metricsPrefix:C.metricsPrefix})
3531
+ if(!D.success){if(D.isLockConflict)return{content:[{type:"text",text:"\u274c "+D.error}],isError:!0}
3532
+ throw Error(D.error)}if(M.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:M.length,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})
3551
3533
  for(let e=0;e<M.length;e++){const r=M[e],n=S[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(n.path,t)
3552
3534
  M[e]={...r,path:o,fullPath:s}}}if(R.length>0&&O)try{await(0,h.validateRequestStatusForDocumentOperation)(O,s,w,a,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3553
3535
  throw e}v=d.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_lines_phase",1,{phase:v})
3554
- const D=[...M.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...R.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:F}=await d.createFileOperationRecords(_,O,t.projectId,C.recordType,P,{operationCount:E.length,fileOperations:M.length,documentOperations:R.length,operations:D,userComment:q},n,o,w,a,C.metricsPrefix,m)
3536
+ const A=[...M.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...R.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:F}=await d.createFileOperationRecords(_,O,t.projectId,C.recordType,P,{operationCount:E.length,fileOperations:M.length,documentOperations:R.length,operations:A,userComment:q},n,o,w,a,C.metricsPrefix,m)
3555
3537
  if(b=F,I=F,v=C.fileOperationPhase,a.incrementCounter("replace_lines_phase",1,{phase:v}),M.length>0&&t.git)try{w.debug("[REPLACE-LINES] Checking for user changes before replace operations")
3556
3538
  const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"replace-lines",{requestId:O,taskId:_,workspaceManager:t.workspaceManager},w,a)
3557
3539
  e.userChangesCommitted&&(w.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before replace-lines operation",{taskId:_,fileOperationsCount:M.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:_,fileOperationsCount:M.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:M.length})
@@ -3560,22 +3542,22 @@ let L=0,z=0,B=0,H=0
3560
3542
  for(const e of M){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3561
3543
  try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
3562
3544
  const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.replacements)
3563
- t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,H++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),L+=t.failedReplacements,z+=t.totalLinesReplaced,B+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,L+=t.failedReplacements,w.error("File operation failed",{path:e.path,error:t.error})}N.push(t)}for(const e of R){const n={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3545
+ t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,H++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),L+=t.failedReplacements,z+=t.totalLinesReplaced,B+=t.totalLinesAdded}catch(r){t.error=(0,p.getErrorMessage)(r),t.failedReplacements=e.replacements.length,L+=t.failedReplacements,w.error("File operation failed",{path:e.path,error:t.error})}N.push(t)}for(const e of R){const n={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3564
3546
  try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
3565
3547
  n.filename=s?.filename
3566
3548
  const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
3567
- n.replacements=l,n.successfulReplacements=l.filter((e=>e.success)).length,n.failedReplacements=l.filter((e=>!e.success)).length,n.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),n.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&n.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),n.success=!0,H++,w.info("Document updated successfully",{documentId:e.documentId,filename:n.filename,successfulReplacements:n.successfulReplacements,failedReplacements:n.failedReplacements,linesReplaced:n.totalLinesReplaced,linesAdded:n.totalLinesAdded})):0===n.failedReplacements&&(n.success=!0),L+=n.failedReplacements,z+=n.totalLinesReplaced,B+=n.totalLinesAdded}catch(t){n.error=(0,f.getErrorMessage)(t),n.failedReplacements=e.replacements.length,L+=n.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:n.error})}N.push(n)}if(R.length>0)try{for(const e of R){const r=N.find((t=>t.documentId===e.documentId))
3568
- r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await d.handleMultiFileGitCommit(_,M,N,H,{operationType:"Replace lines",toolRecordId:I,successField:"successfulReplacements",logger:w,metrics:a,metricsPrefix:"replace_lines"},t),W=d.processMultiFileOperationResults(N,"successfulReplacements"),{successfulOperations:G,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=W
3569
- try{await o.updateToolRecord(I,{metadata:{path:M.length>0?M[0].path:"document:"+R[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:N.length,successfulFiles:Y,failedFiles:Q,operations:D,totalSuccessfulReplacements:J,totalFailedReplacements:L,totalLinesReplaced:z,totalLinesAdded:B,operationsWithChanges:H,processingTime:Date.now()-k,userComment:q,...M.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`Line replacement completed: ${G}/${N.length} operations successful${M.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${V}/${N.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z="## Line Replacement Results\n\n"
3570
- if(t.workspaceManager&&(Z+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Z+="**Summary:**\n",Z+=`- **Files processed:** ${G+V}\n`,Z+=`- **Successful operations:** ${G}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,B>0&&(Z+=`- **Total Lines Added:** ${B}\n`),Z+="\n",U.success&&U.commitHash&&(Z+="**Git Commit:**\n",Z+=`- **Commit Hash:** ${U.commitHash.substring(0,8)}\n`,Z+=`- **Files Committed:** ${U.filesCommitted.length}\n`,U.previousCommitHash&&(Z+=`- **Previous Commit:** ${U.previousCommitHash.substring(0,8)}\n`),Z+="\n"),A.lockAcquired&&A.lockedRequestId&&(Z+=`\u{1f512} **Locked request:** ${A.lockedRequestId}\n\n`),1===N.length){const e=N[0]
3549
+ n.replacements=l,n.successfulReplacements=l.filter((e=>e.success)).length,n.failedReplacements=l.filter((e=>!e.success)).length,n.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),n.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&n.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),n.success=!0,H++,w.info("Document updated successfully",{documentId:e.documentId,filename:n.filename,successfulReplacements:n.successfulReplacements,failedReplacements:n.failedReplacements,linesReplaced:n.totalLinesReplaced,linesAdded:n.totalLinesAdded})):0===n.failedReplacements&&(n.success=!0),L+=n.failedReplacements,z+=n.totalLinesReplaced,B+=n.totalLinesAdded}catch(t){n.error=(0,p.getErrorMessage)(t),n.failedReplacements=e.replacements.length,L+=n.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:n.error})}N.push(n)}if(R.length>0)try{for(const e of R){const r=N.find((t=>t.documentId===e.documentId))
3550
+ r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const W=await d.handleMultiFileGitCommit(_,M,N,H,{operationType:"Replace lines",toolRecordId:I,successField:"successfulReplacements",logger:w,metrics:a,metricsPrefix:"replace_lines"},t),U=d.processMultiFileOperationResults(N,"successfulReplacements"),{successfulOperations:G,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=U
3551
+ try{await o.updateToolRecord(I,{metadata:{path:M.length>0?M[0].path:"document:"+R[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:N.length,successfulFiles:Y,failedFiles:Q,operations:A,totalSuccessfulReplacements:J,totalFailedReplacements:L,totalLinesReplaced:z,totalLinesAdded:B,operationsWithChanges:H,processingTime:Date.now()-k,userComment:q,...M.length>0&&W.success&&W.commitHash&&{commitHash:W.commitHash,previousCommitHash:W.previousCommitHash||void 0}},note:K?`Line replacement completed: ${G}/${N.length} operations successful${M.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${V}/${N.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z="## Line Replacement Results\n\n"
3552
+ if(t.workspaceManager&&(Z+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Z+="**Summary:**\n",Z+=`- **Files processed:** ${G+V}\n`,Z+=`- **Successful operations:** ${G}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,B>0&&(Z+=`- **Total Lines Added:** ${B}\n`),Z+="\n",W.success&&W.commitHash&&(Z+="**Git Commit:**\n",Z+=`- **Commit Hash:** ${W.commitHash.substring(0,8)}\n`,Z+=`- **Files Committed:** ${W.filesCommitted.length}\n`,W.previousCommitHash&&(Z+=`- **Previous Commit:** ${W.previousCommitHash.substring(0,8)}\n`),Z+="\n"),D.lockAcquired&&D.lockedRequestId&&(Z+=`\u{1f512} **Locked request:** ${D.lockedRequestId}\n\n`),1===N.length){const e=N[0]
3571
3553
  if(Z+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?Z+=`**File:** ${e.path}\n`:(Z+="**Document:** "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),e.error?Z+=`**Error:** ${e.error}\n`:(Z+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n",Z+=`**Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(Z+=`**Lines Added:** ${e.totalLinesAdded}\n`)),e.replacements.some((e=>!e.success))){Z+="**Failed Replacement Details:**\n"
3572
3554
  for(const t of e.replacements.filter((e=>!e.success)))Z+=`- Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}}else{Z+="**Summary:**\n",Z+=`- **Total Operations:** ${N.length}\n`,Z+=`- **Successful:** ${G}\n`,Z+=`- **Failed:** ${V}\n`,Z+=`- **Total Replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,B>0&&(Z+=`- **Total Lines Added:** ${B}\n`),Z+="\n",Z+="**Detailed Results:**\n\n"
3573
3555
  for(const e of N){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Document: "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),Z+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error&&(Z+=`- **Error:** ${e.error}\n`),Z+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n",Z+=`- **Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(Z+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.replacements.some((e=>!e.success))){Z+="- **Failed Replacement Details:**\n"
3574
3556
  for(const t of e.replacements.filter((e=>!e.success)))Z+=` - Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}Z+="\n"}}R.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
3575
3557
  const X=Date.now()-k
3576
3558
  return w.info("Replace lines operation completed",{duration:X,success:K,totalOperations:N.length,successfulOperations:G,failedOperations:V}),a.incrementCounter("replace_lines_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
3577
- if(w.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await o.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("replace_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
3578
- const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255),y=t(9470)},6688(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
3559
+ if(w.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await o.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,p.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,p.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("replace_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,p.getErrorMessage)(t)}],isError:!0}}}
3560
+ const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),f=t(9949),p=t(8824),m=t(3255),y=t(9470)},6688(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
3579
3561
  const r=t(9896),n=t(6928)
3580
3562
  exports.sessionIdentity=new class{constructor(){this.discoveryAttempted=!1,this.parentCache=new Map}setIdentity(e){const t=this.identity
3581
3563
  this.identity=e,this.log("setIdentity",{sessionId:e.sessionId,serverUrl:e.serverUrl,agentType:e.agentType||null,prevSessionId:t?.sessionId||null,changed:t?.sessionId!==e.sessionId})}getIdentity(){return this.identity}updateIdentity(e){if(this.identity){const t={...this.identity}
@@ -3622,14 +3604,14 @@ var t={}
3622
3604
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3623
3605
  return o(t,e),t})
3624
3606
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTaskFileHistory=async function(e,t,r,n,o){const s=n.child({tool:"task_file_history"}),h=o.startTimer("tool_execution_time")
3625
- try{const{taskId:g,showDiff:p=!1}=e
3607
+ try{const{taskId:g,showDiff:f=!1}=e
3626
3608
  if(!g)throw(0,i.createValidationError)("Task ID is required")
3627
3609
  if(!/^tas\d{6}$/.test(g))throw(0,i.createValidationError)(`Invalid task ID format: ${g}. Expected format: tas######`)
3628
- s.info("Getting file changes for task "+g,{showDiff:p})
3629
- const f=r.getTaskClient(),m=r.getToolRecordClient(),y=t.projectId
3610
+ s.info("Getting file changes for task "+g,{showDiff:f})
3611
+ const p=r.getTaskClient(),m=r.getToolRecordClient(),y=t.projectId
3630
3612
  let w
3631
3613
  r.setProjectId(y)
3632
- try{const M=await f.getTask(g)
3614
+ try{const M=await p.getTask(g)
3633
3615
  s.info("Raw task response data",{responseDataType:typeof M,isArray:Array.isArray(M),hasData:null!=M,properties:M&&"object"==typeof M?Object.keys(M):[]}),w=(0,l.extractDataFromResponse)(M,{logger:s,operationName:"getTask",defaultValue:{id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}),s.info("Found task: "+w.title)}catch(R){s.warn("Could not fetch task information: "+(0,u.getErrorMessage)(R)),w={id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}let k=[]
3634
3616
  try{const P=await m.getToolRecordsByTaskId(g)
3635
3617
  if(s.info("Raw records response data",{responseDataType:typeof P,isArray:Array.isArray(P),hasData:null!=P,properties:P&&"object"==typeof P?Object.keys(P):[]}),k=(0,l.extractArrayFromResponse)(P,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const x={}
@@ -3681,62 +3663,62 @@ n&&n.push({filePath:r,recordId:e.id,type:"replace-in-files",timestamp:e.createdA
3681
3663
  C.has(t)||C.set(t,[])
3682
3664
  const r=C.get(t)
3683
3665
  r&&r.push({filePath:t,recordId:e.id,type:e.type,timestamp:e.createdAt,commitHash:e.metadata.commitHash,status:e.metadata.status||"",record:e})})),s.info(`Grouped records by file path. Found ${C.size} unique files.`)
3684
- for(const[$,A]of C.entries())A.sort(((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())),s.info(`File ${$} has ${A.length} records.`),s.info("Records with commit hashes: "+A.filter((e=>e.commitHash)).length)
3666
+ for(const[$,D]of C.entries())D.sort(((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())),s.info(`File ${$} has ${D.length} records.`),s.info("Records with commit hashes: "+D.filter((e=>e.commitHash)).length)
3685
3667
  const _=new Map
3686
- for(const[D,F]of C.entries()){s.info(`Processing file: ${D} (${F.length} records)`)
3668
+ for(const[A,F]of C.entries()){s.info(`Processing file: ${A} (${F.length} records)`)
3687
3669
  const N=new Map
3688
3670
  F.forEach((e=>{e.recordId&&e.record?.metadata?.status&&(N.has(e.recordId)||N.set(e.recordId,[]),N.get(e.recordId)?.push(e.record.metadata.status))})),N.forEach(((e,t)=>{s.info(`Record ${t} status updates: ${e.join(" -> ")}`)}))
3689
3671
  const L=F.filter((e=>e.commitHash))
3690
- if(s.info(`Found ${L.length} records with commit hash for ${D}`),0===L.length){s.info(`No commit hashes found in record metadata for ${D}, trying git log`)
3691
- try{if(t.git){const J={file:D,n:10},K=await t.git.log(J)
3692
- if(K&&K.all&&K.all.length>0){s.info(`Found ${K.all.length} commits for ${D} using git log`)
3693
- const Y=K.all.map((e=>({filePath:D,recordId:"git-"+e.hash.substring(0,8),type:"git-commit",timestamp:new Date(e.date).toISOString(),commitHash:e.hash,status:"completed",record:{id:"git-"+e.hash.substring(0,8),type:"git-commit",content:e.message,createdAt:new Date(e.date).toISOString(),metadata:{commitHash:e.hash}}})))
3672
+ if(s.info(`Found ${L.length} records with commit hash for ${A}`),0===L.length){s.info(`No commit hashes found in record metadata for ${A}, trying git log`)
3673
+ try{if(t.git){const J={file:A,n:10},K=await t.git.log(J)
3674
+ if(K&&K.all&&K.all.length>0){s.info(`Found ${K.all.length} commits for ${A} using git log`)
3675
+ const Y=K.all.map((e=>({filePath:A,recordId:"git-"+e.hash.substring(0,8),type:"git-commit",timestamp:new Date(e.date).toISOString(),commitHash:e.hash,status:"completed",record:{id:"git-"+e.hash.substring(0,8),type:"git-commit",content:e.message,createdAt:new Date(e.date).toISOString(),metadata:{commitHash:e.hash}}})))
3694
3676
  if(Y.length>0){const Q=Y.length>1?Y[Y.length-1]:Y[0],Z=Y[0],X=1===Y.length
3695
- s.info(X?`Using single git commit for ${D}: ${Z.commitHash?Z.commitHash.substring(0,8):"unknown"}`:`Using git commits for ${D}: ${Q.commitHash?Q.commitHash.substring(0,8):"unknown"} to ${Z.commitHash?Z.commitHash.substring(0,8):"unknown"}`)
3677
+ s.info(X?`Using single git commit for ${A}: ${Z.commitHash?Z.commitHash.substring(0,8):"unknown"}`:`Using git commits for ${A}: ${Q.commitHash?Q.commitHash.substring(0,8):"unknown"} to ${Z.commitHash?Z.commitHash.substring(0,8):"unknown"}`)
3696
3678
  let ee=""
3697
- try{if(X)try{const te=[`${Z.commitHash}:${D}`],re=await t.git.show(te)
3698
- re&&re.trim().length>0?(ee=re.split("\n").map((e=>"+"+e)).join("\n"),_.set(D,{firstChange:Q,lastChange:Z,hasDiff:!0,diffText:ee})):_.set(D,{firstChange:Q,lastChange:Z,hasDiff:!1,diffText:"File exists in git history but has no content"})}catch(ne){s.warn("Error getting file content for "+D,{error:ne instanceof Error?ne.message:ne+""}),_.set(D,{firstChange:Q,lastChange:Z,hasDiff:!1,diffText:"Error getting file content from git"})}else{const oe=[`${Q.commitHash}..${Z.commitHash}`,"--",D]
3699
- ee=await t.git.diff(oe),_.set(D,{firstChange:Q,lastChange:Z,hasDiff:!(!ee||0>=ee.trim().length),diffText:ee||"No changes detected in git diff"})}}catch(se){s.warn("Error generating diff for "+D,{error:se instanceof Error?se.message:se+""}),_.set(D,{firstChange:Q,lastChange:Z,hasDiff:!0,diffText:"Error generating diff, but git history is available"})}continue}}else s.info("No git history found for "+D)}}catch(ie){s.warn("Error getting git history for "+D,{error:(0,u.getErrorMessage)(ie)})}_.set(D,{firstChange:F[0],lastChange:F[F.length-1],hasDiff:!1,diffText:"No commit hashes available for this file"})
3679
+ try{if(X)try{const te=[`${Z.commitHash}:${A}`],re=await t.git.show(te)
3680
+ re&&re.trim().length>0?(ee=re.split("\n").map((e=>"+"+e)).join("\n"),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!0,diffText:ee})):_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!1,diffText:"File exists in git history but has no content"})}catch(ne){s.warn("Error getting file content for "+A,{error:ne instanceof Error?ne.message:ne+""}),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!1,diffText:"Error getting file content from git"})}else{const oe=[`${Q.commitHash}..${Z.commitHash}`,"--",A]
3681
+ ee=await t.git.diff(oe),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!(!ee||0>=ee.trim().length),diffText:ee||"No changes detected in git diff"})}}catch(se){s.warn("Error generating diff for "+A,{error:se instanceof Error?se.message:se+""}),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!0,diffText:"Error generating diff, but git history is available"})}continue}}else s.info("No git history found for "+A)}}catch(ie){s.warn("Error getting git history for "+A,{error:(0,u.getErrorMessage)(ie)})}_.set(A,{firstChange:F[0],lastChange:F[F.length-1],hasDiff:!1,diffText:"No commit hashes available for this file"})
3700
3682
  continue}const z=L[0],B=L[L.length-1]
3701
3683
  s.info(`First commit: ${z.commitHash?z.commitHash:"unknown"}, Last commit: ${B.commitHash?B.commitHash:"unknown"}`)
3702
- let H=null,U=!1
3703
- if(t.git&&z.commitHash)try{H=await(0,c.findPreviousCommit)(t.git,D,z.commitHash),H?(U=!0,s.info(`Found previous commit: ${H} for ${D}`)):s.info(`No previous commit found for ${D}, likely a new file`)}catch(ae){s.warn("Error finding previous commit for "+D,{error:(0,u.getErrorMessage)(ae)})}const W=U&&H?{...z,commitHash:H,status:"pre-task"}:z
3704
- if(s.info(`Using ${U?"pre-task":"first task"} commit as baseline for ${D}: ${W.commitHash}`),s.info(`Last commit for ${D}: ${B.commitHash}`),s.info("Commits are "+(W.commitHash===B.commitHash?"identical":"different")),z.commitHash===B.commitHash&&!U){if(p&&!U&&t.git&&B.commitHash)try{const ce=[`${B.commitHash}:${D}`]
3705
- s.info(`Getting new file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${D}`)
3684
+ let H=null,W=!1
3685
+ if(t.git&&z.commitHash)try{H=await(0,c.findPreviousCommit)(t.git,A,z.commitHash),H?(W=!0,s.info(`Found previous commit: ${H} for ${A}`)):s.info(`No previous commit found for ${A}, likely a new file`)}catch(ae){s.warn("Error finding previous commit for "+A,{error:(0,u.getErrorMessage)(ae)})}const U=W&&H?{...z,commitHash:H,status:"pre-task"}:z
3686
+ if(s.info(`Using ${W?"pre-task":"first task"} commit as baseline for ${A}: ${U.commitHash}`),s.info(`Last commit for ${A}: ${B.commitHash}`),s.info("Commits are "+(U.commitHash===B.commitHash?"identical":"different")),z.commitHash===B.commitHash&&!W){if(f&&!W&&t.git&&B.commitHash)try{const ce=[`${B.commitHash}:${A}`]
3687
+ s.info(`Getting new file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${A}`)
3706
3688
  const le=await t.git.show(ce)
3707
3689
  if(le&&le.trim().length>0){let de=""
3708
3690
  const ue=le.split("\n")
3709
3691
  for(const he of ue)de+=`+${he}\n`
3710
- _.set(D,{firstChange:W,lastChange:B,hasDiff:!0,diffText:de}),s.info(`Formatted new file content as diff, ${ue.length} lines`)
3711
- continue}}catch(ge){s.warn("Error getting new file content for "+D,{error:(0,u.getErrorMessage)(ge)})}_.set(D,{firstChange:W,lastChange:B,hasDiff:!1,diffText:"Only one commit available for this file"})
3712
- continue}if(z.commitHash===B.commitHash&&U){if(H===z.commitHash){_.set(D,{firstChange:W,lastChange:B,hasDiff:!1,diffText:"No changes detected"})
3692
+ _.set(A,{firstChange:U,lastChange:B,hasDiff:!0,diffText:de}),s.info(`Formatted new file content as diff, ${ue.length} lines`)
3693
+ continue}}catch(ge){s.warn("Error getting new file content for "+A,{error:(0,u.getErrorMessage)(ge)})}_.set(A,{firstChange:U,lastChange:B,hasDiff:!1,diffText:"Only one commit available for this file"})
3694
+ continue}if(z.commitHash===B.commitHash&&W){if(H===z.commitHash){_.set(A,{firstChange:U,lastChange:B,hasDiff:!1,diffText:"No changes detected"})
3713
3695
  continue}s.info("Special case: First and last task commits are the same, but pre-task commit is different")}let G="",V=!1
3714
- if(p||"pre-task"!==W.status){try{if(t.git){try{await t.git.show([`${B.commitHash}:${D}`])}catch(fe){s.warn(`File ${D} does not exist in commit ${B.commitHash}, might be deleted or moved`),G="File was deleted or moved from this location during the task",V=!0,_.set(D,{firstChange:W,lastChange:B,hasDiff:V,diffText:G})
3715
- continue}let pe
3716
- if("pre-task"===W.status?(pe=[`${W.commitHash}..${B.commitHash}`,"--",D],s.info(`Comparing pre-task commit with final commit: ${W.commitHash?W.commitHash.substring(0,8):"unknown"}..${B.commitHash?B.commitHash.substring(0,8):"unknown"} for ${D}`)):(pe=["4b825dc642cb6eb9a060e54bf8d69288fbee4904.."+B.commitHash,"--",D],s.info(`File created during task, showing full file diff using empty tree object: ${B.commitHash?B.commitHash.substring(0,8):"unknown"} for ${D}`)),G=await t.git.diff(pe),V=!!G&&G.trim().length>0,!V&&W.commitHash!==B.commitHash){s.info("No diff found between commits but commits are different, trying direct file content comparison")
3717
- try{const me=await t.git.show([`${W.commitHash}:${D}`]),ye=await t.git.show([`${B.commitHash}:${D}`])
3718
- if(me!==ye&&(V=!0,G="Changes detected through direct content comparison (not visible in standard diff)",p)){const we=me.split("\n"),ke=ye.split("\n")
3719
- Math.abs(we.length-ke.length)>0&&(G+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),me.includes("\0")||ye.includes("\0")?G+="\n\nBinary content detected - changes not displayed":me.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(G+="\n\nWhitespace-only changes detected")}}catch(be){s.warn("Error in direct file comparison: "+(be instanceof Error?be.message:be+""))}}s.info(`Diff generation result for ${D}: hasDiff=${V}, length=${G.length}`)}}catch(Ie){if(s.warn("Error getting diff for "+D,{error:(0,u.getErrorMessage)(Ie),firstCommit:z.commitHash||"unknown",lastCommit:B.commitHash||"unknown"}),G="Error getting diff: "+(0,u.getErrorMessage)(Ie),"pre-task"!==z.status&&t.git)try{const ve=[`${B.commitHash}:${D}`]
3720
- s.info(`Trying fallback to show file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${D}`)
3696
+ if(f||"pre-task"!==U.status){try{if(t.git){try{await t.git.show([`${B.commitHash}:${A}`])}catch(pe){s.warn(`File ${A} does not exist in commit ${B.commitHash}, might be deleted or moved`),G="File was deleted or moved from this location during the task",V=!0,_.set(A,{firstChange:U,lastChange:B,hasDiff:V,diffText:G})
3697
+ continue}let fe
3698
+ if("pre-task"===U.status?(fe=[`${U.commitHash}..${B.commitHash}`,"--",A],s.info(`Comparing pre-task commit with final commit: ${U.commitHash?U.commitHash.substring(0,8):"unknown"}..${B.commitHash?B.commitHash.substring(0,8):"unknown"} for ${A}`)):(fe=["4b825dc642cb6eb9a060e54bf8d69288fbee4904.."+B.commitHash,"--",A],s.info(`File created during task, showing full file diff using empty tree object: ${B.commitHash?B.commitHash.substring(0,8):"unknown"} for ${A}`)),G=await t.git.diff(fe),V=!!G&&G.trim().length>0,!V&&U.commitHash!==B.commitHash){s.info("No diff found between commits but commits are different, trying direct file content comparison")
3699
+ try{const me=await t.git.show([`${U.commitHash}:${A}`]),ye=await t.git.show([`${B.commitHash}:${A}`])
3700
+ if(me!==ye&&(V=!0,G="Changes detected through direct content comparison (not visible in standard diff)",f)){const we=me.split("\n"),ke=ye.split("\n")
3701
+ Math.abs(we.length-ke.length)>0&&(G+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),me.includes("\0")||ye.includes("\0")?G+="\n\nBinary content detected - changes not displayed":me.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(G+="\n\nWhitespace-only changes detected")}}catch(be){s.warn("Error in direct file comparison: "+(be instanceof Error?be.message:be+""))}}s.info(`Diff generation result for ${A}: hasDiff=${V}, length=${G.length}`)}}catch(Ie){if(s.warn("Error getting diff for "+A,{error:(0,u.getErrorMessage)(Ie),firstCommit:z.commitHash||"unknown",lastCommit:B.commitHash||"unknown"}),G="Error getting diff: "+(0,u.getErrorMessage)(Ie),"pre-task"!==z.status&&t.git)try{const ve=[`${B.commitHash}:${A}`]
3702
+ s.info(`Trying fallback to show file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${A}`)
3721
3703
  const Ce=await t.git.show(ve)
3722
- if(Ce&&Ce.trim().length>0){if(p){let _e=""
3704
+ if(Ce&&Ce.trim().length>0){if(f){let _e=""
3723
3705
  const Ee=Ce.split("\n")
3724
3706
  for(const qe of Ee)_e+=`+${qe}\n`
3725
3707
  G=_e}else G="File created during this task. Content:\n"+Ce
3726
- V=!0,s.info("Fallback succeeded, got file content of length "+Ce.length)}}catch(Se){s.warn("Fallback also failed for "+D,{error:Se instanceof Error?Se.message:Se+""})}}_.set(D,{firstChange:W,lastChange:B,hasDiff:V,diffText:G||"No changes detected between commits"})}else V=W.commitHash!==B.commitHash,G=V?"File has changes":"No changes detected between commits",_.set(D,{firstChange:W,lastChange:B,hasDiff:V,diffText:G})}let E=`# File Changes for Task: ${g}\n\n`
3708
+ V=!0,s.info("Fallback succeeded, got file content of length "+Ce.length)}}catch(Se){s.warn("Fallback also failed for "+A,{error:Se instanceof Error?Se.message:Se+""})}}_.set(A,{firstChange:U,lastChange:B,hasDiff:V,diffText:G||"No changes detected between commits"})}else V=U.commitHash!==B.commitHash,G=V?"File has changes":"No changes detected between commits",_.set(A,{firstChange:U,lastChange:B,hasDiff:V,diffText:G})}let E=`# File Changes for Task: ${g}\n\n`
3727
3709
  w&&"object"==typeof w&&(E+="## Task Information\n",E+=`- **Title**: ${w.title||"Unknown"}\n`,E+=`- **Status**: ${w.status||"Unknown"}\n`,E+=`- **Description**: ${w.description||"No description"}\n\n`)
3728
3710
  const q=3e3
3729
3711
  let S=0,T=!1
3730
- if(p){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
3731
- T=S>q,s.info(`Total diff size: ${S} lines (limit: ${q} lines)`),s.info(`Diffs ${T?"will be limited":"will be shown"} based on size`)}if(E+="## Summary\n",E+=`- **Files Modified**: ${C.size}\n`,E+=`- **Total File Operations**: ${v.length}\n`,E+="- **What's Shown**: For existing files, comparing state before task started with final state.\n",E+=" For files created during task, showing the entire file as created.\n",T?(E+=`- **Diff Display**: Limited (total diff size of ${S} lines exceeds limit of ${q} lines)\n`,E+=" Use file-history tool with individual files to see detailed changes\n\n"):E+=`- **Diff Display**: ${p?"Enabled":"Disabled"} (use showDiff=${!p} to ${p?"hide":"show"} diffs)\n\n`,I.allMoves.length>0){E+="## Move Operations\n\n",E+=`Detected ${I.allMoves.length} file move operation(s):\n\n`
3712
+ if(f){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
3713
+ T=S>q,s.info(`Total diff size: ${S} lines (limit: ${q} lines)`),s.info(`Diffs ${T?"will be limited":"will be shown"} based on size`)}if(E+="## Summary\n",E+=`- **Files Modified**: ${C.size}\n`,E+=`- **Total File Operations**: ${v.length}\n`,E+="- **What's Shown**: For existing files, comparing state before task started with final state.\n",E+=" For files created during task, showing the entire file as created.\n",T?(E+=`- **Diff Display**: Limited (total diff size of ${S} lines exceeds limit of ${q} lines)\n`,E+=" Use file-history tool with individual files to see detailed changes\n\n"):E+=`- **Diff Display**: ${f?"Enabled":"Disabled"} (use showDiff=${!f} to ${f?"hide":"show"} diffs)\n\n`,I.allMoves.length>0){E+="## Move Operations\n\n",E+=`Detected ${I.allMoves.length} file move operation(s):\n\n`
3732
3714
  for(const Me of I.allMoves)E+=`- **${Me.source}** \u2192 **${Me.destination}**\n`,E+=` - Operation: ${Me.type}\n`,E+=` - Timestamp: ${new Date(Me.timestamp).toLocaleString()}\n`,E+=` - Record ID: ${Me.recordId}\n\n`}E+="## Modified Files\n\n"
3733
3715
  for(const[Re,Pe]of _.entries()){const{normalizedPath:xe,fullPath:Oe}=d.validateAndNormalizePath(Re,t)
3734
3716
  let je=!1
3735
3717
  try{await a.access(Oe),je=!0}catch{}E+=`### ${Re} ${je?"":"(Deleted)"}\n\n`
3736
- const $e=new Date(Pe.firstChange.timestamp).toLocaleString(),Ae=new Date(Pe.lastChange.timestamp).toLocaleString()
3737
- E+=`**First Change**: ${$e}\n`,E+=`**Last Change**: ${Ae}\n`,"pre-task"===Pe.firstChange.status&&Pe.firstChange.commitHash?E+=`**Pre-Task Commit**: ${Pe.firstChange.commitHash.substring(0,8)}\n`:Pe.firstChange.commitHash&&(E+=`**File Created During Task**: ${Pe.firstChange.commitHash.substring(0,8)}\n`),Pe.lastChange.commitHash&&(E+=`**Final Commit**: ${Pe.lastChange.commitHash.substring(0,8)}\n`)
3738
- const De=I.sourceToMove.get(Re),Fe=I.destToMove.get(Re)
3739
- De?E+=`**\u2139\ufe0f Move Operation**: This file was moved TO **${De.destination}**\n`:Fe&&(E+=`**\u2139\ufe0f Move Operation**: This file was moved FROM **${Fe.source}**\n`),p&&!T?Pe.hasDiff?(E+="\n**Changes**:\n",E+="```diff\n",E+=Pe.diffText,E+="\n```\n\n"):E+=`\n**Note**: ${Pe.diffText}\n\n`:T&&Pe.hasDiff?(E+=`\n**Note**: File has changes (${Pe.diffText?Pe.diffText.split("\n").length:0} lines). `,E+=`Compare ${Pe.firstChange.commitHash?Pe.firstChange.commitHash.substring(0,8):"unknown"}..${Pe.lastChange.commitHash?Pe.lastChange.commitHash.substring(0,8):"unknown"} to see changes.\n\n`):Pe.hasDiff?E+="\n**Note**: File has changes. Use showDiff=true to see the diff.\n\n":E+=`\n**Note**: ${Pe.diffText}\n\n`,E+="---\n\n"}return h({success:!0,fileCount:C.size}),{content:[{type:"text",text:E}]}}catch(Ne){return s.error("Error in task file history tool",{error:Ne instanceof Error?Ne.stack:Ne+""}),h({success:!1,error:Ne instanceof Error?Ne.name:"unknown"}),{content:[{type:"text",text:"Error: "+(0,u.getErrorMessage)(Ne)}],isError:!0}}}
3718
+ const $e=new Date(Pe.firstChange.timestamp).toLocaleString(),De=new Date(Pe.lastChange.timestamp).toLocaleString()
3719
+ E+=`**First Change**: ${$e}\n`,E+=`**Last Change**: ${De}\n`,"pre-task"===Pe.firstChange.status&&Pe.firstChange.commitHash?E+=`**Pre-Task Commit**: ${Pe.firstChange.commitHash.substring(0,8)}\n`:Pe.firstChange.commitHash&&(E+=`**File Created During Task**: ${Pe.firstChange.commitHash.substring(0,8)}\n`),Pe.lastChange.commitHash&&(E+=`**Final Commit**: ${Pe.lastChange.commitHash.substring(0,8)}\n`)
3720
+ const Ae=I.sourceToMove.get(Re),Fe=I.destToMove.get(Re)
3721
+ Ae?E+=`**\u2139\ufe0f Move Operation**: This file was moved TO **${Ae.destination}**\n`:Fe&&(E+=`**\u2139\ufe0f Move Operation**: This file was moved FROM **${Fe.source}**\n`),f&&!T?Pe.hasDiff?(E+="\n**Changes**:\n",E+="```diff\n",E+=Pe.diffText,E+="\n```\n\n"):E+=`\n**Note**: ${Pe.diffText}\n\n`:T&&Pe.hasDiff?(E+=`\n**Note**: File has changes (${Pe.diffText?Pe.diffText.split("\n").length:0} lines). `,E+=`Compare ${Pe.firstChange.commitHash?Pe.firstChange.commitHash.substring(0,8):"unknown"}..${Pe.lastChange.commitHash?Pe.lastChange.commitHash.substring(0,8):"unknown"} to see changes.\n\n`):Pe.hasDiff?E+="\n**Note**: File has changes. Use showDiff=true to see the diff.\n\n":E+=`\n**Note**: ${Pe.diffText}\n\n`,E+="---\n\n"}return h({success:!0,fileCount:C.size}),{content:[{type:"text",text:E}]}}catch(Ne){return s.error("Error in task file history tool",{error:Ne instanceof Error?Ne.stack:Ne+""}),h({success:!1,error:Ne instanceof Error?Ne.name:"unknown"}),{content:[{type:"text",text:"Error: "+(0,u.getErrorMessage)(Ne)}],isError:!0}}}
3740
3722
  const i=t(9860),a=s(t(1943)),c=t(9671),l=t(2960),d=s(t(5967)),u=t(8824)},6928(module){module.exports=require("path")},6975(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClientAdapter=void 0
3741
3723
  const r=t(1058)
3742
3724
  exports.ProjectClientAdapter=class{constructor(e,t){this.client=e,this.logger=t.child({component:"project-client-adapter"}),this.logger.info("ProjectClientAdapter initialized")}isOnline(){return!this.client.isOffline()}async fetchProject(e){try{return this.logger.debug("ProjectClientAdapter.fetchProject called",{projectId:e}),await this.client.getProject(e)}catch(t){return this.logger.error("Error in ProjectClientAdapter.fetchProject",{projectId:e,error:t instanceof Error?t.stack:t+""}),null}}async createProject(e){try{this.logger.debug("ProjectClientAdapter.createProject called",{projectName:e.name,projectId:e.id}),this.logger.info("Creating project via adapter",{name:e.name,id:e.id,description:e.description?.substring(0,50)})
@@ -3858,10 +3840,10 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentit
3858
3840
  i.existsSync(n)||i.mkdirSync(n,{recursive:!0})
3859
3841
  const s=(new Date).toISOString(),c=Object.keys(r).length?" "+JSON.stringify(r):""
3860
3842
  i.appendFileSync(o,`[${s}] ${e} | ${t}${c}\n`)}catch(e){}}
3861
- const i=s(t(9896)),a=s(t(6928))},7334(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateRequest=async function(e,t,l,d,u,h,g){const p=d.child({tool:"create_request"})
3862
- p.info("Creating new request",{args:e})
3863
- const f=u.startTimer("tool_handler_duration")
3864
- try{const d=function(e){try{return r.CreateRequestSchema.parse(e)}catch(e){if(e instanceof s.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
3843
+ const i=s(t(9896)),a=s(t(6928))},7334(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateRequest=async function(e,t,l,d,u,h,g){const f=d.child({tool:"create_request"})
3844
+ f.info("Creating new request",{args:e})
3845
+ const p=u.startTimer("tool_handler_duration")
3846
+ try{if(e&&"string"==typeof e.acceptanceCriteria)try{e.acceptanceCriteria=JSON.parse(e.acceptanceCriteria)}catch{}const d=function(e){try{return r.CreateRequestSchema.parse(e)}catch(e){if(e instanceof s.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
3865
3847
  throw new n.ValidationError("Invalid input: "+(0,i.getErrorMessage)(e))}}(e)
3866
3848
  u.incrementCounter("create_request_attempts",1,{type:d.type,criteriaCounts:d.acceptanceCriteria.length})
3867
3849
  const m=t.projectId
@@ -3874,22 +3856,22 @@ if(e){const t=l.getCLISessionClient()
3874
3856
  if(t){const r=await t.getByExternalId(e)
3875
3857
  if(r?.workflowId){const e=await l.proxyGet("/api/workflows/"+r.workflowId),t=e?.data||e
3876
3858
  t?.approvalMode&&(w=(0,a.getApprovalMode)(t.approvalMode))}}}if("none"===w)try{const e=await l.proxyGet("/api/projects/"+m),t=e?.data||e,r=t?.metadata?.defaultApprovalMode
3877
- r&&(w=(0,a.getApprovalMode)(r))}catch(e){p.warn("Failed to read project metadata for approvalMode fallback",{error:(0,i.getErrorMessage)(e)})}}catch(e){p.warn("Failed to resolve approval mode, using default",{error:(0,i.getErrorMessage)(e)})}const k="require-approval"===w&&"quick-edit"!==d.type?"pending_approval":"open",b={title:d.title,description:d.description,type:d.type,acceptanceCriteria:d.acceptanceCriteria,status:k,...d.planDocumentId&&{planDocumentId:d.planDocumentId},...g&&{cliOrigin:g}}
3878
- p.info("Creating request via request client",{projectId:m,title:d.title,type:d.type,criteriaCount:d.acceptanceCriteria.length})
3859
+ r&&(w=(0,a.getApprovalMode)(r))}catch(e){f.warn("Failed to read project metadata for approvalMode fallback",{error:(0,i.getErrorMessage)(e)})}}catch(e){f.warn("Failed to resolve approval mode, using default",{error:(0,i.getErrorMessage)(e)})}const k="require-approval"===w&&"quick-edit"!==d.type?"pending_approval":"open",b={title:d.title,description:d.description,type:d.type,acceptanceCriteria:d.acceptanceCriteria,status:k,...d.planDocumentId&&{planDocumentId:d.planDocumentId},...g&&{cliOrigin:g}}
3860
+ f.info("Creating request via request client",{projectId:m,title:d.title,type:d.type,criteriaCount:d.acceptanceCriteria.length})
3879
3861
  const I=await y.createRequest(b)
3880
- p.debug("Create request response structure",{type:typeof I,isArray:Array.isArray(I),hasData:null!=I,properties:I?Object.keys(I):[],dataPreview:I?JSON.stringify(I).substring(0,200)+"...":"null"})
3881
- const v=(0,o.extractDataFromResponse)(I,{logger:p,operationName:"createRequest",throwOnNoData:!0}),C="data"in v?v.data:v
3862
+ f.debug("Create request response structure",{type:typeof I,isArray:Array.isArray(I),hasData:null!=I,properties:I?Object.keys(I):[],dataPreview:I?JSON.stringify(I).substring(0,200)+"...":"null"})
3863
+ const v=(0,o.extractDataFromResponse)(I,{logger:f,operationName:"createRequest",throwOnNoData:!0}),C="data"in v?v.data:v
3882
3864
  let _,E={created:!1}
3883
- if(h?.workspaceManager)try{await h.workspaceManager.initializeRequest(C.id,C.title),E={created:!0,branchName:"requests/"+C.id,message:"Branch created successfully"},p.info("Request branch initialized successfully",{requestId:C.id,branchName:E.branchName,title:C.title})}catch(e){p.warn("Failed to initialize request branch, will retry on first operation",{requestId:C.id,error:(0,i.getErrorMessage)(e)})}else"quick-edit"===d.type?p.info("Quick-edit request - skipping branch creation, will work directly on main",{requestId:C.id}):p.debug("No workspace manager available, branch creation deferred",{requestId:C.id})
3884
- p.info("Request created successfully",{requestId:C.id,title:C.title,branchCreated:E.created,branchName:E.branchName})
3865
+ if(h?.workspaceManager)try{await h.workspaceManager.initializeRequest(C.id,C.title),E={created:!0,branchName:"requests/"+C.id,message:"Branch created successfully"},f.info("Request branch initialized successfully",{requestId:C.id,branchName:E.branchName,title:C.title})}catch(e){f.warn("Failed to initialize request branch, will retry on first operation",{requestId:C.id,error:(0,i.getErrorMessage)(e)})}else"quick-edit"===d.type?f.info("Quick-edit request - skipping branch creation, will work directly on main",{requestId:C.id}):f.debug("No workspace manager available, branch creation deferred",{requestId:C.id})
3866
+ f.info("Request created successfully",{requestId:C.id,title:C.title,branchCreated:E.created,branchName:E.branchName})
3885
3867
  try{const e=l.getToolRecordClient()
3886
3868
  if(e){const t=await e.createToolRecord({requestId:C.id,projectId:m,type:"create-request",metadata:{status:"completed",timestamp:(new Date).toISOString(),requestType:C.type,requestTitle:C.title,requestDescription:C.description,criteriaCount:C.acceptanceCriteria.length,branchCreated:E.created,branchName:E.created?E.branchName:null},note:`Created request "${C.title}" of type ${C.type}${E.created?" with branch "+E.branchName:" - branch will be created on first file operation"}`})
3887
- _=t?.id}}catch(e){p.warn("Failed to create tool record for request creation",{error:(0,i.getErrorMessage)(e),requestId:C.id})}f({success:!0,type:d.type,hasProjectId:!0}),p.info("Request created successfully",{requestId:C.id,title:C.title,type:C.type,projectId:m})
3869
+ _=t?.id}}catch(e){f.warn("Failed to create tool record for request creation",{error:(0,i.getErrorMessage)(e),requestId:C.id})}p({success:!0,type:d.type,hasProjectId:!0}),f.info("Request created successfully",{requestId:C.id,title:C.title,type:C.type,projectId:m})
3888
3870
  const q=C.localId||C.id
3889
3871
  let S="pending_approval"===k?`Created Request ${q} (pending approval)`:"Created Request "+q
3890
- return _&&(S+=`\n[RECORD:${_}]`),{content:[{type:"text",text:S}]}}catch(r){if(p.error("Failed to create request",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new requests")||r.message.includes("disabled due to tier limits")))p.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
3872
+ return _&&(S+=`\n[RECORD:${_}]`),{content:[{type:"text",text:S}]}}catch(r){if(f.error("Failed to create request",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new requests")||r.message.includes("disabled due to tier limits")))f.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
3891
3873
  else{const n=l.getToolRecordClient()
3892
- n&&await n.createToolRecord({projectId:t.projectId,type:"create-request",metadata:{status:"failed",timestamp:(new Date).toISOString(),requestTitle:e.title,requestType:e.type,requestDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),criteriaCount:e.acceptanceCriteria?e.acceptanceCriteria.length:0,branchCreated:!1,branchName:null,error:(0,i.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create request: "+e.title})}}catch(e){p.error("Failed to create failure record for request creation",{error:e instanceof Error?e.message:e+""})}if(f({success:!1,error:r instanceof Error?r.name:"unknown"}),r instanceof s.ZodError&&r.errors.length>0){const e=r.errors[0]
3874
+ n&&await n.createToolRecord({projectId:t.projectId,type:"create-request",metadata:{status:"failed",timestamp:(new Date).toISOString(),requestTitle:e.title,requestType:e.type,requestDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),criteriaCount:e.acceptanceCriteria?e.acceptanceCriteria.length:0,branchCreated:!1,branchName:null,error:(0,i.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create request: "+e.title})}}catch(e){f.error("Failed to create failure record for request creation",{error:e instanceof Error?e.message:e+""})}if(p({success:!1,error:r instanceof Error?r.name:"unknown"}),r instanceof s.ZodError&&r.errors.length>0){const e=r.errors[0]
3893
3875
  let t=e.message
3894
3876
  return e.path.includes("acceptanceCriteria")&&(t=`Acceptance criteria: ${t}. Please provide a list of criteria descriptions.`),{content:[{type:"text",text:"Error: "+t}],isError:!0}}let n=(0,i.getErrorMessage)(r),o="Unable to create request. Please check your input and try again."
3895
3877
  return(n.includes("Project cannot accept new requests")||n.includes("Project is inactive due to tier limits"))&&(o="This project is currently inactive due to tier limits. Only your oldest projects can accept new requests. Please use an active project or upgrade your tier for more simultaneous projects."),{content:[{type:"text",text:`Error: ${n}\n\n${o}`}],isError:!0}}}
@@ -3904,11 +3886,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
3904
3886
  var t={}
3905
3887
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3906
3888
  return o(t,e),t})
3907
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,t,r,n,o,s,h,g){const p=s.child({tool:"modify_file"})
3908
- try{const s=a.validateArgs(e,i.ModifyFileSchema),{taskId:u,operations:f,comment:m}=s
3909
- p.info("Processing modify-file operations",{taskId:u,operationCount:f.length,comment:m})
3889
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,t,r,n,o,s,h,g){const f=s.child({tool:"modify_file"})
3890
+ try{const s=a.validateArgs(e,i.ModifyFileSchema),{taskId:u,operations:p,comment:m}=s
3891
+ f.info("Processing modify-file operations",{taskId:u,operationCount:p.length,comment:m})
3910
3892
  const y=[],w=[],k=[],b=[],I=[]
3911
- for(const e of f){const t={path:e.path,documentId:e.documentId}
3893
+ for(const e of p){const t={path:e.path,documentId:e.documentId}
3912
3894
  switch(e.operationType){case"replace-string":y.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
3913
3895
  break
3914
3896
  case"insert-lines":w.push({...t,insertions:e.insertLines.insertions})
@@ -3918,40 +3900,40 @@ break
3918
3900
  case"delete-string":b.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
3919
3901
  break
3920
3902
  case"delete-lines":I.push({...t,lines:e.deleteLines.lines})}}const v=[]
3921
- if(y.length>0){p.info("Routing to replace-strings handler",{operationCount:y.length})
3922
- const e=await(0,c.handleReplaceStrings)({taskId:u,operations:y,comment:m+" [via modify-file: replace-string]"},t,r,n,o,p,h,g)
3923
- v.push({type:"replace-string",result:e})}if(w.length>0){p.info("Routing to insert-lines handler",{operationCount:w.length})
3924
- const e=await(0,l.handleInsertLines)({taskId:u,operations:w,comment:m+" [via modify-file: insert-lines]"},t,r,n,o,p,h,g)
3925
- v.push({type:"insert-lines",result:e})}if(k.length>0){p.info("Routing to replace-lines handler",{operationCount:k.length})
3926
- const e=await(0,d.handleReplaceLines)({taskId:u,operations:k,comment:m+" [via modify-file: replace-lines]"},t,r,n,o,p,h,g)
3927
- v.push({type:"replace-lines",result:e})}if(b.length>0){p.info("Routing delete-string to replace-strings handler",{operationCount:b.length})
3928
- const e=await(0,c.handleReplaceStrings)({taskId:u,operations:b,comment:m+" [via modify-file: delete-string]"},t,r,n,o,p,h,g)
3929
- v.push({type:"delete-string",result:e})}if(I.length>0){p.info("Processing delete-lines operations",{operationCount:I.length})
3930
- const e=I.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),s=await(0,d.handleReplaceLines)({taskId:u,operations:e,comment:m+" [via modify-file: delete-lines]"},t,r,n,o,p,h,g)
3903
+ if(y.length>0){f.info("Routing to replace-strings handler",{operationCount:y.length})
3904
+ const e=await(0,c.handleReplaceStrings)({taskId:u,operations:y,comment:m+" [via modify-file: replace-string]"},t,r,n,o,f,h,g)
3905
+ v.push({type:"replace-string",result:e})}if(w.length>0){f.info("Routing to insert-lines handler",{operationCount:w.length})
3906
+ const e=await(0,l.handleInsertLines)({taskId:u,operations:w,comment:m+" [via modify-file: insert-lines]"},t,r,n,o,f,h,g)
3907
+ v.push({type:"insert-lines",result:e})}if(k.length>0){f.info("Routing to replace-lines handler",{operationCount:k.length})
3908
+ const e=await(0,d.handleReplaceLines)({taskId:u,operations:k,comment:m+" [via modify-file: replace-lines]"},t,r,n,o,f,h,g)
3909
+ v.push({type:"replace-lines",result:e})}if(b.length>0){f.info("Routing delete-string to replace-strings handler",{operationCount:b.length})
3910
+ const e=await(0,c.handleReplaceStrings)({taskId:u,operations:b,comment:m+" [via modify-file: delete-string]"},t,r,n,o,f,h,g)
3911
+ v.push({type:"delete-string",result:e})}if(I.length>0){f.info("Processing delete-lines operations",{operationCount:I.length})
3912
+ const e=I.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),s=await(0,d.handleReplaceLines)({taskId:u,operations:e,comment:m+" [via modify-file: delete-lines]"},t,r,n,o,f,h,g)
3931
3913
  v.push({type:"delete-lines",result:s})}const C=v.some((e=>e.result.isError)),_=v.filter((e=>!e.result.isError)).length,E=v.filter((e=>e.result.isError)).length
3932
3914
  let q="## Modify File Results\n\n"
3933
3915
  q+="**Summary:**\n",q+=`- **Total operation types:** ${v.length}\n`,q+=`- **Successful:** ${_}\n`,q+=`- **Failed:** ${E}\n\n`
3934
3916
  for(const{type:e,result:t}of v)q+=`### ${e} operations\n`,q+=t.content[0].text+"\n\n"
3935
- return p.info("Modify-file operations completed",{totalOperationTypes:v.length,successCount:_,errorCount:E}),h.incrementCounter("modify_file_total",1,{success:!C}),{content:[{type:"text",text:q}],isError:C}}catch(e){return p.error("Modify-file operation failed",{error:e instanceof Error?e.stack:e+""}),h.incrementCounter("modify_file_errors",1),{content:[{type:"text",text:"\u274c **Modify File Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
3917
+ return f.info("Modify-file operations completed",{totalOperationTypes:v.length,successCount:_,errorCount:E}),h.incrementCounter("modify_file_total",1,{success:!C}),{content:[{type:"text",text:q}],isError:C}}catch(e){return f.error("Modify-file operation failed",{error:e instanceof Error?e.stack:e+""}),h.incrementCounter("modify_file_errors",1),{content:[{type:"text",text:"\u274c **Modify File Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
3936
3918
  const i=t(6183),a=s(t(5967)),c=t(3306),l=t(6486),d=t(6651),u=t(8824)},7478(e,exports,t){async function r(e,t,r){const n=r.startTimer("git_get_current_branch_duration")
3937
3919
  try{const o=(await e.status()).current
3938
3920
  if(!o)throw new g.ValidationError("Repository is in detached HEAD state or branch detection failed")
3939
- return t.debug("Retrieved current branch",{branch:o}),r.incrementCounter("git_get_current_branch_success",1),n({success:!0}),o}catch(e){const o=(0,f.getErrorMessage)(e)
3921
+ return t.debug("Retrieved current branch",{branch:o}),r.incrementCounter("git_get_current_branch_success",1),n({success:!0}),o}catch(e){const o=(0,p.getErrorMessage)(e)
3940
3922
  throw t.error("Failed to get current branch",{error:o}),r.incrementCounter("git_get_current_branch_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to get current branch: "+o)}}async function n(e,t,r,n){const o=n.startTimer("git_branch_exists_duration")
3941
3923
  try{const s=(await e.branch(["-l"])).all.includes(t)
3942
- return r.debug("Checked branch existence",{branchName:t,exists:s}),n.incrementCounter("git_branch_exists_check",1,{exists:s.toString()}),o({success:!0}),s}catch(e){const s=(0,f.getErrorMessage)(e)
3924
+ return r.debug("Checked branch existence",{branchName:t,exists:s}),n.incrementCounter("git_branch_exists_check",1,{exists:s.toString()}),o({success:!0}),s}catch(e){const s=(0,p.getErrorMessage)(e)
3943
3925
  return r.error("Failed to check branch existence",{branchName:t,error:s}),n.incrementCounter("git_branch_exists_failure",1),o({success:!1,error:e instanceof Error?e.name:"unknown"}),!1}}async function o(e,t,o,s){const i=s.startTimer("git_switch_branch_duration")
3944
3926
  try{const a=await r(e,o,s)
3945
3927
  if(a===t)return o.debug("Already on target branch",{branchName:t}),s.incrementCounter("git_switch_branch_noop",1),i({success:!0,reason:"already_on_branch"}),{success:!0,branchName:t,previousBranch:a,message:`Already on branch '${t}'`}
3946
3928
  if(!await n(e,t,o,s)){const e=`Branch '${t}' does not exist`
3947
3929
  throw o.error(e),s.incrementCounter("git_switch_branch_not_found",1),i({success:!1,reason:"branch_not_found"}),new g.ValidationError(e)}await e.checkout(t)
3948
3930
  const c=await e.revparse(["HEAD"])
3949
- return o.info("Switched to branch",{branchName:t,previousBranch:a,commitHash:c.substring(0,8)}),s.incrementCounter("git_switch_branch_success",1),i({success:!0}),{success:!0,branchName:t,previousBranch:a,commitHash:c,message:`Switched from '${a}' to '${t}'`}}catch(e){const r=(0,f.getErrorMessage)(e)
3931
+ return o.info("Switched to branch",{branchName:t,previousBranch:a,commitHash:c.substring(0,8)}),s.incrementCounter("git_switch_branch_success",1),i({success:!0}),{success:!0,branchName:t,previousBranch:a,commitHash:c,message:`Switched from '${a}' to '${t}'`}}catch(e){const r=(0,p.getErrorMessage)(e)
3950
3932
  throw o.error("Failed to switch branch",{branchName:t,error:r}),s.incrementCounter("git_switch_branch_failure",1),i({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to switch to branch '${t}': ${r}`)}}async function s(e,t,r){const n=r.startTimer("git_repository_status_duration")
3951
3933
  try{let o,s=!0
3952
3934
  try{o=await e.status()}catch(e){return s=!1,t.warn("Not a git repository or git not available"),r.incrementCounter("git_repository_status_not_git",1),n({success:!0,reason:"not_git_repo"}),{isGitRepository:!1,currentBranch:"",isClean:!1,hasMainBranch:!1,hasMasterBranch:!1,defaultBranch:"",uncommittedChanges:[],branches:[]}}const i=o.current||"",a=0===o.files.length,c=o.files.map((e=>e.path)),l=await e.branch(["-l"]),d=l.all.map((e=>({name:e,isCurrentBranch:e===i}))),u=l.all.includes("main"),h=l.all.includes("master")
3953
3935
  let g=""
3954
- return u?g="main":h?g="master":d.length>0&&(g=d[0].name),t.debug("Retrieved repository status",{currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,branchCount:d.length,uncommittedCount:c.length}),r.incrementCounter("git_repository_status_success",1),n({success:!0}),{isGitRepository:s,currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,uncommittedChanges:c,branches:d}}catch(e){const o=(0,f.getErrorMessage)(e)
3936
+ return u?g="main":h?g="master":d.length>0&&(g=d[0].name),t.debug("Retrieved repository status",{currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,branchCount:d.length,uncommittedCount:c.length}),r.incrementCounter("git_repository_status_success",1),n({success:!0}),{isGitRepository:s,currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,uncommittedChanges:c,branches:d}}catch(e){const o=(0,p.getErrorMessage)(e)
3955
3937
  throw t.error("Failed to get repository status",{error:o}),r.incrementCounter("git_repository_status_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to get repository status: "+o)}}function i(e){return"requests/"+e}async function a(e,t,r){const n=r.startTimer("git_uncommitted_changes_check_duration")
3956
3938
  try{t.debug("Starting uncommitted changes check"),t.debug("Checking for uncommitted changes before merge"),Date.now()
3957
3939
  const o=await e.status()
@@ -3963,7 +3945,7 @@ t.debug("Uncommitted changes summary",{hasChanges:l,totalFiles:c,staged:s.length
3963
3945
  let d=""
3964
3946
  if(l){const e=[]
3965
3947
  s.length>0&&e.push(s.length+" staged file(s)"),i.length>0&&e.push(i.length+" unstaged file(s)"),a.length>0&&e.push(a.length+" untracked file(s)"),d=`Found ${c} uncommitted change(s): ${e.join(", ")}`}else d="No uncommitted changes detected"
3966
- return(0,h.isDebugToolsEnabled)()&&t.debug("Summary",{summary:d}),t.debug("Uncommitted changes check completed",{hasChanges:l,staged:s.length,unstaged:i.length,untracked:a.length,total:c,summary:d}),r.incrementCounter("git_uncommitted_changes_check_success",1),r.recordValue("git_uncommitted_changes_total_files",c),n({success:!0}),{hasChanges:l,stagedFiles:s,unstagedFiles:i,untrackedFiles:a,totalFiles:c,summary:d}}catch(e){const o=(0,f.getErrorMessage)(e)
3948
+ return(0,h.isDebugToolsEnabled)()&&t.debug("Summary",{summary:d}),t.debug("Uncommitted changes check completed",{hasChanges:l,staged:s.length,unstaged:i.length,untracked:a.length,total:c,summary:d}),r.incrementCounter("git_uncommitted_changes_check_success",1),r.recordValue("git_uncommitted_changes_total_files",c),n({success:!0}),{hasChanges:l,stagedFiles:s,unstagedFiles:i,untrackedFiles:a,totalFiles:c,summary:d}}catch(e){const o=(0,p.getErrorMessage)(e)
3967
3949
  throw t.error("Failed to check uncommitted changes",{error:o}),r.incrementCounter("git_uncommitted_changes_check_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to check uncommitted changes: "+o)}}var c,l=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3968
3950
  var o=Object.getOwnPropertyDescriptor(t,r)
3969
3951
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),d=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),u=this&&this.__importStar||(c=function(e){return c=Object.getOwnPropertyNames||function(e){var t=[]
@@ -3977,42 +3959,42 @@ try{if(await n(e,t,s,i)){const e=`Branch '${t}' already exists`
3977
3959
  return s.warn(e),i.incrementCounter("git_create_branch_already_exists",1),c({success:!1,reason:"already_exists"}),{success:!1,branchName:t,message:e}}const l=await r(e,s,i)
3978
3960
  await e.checkoutBranch(t,o)
3979
3961
  const d=await e.revparse(["HEAD"]),u=a||l
3980
- return await e.checkout(u),s.info("Created new branch",{branchName:t,fromBranch:o,currentBranch:l,returnedToBranch:u,commitHash:d.substring(0,8)}),i.incrementCounter("git_create_branch_success",1),c({success:!0}),{success:!0,branchName:t,previousBranch:l,commitHash:d,message:`Created branch '${t}' from '${o}'`}}catch(e){const r=(0,f.getErrorMessage)(e)
3962
+ return await e.checkout(u),s.info("Created new branch",{branchName:t,fromBranch:o,currentBranch:l,returnedToBranch:u,commitHash:d.substring(0,8)}),i.incrementCounter("git_create_branch_success",1),c({success:!0}),{success:!0,branchName:t,previousBranch:l,commitHash:d,message:`Created branch '${t}' from '${o}'`}}catch(e){const r=(0,p.getErrorMessage)(e)
3981
3963
  throw s.error("Failed to create branch",{branchName:t,fromBranch:o,error:r}),i.incrementCounter("git_create_branch_failure",1),c({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to create branch '${t}': ${r}`)}},exports.switchToBranch=o,exports.mergeBranch=async function(e,t,s,i,a,c){const l=a.startTimer("git_merge_branch_duration")
3982
3964
  try{const d=await r(e,i,a)
3983
3965
  if(d!==s&&await o(e,s,i,a),!await n(e,t,i,a)){const e=`Source branch '${t}' does not exist`
3984
3966
  throw i.error(e),a.incrementCounter("git_merge_branch_source_not_found",1),l({success:!1,reason:"source_not_found"}),new g.ValidationError(e)}const u=c?["--no-ff","-m",c,t]:["--no-ff",t],h=(await e.merge(u),await e.revparse(["HEAD"]))
3985
- return i.info("Successfully merged branch",{sourceBranch:t,targetBranch:s,commitHash:h.substring(0,8),mergeMessage:c||"default merge message"}),a.incrementCounter("git_merge_branch_success",1),l({success:!0}),{success:!0,branchName:s,previousBranch:d,commitHash:h,message:`Merged '${t}' into '${s}'`}}catch(e){const r=(0,f.getErrorMessage)(e)
3967
+ return i.info("Successfully merged branch",{sourceBranch:t,targetBranch:s,commitHash:h.substring(0,8),mergeMessage:c||"default merge message"}),a.incrementCounter("git_merge_branch_success",1),l({success:!0}),{success:!0,branchName:s,previousBranch:d,commitHash:h,message:`Merged '${t}' into '${s}'`}}catch(e){const r=(0,p.getErrorMessage)(e)
3986
3968
  throw i.error("Failed to merge branch",{sourceBranch:t,targetBranch:s,error:r}),a.incrementCounter("git_merge_branch_failure",1),l({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to merge '${t}' into '${s}': ${r}`)}},exports.deleteBranch=async function(e,t,o=!1,s,i){const a=i.startTimer("git_delete_branch_duration")
3987
3969
  try{const c=await r(e,s,i)
3988
3970
  if(c===t){const e=`Cannot delete current branch '${t}'`
3989
3971
  throw s.error(e),i.incrementCounter("git_delete_branch_current_branch",1),a({success:!1,reason:"current_branch"}),new g.ValidationError(e)}if("main"===t||"master"===t){const e=`Cannot delete protected branch '${t}'`
3990
3972
  throw s.error(e),i.incrementCounter("git_delete_branch_protected",1),a({success:!1,reason:"protected_branch"}),new g.ValidationError(e)}if(!await n(e,t,s,i)){const e=`Branch '${t}' does not exist`
3991
3973
  return s.warn(e),i.incrementCounter("git_delete_branch_not_found",1),a({success:!1,reason:"not_found"}),{success:!1,branchName:t,message:e}}const l=o?["-D",t]:["-d",t]
3992
- return await e.branch(l),s.info("Deleted branch",{branchName:t,force:o,currentBranch:c}),i.incrementCounter("git_delete_branch_success",1),a({success:!0}),{success:!0,branchName:t,previousBranch:c,message:`Deleted branch '${t}'${o?" (forced)":""}`}}catch(e){const r=(0,f.getErrorMessage)(e)
3974
+ return await e.branch(l),s.info("Deleted branch",{branchName:t,force:o,currentBranch:c}),i.incrementCounter("git_delete_branch_success",1),a({success:!0}),{success:!0,branchName:t,previousBranch:c,message:`Deleted branch '${t}'${o?" (forced)":""}`}}catch(e){const r=(0,p.getErrorMessage)(e)
3993
3975
  throw s.error("Failed to delete branch",{branchName:t,force:o,error:r}),i.incrementCounter("git_delete_branch_failure",1),a({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to delete branch '${t}': ${r}`)}},exports.getRepositoryStatus=s,exports.validateGitRepository=async function(e,t,r){const n=r.startTimer("git_validate_repository_duration")
3994
3976
  try{const o=await s(e,t,r)
3995
- return o.isGitRepository?(o.currentBranch||(t.warn("Git repository in detached HEAD state"),r.incrementCounter("git_validate_repository_detached_head",1)),o.isClean||(t.warn("Git repository has uncommitted changes",{count:o.uncommittedChanges.length,files:o.uncommittedChanges.slice(0,5)}),r.incrementCounter("git_validate_repository_dirty",1)),o.defaultBranch||(t.warn("No default branch found in git repository"),r.incrementCounter("git_validate_repository_no_default_branch",1)),t.info("Git repository validation completed",{currentBranch:o.currentBranch,isClean:o.isClean,defaultBranch:o.defaultBranch,branchCount:o.branches.length}),r.incrementCounter("git_validate_repository_success",1),n({success:!0}),o):(t.warn("Git repository validation failed: not a git repository"),r.incrementCounter("git_validate_repository_not_git",1),n({success:!1,reason:"not_git_repo"}),o)}catch(e){const o=(0,f.getErrorMessage)(e)
3977
+ return o.isGitRepository?(o.currentBranch||(t.warn("Git repository in detached HEAD state"),r.incrementCounter("git_validate_repository_detached_head",1)),o.isClean||(t.warn("Git repository has uncommitted changes",{count:o.uncommittedChanges.length,files:o.uncommittedChanges.slice(0,5)}),r.incrementCounter("git_validate_repository_dirty",1)),o.defaultBranch||(t.warn("No default branch found in git repository"),r.incrementCounter("git_validate_repository_no_default_branch",1)),t.info("Git repository validation completed",{currentBranch:o.currentBranch,isClean:o.isClean,defaultBranch:o.defaultBranch,branchCount:o.branches.length}),r.incrementCounter("git_validate_repository_success",1),n({success:!0}),o):(t.warn("Git repository validation failed: not a git repository"),r.incrementCounter("git_validate_repository_not_git",1),n({success:!1,reason:"not_git_repo"}),o)}catch(e){const o=(0,p.getErrorMessage)(e)
3996
3978
  throw t.error("Git repository validation failed",{error:o}),r.incrementCounter("git_validate_repository_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Git repository validation failed: "+o)}},exports.sanitizeBranchName=function(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,50)},exports.generateRequestBranchName=i,exports.generateMergeMessagePatterns=function(e){const t=i(e)
3997
3979
  return[`Merge ${t}-`,"Merge "+t,`Merge ${t}-.*\\(resolved conflicts\\)`,`Merge ${t} \\(resolved conflicts\\)`]},exports.parseRequestIdFromBranchName=function(e){const t=e.match(/^feature\/(req\d{6})-/)
3998
3980
  return t?t[1]:null},exports.switchToDefaultBranch=async function(e,t,r){const n=r.startTimer("git_switch_to_default_duration")
3999
3981
  try{const i=await s(e,t,r)
4000
3982
  if(!i.defaultBranch){const e="No default branch found"
4001
3983
  return t.warn(e),r.incrementCounter("git_switch_to_default_no_branch",1),n({success:!1,reason:"no_default_branch"}),{success:!1,branchName:"",message:e}}const a=await o(e,i.defaultBranch,t,r)
4002
- return a.success?(t.info("Switched to default branch",{defaultBranch:i.defaultBranch,previousBranch:a.previousBranch}),r.incrementCounter("git_switch_to_default_success",1),n({success:!0})):(r.incrementCounter("git_switch_to_default_failed",1),n({success:!1,reason:"switch_failed"})),a}catch(e){const o=(0,f.getErrorMessage)(e)
3984
+ return a.success?(t.info("Switched to default branch",{defaultBranch:i.defaultBranch,previousBranch:a.previousBranch}),r.incrementCounter("git_switch_to_default_success",1),n({success:!0})):(r.incrementCounter("git_switch_to_default_failed",1),n({success:!1,reason:"switch_failed"})),a}catch(e){const o=(0,p.getErrorMessage)(e)
4003
3985
  throw t.error("Failed to switch to default branch",{error:o}),r.incrementCounter("git_switch_to_default_error",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to switch to default branch: "+o)}},exports.ensureRepositoryReady=async function(e,t,r){const n=r.startTimer("git_ensure_repository_ready_duration")
4004
3986
  try{const o=await s(e,t,r),i=[]
4005
3987
  o.isGitRepository||i.push("Not a git repository"),o.currentBranch||i.push("Repository is in detached HEAD state"),o.defaultBranch||i.push("No default branch (main/master) found")
4006
3988
  const a=0===i.length
4007
- return t.debug("Repository readiness check completed",{ready:a,issueCount:i.length,issues:i}),r.incrementCounter("git_ensure_repository_ready_check",1,{ready:a.toString()}),n({success:!0,ready:a.toString()}),{ready:a,status:o,issues:i}}catch(e){const o=(0,f.getErrorMessage)(e)
3989
+ return t.debug("Repository readiness check completed",{ready:a,issueCount:i.length,issues:i}),r.incrementCounter("git_ensure_repository_ready_check",1,{ready:a.toString()}),n({success:!0,ready:a.toString()}),{ready:a,status:o,issues:i}}catch(e){const o=(0,p.getErrorMessage)(e)
4008
3990
  return t.error("Failed to check repository readiness",{error:o}),r.incrementCounter("git_ensure_repository_ready_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),{ready:!1,status:{isGitRepository:!1,currentBranch:"",isClean:!1,hasMainBranch:!1,hasMasterBranch:!1,defaultBranch:"",uncommittedChanges:[],branches:[]},issues:["Repository check failed: "+o]}}},exports.hasMainChangedSinceRevert=async function(e,t,r,n){const o=n.startTimer("git_check_main_changed_since_revert")
4009
3991
  try{r.debug("Starting main branch change detection",{providedRevertCommitHash:t.substring(0,8),fullRevertCommitHash:t})
4010
3992
  const n=await e.revparse(["HEAD"])
4011
3993
  r.debug("Git state captured",{currentMainHash:n.substring(0,8),fullCurrentMainHash:n,revertCommitHash:t.substring(0,8),fullRevertCommitHash:t,hashesMatch:n===t})
4012
3994
  try{const t=await e.revparse(["--abbrev-ref","HEAD"]),n=await e.status(),o=await e.log(["--oneline","-5"])
4013
- r.debug("Additional git context",{currentBranch:t,gitStatus:{ahead:n.ahead,behind:n.behind,current:n.current,tracking:n.tracking,staged:n.staged.length,modified:n.modified.length},recentCommits:o.all.map((e=>({hash:e.hash.substring(0,8),message:e.message})))})}catch(e){r.warn("Failed to gather additional git context",{error:e instanceof Error?e.message:e+""})}const s=await(0,p.validateCommitHash)(e,t,r,"hasMainChangedSinceRevert-revert-validation")
3995
+ r.debug("Additional git context",{currentBranch:t,gitStatus:{ahead:n.ahead,behind:n.behind,current:n.current,tracking:n.tracking,staged:n.staged.length,modified:n.modified.length},recentCommits:o.all.map((e=>({hash:e.hash.substring(0,8),message:e.message})))})}catch(e){r.warn("Failed to gather additional git context",{error:e instanceof Error?e.message:e+""})}const s=await(0,f.validateCommitHash)(e,t,r,"hasMainChangedSinceRevert-revert-validation")
4014
3996
  if(!s.valid)throw r.error("Revert commit validation failed",{revertCommitHash:t.substring(0,8),error:s.error}),Error(`Revert commit ${t.substring(0,8)} not found or not reachable: ${s.error}`)
4015
- const i=await(0,p.validateCommitHash)(e,n,r,"hasMainChangedSinceRevert-head-validation")
3997
+ const i=await(0,f.validateCommitHash)(e,n,r,"hasMainChangedSinceRevert-head-validation")
4016
3998
  if(!i.valid)throw r.error("Current HEAD validation failed",{currentMainHash:n.substring(0,8),error:i.error}),Error(`Current HEAD ${n.substring(0,8)} validation failed: ${i.error}`)
4017
3999
  if(n===t)return r.info("Main branch unchanged since revert - exact hash match",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),fullHashMatch:!0}),o({success:!0,changed:"false"}),{hasChanged:!1,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:0,message:"Main branch has not changed since revert"}
4018
4000
  r.debug("Hash comparison shows difference, checking ancestor relationship",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),hashesEqual:!1})
@@ -4020,10 +4002,10 @@ let a=!1,c=0,l=null
4020
4002
  for(let n=1;3>=n;n++)try{r.debug("Checking ancestor relationship with merge-base",{revertCommitHash:t.substring(0,8),currentHead:"HEAD",attempt:n}),n>1&&(await new Promise((e=>setTimeout(e,100))),r.debug("Retry attempt after delay",{attempt:n,delay:100})),await e.raw(["merge-base","--is-ancestor",t,"HEAD"]),r.debug("Revert commit is ancestor of HEAD, counting commits between them",{attempt:n})
4021
4003
  const o=await e.raw(["rev-list","--count",t+"..HEAD"])
4022
4004
  c=parseInt(o.trim(),10),a=!0
4023
- break}catch(e){l=e,r.debug("Ancestor check attempt failed",{attempt:n,error:(0,f.getErrorMessage)(e)}),3===n&&r.debug("All ancestor check attempts failed, treating as non-ancestor")}if(a){try{const n=await e.raw(["rev-list","--oneline",t+"..HEAD"])
4005
+ break}catch(e){l=e,r.debug("Ancestor check attempt failed",{attempt:n,error:(0,p.getErrorMessage)(e)}),3===n&&r.debug("All ancestor check attempts failed, treating as non-ancestor")}if(a){try{const n=await e.raw(["rev-list","--oneline",t+"..HEAD"])
4024
4006
  r.debug("Commits found between revert and HEAD",{count:c,commits:n.trim().split("\n").filter((e=>e.length>0))})}catch(e){r.warn("Could not list commits between revert and HEAD",{error:e instanceof Error?e.message:e+""})}return r.info("Main branch has changed since revert - ancestor relationship confirmed",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),commitsSinceRevert:c,isAncestor:!0}),o({success:!0,changed:"true"}),{hasChanged:!0,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:c,message:`Main branch has ${c} new commit${c>1?"s":""} since revert`}}r.warn("Revert commit is not an ancestor of current HEAD after retries - investigating relationship",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),lastAncestorError:l instanceof Error?l.message:l+"",attempts:3})
4025
4007
  try{const o=await e.raw(["merge-base",t,"HEAD"])
4026
- r.debug("Merge base found between revert commit and HEAD",{mergeBase:o.trim().substring(0,8),revertCommitHash:t.substring(0,8),currentMainHash:n.substring(0,8)})}catch(e){r.warn("Could not find merge base",{error:e instanceof Error?e.message:e+""})}try{await e.raw(["merge-base","--is-ancestor","HEAD",t]),r.error("CRITICAL: Current HEAD is ancestor of revert commit - possible git state corruption or incorrect revert hash",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),implication:"This suggests the stored revert commit hash may be incorrect or from a different branch state"})}catch(e){r.debug("HEAD is not ancestor of revert commit either - commits may be on divergent paths",{error:e instanceof Error?e.message:e+""})}return o({success:!0,changed:"unknown"}),{hasChanged:!0,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:-1,message:"Cannot determine relationship between revert commit and current HEAD - assuming changed for safety. This may indicate a stored revert commit hash issue."}}catch(e){const n=(0,f.getErrorMessage)(e)
4008
+ r.debug("Merge base found between revert commit and HEAD",{mergeBase:o.trim().substring(0,8),revertCommitHash:t.substring(0,8),currentMainHash:n.substring(0,8)})}catch(e){r.warn("Could not find merge base",{error:e instanceof Error?e.message:e+""})}try{await e.raw(["merge-base","--is-ancestor","HEAD",t]),r.error("CRITICAL: Current HEAD is ancestor of revert commit - possible git state corruption or incorrect revert hash",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),implication:"This suggests the stored revert commit hash may be incorrect or from a different branch state"})}catch(e){r.debug("HEAD is not ancestor of revert commit either - commits may be on divergent paths",{error:e instanceof Error?e.message:e+""})}return o({success:!0,changed:"unknown"}),{hasChanged:!0,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:-1,message:"Cannot determine relationship between revert commit and current HEAD - assuming changed for safety. This may indicate a stored revert commit hash issue."}}catch(e){const n=(0,p.getErrorMessage)(e)
4027
4009
  throw r.error("Failed to check if main changed since revert",{revertCommitHash:t.substring(0,8),error:n}),o({success:!1,error:e instanceof Error?e.name:"unknown"}),Error("Failed to check main branch changes: "+n)}},exports.findRevertCommitHash=async function(e,t,r){try{r.debug("Searching for revert commit hash in tool records",{requestId:e})
4028
4010
  const n=await t.getToolRecordsByRequestId(e,"revert-request")
4029
4011
  if(n.sort(((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime())),!n||0===n.length)return r.debug("No revert tool records found for request",{requestId:e}),{found:!1,message:"No revert operations found for this request"}
@@ -4032,7 +4014,7 @@ for(const t of n)if(r.debug("Examining tool record",{requestId:e,recordId:t.id,r
4032
4014
  r.debug("Found potential revert commit hash, validating...",{requestId:e,revertCommitHash:o.substring(0,8),fullRevertCommitHash:o,revertType:n,recordId:t.id,revertedAt:t.createdAt})
4033
4015
  try{if(!/^[a-f0-9]{40}$/i.test(o)){r.warn("Invalid commit hash format found in tool record",{requestId:e,invalidHash:o,recordId:t.id,format:"Expected 40-character hex string"})
4034
4016
  continue}return r.info("Found valid revert commit hash from tool records",{requestId:e,revertCommitHash:o.substring(0,8),fullRevertCommitHash:o,revertType:n,recordId:t.id,revertedAt:t.createdAt,hashFormat:"valid"}),{found:!0,revertCommitHash:o,revertType:n,revertedAt:t.createdAt,message:`Found ${n} revert commit from ${t.createdAt}`}}catch(n){r.warn("Revert commit hash validation failed, trying next record",{requestId:e,revertCommitHash:o.substring(0,8),recordId:t.id,error:n instanceof Error?n.message:n+""})
4035
- continue}}return r.warn("Found revert tool records but none have completed status with commit hash",{requestId:e,recordCount:n.length,records:n.map((e=>({type:e.type,status:e.metadata?.status,hasCommitHash:!!e.metadata?.revertCommitHash})))}),{found:!1,message:"Found revert records but none were completed successfully"}}catch(t){const n=(0,f.getErrorMessage)(t)
4017
+ continue}}return r.warn("Found revert tool records but none have completed status with commit hash",{requestId:e,recordCount:n.length,records:n.map((e=>({type:e.type,status:e.metadata?.status,hasCommitHash:!!e.metadata?.revertCommitHash})))}),{found:!1,message:"Found revert records but none were completed successfully"}}catch(t){const n=(0,p.getErrorMessage)(t)
4036
4018
  return r.error("Failed to find revert commit hash from tool records",{requestId:e,error:n}),{found:!1,message:"Failed to search tool records: "+n}}},exports.checkUncommittedChanges=a,exports.commitUserChanges=async function(e,t,r,n,o){const s=o.startTimer("git_commit_user_changes_duration")
4037
4019
  try{if(!r.hasChanges)throw new g.ValidationError("No uncommitted changes to commit")
4038
4020
  n.debug("Starting user changes commit process",{staged:r.stagedFiles.length,unstaged:r.unstagedFiles.length,untracked:r.untrackedFiles.length,total:r.totalFiles}),n.info("Committing user changes before merge",{requestId:t,staged:r.stagedFiles.length,unstaged:r.unstagedFiles.length,untracked:r.untrackedFiles.length,total:r.totalFiles})
@@ -4041,7 +4023,7 @@ i.length>0?(n.debug("Staging files",{files:i.slice(0,10),total:i.length}),await
4041
4023
  const a=`chore: commit user changes before merging request ${t}\n\n${r.summary}\n\nThis commit preserves user modifications made during the request lifecycle\nbefore proceeding with the branch merge operation.`
4042
4024
  n.debug("Commit message",{message:a.split("\n")[0]}),n.debug("Creating commit"),await e.commit(a)
4043
4025
  const c=await e.revparse(["HEAD"])
4044
- return n.debug("Commit created successfully",{commitHash:c.substring(0,8),filesCommitted:r.totalFiles}),n.info("Successfully committed user changes",{requestId:t,commitHash:c.substring(0,8),filesCommitted:r.totalFiles,message:a.split("\n")[0]}),o.incrementCounter("git_commit_user_changes_success",1),o.recordValue("git_commit_user_changes_files",r.totalFiles),s({success:!0}),{commitHash:c,message:a,filesCommitted:r.totalFiles}}catch(e){const i=(0,f.getErrorMessage)(e)
4026
+ return n.debug("Commit created successfully",{commitHash:c.substring(0,8),filesCommitted:r.totalFiles}),n.info("Successfully committed user changes",{requestId:t,commitHash:c.substring(0,8),filesCommitted:r.totalFiles,message:a.split("\n")[0]}),o.incrementCounter("git_commit_user_changes_success",1),o.recordValue("git_commit_user_changes_files",r.totalFiles),s({success:!0}),{commitHash:c,message:a,filesCommitted:r.totalFiles}}catch(e){const i=(0,p.getErrorMessage)(e)
4045
4027
  throw n.error("Failed to commit user changes",{requestId:t,error:i,uncommittedFiles:r.totalFiles}),o.incrementCounter("git_commit_user_changes_failure",1),s({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to commit user changes: "+i)}},exports.commitUserChangesBeforeToolOperation=async function(e,r,n,o,s){const i=s.startTimer("git_pre_tool_user_changes_duration")
4046
4028
  try{let c=Date.now()
4047
4029
  o.debug("Checking for user changes before tool operation",{toolName:r})
@@ -4058,8 +4040,8 @@ const h=`${u}\n\n${{...d,summary:`User changes detected before ${r}: ${d.summary
4058
4040
  o.debug("Committing user changes with message",{firstLine:h.split("\n")[0]})
4059
4041
  const g=[...d.unstagedFiles,...d.untrackedFiles]
4060
4042
  c=Date.now(),g.length>0&&(o.debug("Staging files before tool operation",{files:g.slice(0,10),total:g.length}),await l.add(g)),Date.now(),c=Date.now(),await l.commit(h),Date.now()
4061
- const p=await l.revparse(["HEAD"])
4062
- return o.debug("User changes committed successfully before tool",{commitHash:p.substring(0,8),filesCommitted:d.totalFiles,toolName:r}),o.info("Successfully committed user changes before tool operation",{toolName:r,requestId:n.requestId,taskId:n.taskId,commitHash:p.substring(0,8),filesCommitted:d.totalFiles}),s.incrementCounter("git_pre_tool_user_changes_committed",1),s.recordValue("git_pre_tool_user_changes_files",d.totalFiles),i({success:!0,reason:"changes_committed"}),{userChangesCommitted:!0,commitHash:p,filesCommitted:d.totalFiles}}catch(e){const t=(0,f.getErrorMessage)(e)
4043
+ const f=await l.revparse(["HEAD"])
4044
+ return o.debug("User changes committed successfully before tool",{commitHash:f.substring(0,8),filesCommitted:d.totalFiles,toolName:r}),o.info("Successfully committed user changes before tool operation",{toolName:r,requestId:n.requestId,taskId:n.taskId,commitHash:f.substring(0,8),filesCommitted:d.totalFiles}),s.incrementCounter("git_pre_tool_user_changes_committed",1),s.recordValue("git_pre_tool_user_changes_files",d.totalFiles),i({success:!0,reason:"changes_committed"}),{userChangesCommitted:!0,commitHash:f,filesCommitted:d.totalFiles}}catch(e){const t=(0,p.getErrorMessage)(e)
4063
4045
  return o.debug("Failed to commit user changes before tool",{toolName:r,error:t}),o.warn("Failed to commit user changes before tool operation",{toolName:r,requestId:n.requestId,taskId:n.taskId,error:t}),s.incrementCounter("git_pre_tool_user_changes_failed",1),i({success:!1,error:e instanceof Error?e.name:"unknown"}),{userChangesCommitted:!1}}},exports.findLargeUntrackedFiles=async function(e,r=104857600){const n=[]
4064
4046
  try{const o=t(3807).simpleGit(e),s=(await o.status()).not_added||[]
4065
4047
  for(const t of s)try{const o=y.join(e,t),s=m.statSync(o)
@@ -4068,7 +4050,7 @@ const t=e.reduce(((e,t)=>e+t.sizeMB),0)
4068
4050
  let r=`\n\n\u26a0\ufe0f **Performance Warning**: Large untracked files detected (${Math.round(t)} MB total) that may slow git operations:\n`
4069
4051
  for(const t of e.slice(0,5))r+=`- \`${t.path}\` (${t.sizeMB} MB)\n`
4070
4052
  return e.length>5&&(r+=`- ... and ${e.length-5} more large files\n`),r+="\nConsider adding these to `.gitignore` or moving them outside the repository.",r}
4071
- const h=t(3444),g=t(9860),p=t(3922),f=t(8824),m=u(t(9896)),y=u(t(6928))},7575(e,exports){var t
4053
+ const h=t(3444),g=t(9860),f=t(3922),p=t(8824),m=u(t(9896)),y=u(t(6928))},7575(e,exports){var t
4072
4054
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.FileOperationPhase=exports.RequestLockError=void 0,exports.RequestLockError=class extends Error{constructor(e,t,r,n){super(e),this.requestId=t,this.lockedByAgent=r,this.lockedAt=n,this.name="RequestLockError"}},function(e){e.VALIDATION="validation",e.TASK_VALIDATION="task_validation",e.RECORD_CREATION="record_creation",e.FILE_WRITE="file_write",e.STRING_REPLACEMENT="string_replacement",e.GIT_COMMIT="git_commit",e.RECORD_UPDATE_SUCCESS="record_update_success",e.RECORD_UPDATE_FAILURE="record_update_failure"}(t||(exports.FileOperationPhase=t={}))},7609(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleUpdatePlan=async function(e,t,n,o){const s=o.child({tool:"plan_operations",operation:"update"})
4073
4055
  try{const t=n.getDocumentClient(),r=await t.getDocument(e.planId)
4074
4056
  if(!r)return{content:[{type:"text",text:"\u274c Plan not found: "+e.planId}],isError:!0}
@@ -4088,7 +4070,7 @@ try{const n=e.replace(/\/$/,"")+"/session",o=await fetch(n)
4088
4070
  if(!o.ok)return void i.warn("Failed to get session list",{status:o.status})
4089
4071
  const a=await o.json(),c=a.sort(((e,t)=>t.time.updated-e.time.updated)),l=e.replace(/\/$/,"")+"/session/status",d=await fetch(l)
4090
4072
  if(!d.ok)return void i.warn("Failed to get session status",{status:d.status})
4091
- const u=await d.json(),h=c.filter((e=>"busy"===u[e.id]?.type)),g=5,p=c.slice(0,g),f=new Set(h.map((e=>e.id))),m=[...h,...p.filter((e=>!f.has(e.id)))]
4073
+ const u=await d.json(),h=c.filter((e=>"busy"===u[e.id]?.type)),g=5,f=c.slice(0,g),p=new Set(h.map((e=>e.id))),m=[...h,...f.filter((e=>!p.has(e.id)))]
4092
4074
  let y=null
4093
4075
  const w=[]
4094
4076
  for(const n of m)try{const o=`${e.replace(/\/$/,"")}/session/${n.id}/message?limit=50`,a=await fetch(o)
@@ -4136,33 +4118,33 @@ try{if(!t.git)return r.debug("No git repository available"),n.incrementCounter("
4136
4118
  const s=await u.getRepositoryStatus(t.git,r,n),i=s.branches.filter((t=>t.name==="requests/"+e)),a=i.length>0,c=a?i[0].name:void 0,l=i.map((e=>e.name))
4137
4119
  return r.debug("Searched for feature branch",{requestId:e,found:a,branchName:c,matchingBranches:l.length,totalBranches:s.branches.length}),n.incrementCounter("find_feature_branch_success",1,{found:a.toString()}),o({success:!0,found:a.toString()}),{found:a,branchName:c,allBranches:l}}catch(t){const s=(0,g.getErrorMessage)(t)
4138
4120
  return r.warn("Failed to find feature branch for request",{requestId:e,error:s}),n.incrementCounter("find_feature_branch_failure",1),o({success:!1,error:t instanceof Error?t.name:"unknown"}),{found:!1}}}async function o(e,o,s,i,a,c){if(!o||!s.git)return{switched:!1,message:"No branch switch needed"}
4139
- let l=!1,f=Date.now()
4140
- try{s.syncBranchState&&await s.syncBranchState(),Date.now(),f=Date.now()
4121
+ let l=!1,p=Date.now()
4122
+ try{s.syncBranchState&&await s.syncBranchState(),Date.now(),p=Date.now()
4141
4123
  const e=s.getCurrentBranchContext?await s.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
4142
4124
  if(Date.now(),e.requestId===o)return i.debug("Already in correct request context",{requestId:o,currentBranch:e.branch}),{switched:!1,branchName:e.branch||void 0,message:`Already in request ${o} context`,lockAcquired:!1}
4143
4125
  if(s.workspaceManager){i.debug("Using WorkspaceManager for request context switching",{requestId:o,currentMode:s.workspaceManager.getCurrentContext().mode})
4144
4126
  try{if("multi-agent"===s.workspaceManager.getCurrentContext().mode)if(i.debug("Multi-agent mode: checking request lock before auto-switch",{requestId:o}),s.apiClient)try{const e=s.apiClient.getRequestClient(),{sessionTag:t}=(0,h.getGlobalClientInfo)()
4145
- f=Date.now()
4127
+ p=Date.now()
4146
4128
  const r=await e.getRequestLockStatus(o)
4147
4129
  if(Date.now(),r.isLocked&&r.lockedBySessionTag!==t){i.warn("Auto-switch blocked by request lock",{requestId:o,lockedByAgent:r.lockedBySessionTag,currentAgent:t,lockedAt:r.lockedAt})
4148
4130
  let e=`Request ${o} is currently locked by another agent (${r.lockedBySessionTag}).\n\nLocked since: ${r.lockedAt||"unknown"}\n\nIn multi-agent mode, only one agent can work on a request at a time. Please wait for the other agent to complete their work or contact an administrator if the lock appears stale.`
4149
4131
  if(s.lockOverrideManager&&s.configManager)try{const t=await s.configManager.getEffectiveConfig(s.mainBasePath)
4150
- t.lockOverride.enabled&&(e+=`\n\n**To take over this request (only if safe to do so), use switch_to_branch with password: \`${s.lockOverrideManager.generatePassword(o,t.lockOverride.passwordValidityMinutes)}\` (valid for ${t.lockOverride.passwordValidityMinutes} minutes)**`)}catch(e){i.warn("Failed to check lock override config",{error:e})}throw new p.RequestLockError(e,o,r.lockedBySessionTag,r.lockedAt)}if(!r.isLocked){f=Date.now(),i.debug("Acquiring lock for auto-switch",{requestId:o,sessionTag:t})
4132
+ t.lockOverride.enabled&&(e+=`\n\n**To take over this request (only if safe to do so), use switch_to_branch with password: \`${s.lockOverrideManager.generatePassword(o,t.lockOverride.passwordValidityMinutes)}\` (valid for ${t.lockOverride.passwordValidityMinutes} minutes)**`)}catch(e){i.warn("Failed to check lock override config",{error:e})}throw new f.RequestLockError(e,o,r.lockedBySessionTag,r.lockedAt)}if(!r.isLocked){p=Date.now(),i.debug("Acquiring lock for auto-switch",{requestId:o,sessionTag:t})
4151
4133
  const r=await e.lockRequest(o,t)
4152
4134
  if(Date.now(),!r.locked){const e=`Failed to acquire lock for request ${o} during auto-switch`
4153
4135
  throw i.warn("Auto-switch lock acquisition failed",{requestId:o}),Error(e)}i.info("Successfully acquired lock for auto-switch",{requestId:o,sessionTag:t,lockedAt:r.lockedAt}),l=!0}}catch(e){throw i.error("Lock check/acquisition failed during auto-switch",{requestId:o,error:e instanceof Error?e.message:e+""}),e}else i.warn("Multi-agent mode but no API client available for locking",{requestId:o})
4154
- i.debug("Ensuring workspace is ready for file operations",{requestId:o,reason:"first-file-operation"}),f=Date.now(),await s.workspaceManager.ensureWorkspaceReady(o),Date.now()
4136
+ i.debug("Ensuring workspace is ready for file operations",{requestId:o,reason:"first-file-operation"}),p=Date.now(),await s.workspaceManager.ensureWorkspaceReady(o),Date.now()
4155
4137
  const e=s.workspaceManager.getCurrentContext()
4156
4138
  if(e.basePath&&(s.git=(0,d.simpleGit)(e.basePath),i.info("Updated git instance to worktree path",{requestId:o,gitWorkingDirectory:e.basePath,mode:e.mode,branchName:e.branchName})),e.requestId!==o){const t=`Workspace switch validation failed. Expected requestId: ${o}, but got: ${e.requestId}`
4157
4139
  throw i.error("Post-switch context validation failed",{requestId:o,expectedRequestId:o,actualRequestId:e.requestId,actualBasePath:e.basePath,mode:e.mode}),Error(t)}i.info("Workspace is ready via WorkspaceManager",{requestId:o,mode:s.workspaceManager.getCurrentContext().mode,workflow:"hybrid-creation-lazy-worktree",validation:"context_validated"})
4158
4140
  try{const{findLargeUntrackedFiles:r,formatLargeFileWarning:n}=await Promise.resolve().then(t.t.bind(t,7478,23)),a=await r(e.basePath)
4159
4141
  if(a.length>0){const e=n(a)
4160
- s.workspaceManager.largeFileWarning=e,i.warn("Large untracked files detected",{requestId:o,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){i.debug("Large file check failed",{error:e})}return a.incrementCounter(c+"_auto_context_switch_success",1),{switched:!0,branchName:s.workspaceManager.getCurrentContext().branchName,message:"Workspace ready for request "+o,lockAcquired:l,lockedRequestId:l?o:void 0}}catch(e){if(e instanceof p.RequestLockError)throw i.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4142
+ s.workspaceManager.largeFileWarning=e,i.warn("Large untracked files detected",{requestId:o,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){i.debug("Large file check failed",{error:e})}return a.incrementCounter(c+"_auto_context_switch_success",1),{switched:!0,branchName:s.workspaceManager.getCurrentContext().branchName,message:"Workspace ready for request "+o,lockAcquired:l,lockedRequestId:l?o:void 0}}catch(e){if(e instanceof f.RequestLockError)throw i.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4161
4143
  return i.error("Error switching to request context",{requestId:o,error:(0,g.getErrorMessage)(e)}),a.incrementCounter(c+"_auto_context_switch_error",1),{switched:!1,message:"Context switch error: "+(0,g.getErrorMessage)(e)}}}i.warn("WorkspaceManager not available, falling back to legacy branch switching",{requestId:o})
4162
4144
  const m=await n(o,s,i,a)
4163
4145
  if(!m.found||!m.branchName)return i.warn("No feature branch found for request during auto-switch",{requestId:o,availableBranches:m.allBranches||[]}),a.incrementCounter(c+"_auto_branch_switch_no_branch",1),{switched:!1,message:"No feature branch found for request "+o}
4164
4146
  const y=await r(s,i,a),w=await u.switchToBranch(s.git,m.branchName,i,a)
4165
- return w.success?(s.updateBranchState&&await s.updateBranchState(m.branchName,o),i.info("Auto-switched to request branch after task promotion",{requestId:o,fromBranch:y,toBranch:m.branchName}),a.incrementCounter(c+"_auto_branch_switch_success",1),{switched:!0,branchName:m.branchName,message:"Switched to "+m.branchName}):(i.warn("Failed to auto-switch to request branch",{requestId:o,targetBranch:m.branchName,error:w.message}),a.incrementCounter(c+"_auto_branch_switch_failure",1),{switched:!1,message:"Failed to switch: "+w.message})}catch(e){if(e instanceof p.RequestLockError)throw i.warn("Auto-switch blocked by request lock in legacy mode, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4147
+ return w.success?(s.updateBranchState&&await s.updateBranchState(m.branchName,o),i.info("Auto-switched to request branch after task promotion",{requestId:o,fromBranch:y,toBranch:m.branchName}),a.incrementCounter(c+"_auto_branch_switch_success",1),{switched:!0,branchName:m.branchName,message:"Switched to "+m.branchName}):(i.warn("Failed to auto-switch to request branch",{requestId:o,targetBranch:m.branchName,error:w.message}),a.incrementCounter(c+"_auto_branch_switch_failure",1),{switched:!1,message:"Failed to switch: "+w.message})}catch(e){if(e instanceof f.RequestLockError)throw i.warn("Auto-switch blocked by request lock in legacy mode, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4166
4148
  return i.error("Error during auto-switch to request branch",{requestId:o,error:(0,g.getErrorMessage)(e)}),a.incrementCounter(c+"_auto_branch_switch_error",1),{switched:!1,message:"Error during switch: "+(0,g.getErrorMessage)(e)}}}function s(e,t,r,n){if(!e.workspaceManager)return n.debug("No workspace manager available, skipping context validation",{operation:r,requestId:t}),{isValid:!0}
4167
4149
  const o=e.workspaceManager.getCurrentContext()
4168
4150
  if("multi-agent"!==o.mode)return n.debug("Single-agent mode detected, skipping multi-agent context validation",{operation:r,requestId:t,mode:o.mode}),{isValid:!0}
@@ -4212,8 +4194,8 @@ return r.debug("Single-agent mode: determined expected branch",{taskId:e,request
4212
4194
  try{const e=await o(0,r,n,a,c,l)
4213
4195
  if(e.switched&&a.info(`Auto-switched to request workspace during ${i} operation`,{requestId:r,branchName:e.branchName,message:e.message,taskPromoted:t,operation:i}),d&&r){const t=s(n,r,i,a)
4214
4196
  if(!t.isValid)return a.error("Workspace context validation failed for "+i,{requestId:r,operation:i,error:t.errorMessage}),{success:!1,switched:e.switched,branchName:e.branchName,error:t.errorMessage,lockAcquired:e.lockAcquired,lockedRequestId:e.lockedRequestId}}return a.debug("Workspace context successfully ensured for "+i,{requestId:r,operation:i,switched:e.switched,branchName:e.branchName}),{success:!0,switched:e.switched,branchName:e.branchName,lockAcquired:e.lockAcquired,lockedRequestId:e.lockedRequestId}}catch(e){const t=(0,g.getErrorMessage)(e)
4215
- return e instanceof p.RequestLockError?(a.warn(i+" operation blocked by request lock",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,operation:i}),{success:!1,switched:!1,error:e.message,isLockConflict:!0}):(a.error("Error ensuring workspace context for "+i,{requestId:r,operation:i,error:t}),{success:!1,switched:!1,error:t})}}
4216
- const d=t(3807),u=l(t(7478)),h=t(5172),g=t(8824),p=t(7575)
4197
+ return e instanceof f.RequestLockError?(a.warn(i+" operation blocked by request lock",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,operation:i}),{success:!1,switched:!1,error:e.message,isLockConflict:!0}):(a.error("Error ensuring workspace context for "+i,{requestId:r,operation:i,error:t}),{success:!1,switched:!1,error:t})}}
4198
+ const d=t(3807),u=l(t(7478)),h=t(5172),g=t(8824),f=t(7575)
4217
4199
  l(t(9896)),l(t(6928))},7634(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestLockManager=exports.WorktreeManager=void 0
4218
4200
  var r=t(1502)
4219
4201
  Object.defineProperty(exports,"WorktreeManager",{enumerable:!0,get(){return r.WorktreeManager}})
@@ -4250,8 +4232,9 @@ const e=this.worktreeManager.getWorktreeInfo(n)
4250
4232
  if(e&&e.worktreePath)return this.currentRequestId=n,this.currentWorktreePath=e.worktreePath,this.currentGit=(0,o.simpleGit)(e.worktreePath),void this.logger.info("Switched to existing ready workspace",{requestId:n,worktreePath:e.worktreePath})}try{a.WorkspaceLogging.logOperation(this.logger,"info","Ensuring workspace ready by creating/switching to worktree",e,"multi-agent","ensureWorkspaceReady",{currentState:this.workspaceStates.get(n)||"not-initialized",currentRequestId:this.currentRequestId,architecture:"hybrid-creation"})
4251
4233
  const r=await this.worktreeManager.ensureWorktreeExists(n,void 0,void 0)
4252
4234
  if(!r.success)throw Error("Failed to create worktree: "+r.message)
4253
- this.currentRequestId=n,this.currentWorktreePath=r.worktreePath,this.currentGit=(0,o.simpleGit)(r.worktreePath),this.workspaceStates.set(n,"ready"),r.created&&(this.workspaceKnownClean=!0,this.logger.debug("Fresh worktree created - marking workspace as known clean",{requestId:n,worktreePath:r.worktreePath}))
4254
- const s=Date.now()-t
4235
+ if(this.currentRequestId=n,this.currentWorktreePath=r.worktreePath,this.currentGit=(0,o.simpleGit)(r.worktreePath),this.workspaceStates.set(n,"ready"),r.created){this.workspaceKnownClean=!0
4236
+ try{const e=(0,o.simpleGit)(r.worktreePath),t=(await this.mainGit.branch()).all.includes("main")?"main":"master",s=await this.mainGit.revparse([t]),i=await e.revparse(["HEAD"])
4237
+ s!==i&&0===(await e.log({from:t,to:"HEAD"})).total&&(await e.rebase([t]),this.logger.info("Rebased fresh request branch onto latest main",{requestId:n,mainHead:s.substring(0,8),previousHead:i.substring(0,8)}))}catch(e){this.logger.warn("Failed to rebase onto main, proceeding with existing branch",{requestId:n,error:(0,i.getErrorMessage)(e)})}}const s=Date.now()-t
4255
4238
  this.metrics.recordValue("workspace.ensure_ready",s),a.WorkspaceLogging.logOperation(this.logger,"info","Workspace is ready with worktree",e,"multi-agent","ensureWorkspaceReady",{worktreePath:r.worktreePath,branchName:r.branchName,duration:s,architecture:"hybrid-creation"})}catch(r){const n=Date.now()-t
4256
4239
  throw this.metrics.recordValue("workspace.ensure_ready",n),a.WorkspaceLogging.logOperation(this.logger,"error","Failed to ensure workspace ready",e,"multi-agent","ensureWorkspaceReady",{error:(0,i.getErrorMessage)(r),duration:n}),r}}else this.logger.debug("Workspace already ready and in correct context",{requestId:n,worktreePath:this.currentWorktreePath})}async switchToRequest(e,t){this.logger.debug("switchToRequest called",{requestId:e,options:t})
4257
4240
  const r=Date.now(),n=this.getCurrentContext()
@@ -4284,7 +4267,7 @@ try{this.currentRequestId===r&&await this.switchToMain()
4284
4267
  const e=await this.worktreeManager.removeWorktree(r,!1)
4285
4268
  if(!e.success)throw Error(e.message||"Failed to remove worktree")
4286
4269
  this.logger.info("Successfully cancelled request",{requestId:r})}catch(e){throw this.logger.error("Failed to cancel request",{requestId:r,error:(0,i.getErrorMessage)(e)}),e}}getCurrentContext(){const e={requestId:this.currentRequestId,basePath:this.currentWorktreePath||this.basePath,branchName:this.currentRequestId?"requests/"+this.currentRequestId:"main",isMainBranch:!this.currentRequestId,mode:"multi-agent"}
4287
- return this.logger.debug("getCurrentContext returning",{context:e}),e}async getWorkspaceInfo(e){try{const t=a.WorkspaceValidation.validateRequestId(e)
4270
+ return this.logger.debug("getCurrentContext returning",{context:e}),e}resetCurrentContext(){this.currentRequestId&&this.logger.info("Resetting workspace context (session switch)",{prevRequestId:this.currentRequestId,prevWorktreePath:this.currentWorktreePath}),this.currentRequestId=null,this.currentWorktreePath=null,this.currentGit=this.mainGit}async getWorkspaceInfo(e){try{const t=a.WorkspaceValidation.validateRequestId(e)
4288
4271
  if(!t.isValid)return null
4289
4272
  const r=t.sanitized,n=await this.getWorktreeInfo(r)
4290
4273
  return n?{requestId:r,path:n.worktreePath,branchName:n.branchName,isActive:this.currentRequestId===r,created:new Date,lastAccessed:new Date}:null}catch(t){return this.logger.error("Failed to get workspace info",{requestId:e,error:(0,i.getErrorMessage)(t)}),null}}async listActiveWorkspaces(){try{return(await this.worktreeManager.listActiveWorktrees()).map((e=>this.convertWorktreeInfoToWorkspaceInfo(e)))}catch(e){return this.logger.error("Failed to list active workspaces",{error:(0,i.getErrorMessage)(e)}),[]}}extractRequestIdFromBranch(e){const t=e.match(/^requests\/(.+)$/)
@@ -4309,7 +4292,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
4309
4292
  var t={}
4310
4293
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
4311
4294
  return o(t,e),t})
4312
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,t,r,n,o,s,g,p,f){const m=g.child({tool:"manage_files"})
4295
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,t,r,n,o,s,g,f,p){const m=g.child({tool:"manage_files"})
4313
4296
  try{const h=a.validateArgs(e,i.ManageFilesSchema),{taskId:g,operations:y,comment:w}=h
4314
4297
  m.info("Processing manage-files operations",{taskId:g,operationCount:y.length,comment:w})
4315
4298
  const k=[],b=[],I=[],v=[]
@@ -4321,18 +4304,18 @@ case"delete-files":I.push(...e.deleteFiles.targets)
4321
4304
  break
4322
4305
  case"get-file-info":v.push({path:e.getFileInfo.path})}const C=[]
4323
4306
  for(const e of k){m.info("Routing to create-directory handler",{path:e.path})
4324
- const s=await(0,c.handleCreateDirectory)({taskId:g,path:e.path,comment:w+" [via manage-files: create-directory]"},t,r,n,o,m,p,f)
4307
+ const s=await(0,c.handleCreateDirectory)({taskId:g,path:e.path,comment:w+" [via manage-files: create-directory]"},t,r,n,o,m,f,p)
4325
4308
  C.push({type:"create-directory",result:s})}if(b.length>0){m.info("Routing to move-files handler",{operationCount:b.length})
4326
- const e=await(0,l.handleMoveFiles)({taskId:g,operations:b,comment:w+" [via manage-files: move-files]"},t,r,n,o,m,p,f)
4309
+ const e=await(0,l.handleMoveFiles)({taskId:g,operations:b,comment:w+" [via manage-files: move-files]"},t,r,n,o,m,f,p)
4327
4310
  C.push({type:"move-files",result:e})}if(I.length>0){m.info("Routing to delete-files handler",{operationCount:I.length})
4328
- const e=await(0,u.handleDeleteFiles)({taskId:g,operations:I,comment:w+" [via manage-files: delete-files]"},t,s,m,p,f)
4311
+ const e=await(0,u.handleDeleteFiles)({taskId:g,operations:I,comment:w+" [via manage-files: delete-files]"},t,s,m,f,p)
4329
4312
  C.push({type:"delete-files",result:e})}for(const e of v){m.info("Routing to get-file-info handler",{path:e.path})
4330
- const r=await(0,d.handleGetFileInfo)({path:e.path},t,m,p)
4313
+ const r=await(0,d.handleGetFileInfo)({path:e.path},t,m,f)
4331
4314
  C.push({type:"get-file-info",result:r})}const _=C.some((e=>e.result.isError)),E=C.filter((e=>!e.result.isError)).length,q=C.filter((e=>e.result.isError)).length
4332
4315
  let S="## Manage Files Results\n\n"
4333
4316
  S+="**Summary:**\n",S+=`- **Total operation types:** ${C.length}\n`,S+=`- **Successful:** ${E}\n`,S+=`- **Failed:** ${q}\n\n`
4334
4317
  for(const{type:e,result:t}of C)S+=`### ${e} operations\n`,S+=t.content[0].text+"\n\n"
4335
- return m.info("Manage-files operations completed",{totalOperationTypes:C.length,successCount:E,errorCount:q}),p.incrementCounter("manage_files_total",1,{success:!_}),{content:[{type:"text",text:S}],isError:_}}catch(e){return m.error("Manage-files operation failed",{error:e instanceof Error?e.stack:e+""}),p.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
4318
+ return m.info("Manage-files operations completed",{totalOperationTypes:C.length,successCount:E,errorCount:q}),f.incrementCounter("manage_files_total",1,{success:!_}),{content:[{type:"text",text:S}],isError:_}}catch(e){return m.error("Manage-files operation failed",{error:e instanceof Error?e.stack:e+""}),f.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
4336
4319
  const i=t(6183),a=s(t(5967)),c=t(8309),l=t(2414),d=t(3628),u=t(5992),h=t(8824)},7713(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
4337
4320
  const r=t(6183),n=t(5303)
4338
4321
  exports.def={name:"plan_read",description:"Read project plans.\n\nOperations:\n\u2022 get - Get a plan by ID with full content\n\u2022 list - List all plans in the project\n\u2022 get-history - View version history of a plan\n\u2022 get-requests - List requests linked to a plan",schema:r.PlanReadSchema,annotations:{title:"Plan Read",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handlePlanRead)(e,t.context,t.apiClient,t.logger,t.metrics)}}},7784(e,exports,t){async function validateWorktreeForConflictResolution(e,r,s){const i=[],a=o.default.join(r,e),c="requests/"+e
@@ -4353,8 +4336,8 @@ const n=r(t(9896)),o=r(t(6928))},7834(e,exports,t){Object.defineProperty(exports
4353
4336
  const r=t(5806),n=t(5715)
4354
4337
  exports.def={name:"complete_request",description(e){return e.testsRequired?"Mark request as complete with test verification":"Mark request as complete (no test verification needed)"},schema(){return(0,r.getDynamicCompleteRequestSchema)()},annotations:{title:"Complete Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0},hidden:!0,handler(e,t){return(0,n.handleCompleteRequest)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},7849(e,exports,t){async function r(e,t,r,n,o,s,a,l,d,u){const h=Date.now()
4355
4338
  if(!r||""===r.trim())throw new c.ValidationError("Project ID is required and cannot be empty for tool record creation")
4356
- try{const c=await a.createToolRecord({taskId:e,requestId:t,projectId:r,type:n,metadata:{path:o,operation:n,status:"pending",timestamp:(new Date).toISOString(),fileExtension:i.default.extname(o).slice(1),fileOperationId:`${e}-${Date.now()}`,...s},note:`${"write-file"===n?"Writing":"Modifying"} file: ${o}`}),g=c.id,p=c.localId
4357
- return l.info("Tool record created with IDs",{recordId:g,localRecordId:p,hasLocalId:!!c.localId,recordKeys:Object.keys(c),fullRecord:JSON.stringify(c)}),l.info("Created tool record for file operation: "+n,{taskId:e,projectId:r,path:o,recordId:g,localRecordId:p}),d.recordValue(u+"_tool_record_creation_time",Date.now()-h),d.incrementCounter(u+"_tool_record_creation_success",1),{recordId:g,localRecordId:p}}catch(t){d.incrementCounter(u+"_tool_record_creation_failure",1),d.recordValue(u+"_tool_record_creation_time",Date.now()-h)
4339
+ try{const c=await a.createToolRecord({taskId:e,requestId:t,projectId:r,type:n,metadata:{path:o,operation:n,status:"pending",timestamp:(new Date).toISOString(),fileExtension:i.default.extname(o).slice(1),fileOperationId:`${e}-${Date.now()}`,...s},note:`${"write-file"===n?"Writing":"Modifying"} file: ${o}`}),g=c.id,f=c.localId
4340
+ return l.info("Tool record created with IDs",{recordId:g,localRecordId:f,hasLocalId:!!c.localId,recordKeys:Object.keys(c),fullRecord:JSON.stringify(c)}),l.info("Created tool record for file operation: "+n,{taskId:e,projectId:r,path:o,recordId:g,localRecordId:f}),d.recordValue(u+"_tool_record_creation_time",Date.now()-h),d.incrementCounter(u+"_tool_record_creation_success",1),{recordId:g,localRecordId:f}}catch(t){d.incrementCounter(u+"_tool_record_creation_failure",1),d.recordValue(u+"_tool_record_creation_time",Date.now()-h)
4358
4341
  const n=t instanceof Error?`${t.message} (${JSON.stringify(t)})`:t+""
4359
4342
  return l.warn("Failed to create tool record for file operation: "+n,{taskId:e,projectId:r,path:o,error:t instanceof Error?t.stack:t+""}),{}}}async function n(e,t,r,n,o,s,a,c,l){const u=Date.now()
4360
4343
  try{await s.updateToolRecord(e,{metadata:{path:t,operation:r,timestamp:(new Date).toISOString(),fileExtension:i.default.extname(t).slice(1),fileUpdateId:`${e}-${Date.now()}`,...n},note:o}),a.info("Updated tool record for file operation: "+r,{path:t,recordId:e,status:n.status}),c.recordValue(l+"_tool_record_update_time",Date.now()-u),c.incrementCounter(l+"_tool_record_update_success",1)}catch(n){c.incrementCounter(l+"_tool_record_update_failure",1),c.recordValue(l+"_tool_record_update_time",Date.now()-u),a.warn("Failed to update tool record for file operation: "+r,{path:t,recordId:e,error:(0,d.getErrorMessage)(n)})}}async function o(e,t,r,n,o){const{operationType:s,toolRecordId:i,successField:c,logger:l,metrics:u,metricsPrefix:h}=n
@@ -4367,35 +4350,35 @@ if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext()
4367
4350
  "multi-agent"===t.mode&&t.requestId&&(d=(0,a.simpleGit)(t.basePath),l.debug("Using WorkspaceManager git instance for multi-file commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,filesCount:n.length}))}if(!d)return l.debug("No git repository available, skipping commit"),{filesCommitted:[],success:!0}
4368
4351
  let g=null
4369
4352
  try{g=(await d.revparse(["HEAD"])).trim()}catch(e){l.warn("Failed to get current commit hash",{error:e})}for(const e of n)await d.add(e)
4370
- const p=1===n.length?`${s} in ${n[0]} (${i})`:`${s} in ${n.length} files (${i})`,f=(await d.commit(p)).commit
4371
- return l.info("Changes committed to git via shared multi-file utility",{commitMessage:p,filesCommitted:n.length,commitHash:f?.substring(0,8),previousCommitHash:g?.substring(0,8),toolRecordId:i,operationType:s}),u.incrementCounter(h+"_git_commit_success",1),u.recordValue(h+"_files_committed",n.length),{commitHash:f,previousCommitHash:g,filesCommitted:n,success:!0}}catch(e){const t=(0,d.getErrorMessage)(e)
4353
+ const f=1===n.length?`${s} in ${n[0]} (${i})`:`${s} in ${n.length} files (${i})`,p=(await d.commit(f)).commit
4354
+ return l.info("Changes committed to git via shared multi-file utility",{commitMessage:f,filesCommitted:n.length,commitHash:p?.substring(0,8),previousCommitHash:g?.substring(0,8),toolRecordId:i,operationType:s}),u.incrementCounter(h+"_git_commit_success",1),u.recordValue(h+"_files_committed",n.length),{commitHash:p,previousCommitHash:g,filesCommitted:n,success:!0}}catch(e){const t=(0,d.getErrorMessage)(e)
4372
4355
  return l.warn("Git operations failed via shared multi-file utility",{error:t,operationType:s,note:"File changes were saved but not committed to git"}),u.incrementCounter(h+"_git_commit_failure",1),{filesCommitted:[],success:!1,error:t}}}var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
4373
4356
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.createToolRecord=r,exports.updateToolRecord=n,exports.createFileOperationRecords=async function(e,t,n,o,s,i,a,c,l,u,h){const g=Date.now()
4374
- let p,f
4357
+ let f,p
4375
4358
  l.debug("createFileOperationRecords called",{taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,operationType:o,path:s})
4376
4359
  try{const a=await r(e,t,n,o,s,i,c,l,u,h)
4377
- return p=a.recordId,f=a.localRecordId,l.info("Created tool record for file operation: "+o,{taskId:e,path:s,toolRecordId:p,localToolRecordId:f}),{toolRecordId:p,localToolRecordId:f}}catch(r){throw l.error("Failed to create tool record for file operation: "+o,{error:(0,d.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0,taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,path:s}),u.recordValue(h+"_record_creation_time",Date.now()-g),u.incrementCounter(h+"_record_creation_error",1),r}},exports.updateFileOperationRecords=async function(e,t,r,o,s,i,a,c,l,u,h,g,p){try{t&&h.info("Task record update skipped (task records removed): "+t,{taskId:e,path:o}),r&&await n(r,o,s,a,c,u,h,g,p)}catch(t){h.warn("Error updating tool record for operation: "+s,{error:(0,d.getErrorMessage)(t),taskId:e,normalizedPath:o,toolRecordId:r})}},exports.checkAndCommitUserMods=async function(e,t,r,n,o){if(!t.git)return{hadUserMods:!1}
4360
+ return f=a.recordId,p=a.localRecordId,l.info("Created tool record for file operation: "+o,{taskId:e,path:s,toolRecordId:f,localToolRecordId:p}),{toolRecordId:f,localToolRecordId:p}}catch(r){throw l.error("Failed to create tool record for file operation: "+o,{error:(0,d.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0,taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,path:s}),u.recordValue(h+"_record_creation_time",Date.now()-g),u.incrementCounter(h+"_record_creation_error",1),r}},exports.updateFileOperationRecords=async function(e,t,r,o,s,i,a,c,l,u,h,g,f){try{t&&h.info("Task record update skipped (task records removed): "+t,{taskId:e,path:o}),r&&await n(r,o,s,a,c,u,h,g,f)}catch(t){h.warn("Error updating tool record for operation: "+s,{error:(0,d.getErrorMessage)(t),taskId:e,normalizedPath:o,toolRecordId:r})}},exports.checkAndCommitUserMods=async function(e,t,r,n,o){if(!t.git)return{hadUserMods:!1}
4378
4361
  try{let s=t.git
4379
4362
  if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
4380
4363
  "multi-agent"===e.mode&&e.requestId&&(s=(0,a.simpleGit)(e.basePath))}if((await s.diff(["--name-only","HEAD","--",e])).trim().length>0){r.info(`File ${e} has uncommitted changes, preserving user modifications`),await s.add(e)
4381
4364
  const t=await s.commit("[USER-MODS] Preserve user modifications before tool operation: "+e)
4382
4365
  return r.info("Created user modifications commit",{filePath:e,userModsCommitHash:t.commit}),n.incrementCounter(o+"_user_mods_commits_created",1),{hadUserMods:!0,userModsCommitHash:t.commit}}return{hadUserMods:!1}}catch(t){return r.warn("Failed to check/preserve user modifications for "+e,{error:(0,d.getErrorMessage)(t)}),n.incrementCounter(o+"_user_mods_check_failures",1),{hadUserMods:!1}}},exports.commitToGit=async function(e,t,r,n,o,s,i,c,u){const h=Date.now()
4383
- let g,p=null
4384
- try{let f=s.git
4366
+ let g,f=null
4367
+ try{let p=s.git
4385
4368
  if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext()
4386
4369
  if("multi-agent"===t.mode&&t.requestId){if(!t.basePath.includes("/worktrees/")&&!t.basePath.includes("\\worktrees\\"))throw i.error("CRITICAL BUG: Multi-agent mode but basePath is not a worktree path",{taskId:e,requestId:t.requestId,basePath:t.basePath,expectedPattern:"should contain /worktrees/ or \\worktrees\\",issue:"workspace_context_incorrect"}),Error(`Multi-agent mode context error: basePath '${t.basePath}' is not a worktree path. This will cause commits to go to main branch instead of the request branch.`)
4387
- f=(0,a.simpleGit)(t.basePath),i.debug("Using WorkspaceManager git instance for commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,worktreeValidated:!0})}}if(f){i.info("commitToGit called with:",{taskId:e,recordId:r,localRecordId:n,hasLocalRecordId:!!n,localRecordIdType:typeof n,normalizedPath:t})
4370
+ p=(0,a.simpleGit)(t.basePath),i.debug("Using WorkspaceManager git instance for commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,worktreeValidated:!0})}}if(p){i.info("commitToGit called with:",{taskId:e,recordId:r,localRecordId:n,hasLocalRecordId:!!n,localRecordIdType:typeof n,normalizedPath:t})
4388
4371
  let a=!1,m=""
4389
- try{if(m=(await f.raw(["rev-parse","--show-toplevel"])).trim(),a=m.includes("/worktrees/")||m.includes("\\worktrees\\"),i.info("Git context detection for commit operation:",{taskId:e,gitRepoPath:m,isWorktreeOperation:a,multiAgentMode:s.multiAgentMode,targetFile:t,expectedContext:s.multiAgentMode?"worktree":"main repo"}),s.multiAgentMode&&!a)throw i.error("CRITICAL: Multi-agent operation using main repo Git instead of worktree",{taskId:e,detectedPath:m,targetFile:t,currentRequestId:s.getCurrentRequestId?s.getCurrentRequestId():"unknown"}),Error(`Git context mismatch: Multi-agent operation attempted to commit ${t} using main repository Git instance at ${m}, but should use worktree Git instance. This will fail due to .gitignore rules.`)}catch(e){i.warn("Failed to get Git instance info:",{error:e instanceof Error?e.message:e+""})}try{const r=await f.revparse(["--abbrev-ref","HEAD"]),n=await f.revparse(["HEAD"]),o=await f.revparse(["--show-toplevel"])
4372
+ try{if(m=(await p.raw(["rev-parse","--show-toplevel"])).trim(),a=m.includes("/worktrees/")||m.includes("\\worktrees\\"),i.info("Git context detection for commit operation:",{taskId:e,gitRepoPath:m,isWorktreeOperation:a,multiAgentMode:s.multiAgentMode,targetFile:t,expectedContext:s.multiAgentMode?"worktree":"main repo"}),s.multiAgentMode&&!a)throw i.error("CRITICAL: Multi-agent operation using main repo Git instead of worktree",{taskId:e,detectedPath:m,targetFile:t,currentRequestId:s.getCurrentRequestId?s.getCurrentRequestId():"unknown"}),Error(`Git context mismatch: Multi-agent operation attempted to commit ${t} using main repository Git instance at ${m}, but should use worktree Git instance. This will fail due to .gitignore rules.`)}catch(e){i.warn("Failed to get Git instance info:",{error:e instanceof Error?e.message:e+""})}try{const r=await p.revparse(["--abbrev-ref","HEAD"]),n=await p.revparse(["HEAD"]),o=await p.revparse(["--show-toplevel"])
4390
4373
  i.info("Git repository status before commit:",{taskId:e,currentBranch:r.trim(),currentCommit:n.trim().substring(0,8),repoPath:o.trim(),targetFile:t,multiAgentMode:s.multiAgentMode||!1,currentRequestId:s.getCurrentRequestId?s.getCurrentRequestId():"none"})
4391
4374
  const a=r.trim(),c=s.getCurrentRequestId?s.getCurrentRequestId():null
4392
4375
  if(s.multiAgentMode&&c){const t="requests/"+c
4393
- a!=="requests/"+c?i.warn("Multi-agent file operation may be on wrong branch",{taskId:e,actualBranch:a,expectedPattern:t,requestId:c}):i.info("Multi-agent file operation on expected branch",{taskId:e,branchName:a,requestId:c})}}catch(e){i.warn("Failed to get Git status before commit:",{error:e instanceof Error?e.message:e+""})}try{if(f){const r=await f.revparse(["HEAD"])
4394
- p=await(0,l.findPreviousCommit)(f,t,r),i.info(`Previous commit hash for ${t}: ${p||"none (new file)"}`,{taskId:e,gitInstancePath:m||"unknown",isWorktreeOperation:a,usingCorrectGitInstance:!0})}else i.warn("Git not available for previous commit detection: "+t,{taskId:e,reason:"no_git_instance"})}catch(e){i.warn(`Failed to find previous commit for ${t}:`,{error:(0,d.getErrorMessage)(e)})}const y=n?`[RECORD:${n}] ${o}`:o
4395
- await f.add(t),g=(await f.commit(y)).commit
4396
- try{const r=await f.revparse(["--abbrev-ref","HEAD"]),n=await f.revparse(["HEAD"])
4397
- i.info("Git repository status after commit:",{taskId:e,postCommitBranch:r.trim(),postCommitHash:n.trim().substring(0,8),commitAdvanced:n.trim()!==(p||""),targetFile:t}),g&&n.trim()!==g&&i.warn("Commit hash mismatch after commit",{taskId:e,expectedCommitHash:g,actualHeadHash:n.trim(),targetFile:t})}catch(e){i.warn("Failed to verify post-commit status:",{error:e instanceof Error?e.message:e+""})}i.info("Committed file changes to Git: "+t,{taskId:e,path:t,recordId:r,localRecordId:n,commitHash:g,previousCommitHash:p}),c.recordValue(u+"_git_commit_time",Date.now()-h),c.incrementCounter(u+"_git_commit_success",1)}else i.warn("No Git repository available, skipping commit",{taskId:e,path:t})
4398
- return{commitHash:g,previousCommitHash:p}}catch(r){return c.incrementCounter(u+"_git_commit_failure",1),c.recordValue(u+"_git_commit_time",Date.now()-h),i.warn("Failed to commit file changes to Git: "+t,{taskId:e,path:t,error:r instanceof Error?r.stack:r+""}),{commitHash:void 0,previousCommitHash:p}}},exports.commitMultipleFilesToGit=o,exports.handleMultiFileGitCommit=async function(e,t,r,n,s,i){const{logger:a,metricsPrefix:c,metrics:l}=s
4376
+ a!=="requests/"+c?i.warn("Multi-agent file operation may be on wrong branch",{taskId:e,actualBranch:a,expectedPattern:t,requestId:c}):i.info("Multi-agent file operation on expected branch",{taskId:e,branchName:a,requestId:c})}}catch(e){i.warn("Failed to get Git status before commit:",{error:e instanceof Error?e.message:e+""})}try{if(p){const r=await p.revparse(["HEAD"])
4377
+ f=await(0,l.findPreviousCommit)(p,t,r),i.info(`Previous commit hash for ${t}: ${f||"none (new file)"}`,{taskId:e,gitInstancePath:m||"unknown",isWorktreeOperation:a,usingCorrectGitInstance:!0})}else i.warn("Git not available for previous commit detection: "+t,{taskId:e,reason:"no_git_instance"})}catch(e){i.warn(`Failed to find previous commit for ${t}:`,{error:(0,d.getErrorMessage)(e)})}const y=n?`[RECORD:${n}] ${o}`:o
4378
+ await p.add(t),g=(await p.commit(y)).commit
4379
+ try{const r=await p.revparse(["--abbrev-ref","HEAD"]),n=await p.revparse(["HEAD"])
4380
+ i.info("Git repository status after commit:",{taskId:e,postCommitBranch:r.trim(),postCommitHash:n.trim().substring(0,8),commitAdvanced:n.trim()!==(f||""),targetFile:t}),g&&n.trim()!==g&&i.warn("Commit hash mismatch after commit",{taskId:e,expectedCommitHash:g,actualHeadHash:n.trim(),targetFile:t})}catch(e){i.warn("Failed to verify post-commit status:",{error:e instanceof Error?e.message:e+""})}i.info("Committed file changes to Git: "+t,{taskId:e,path:t,recordId:r,localRecordId:n,commitHash:g,previousCommitHash:f}),c.recordValue(u+"_git_commit_time",Date.now()-h),c.incrementCounter(u+"_git_commit_success",1)}else i.warn("No Git repository available, skipping commit",{taskId:e,path:t})
4381
+ return{commitHash:g,previousCommitHash:f}}catch(r){return c.incrementCounter(u+"_git_commit_failure",1),c.recordValue(u+"_git_commit_time",Date.now()-h),i.warn("Failed to commit file changes to Git: "+t,{taskId:e,path:t,error:r instanceof Error?r.stack:r+""}),{commitHash:void 0,previousCommitHash:f}}},exports.commitMultipleFilesToGit=o,exports.handleMultiFileGitCommit=async function(e,t,r,n,s,i){const{logger:a,metricsPrefix:c,metrics:l}=s
4399
4382
  return 0===t.length||0===n?(a.debug("No file operations with changes to commit"),{filesCommitted:[],success:!0}):(l.incrementCounter(c+"_phase",1,{phase:u.FileOperationPhase.GIT_COMMIT}),await o(e,t,r,s,i))}
4400
4383
  const i=s(t(6928)),a=t(3807),c=t(9860),l=t(9671),d=t(8824),u=t(7575)},7960(e,exports){function t(){const e=process.argv[1]||""
4401
4384
  if(e.includes("/dist-dev/")||e.includes("\\dist-dev\\"))return!0
@@ -4405,17 +4388,17 @@ return!(!t.includes("/dist-dev")&&!t.includes("\\dist-dev"))}Object.defineProper
4405
4388
  if(r.debug("getClientInfoForMetadata called",{mcpServerExists:!!e,mcpServerType:typeof e,hasGetClientInfo:e?typeof e.getClientInfo:void 0,mcpServerKeys:e?Object.keys(e):void 0}),e&&"function"==typeof e.getClientInfo)try{t=e.getClientInfo(),r.debug("mcpServer.getClientInfo() returned",{clientInfo:t,clientInfoType:typeof t,name:t?.name,version:t?.version})}catch(e){r.debug("mcpServer.getClientInfo() failed",{error:e})}else r.debug("mcpServer not available or getClientInfo not a function")
4406
4389
  const n={clientName:t.name,clientVersion:t.version}
4407
4390
  return r.debug("getClientInfoForMetadata returning",{result:n}),n}
4408
- const r=t(3444).defaultLogger.child({component:"client-info-utils"})},8035(e,exports,t){function r(e,t,r){try{const n=`[${(new Date).toISOString()}] [detached-subagent] ${t}${r?" "+JSON.stringify(r):""}\n`,o=(0,a.join)(e||process.cwd(),".alchemy_lab","spawn-debug.log");(0,i.appendFileSync)(o,n)}catch{}}function n(e){const{agent:t,prompt:n,cwd:c,parentServerUrl:l,parentSessionId:d,sessionId:u,model:h,initialBranch:g,serverUrl:p,onSpawn:f,onError:m}=e
4391
+ const r=t(3444).defaultLogger.child({component:"client-info-utils"})},8035(e,exports,t){function r(e,t,r){try{const n=`[${(new Date).toISOString()}] [detached-subagent] ${t}${r?" "+JSON.stringify(r):""}\n`,o=(0,a.join)(e||process.cwd(),".alchemy_lab","spawn-debug.log");(0,i.appendFileSync)(o,n)}catch{}}function n(e){const{agent:t,prompt:n,cwd:c,parentServerUrl:l,parentSessionId:d,sessionId:u,model:h,initialBranch:g,serverUrl:f,onSpawn:p,onError:m}=e
4409
4392
  try{const s={...process.env}
4410
4393
  l&&(s.OPENCODE_PARENT_SERVER=l),g&&(s.ALCHEMY_INITIAL_BRANCH=g),e.allowParallel&&(s.ALCHEMY_ALLOW_PARALLEL="1")
4411
4394
  const d=new Date,m=`${(d.getHours()+"").padStart(2,"0")}${(d.getMinutes()+"").padStart(2,"0")}${(d.getSeconds()+"").padStart(2,"0")}`,y=Math.random().toString(36).substring(2,7)
4412
4395
  let w
4413
- if(s.ALCHEMY_SESSION_TAG=`mcp-${m}-${y}`,r(c,"Spawn env setup",{agent:t,initialBranch:g||"none",hasParentServer:!!l,sessionId:u||"new",attachMode:!!p}),w=p&&u&&n?["run","--attach",p,"--session",u,"--agent",t,n]:u&&n?["run","--session",u,"--agent",t,n]:n?["run","--agent",t,n]:["run","--agent",t],h){const e=w.findIndex((e=>e===n))
4396
+ if(s.ALCHEMY_SESSION_TAG=`mcp-${m}-${y}`,r(c,"Spawn env setup",{agent:t,initialBranch:g||"none",hasParentServer:!!l,sessionId:u||"new",attachMode:!!f}),w=f&&u&&n?["run","--attach",f,"--session",u,"--agent",t,n]:u&&n?["run","--session",u,"--agent",t,n]:n?["run","--agent",t,n]:["run","--agent",t],h){const e=w.findIndex((e=>e===n))
4414
4397
  e>0?w.splice(e,0,"--model",h):w.push("--model",h)}r(c,"Spawning opencode",{args:w.map((e=>e===n?`[prompt:${e.length}chars]`:e)),model:h||"not specified",promptLength:n?.length,promptPreview:n?.slice(0,100),cwd:c,hasSessionId:!!u,hasParentServerUrl:!!l})
4415
4398
  const k=(0,a.join)(c||process.cwd(),".alchemy_lab"),b=(0,a.join)(k,"spawn-stderr.log")
4416
4399
  let I
4417
4400
  try{I=(0,i.openSync)(b,"a")}catch{}const v=(0,o.spawn)("opencode",w,{detached:!0,stdio:["ignore","ignore",I??"ignore"],cwd:c||process.cwd(),env:s})
4418
- return v.unref(),f&&f(v.pid),{success:!0,pid:v.pid}}catch(e){const t=(0,s.getErrorMessage)(e)
4401
+ return v.unref(),p&&p(v.pid),{success:!0,pid:v.pid}}catch(e){const t=(0,s.getErrorMessage)(e)
4419
4402
  return m&&e instanceof Error&&m(e),{success:!1,error:t}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.spawnDetachedSubagent=n,exports.spawnJournalSubagent=function(e,t,r,o){return n({agent:"journal",prompt:`Generate a journal entry for request ${e}.\n\nSteps:\n1. Use ${t}__generate_request_journal tool with requestId: ${e}\n2. Write a concise narrative journal entry based on the returned data covering:\n - What was implemented and why\n - Key decisions and trade-offs made\n - Challenges encountered and solutions\n - Files modified and their purposes\n - How acceptance criteria were met\n3. Save as JOURNAL-${e}.md using ${t}__document_operations (operation: create, type: Report)\n\nKeep it story-focused and informative.`,cwd:r,parentServerUrl:o})},exports.spawnWorkSubagent=function(e,t,r){return n({agent:"work",prompt:e,cwd:t,parentServerUrl:r})}
4420
4403
  const o=t(5317),s=t(8824),i=t(9896),a=t(6928)},8037(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListRequests=async function(e,t,i,a,c){const l=a.child({tool:"list_requests"}),d=c.startTimer("tool_execution_time")
4421
4404
  try{const{filters:s={}}=e,a=["open","in_progress","ready_for_review","completed","canceled","reverted"]
@@ -4430,18 +4413,18 @@ s.status&&"undefined"!==s.status&&(u.status=s.status),s.type&&"undefined"!==s.ty
4430
4413
  const h=i.getRequestClient(),g=await h.listRequests(u)
4431
4414
  if(l.debug("=== RAW SERVER RESPONSE DEBUG ===",{responseType:typeof g,isArray:Array.isArray(g),responseKeys:g?Object.keys(g):[],fullResponse:JSON.stringify(g,null,2)}),g&&"object"==typeof g&&"data"in g){const e=g.data
4432
4415
  l.debug("=== SERVER RESPONSE DATA SECTION ===",{dataType:typeof e,isDataArray:Array.isArray(e),dataLength:Array.isArray(e)?e.length:"not array",firstItemKeys:Array.isArray(e)&&e.length>0?Object.keys(e[0]):"no items",firstItemSample:Array.isArray(e)&&e.length>0?JSON.stringify(e[0],null,2):"no items"}),Array.isArray(e)&&e.length>0&&e.slice(0,3).forEach(((e,t)=>{l.info(`=== ITEM ${t+1} LOCK INFO CHECK ===`,{id:e.id,hasLockInfo:"lockInfo"in e,lockInfoValue:e.lockInfo,allKeys:Object.keys(e),lockRelatedKeys:Object.keys(e).filter((e=>e.toLowerCase().includes("lock")))})}))}l.debug("Raw requests response data",{responseData:JSON.stringify(g)}),l.debug("Requests response structure",{type:typeof g,isArray:Array.isArray(g),hasData:null!=g,properties:g?Object.keys(g):[],dataPreview:g?JSON.stringify(g).substring(0,200)+"...":"null"}),l.debug("=== BEFORE EXTRACTION ===",{responseHasData:g&&"data"in g,responseDataLength:g&&"data"in g&&Array.isArray(g.data)?g.data.length:"not array",firstItemBeforeExtraction:g&&"data"in g&&Array.isArray(g.data)&&g.data.length>0?{id:g.data[0].id,hasLockInfo:"lockInfo"in g.data[0],lockInfo:g.data[0].lockInfo,allKeys:Object.keys(g.data[0])}:"no data"})
4433
- const p=(0,n.extractArrayFromResponse)(g,{logger:l,operationName:"listRequests",defaultValue:[]})
4434
- l.info("=== AFTER EXTRACTION ===",{extractedCount:p.length,firstItemAfterExtraction:p.length>0?{id:p[0].id,hasLockInfo:"lockInfo"in p[0],lockInfo:p[0].lockInfo,allKeys:Object.keys(p[0])}:"no items"}),l.info(`Extracted ${p.length} requests from response`)
4435
- const f=t.multiAgentMode||!1
4436
- if(l.debug("Lock info analysis",{multiAgentModeEnabled:f,requestCount:p.length,environmentVariable:process.env.ALCHEMY_MULTI_AGENT,firstRequestSample:p.length>0?{id:p[0].id,hasLockInfo:!!p[0].lockInfo,lockInfo:p[0].lockInfo,allProperties:Object.keys(p[0])}:"No requests to sample"}),p.length>0&&p.forEach(((e,t)=>{l.debug(`Request ${t+1} lock debug`,{id:e.id,title:e.title?.substring(0,50)+"...",hasLockInfo:!!e.lockInfo,lockInfoDetails:e.lockInfo||"NO LOCK INFO",allKeys:Object.keys(e).filter((e=>e.includes("lock")||e.includes("Lock")))})})),0===p.length)return d({success:!0,requestCount:0}),{content:[{type:"text",text:"No requests found with the specified filters."}]}
4437
- l.info("=== PRE-DISPLAY REQUEST ANALYSIS ===",{totalRequests:p.length,multiAgentMode:f,environmentVar:process.env.ALCHEMY_MULTI_AGENT}),p.forEach(((e,t)=>{l.info(`=== REQUEST ${t+1}/${p.length} PRE-DISPLAY ANALYSIS ===`,{id:e.id,title:e.title?.substring(0,30)+"...",hasLockInfo:"lockInfo"in e,lockInfoType:typeof e.lockInfo,lockInfoValue:e.lockInfo,lockInfoIsNull:null===e.lockInfo,lockInfoIsUndefined:void 0===e.lockInfo,allProperties:Object.keys(e),lockRelatedProperties:Object.keys(e).filter((e=>e.toLowerCase().includes("lock")||e.toLowerCase().includes("session")||e.toLowerCase().includes("expire")))}),e.lockInfo&&l.info(`=== REQUEST ${e.id} LOCK INFO DEEP DIVE ===`,{lockInfoKeys:Object.keys(e.lockInfo),isLocked:e.lockInfo.isLocked,lockedBySessionTag:e.lockInfo.lockedBySessionTag,timeRemainingFormatted:e.lockInfo.timeRemainingFormatted,isExpired:e.lockInfo.isExpired,fullLockInfo:JSON.stringify(e.lockInfo,null,2)})}))
4438
- const m=p.map((e=>{let t=""
4439
- if(l.info(`=== FORMATTING REQUEST ${e.id} ===`,{multiAgentMode:f,hasLockInfo:!!e.lockInfo,lockInfoValue:e.lockInfo,willShowLockInfo:!!e.lockInfo,note:"Lock info displayed when available regardless of mode"}),e.lockInfo){if(l.debug(`Processing lock info for ${e.id}:`,e.lockInfo),e.lockInfo.isLocked&&!e.lockInfo.isExpired){const{sessionTag:r}=(0,o.getGlobalClientInfo)(),n=e.lockInfo.lockedBySessionTag||"unknown"
4416
+ const f=(0,n.extractArrayFromResponse)(g,{logger:l,operationName:"listRequests",defaultValue:[]})
4417
+ l.info("=== AFTER EXTRACTION ===",{extractedCount:f.length,firstItemAfterExtraction:f.length>0?{id:f[0].id,hasLockInfo:"lockInfo"in f[0],lockInfo:f[0].lockInfo,allKeys:Object.keys(f[0])}:"no items"}),l.info(`Extracted ${f.length} requests from response`)
4418
+ const p=t.multiAgentMode||!1
4419
+ if(l.debug("Lock info analysis",{multiAgentModeEnabled:p,requestCount:f.length,environmentVariable:process.env.ALCHEMY_MULTI_AGENT,firstRequestSample:f.length>0?{id:f[0].id,hasLockInfo:!!f[0].lockInfo,lockInfo:f[0].lockInfo,allProperties:Object.keys(f[0])}:"No requests to sample"}),f.length>0&&f.forEach(((e,t)=>{l.debug(`Request ${t+1} lock debug`,{id:e.id,title:e.title?.substring(0,50)+"...",hasLockInfo:!!e.lockInfo,lockInfoDetails:e.lockInfo||"NO LOCK INFO",allKeys:Object.keys(e).filter((e=>e.includes("lock")||e.includes("Lock")))})})),0===f.length)return d({success:!0,requestCount:0}),{content:[{type:"text",text:"No requests found with the specified filters."}]}
4420
+ l.info("=== PRE-DISPLAY REQUEST ANALYSIS ===",{totalRequests:f.length,multiAgentMode:p,environmentVar:process.env.ALCHEMY_MULTI_AGENT}),f.forEach(((e,t)=>{l.info(`=== REQUEST ${t+1}/${f.length} PRE-DISPLAY ANALYSIS ===`,{id:e.id,title:e.title?.substring(0,30)+"...",hasLockInfo:"lockInfo"in e,lockInfoType:typeof e.lockInfo,lockInfoValue:e.lockInfo,lockInfoIsNull:null===e.lockInfo,lockInfoIsUndefined:void 0===e.lockInfo,allProperties:Object.keys(e),lockRelatedProperties:Object.keys(e).filter((e=>e.toLowerCase().includes("lock")||e.toLowerCase().includes("session")||e.toLowerCase().includes("expire")))}),e.lockInfo&&l.info(`=== REQUEST ${e.id} LOCK INFO DEEP DIVE ===`,{lockInfoKeys:Object.keys(e.lockInfo),isLocked:e.lockInfo.isLocked,lockedBySessionTag:e.lockInfo.lockedBySessionTag,timeRemainingFormatted:e.lockInfo.timeRemainingFormatted,isExpired:e.lockInfo.isExpired,fullLockInfo:JSON.stringify(e.lockInfo,null,2)})}))
4421
+ const m=f.map((e=>{let t=""
4422
+ if(l.info(`=== FORMATTING REQUEST ${e.id} ===`,{multiAgentMode:p,hasLockInfo:!!e.lockInfo,lockInfoValue:e.lockInfo,willShowLockInfo:!!e.lockInfo,note:"Lock info displayed when available regardless of mode"}),e.lockInfo){if(l.debug(`Processing lock info for ${e.id}:`,e.lockInfo),e.lockInfo.isLocked&&!e.lockInfo.isExpired){const{sessionTag:r}=(0,o.getGlobalClientInfo)(),n=e.lockInfo.lockedBySessionTag||"unknown"
4440
4423
  t=n===r?` [LOCKED by me, expires in ${e.lockInfo.timeRemainingFormatted}]`:` [LOCKED by ${n.length>20?n.substring(0,17)+"...":n}, expires in ${e.lockInfo.timeRemainingFormatted}]`}else t=" [AVAILABLE]"
4441
4424
  l.debug(`Generated lock info for ${e.id}: "${t}"`)}else l.debug("No lock info available for "+e.id)
4442
- return`**${e.title}** (${e.id}) [${e.type}]${t}\nStatus: ${e.status}\nType: ${e.type}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}\n`})).join("\n---\n"),y=p.some((e=>e.lockInfo))
4443
- let w=`Found ${p.length} request${1===p.length?"":"s"}:`
4444
- return y&&f&&(w+="\n\n**Lock Status:**\n",w+="LOCKED = Locked by an agent (shows session name and expiration)\n",w+="AVAILABLE = Not currently locked, safe to work on\n"),d({success:!0,requestCount:p.length}),{content:[{type:"text",text:`${w}\n\n${m}`}]}}catch(t){return l.error("Error listing requests",{args:e,error:t instanceof Error?t.stack:t+""}),d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:"Error listing requests: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
4425
+ return`**${e.title}** (${e.id}) [${e.type}]${t}\nStatus: ${e.status}\nType: ${e.type}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}\n`})).join("\n---\n"),y=f.some((e=>e.lockInfo))
4426
+ let w=`Found ${f.length} request${1===f.length?"":"s"}:`
4427
+ return y&&p&&(w+="\n\n**Lock Status:**\n",w+="LOCKED = Locked by an agent (shows session name and expiration)\n",w+="AVAILABLE = Not currently locked, safe to work on\n"),d({success:!0,requestCount:f.length}),{content:[{type:"text",text:`${w}\n\n${m}`}]}}catch(t){return l.error("Error listing requests",{args:e,error:t instanceof Error?t.stack:t+""}),d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:"Error listing requests: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
4445
4428
  const r=t(9860),n=t(2960),o=t(5172),s=t(8824)},8045(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
4446
4429
  const r=t(6183),n=t(7456)
4447
4430
  exports.def={name:"modify_file",description:'Make targeted edits to existing files and documents.\n\nOperations:\n\u2022 replace-string - Find and replace text\n - mode: \'unique\' (default, safer - fails if multiple matches)\n - mode: \'all\' (replaces all occurrences)\n\u2022 delete-string - Remove text patterns (same modes as replace-string)\n\u2022 insert-lines - Insert content before/after/between lines\n\u2022 replace-lines - Replace specific line numbers\n\u2022 delete-lines - Remove specific line numbers\n\nLine specification (string format for line-based operations):\n- Single line: "lines": "5"\n- Multiple lines: "lines": "1,3,7,10"\n- Range: "lines": "10-15"\n\nRead file first to know line numbers. Supports multiple files and operations in one call. Works with both filesystem files (path) and tracked documents (documentId).',schema:r.ModifyFileSchema,annotations:{title:"Modify File",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,handler(e,t){return(0,n.handleModifyFile)(e,t.context,t.apiClient.getTaskClient(),t.apiClient.getToolRecordClient(),t.apiClient.getRequestClient(),t.logger,t.metrics,t.mcpServer)}}},8291(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
@@ -4468,33 +4451,33 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
4468
4451
  var t={}
4469
4452
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
4470
4453
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
4471
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,t,r,n,o,s,i,p){const f=s.child({tool:"create_directory"}),m=Date.now()
4454
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,t,r,n,o,s,i,f){const p=s.child({tool:"create_directory"}),m=Date.now()
4472
4455
  let y,w,k=d.FileOperationPhase.VALIDATION
4473
4456
  const b={toolName:"create-directory",operationName:"create",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"create-directory",metricsPrefix:"create_directory",successMessage:"Successfully created directory {path}",failureMessage:"Failed to create directory {path}"}
4474
4457
  try{const s=d.validateArgs(e,l.CreateDirectorySchema),{taskId:u,path:h,comment:g}=s
4475
- f.info("Creating directory: "+h,{taskId:u,path:h,comment:g}),d.validateTaskIdFormat(u,f,i,b.metricsPrefix),t.getCurrentBranchContext&&await t.getCurrentBranchContext()
4458
+ p.info("Creating directory: "+h,{taskId:u,path:h,comment:g}),d.validateTaskIdFormat(u,p,i,b.metricsPrefix),t.getCurrentBranchContext&&await t.getCurrentBranchContext()
4476
4459
  const{normalizedPath:I,fullPath:v}=d.validateAndNormalizePath(h,t)
4477
4460
  k=d.FileOperationPhase.TASK_VALIDATION,i.incrementCounter("create_directory_phase",1,{phase:k})
4478
- const C=await d.validateTaskId(u,I,r,f,i,b.metricsPrefix),_=C?.requestId,E=await d.validateWorkItemStates(u,I,r,o,t,f,i,b.metricsPrefix),q=await d.autoPromoteTaskStatus(u,C.status,_,E.request?.status,I,r,o,f,i,b.metricsPrefix)
4479
- q.taskPromoted&&f.info(`Auto-promoted task ${u} (${C.title||"Untitled"}) to in_progress for file operation`,{taskId:u,taskTitle:C.title,previousStatus:C.status,newStatus:q.newTaskStatus,path:I}),q.requestPromoted&&f.info(`Auto-promoted request ${_} to in_progress for file operation`,{requestId:_,previousStatus:E.request?.status,newStatus:q.newRequestStatus,triggeringTaskId:u})
4480
- const S=await d.ensureCorrectWorkspaceContext({taskPromoted:q.taskPromoted,requestId:_,context:t,operation:"create-directory",logger:f,metrics:i,metricsPrefix:b.metricsPrefix})
4461
+ const C=await d.validateTaskId(u,I,r,p,i,b.metricsPrefix),_=C?.requestId,E=await d.validateWorkItemStates(u,I,r,o,t,p,i,b.metricsPrefix),q=await d.autoPromoteTaskStatus(u,C.status,_,E.request?.status,I,r,o,p,i,b.metricsPrefix)
4462
+ q.taskPromoted&&p.info(`Auto-promoted task ${u} (${C.title||"Untitled"}) to in_progress for file operation`,{taskId:u,taskTitle:C.title,previousStatus:C.status,newStatus:q.newTaskStatus,path:I}),q.requestPromoted&&p.info(`Auto-promoted request ${_} to in_progress for file operation`,{requestId:_,previousStatus:E.request?.status,newStatus:q.newRequestStatus,triggeringTaskId:u})
4463
+ const S=await d.ensureCorrectWorkspaceContext({taskPromoted:q.taskPromoted,requestId:_,context:t,operation:"create-directory",logger:p,metrics:i,metricsPrefix:b.metricsPrefix})
4481
4464
  if(!S.success){if(S.isLockConflict)return{content:[{type:"text",text:"\u274c "+S.error}],isError:!0}
4482
4465
  throw Error(S.error)}let T=!1
4483
4466
  try{T=(await a.default.stat(v)).isDirectory()}catch{T=!1}k=d.FileOperationPhase.RECORD_CREATION,i.incrementCounter("create_directory_phase",1,{phase:k})
4484
- const{toolRecordId:M,localToolRecordId:R}=await d.createFileOperationRecords(u,_,t.projectId,b.recordType,I,{directoryExists:T,userComment:g},r,n,f,i,b.metricsPrefix,p)
4467
+ const{toolRecordId:M,localToolRecordId:R}=await d.createFileOperationRecords(u,_,t.projectId,b.recordType,I,{directoryExists:T,userComment:g},r,n,p,i,b.metricsPrefix,f)
4485
4468
  y=M,w=M,k=b.fileOperationPhase,i.incrementCounter("create_directory_phase",1,{phase:k})
4486
4469
  let P=T
4487
- if(!T){await a.default.mkdir(v,{recursive:!0}),f.info("Successfully created directory "+I)
4470
+ if(!T){await a.default.mkdir(v,{recursive:!0}),p.info("Successfully created directory "+I)
4488
4471
  try{const e=c.default.join(v,".gitkeep")
4489
- await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),P=!0,f.info("Created .gitkeep file for Git tracking")}catch(e){f.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),P=!1}}const x=Date.now()-m
4472
+ await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),P=!0,p.info("Created .gitkeep file for Git tracking")}catch(e){p.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),P=!1}}const x=Date.now()-m
4490
4473
  i.recordValue("create_directory_time",x),i.incrementCounter("create_directory_success",1),k=d.FileOperationPhase.GIT_COMMIT,i.incrementCounter("create_directory_phase",1,{phase:k})
4491
- const O=`Create directory: ${I} - ${g||"Create directory"}`,j=!T&&P?I+"/.gitkeep":I,$=await d.commitToGit(u,j,M,R,O,t,f,i,b.metricsPrefix)
4492
- k=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("create_directory_phase",1,{phase:k}),await d.updateFileOperationRecords(u,y,w,I,b.recordType,`Successfully ${T?"verified":"created"} directory: ${I}`,{status:"completed",commitHash:$.commitHash,previousCommitHash:$.previousCommitHash,directoryExists:T,isDirectory:!0,userComment:g},`Successfully ${T?"verified":"created"} directory: ${I}`,r,n,f,i,b.metricsPrefix)
4493
- const A=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
4494
- return{content:[{type:"text",text:T?"Directory already exists":`Successfully created directory${$.commitHash?"\nCommit: "+$.commitHash.substring(0,8):""}${A.requestId?"\nBranch: "+A.requestId:""}${S.lockAcquired&&S.lockedRequestId?"\n\u{1f512} **Locked request:** "+S.lockedRequestId:""}`}]}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
4495
- await n.createToolRecord({...r?{}:{taskId:e.taskId},projectId:t.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(o)}`})}catch(t){f.error("Failed to create failure record for create directory operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,path:e.path})}const s=Date.now()-m
4496
- if(i.recordValue("create_directory_time",s),i.incrementCounter("create_directory_errors",1),f.error("Error creating directory:",{error:(0,g.getErrorMessage)(o),time:s}),(y||w)&&e.taskId){k=d.FileOperationPhase.RECORD_UPDATE_FAILURE
4497
- try{await d.updateFileOperationRecords(e.taskId,y,w,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(o),userComment:e.comment},"Failed to create directory "+e.path,r,n,f,i,b.metricsPrefix)}catch(t){f.error("Failed to update record with failure status",{taskId:e.taskId,recordId:y,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(o,k,f,i,e,b)}}
4474
+ const O=`Create directory: ${I} - ${g||"Create directory"}`,j=!T&&P?I+"/.gitkeep":I,$=await d.commitToGit(u,j,M,R,O,t,p,i,b.metricsPrefix)
4475
+ k=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("create_directory_phase",1,{phase:k}),await d.updateFileOperationRecords(u,y,w,I,b.recordType,`Successfully ${T?"verified":"created"} directory: ${I}`,{status:"completed",commitHash:$.commitHash,previousCommitHash:$.previousCommitHash,directoryExists:T,isDirectory:!0,userComment:g},`Successfully ${T?"verified":"created"} directory: ${I}`,r,n,p,i,b.metricsPrefix)
4476
+ const D=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
4477
+ return{content:[{type:"text",text:T?"Directory already exists":`Successfully created directory${$.commitHash?"\nCommit: "+$.commitHash.substring(0,8):""}${D.requestId?"\nBranch: "+D.requestId:""}${S.lockAcquired&&S.lockedRequestId?"\n\u{1f512} **Locked request:** "+S.lockedRequestId:""}`}]}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
4478
+ await n.createToolRecord({...r?{}:{taskId:e.taskId},projectId:t.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(o)}`})}catch(t){p.error("Failed to create failure record for create directory operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,path:e.path})}const s=Date.now()-m
4479
+ if(i.recordValue("create_directory_time",s),i.incrementCounter("create_directory_errors",1),p.error("Error creating directory:",{error:(0,g.getErrorMessage)(o),time:s}),(y||w)&&e.taskId){k=d.FileOperationPhase.RECORD_UPDATE_FAILURE
4480
+ try{await d.updateFileOperationRecords(e.taskId,y,w,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(o),userComment:e.comment},"Failed to create directory "+e.path,r,n,p,i,b.metricsPrefix)}catch(t){p.error("Failed to update record with failure status",{taskId:e.taskId,recordId:y,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(o,k,p,i,e,b)}}
4498
4481
  const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(8824)},8317(e,exports,t){function r(e){const t=[]
4499
4482
  return"write-file"===e.type&&e.metadata?.path?t.push(e.metadata.path):"replace-in-files"===e.type&&e.metadata?.operations?e.metadata.operations.forEach((e=>{e.path&&t.push(e.path)})):"move-files"===e.type&&e.metadata?.successfulOperations?e.metadata.successfulOperations.forEach((e=>{e.destination&&t.push(e.destination)})):"delete-files"===e.type&&e.metadata?.paths?t.push(...e.metadata.paths):"manage-files"===e.type&&e.metadata?.operations&&e.metadata.operations.forEach((e=>{e.createDirectory?.path&&t.push(e.createDirectory.path),e.moveFiles?.moves&&e.moveFiles.moves.forEach((e=>{e.destination&&t.push(e.destination)})),e.deleteFiles?.targets&&e.deleteFiles.targets.forEach((e=>{e.path&&t.push(e.path)}))})),[...new Set(t)]}function n(e){switch(e){case"write-file":return"\u{1f4dd} Write File"
4500
4483
  case"replace-in-files":return"\u{1f504} Replace in Files"
@@ -4502,11 +4485,11 @@ case"move-files":return"\u{1f4cb} Move Files"
4502
4485
  case"delete-files":return"\u{1f5d1}\ufe0f Delete Files"
4503
4486
  case"manage-files":return"\u{1f4c1} Manage Files"
4504
4487
  default:return e}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestFileHistory=async function(e,t,a,c,l){const d=c.child({tool:"request_file_history"}),u=l.startTimer("tool_execution_time")
4505
- try{const{requestId:c,detailLevel:h="summary",taskId:g,showDiff:p=!1,fileFilter:f}=e
4488
+ try{const{requestId:c,detailLevel:h="summary",taskId:g,showDiff:f=!1,fileFilter:p}=e
4506
4489
  if(!c)throw(0,o.createValidationError)("Request ID is required")
4507
4490
  if(!/^req[_\d].+$/.test(c))throw(0,o.createValidationError)(`Invalid request ID format: ${c}. Expected format: req_[26 chars] or req######`)
4508
4491
  if(g&&!/^tas\d{6}$/.test(g))throw(0,o.createValidationError)(`Invalid task ID format: ${g}. Expected format: tas######`)
4509
- if(d.info("Getting file changes for request "+c,{detailLevel:h,taskId:g,showDiff:p}),!t.git)throw Error("Git integration not available in this context")
4492
+ if(d.info("Getting file changes for request "+c,{detailLevel:h,taskId:g,showDiff:f}),!t.git)throw Error("Git integration not available in this context")
4510
4493
  const m=t.projectId
4511
4494
  let y
4512
4495
  a.setProjectId(m)
@@ -4529,7 +4512,7 @@ let r=0
4529
4512
  e.forEach((e=>{e.replacements&&(r+=e.replacements.length)})),d+=`**Replacements**: ${r}\n`}if(t.metadata?.commitHash&&(d+=`**Commit**: ${t.metadata.commitHash.substring(0,8)}\n`,s||5>=h.length))try{const e=await a.diff([t.metadata.commitHash+"^",t.metadata.commitHash])
4530
4513
  if(e&&e.trim()){const r=500,n=e.length
4531
4514
  if(n>r){const o=e.substring(0,r),s=(n/1024).toFixed(1)
4532
- d+=`\n**Changes preview** (first ${r} chars):\n\`\`\`diff\n${o}\n\`\`\`\n`,d+=`... (diff truncated, ${s}KB total)\n`,d+=`\u{1f4a1} Use \`file-history\` tool with commit \`${t.metadata.commitHash.substring(0,8)}\` to see full diff\n`}else d+=`\n**Changes:**\n\`\`\`diff\n${e}\n\`\`\`\n`}}catch(e){c.debug("Could not fetch diff for commit",{commit:t.metadata.commitHash,error:(0,i.getErrorMessage)(e)})}d+="\n---\n\n"}return d}(y,o,g,p,t.git,d,f)
4515
+ d+=`\n**Changes preview** (first ${r} chars):\n\`\`\`diff\n${o}\n\`\`\`\n`,d+=`... (diff truncated, ${s}KB total)\n`,d+=`\u{1f4a1} Use \`file-history\` tool with commit \`${t.metadata.commitHash.substring(0,8)}\` to see full diff\n`}else d+=`\n**Changes:**\n\`\`\`diff\n${e}\n\`\`\`\n`}}catch(e){c.debug("Could not fetch diff for commit",{commit:t.metadata.commitHash,error:(0,i.getErrorMessage)(e)})}d+="\n---\n\n"}return d}(y,o,g,f,t.git,d,p)
4533
4516
  return u({success:!0,recordCount:o.length}),{content:[{type:"text",text:s}]}}{const e=a.getToolRecordClient()
4534
4517
  let n=[]
4535
4518
  try{g?(n=await e.getToolRecordsByTaskId(g),d.info(`Fetched ${n.length} records for task ${g}`)):(n=await e.getToolRecordsByRequestId(c),d.info(`Fetched ${n.length} records for request ${c}`))}catch(e){d.warn("Error fetching tool records: "+(0,i.getErrorMessage)(e)),n=[]}const o=await async function(e,t){const n=new Map
@@ -4539,7 +4522,7 @@ if(!["write-file","replace-in-files","move-files","delete-files","manage-files"]
4539
4522
  o++
4540
4523
  const i=r(s)
4541
4524
  for(const e of i)t&&!RegExp(t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")).test(e)||n.has(e)||n.set(e,{path:e,status:"M",linesAdded:0,linesDeleted:0,isBinary:!1})}const s=Array.from(n.values())
4542
- return{summary:{filesChanged:s.length,linesAdded:0,linesDeleted:0,binaryFiles:0,renamedFiles:0,totalCommits:o,timespan:void 0},files:s}}(n,f,t.git),s=function(e,t,r){const{requestInfo:n,branchInfo:o,summary:s,files:i,commits:a}=e
4525
+ return{summary:{filesChanged:s.length,linesAdded:0,linesDeleted:0,binaryFiles:0,renamedFiles:0,totalCommits:o,timespan:void 0},files:s}}(n,p,t.git),s=function(e,t,r){const{requestInfo:n,branchInfo:o,summary:s,files:i,commits:a}=e
4543
4526
  let c=`# File Changes for Request: ${n.id}\n\n`
4544
4527
  if("Unknown Request"===n.title&&"unknown"===n.status||(c+=`**Request:** ${n.title}\n`,"unknown"!==n.status&&(c+=`**Status:** ${n.status}\n`),c+="\n"),r&&(c+=`**Filter:** \`${r}\`\n`),c+=`**Files Changed:** ${s.filesChanged}\n`,s.filesChanged>0&&(c+=`**Changes:** +${s.linesAdded} -${s.linesDeleted} lines\n`,s.totalCommits>0&&(c+=`**Commits:** ${s.totalCommits}\n`)),c+="\n",0===i.length)c+="No file changes found.\n\n"
4545
4528
  else{const e=50,t=i.slice(0,e),r=i.length-e
@@ -4549,7 +4532,7 @@ case"D":return"\u{1f5d1}\ufe0f"
4549
4532
  case"R":return"\u{1f4cb}"
4550
4533
  case"C":return"\u{1f4d1}"
4551
4534
  case"T":return"\u{1f504}"}}(e.status)
4552
- c+=`- ${t} ${e.path}`,e.renamedFrom&&(c+=` (renamed from ${e.renamedFrom})`),c+="\n"})),r>0&&(c+=`\n... and ${r} more file${1===r?"":"s"}\n`,c+="\n\u{1f4a1} Use fileFilter to narrow results or use detailed mode to see all files.\n"),c+="\n"}return c}({requestInfo:y,branchInfo:{branchName:"requests/"+c,baseCommit:"",headCommit:"",exists:!1,isCompleted:"completed"===y.status},summary:o.summary,files:o.files,commits:[]},0,f)
4535
+ c+=`- ${t} ${e.path}`,e.renamedFrom&&(c+=` (renamed from ${e.renamedFrom})`),c+="\n"})),r>0&&(c+=`\n... and ${r} more file${1===r?"":"s"}\n`,c+="\n\u{1f4a1} Use fileFilter to narrow results or use detailed mode to see all files.\n"),c+="\n"}return c}({requestInfo:y,branchInfo:{branchName:"requests/"+c,baseCommit:"",headCommit:"",exists:!1,isCompleted:"completed"===y.status},summary:o.summary,files:o.files,commits:[]},0,p)
4553
4536
  return u({success:!0,filesChanged:o.summary.filesChanged}),{content:[{type:"text",text:s}]}}}catch(e){return d.error("Error in request file history tool",{error:e instanceof Error?e.stack:e+""}),u({success:!1,error:e instanceof Error?e.name:"unknown"}),{content:[{type:"text",text:"Error: "+(0,i.getErrorMessage)(e)}],isError:!0}}}
4554
4537
  const o=t(9860),s=t(2960),i=t(8824)},8349(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDebugGitLog=async function(e,t){try{if(!t.git)return{content:[{type:"text",text:"No git repository available"}]}
4555
4538
  const e=await t.git.log(),r="req000010",n=e.all.filter((e=>e.message.includes(r))),o=e.all.filter((e=>e.message.toLowerCase().includes("merge"))),s=e.all.slice(0,10)
@@ -4567,28 +4550,28 @@ o+=`**${t}** \u2014 ${e.filename}\n`,o+=` Updated: ${r}\n`,n&&(o+=` ${n}\n`),o
4567
4550
  const r=t(8824)},8411(e,exports,t){function r(e){if(!a.default.existsSync(e))return null
4568
4551
  try{const t=a.default.readFileSync(e,"utf8").trim()
4569
4552
  try{const e=JSON.parse(t)
4570
- return p.debug("Read JSON lock data",e),e}catch{const e=parseInt(t,10)
4571
- if(isNaN(e))return p.warn("Invalid lock file content",{content:t}),null
4553
+ return f.debug("Read JSON lock data",e),e}catch{const e=parseInt(t,10)
4554
+ if(isNaN(e))return f.warn("Invalid lock file content",{content:t}),null
4572
4555
  const r={mode:"single-agent",created:(new Date).toISOString(),hostname:"unknown",pid:e}
4573
- return p.debug("Read legacy PID lock data",r),r}}catch(e){return p.error("Error reading lock file",{error:(0,h.getErrorMessage)(e)}),null}}function n(e){try{return process.kill(e,0),!0}catch{return!1}}function o(e,t,n,o,i){try{const c={mode:i?"multi-agent":"single-agent",created:o,hostname:l.default.hostname(),...i?{}:{pid:n}}
4556
+ return f.debug("Read legacy PID lock data",r),r}}catch(e){return f.error("Error reading lock file",{error:(0,h.getErrorMessage)(e)}),null}}function n(e){try{return process.kill(e,0),!0}catch{return!1}}function o(e,t,n,o,i){try{const c={mode:i?"multi-agent":"single-agent",created:o,hostname:l.default.hostname(),...i?{}:{pid:n}}
4574
4557
  if(a.default.writeFileSync(e,JSON.stringify(c,null,2)),i){const r={count:1,processes:[{pid:n,started:o}]}
4575
4558
  a.default.writeFileSync(t,JSON.stringify(r,null,2)),s(e,t,n)}else!function(e,t){["SIGINT","SIGTERM","exit"].forEach((n=>{process.on(n,(()=>{try{if(a.default.existsSync(e)){const o=r(e)
4576
- o&&o.pid===t&&(a.default.unlinkSync(e),p.debug("Removed single-agent lock file",{signal:n,pid:t}))}}catch(e){p.error("Error removing single-agent lock file",{error:e instanceof Error?e.message:e+"",signal:n})}"exit"!==n&&process.exit(0)}))}))}(e,n)
4577
- return p.info("Created new lock",{mode:c.mode,pid:n}),!0}catch(e){return p.error("Error creating new lock",{error:(0,h.getErrorMessage)(e)}),!1}}function s(e,t,r){["SIGINT","SIGTERM","exit"].forEach((n=>{process.on(n,(()=>{try{if(a.default.existsSync(t)){const o=a.default.readFileSync(t,"utf8"),s=JSON.parse(o)
4578
- s.processes=s.processes.filter((e=>e.pid!==r)),s.count=s.processes.length,s.count>0?(a.default.writeFileSync(t,JSON.stringify(s,null,2)),p.debug("Removed process from multi-agent references",{signal:n,pid:r,remaining:s.count})):(a.default.unlinkSync(t),a.default.existsSync(e)&&a.default.unlinkSync(e),p.debug("Removed multi-agent lock files (last process)",{signal:n,pid:r}))}}catch(e){p.error("Error removing multi-agent lock files",{error:e instanceof Error?e.message:e+"",signal:n})}"exit"!==n&&process.exit(0)}))}))}var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
4559
+ o&&o.pid===t&&(a.default.unlinkSync(e),f.debug("Removed single-agent lock file",{signal:n,pid:t}))}}catch(e){f.error("Error removing single-agent lock file",{error:e instanceof Error?e.message:e+"",signal:n})}"exit"!==n&&process.exit(0)}))}))}(e,n)
4560
+ return f.info("Created new lock",{mode:c.mode,pid:n}),!0}catch(e){return f.error("Error creating new lock",{error:(0,h.getErrorMessage)(e)}),!1}}function s(e,t,r){["SIGINT","SIGTERM","exit"].forEach((n=>{process.on(n,(()=>{try{if(a.default.existsSync(t)){const o=a.default.readFileSync(t,"utf8"),s=JSON.parse(o)
4561
+ s.processes=s.processes.filter((e=>e.pid!==r)),s.count=s.processes.length,s.count>0?(a.default.writeFileSync(t,JSON.stringify(s,null,2)),f.debug("Removed process from multi-agent references",{signal:n,pid:r,remaining:s.count})):(a.default.unlinkSync(t),a.default.existsSync(e)&&a.default.unlinkSync(e),f.debug("Removed multi-agent lock files (last process)",{signal:n,pid:r}))}}catch(e){f.error("Error removing multi-agent lock files",{error:e instanceof Error?e.message:e+"",signal:n})}"exit"!==n&&process.exit(0)}))}))}var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
4579
4562
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.acquireProcessLock=function(e,t=!1){const i=c.default.join(e,d.ALCHEMY_DIR_NAME)
4580
- let u,f
4581
- try{a.default.existsSync(i)||(a.default.mkdirSync(i,{recursive:!0}),p.debug(`Created ${d.ALCHEMY_DIR_NAME} directory for lock file`,{alchemyLabDir:i})),u=c.default.join(i,".mcp-server.lock"),f=c.default.join(i,".mcp-agents.refs"),p.debug(`Using ${d.ALCHEMY_DIR_NAME} directory for lock files`,{lockFilePath:u,refsFilePath:f})}catch(t){p.error(`Failed to create ${d.ALCHEMY_DIR_NAME} directory`,{alchemyLabDir:i,error:t instanceof Error?t.message:t+""}),u=c.default.join(e,".mcp-server.lock"),f=c.default.join(e,".mcp-agents.refs"),p.warn("Falling back to base directory for lock files",{lockFilePath:u,refsFilePath:f})}const m=process.pid,y=(new Date).toISOString()
4563
+ let u,p
4564
+ try{a.default.existsSync(i)||(a.default.mkdirSync(i,{recursive:!0}),f.debug(`Created ${d.ALCHEMY_DIR_NAME} directory for lock file`,{alchemyLabDir:i})),u=c.default.join(i,".mcp-server.lock"),p=c.default.join(i,".mcp-agents.refs"),f.debug(`Using ${d.ALCHEMY_DIR_NAME} directory for lock files`,{lockFilePath:u,refsFilePath:p})}catch(t){f.error(`Failed to create ${d.ALCHEMY_DIR_NAME} directory`,{alchemyLabDir:i,error:t instanceof Error?t.message:t+""}),u=c.default.join(e,".mcp-server.lock"),p=c.default.join(e,".mcp-agents.refs"),f.warn("Falling back to base directory for lock files",{lockFilePath:u,refsFilePath:p})}const m=process.pid,y=(new Date).toISOString()
4582
4565
  try{const e=r(u)
4583
- if(p.info("Lock acquisition attempt",{pid:m,multiAgentMode:t,lockFilePath:u,lockExists:!!e,lockData:e?{mode:e.mode,pid:e.pid,hostname:e.hostname,created:e.created}:null}),!e)return p.info("No existing lock - creating new lock",{pid:m,mode:t?"multi-agent":"single-agent"}),o(u,f,m,y,t)
4566
+ if(f.info("Lock acquisition attempt",{pid:m,multiAgentMode:t,lockFilePath:u,lockExists:!!e,lockData:e?{mode:e.mode,pid:e.pid,hostname:e.hostname,created:e.created}:null}),!e)return f.info("No existing lock - creating new lock",{pid:m,mode:t?"multi-agent":"single-agent"}),o(u,p,m,y,t)
4584
4567
  {const r=Date.now()-new Date(e.created).getTime(),i=r>g,c=l.default.hostname(),d=e.hostname!==c&&"unknown"!==e.hostname
4585
- if(i)return p.warn("\u26a0\ufe0f Clearing stale lock (older than 24 hours)",{lockAge:Math.round(r/1e3/60/60)+" hours",lockCreated:e.created,lockHostname:e.hostname}),o(u,f,m,y,t)
4586
- if(d)return p.warn("\u26a0\ufe0f Clearing lock from different machine",{lockHostname:e.hostname,currentHostname:c}),o(u,f,m,y,t)
4587
- if("single-agent"===e.mode)return e.pid===m?(p.debug("Same process already has lock",{pid:m}),!0):n(e.pid)?(p.warn("Cannot acquire lock - single-agent mode active",{existingPid:e.pid,currentPid:m,requestedMode:t?"multi-agent":"single-agent"}),!1):(p.info("Taking over lock from dead single-agent process",{deadPid:e.pid,currentPid:m,newMode:t?"multi-agent":"single-agent"}),o(u,f,m,y,t))
4568
+ if(i)return f.warn("\u26a0\ufe0f Clearing stale lock (older than 24 hours)",{lockAge:Math.round(r/1e3/60/60)+" hours",lockCreated:e.created,lockHostname:e.hostname}),o(u,p,m,y,t)
4569
+ if(d)return f.warn("\u26a0\ufe0f Clearing lock from different machine",{lockHostname:e.hostname,currentHostname:c}),o(u,p,m,y,t)
4570
+ if("single-agent"===e.mode)return e.pid===m?(f.debug("Same process already has lock",{pid:m}),!0):n(e.pid)?(f.warn("Cannot acquire lock - single-agent mode active",{existingPid:e.pid,currentPid:m,requestedMode:t?"multi-agent":"single-agent"}),!1):(f.info("Taking over lock from dead single-agent process",{deadPid:e.pid,currentPid:m,newMode:t?"multi-agent":"single-agent"}),o(u,p,m,y,t))
4588
4571
  if("multi-agent"===e.mode)return t?function(e,t,r){try{let o={count:0,processes:[]}
4589
4572
  if(a.default.existsSync(e)){const t=a.default.readFileSync(e,"utf8")
4590
- o=JSON.parse(t),o.processes=o.processes.filter((e=>n(e.pid))),o.count=o.processes.length}return o.processes.push({pid:t,started:r}),o.count=o.processes.length,a.default.writeFileSync(e,JSON.stringify(o,null,2)),s(e.replace(".mcp-agents.refs",".mcp-server.lock"),e,t),p.info("Joined multi-agent lock",{pid:t,totalAgents:o.count}),!0}catch(e){return p.error("Error joining multi-agent lock",{error:(0,h.getErrorMessage)(e)}),!1}}(f,m,y):(p.warn("Cannot acquire lock - multi-agent mode active",{currentPid:m,requestedMode:"single-agent"}),!1)}return!1}catch(e){return p.error("Error acquiring lock",{error:(0,h.getErrorMessage)(e),pid:m}),!1}}
4591
- const a=i(t(9896)),c=i(t(6928)),l=i(t(857)),d=t(4139),u=t(3444),h=t(8824),g=864e5,p=(0,u.createLogger)({serviceName:"process-lock",level:u.LogLevel.DEBUG,logToFile:!1})},8451(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatFileSize=function(e){return 1024>e?e+" bytes":1048576>e?(e/1024).toFixed(2)+" KB":1073741824>e?(e/1048576).toFixed(2)+" MB":(e/1073741824).toFixed(2)+" GB"},exports.truncate=function(e,t){return e.length>t?e.substring(0,t-3)+"...":e},exports.escapeRegExp=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},exports.countOccurrences=function(e,t){if(0===t.length)return 0
4573
+ o=JSON.parse(t),o.processes=o.processes.filter((e=>n(e.pid))),o.count=o.processes.length}return o.processes.push({pid:t,started:r}),o.count=o.processes.length,a.default.writeFileSync(e,JSON.stringify(o,null,2)),s(e.replace(".mcp-agents.refs",".mcp-server.lock"),e,t),f.info("Joined multi-agent lock",{pid:t,totalAgents:o.count}),!0}catch(e){return f.error("Error joining multi-agent lock",{error:(0,h.getErrorMessage)(e)}),!1}}(p,m,y):(f.warn("Cannot acquire lock - multi-agent mode active",{currentPid:m,requestedMode:"single-agent"}),!1)}return!1}catch(e){return f.error("Error acquiring lock",{error:(0,h.getErrorMessage)(e),pid:m}),!1}}
4574
+ const a=i(t(9896)),c=i(t(6928)),l=i(t(857)),d=t(4139),u=t(3444),h=t(8824),g=864e5,f=(0,u.createLogger)({serviceName:"process-lock",level:u.LogLevel.DEBUG,logToFile:!1})},8451(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatFileSize=function(e){return 1024>e?e+" bytes":1048576>e?(e/1024).toFixed(2)+" KB":1073741824>e?(e/1048576).toFixed(2)+" MB":(e/1073741824).toFixed(2)+" GB"},exports.truncate=function(e,t){return e.length>t?e.substring(0,t-3)+"...":e},exports.escapeRegExp=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},exports.countOccurrences=function(e,t){if(0===t.length)return 0
4592
4575
  let r=0,n=0
4593
4576
  for(;n=e.indexOf(t,n),-1!==n;)r++,n+=t.length
4594
4577
  return r},exports.handleFileOperationError=function(e,t,n,o,s,i){n.error(`${i.toolName} operation failed in phase: ${t}`,{args:s,phase:t,error:e instanceof Error?e.stack:e+""})
@@ -4629,27 +4612,27 @@ const o=new Set(["py","python","yaml","yml","pug","jade","haml","slim","sass","s
4629
4612
  if(!t)throw Error(`Tool "${e}" does not have a defined RecordType mapping. This is a type safety violation. Please add this tool to the TOOL_NAME_TO_RECORD_TYPE_MAP in failure-record-utils.ts.`)
4630
4613
  return t}function n(e){return!!e&&/^tas\d{6}$/.test(e)}function o(e){return!!e&&(/^req\d{6}$/.test(e)||/^req_[\w-]+$/.test(e))}function s(e){return!!e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.toolNameToRecordType=r,exports.isValidTaskId=n,exports.isValidRequestId=o,exports.isValidProjectId=s,exports.createFailureToolRecord=async function(e,t,a,c,l,d,u){if(!c)return void l.warn("ToolRecordClient is not available, skipping failure record creation for "+e)
4631
4614
  if(!s(u.projectId)){const t=Error(`Invalid projectId format: ${u.projectId}. Cannot create failure record without valid projectId.`)
4632
- throw l.error("Cannot create failure record due to invalid projectId",{toolName:e,projectId:u.projectId,error:t.message}),t}const h=Date.now(),g=e.replace(/-/g,"_"),p=(0,i.getErrorMessage)(t),f=t instanceof Error?t.stack:void 0
4615
+ throw l.error("Cannot create failure record due to invalid projectId",{toolName:e,projectId:u.projectId,error:t.message}),t}const h=Date.now(),g=e.replace(/-/g,"_"),f=(0,i.getErrorMessage)(t),p=t instanceof Error?t.stack:void 0
4633
4616
  try{const t=r(e),s={}
4634
4617
  let i,m
4635
4618
  u.taskId&&(n(u.taskId)?i=u.taskId:(s.taskId=u.taskId,l.warn(`Invalid taskId format: ${u.taskId}, not associating failure record with this ID`,{toolName:e,invalidTaskId:u.taskId}))),u.requestId&&(o(u.requestId)?m=u.requestId:(s.requestId=u.requestId,l.warn(`Invalid requestId format: ${u.requestId}, not associating failure record with this ID`,{toolName:e,invalidRequestId:u.requestId})))
4636
- let y=u.note||`Failed to execute ${e}: ${p.substring(0,100)}${p.length>100?"...":""}`
4619
+ let y=u.note||`Failed to execute ${e}: ${f.substring(0,100)}${f.length>100?"...":""}`
4637
4620
  Object.keys(s).length>0&&(y+=` (Warning: Invalid IDs provided: ${Object.entries(s).map((([e,t])=>`${e}: ${t}`)).join(", ")})`)
4638
- const w={projectId:u.projectId,type:t,note:y,metadata:{status:"failed",error:p,errorStack:f,originalToolName:e,timestamp:(new Date).toISOString(),invalidIds:Object.keys(s).length>0?s:void 0,...a}}
4639
- i&&(w.taskId=i),m&&(w.requestId=m),l.info("Creating failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,invalidIds:Object.keys(s).length>0?s:void 0,error:p})
4621
+ const w={projectId:u.projectId,type:t,note:y,metadata:{status:"failed",error:f,errorStack:p,originalToolName:e,timestamp:(new Date).toISOString(),invalidIds:Object.keys(s).length>0?s:void 0,...a}}
4622
+ i&&(w.taskId=i),m&&(w.requestId=m),l.info("Creating failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,invalidIds:Object.keys(s).length>0?s:void 0,error:f})
4640
4623
  const k=await c.createToolRecord(w)
4641
- d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_success",1),l.info("Successfully created failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,toolRecordId:k.id})}catch(t){throw d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_failure",1),l.error("Failed to create failure tool record for "+e,{error:t instanceof Error?t.stack:t+"",toolName:e,...u.taskId&&{originalTaskId:u.taskId},...u.requestId&&{originalRequestId:u.requestId},projectId:u.projectId,originalError:p}),t}}
4624
+ d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_success",1),l.info("Successfully created failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,toolRecordId:k.id})}catch(t){throw d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_failure",1),l.error("Failed to create failure tool record for "+e,{error:t instanceof Error?t.stack:t+"",toolName:e,...u.taskId&&{originalTaskId:u.taskId},...u.requestId&&{originalRequestId:u.requestId},projectId:u.projectId,originalError:f}),t}}
4642
4625
  const i=t(8824),a={write_file:"write-file","delete-file":"delete-file",delete_files:"delete-files",move_files:"move-files","replace-string":"replace-string",replace_strings:"replace-strings",insert_lines:"insert-lines",replace_lines:"replace-lines","file-recover":"file-recover",complete_task:"complete-task","update-task-status":"update-task-status","create-task":"create-task",create_request:"create-request",complete_request:"complete-request",read_files:"discovery","list-directory":"discovery",search:"discovery",file_history:"discovery",request_file_history:"discovery",get_request_information:"discovery",get_task_information:"discovery",list_requests:"discovery",list_tasks:"discovery",create_directory:"write",authenticate:"discovery","find-previous-commit":"discovery"}},8625(e,exports,t){function r(e,t,r){const n=exports.ERROR_TYPE_PROPERTIES[e]||exports.ERROR_TYPE_PROPERTIES[i.INTERNAL_ERROR]
4643
4626
  return{success:!1,error:{code:e,message:t||n.defaultMessage,details:r,retryable:n.retryable,statusCode:n.statusCode}}}function n(e){return"object"==typeof e&&null!==e&&"code"in e&&"statusCode"in e&&"details"in e&&"retryable"in e&&"string"==typeof e.code&&"number"==typeof e.statusCode}function o(e){if(n(e)){const t=r(e.code,e.message,e.details)
4644
4627
  return{statusCode:e.statusCode,body:t}}if(e instanceof Error&&"ConnectionError"===e.name){const t=e
4645
4628
  return{statusCode:503,body:r("CONNECTION_ERROR",t.message||"Connection to remote server failed",{operation:t.operation||"unknown",lastConnectionAttempt:t.lastConnectionAttempt||null,suggestions:["Check your network connection","Verify that the remote server is running","Try again in a few moments"],isConnectionIssue:!0})}}const t=e instanceof Error?e:Error(e+""),o=r(i.INTERNAL_ERROR,t.message||"An unexpected error occurred")
4646
- return{statusCode:o.error.statusCode,body:o}}function s(e){return!n(e)||e.isRetryable()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.UnauthorizedError=exports.McpProtocolError=exports.FileOperationError=exports.ServiceError=exports.DatabaseError=exports.AuthorizationError=exports.AuthenticationError=exports.ValidationError=exports.NotFoundError=exports.AppError=exports.ErrorUtils=exports.ERROR_TYPE_PROPERTIES=void 0,exports.createErrorResponse=r,exports.createAppError=function(e,t="INTERNAL_ERROR",r=500,n){return new a(e,t,r,n)},exports.createNotFoundError=function(e="Resource not found",t){return new c(e,t)},exports.createValidationError=function(e="Invalid input",t){return new l(e,t)},exports.createAuthenticationError=function(e="Authentication required",t){return new d(e,t)},exports.createAuthorizationError=function(e="Not authorized",t){return new u(e,t)},exports.createDatabaseError=function(e="Database error",t){return new h(e,t)},exports.createServiceError=function(e="Service unavailable",t){return new g(e,t)},exports.createFileOperationError=function(e="File operation error",t){return new p(e,t)},exports.createMcpProtocolError=function(e="MCP protocol error",t){return new f(e,t)},exports.isAppError=n,exports.errorToResponse=o,exports.isRetryableError=s
4629
+ return{statusCode:o.error.statusCode,body:o}}function s(e){return!n(e)||e.isRetryable()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.UnauthorizedError=exports.McpProtocolError=exports.FileOperationError=exports.ServiceError=exports.DatabaseError=exports.AuthorizationError=exports.AuthenticationError=exports.ValidationError=exports.NotFoundError=exports.AppError=exports.ErrorUtils=exports.ERROR_TYPE_PROPERTIES=void 0,exports.createErrorResponse=r,exports.createAppError=function(e,t="INTERNAL_ERROR",r=500,n){return new a(e,t,r,n)},exports.createNotFoundError=function(e="Resource not found",t){return new c(e,t)},exports.createValidationError=function(e="Invalid input",t){return new l(e,t)},exports.createAuthenticationError=function(e="Authentication required",t){return new d(e,t)},exports.createAuthorizationError=function(e="Not authorized",t){return new u(e,t)},exports.createDatabaseError=function(e="Database error",t){return new h(e,t)},exports.createServiceError=function(e="Service unavailable",t){return new g(e,t)},exports.createFileOperationError=function(e="File operation error",t){return new f(e,t)},exports.createMcpProtocolError=function(e="MCP protocol error",t){return new p(e,t)},exports.isAppError=n,exports.errorToResponse=o,exports.isRetryableError=s
4647
4630
  const i=t(7388)
4648
4631
  exports.ERROR_TYPE_PROPERTIES={[i.TASK_NOT_FOUND]:{statusCode:404,retryable:!1,defaultMessage:"Task ID does not exist"},[i.TASK_ID_INVALID_FORMAT]:{statusCode:400,retryable:!1,defaultMessage:"Task ID format is invalid"},[i.TASK_VALIDATION_FAILED]:{statusCode:400,retryable:!1,defaultMessage:"Task validation failed"},[i.NETWORK_ERROR]:{statusCode:503,retryable:!0,defaultMessage:"Network error occurred"},[i.SERVER_ERROR]:{statusCode:500,retryable:!0,defaultMessage:"Server error occurred"},[i.CONNECTION_TIMEOUT]:{statusCode:504,retryable:!0,defaultMessage:"Connection timed out"},[i.SERVICE_UNAVAILABLE]:{statusCode:503,retryable:!0,defaultMessage:"Service is currently unavailable"},[i.CONNECTION_ERROR]:{statusCode:503,retryable:!0,defaultMessage:"Connection to remote server failed"},[i.REQUEST_NOT_FOUND]:{statusCode:404,retryable:!1,defaultMessage:"Request ID does not exist"},[i.REQUEST_ID_INVALID_FORMAT]:{statusCode:400,retryable:!1,defaultMessage:"Request ID format is invalid"},[i.REQUEST_VALIDATION_FAILED]:{statusCode:400,retryable:!1,defaultMessage:"Request validation failed"},[i.VALIDATION_ERROR]:{statusCode:400,retryable:!1,defaultMessage:"Validation error"},[i.UNAUTHORIZED]:{statusCode:401,retryable:!1,defaultMessage:"Authentication required"},[i.FORBIDDEN]:{statusCode:403,retryable:!1,defaultMessage:"Access forbidden"},[i.NOT_FOUND]:{statusCode:404,retryable:!1,defaultMessage:"Resource not found"},[i.INTERNAL_ERROR]:{statusCode:500,retryable:!0,defaultMessage:"Internal server error"},[i.BAD_REQUEST]:{statusCode:400,retryable:!1,defaultMessage:"Bad request"},[i.MCP_PROTOCOL_ERROR]:{statusCode:500,retryable:!0,defaultMessage:"MCP protocol error"}},exports.ErrorUtils={isAppError:n,errorToResponse:o,isRetryableError:s,createErrorResponse:r}
4649
4632
  class a extends Error{constructor(e,t="INTERNAL_ERROR",r=500,n){super(e),this.name=this.constructor.name,this.code=t,this.statusCode=r,this.details=n||{},n&&"code"in n&&"string"==typeof n.code&&(this.code=n.code)
4650
4633
  const o=exports.ERROR_TYPE_PROPERTIES[this.code]
4651
4634
  this.retryable=o?o.retryable:!n||!("retryable"in n)||!!n.retryable,Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,retryable:this.retryable,stack:this.stack}}get metadata(){return this.details}isRetryable(){return this.retryable}}class c extends a{constructor(e="Resource not found",t){super(e,i.NOT_FOUND,404,t),this.resourceType="unknown",t&&("taskId"in t?(this.code=i.TASK_NOT_FOUND,this.resourceType="task"):"requestId"in t&&(this.code=i.REQUEST_NOT_FOUND,this.resourceType="request"))}}class l extends a{constructor(e="Invalid input",t){super(e,i.VALIDATION_ERROR,400,t)}}class d extends a{constructor(e="Authentication required",t){super(e,i.UNAUTHORIZED,401,t)}}class u extends a{constructor(e="Not authorized",t){super(e,i.FORBIDDEN,403,t)}}class h extends a{constructor(e="Database error",t){super(e,"DATABASE_ERROR",500,t)}}class g extends a{constructor(e="Service unavailable",t){if(super(e,i.SERVICE_UNAVAILABLE,503,t),t&&"structuredError"in t){const e=t.structuredError
4652
- e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}}}class p extends a{constructor(e="File operation error",t){super(e,"FILE_OPERATION_ERROR",500,t)}}class f extends a{constructor(e="MCP protocol error",t){super(e,i.MCP_PROTOCOL_ERROR,500,t)}}exports.AppError=a,exports.NotFoundError=c,exports.ValidationError=l,exports.AuthenticationError=d,exports.AuthorizationError=u,exports.DatabaseError=h,exports.ServiceError=g,exports.FileOperationError=p,exports.McpProtocolError=f,exports.UnauthorizedError=d},8712(e,exports){function t(e,t){return!(!e||!e.trim())&&RegExp(`^\\s*\\${t}{7}(?:\\s|$)`).test(e)}function r(e,r,n){if(!e||!e.trim())return{cleanContent:"",filesParsed:[],hasConflictMarkers:!1}
4635
+ e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}}}class f extends a{constructor(e="File operation error",t){super(e,"FILE_OPERATION_ERROR",500,t)}}class p extends a{constructor(e="MCP protocol error",t){super(e,i.MCP_PROTOCOL_ERROR,500,t)}}exports.AppError=a,exports.NotFoundError=c,exports.ValidationError=l,exports.AuthenticationError=d,exports.AuthorizationError=u,exports.DatabaseError=h,exports.ServiceError=g,exports.FileOperationError=f,exports.McpProtocolError=p,exports.UnauthorizedError=d},8712(e,exports){function t(e,t){return!(!e||!e.trim())&&RegExp(`^\\s*\\${t}{7}(?:\\s|$)`).test(e)}function r(e,r,n){if(!e||!e.trim())return{cleanContent:"",filesParsed:[],hasConflictMarkers:!1}
4653
4636
  const o=e.split("\n"),s=[],i=new Set
4654
4637
  let a=!1,c=""
4655
4638
  for(let e=0;e<o.length;e++){const l=o[e]
@@ -4710,7 +4693,7 @@ try{const r=await o.log({from:t,to:t,file:s,maxCount:1})
4710
4693
  if(!r.all||0===r.all.length)return{content:[{type:"text",text:`No commit found with hash ${t} for file ${e}`}]}
4711
4694
  const n=r.all[0],i=await o.diff([t+"^",t,"--",s])
4712
4695
  let a="# File History - Commit Diff\n\n"
4713
- return a+=`**File:** ${e}\n`,a+=`**Commit:** ${t.substring(0,8)}\n`,a+=`**Author:** ${n.author_name}\n`,a+=`**Date:** ${n.date}\n`,a+=`**Message:** ${n.message}\n\n`,i&&i.trim()?a+=`## Full Diff\n\n\`\`\`diff\n${i}\n\`\`\`\n`:a+="*No diff available for this commit*\n",{content:[{type:"text",text:a}]}}catch(r){return n.error("Failed to get commit diff",{error:r,commit:t,filePath:e}),{content:[{type:"text",text:`\u274c Failed to get diff for commit ${t}: ${(0,p.getErrorMessage)(r)}`}],isError:!0}}}(a,I,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:b}),await async function(e,t,n,o,s,i,a,c,d,u,p){try{const{normalizedPath:m,fullPath:y}=f.validateAndNormalizePath(e,a)
4696
+ return a+=`**File:** ${e}\n`,a+=`**Commit:** ${t.substring(0,8)}\n`,a+=`**Author:** ${n.author_name}\n`,a+=`**Date:** ${n.date}\n`,a+=`**Message:** ${n.message}\n\n`,i&&i.trim()?a+=`## Full Diff\n\n\`\`\`diff\n${i}\n\`\`\`\n`:a+="*No diff available for this commit*\n",{content:[{type:"text",text:a}]}}catch(r){return n.error("Failed to get commit diff",{error:r,commit:t,filePath:e}),{content:[{type:"text",text:`\u274c Failed to get diff for commit ${t}: ${(0,f.getErrorMessage)(r)}`}],isError:!0}}}(a,I,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:b}),await async function(e,t,n,o,s,i,a,c,d,u,f){try{const{normalizedPath:m,fullPath:y}=p.validateAndNormalizePath(e,a)
4714
4697
  try{await l.access(y)}catch(e){throw Error("File not found: "+m)}const w=a.git
4715
4698
  if(!w)throw Error("Git is not available in this context")
4716
4699
  let k={branch:null,requestId:null,isMain:!0}
@@ -4720,8 +4703,8 @@ else{if(k.isMain&&!o)return d.info("Showing request-level timeline on main branc
4720
4703
  if(k.requestId)return d.info("Showing operation-level detail on request branch",{requestId:k.requestId}),{content:[{type:"text",text:await(0,g.getOperationDetailForFile)(m,k.requestId,c,d,u)}]}
4721
4704
  {const e=await async function(e,t,n,o,s,i,a,c,l,d){const u=[],h=[]
4722
4705
  if(!i.isMain&&i.branch){const g=await r(e,t,n,o,s,i.branch,a,c,l,d)
4723
- u.push(...g),g.length>0&&h.push(i.branch+" (current)")}const g=await r(e,t,n,o,s,"main",a,c,l,d),p=new Set(u.map((e=>e.hash))),f=g.filter((e=>!p.has(e.hash)))
4724
- return u.push(...f),g.length>0&&h.push("main"),u.sort(((e,t)=>new Date(t.date).getTime()-new Date(e.date).getTime())),{versions:u.slice(0,n),sources:h}}(w,m,t,n,o,k,i,c,d,u)
4706
+ u.push(...g),g.length>0&&h.push(i.branch+" (current)")}const g=await r(e,t,n,o,s,"main",a,c,l,d),f=new Set(u.map((e=>e.hash))),p=g.filter((e=>!f.has(e.hash)))
4707
+ return u.push(...p),g.length>0&&h.push("main"),u.sort(((e,t)=>new Date(t.date).getTime()-new Date(e.date).getTime())),{versions:u.slice(0,n),sources:h}}(w,m,t,n,o,k,i,c,d,u)
4725
4708
  b=e.versions,I=`## File History: ${m} (Combined View)\n\n`,I+=`**Current Context:** ${k.isMain?"main":`${k.branch} (${k.requestId})`}\n`,I+=`**History Sources:** ${e.sources.join(", ")}\n\n`}}if(0===b.length)return I+="\u274c **No history found**\n\nThis file has no git history. It may be:\n- A new file that hasn't been committed\n- Located outside the git repository\n- The path may be incorrect\n- No history exists in the specified branch context",{content:[{type:"text",text:I}]}
4726
4709
  const v=b.length,C=Math.min(b.length,t)
4727
4710
  v>t?I+=`\u{1f4ca} **Summary:** ${v} versions found, showing ${C} most recent\n\n`:v>0&&(I+=`\u{1f4ca} **Summary:** ${v} version${v>1?"s":""} found\n\n`),I+=`**Total Versions:** ${b.length}\n`,I+="**Current File Size:** "
@@ -4730,9 +4713,9 @@ for(let e=0;e<b.length;e++){const t=b[e]
4730
4713
  if(I+=`### Version ${e+1} (${t.hash.substring(0,8)})\n`,t.branch&&(I+=`- **Branch:** ${t.branch}\n`),I+=`- **Author:** ${t.author}\n`,I+=`- **Date:** ${t.date}\n`,I+=`- **Message:** ${t.message}\n`,o&&t.traceability&&(I+=`\n${(0,h.formatTraceabilityInfo)(t.traceability)}\n`),n&&t.diff){const e=t.diff.split("\n")
4731
4714
  let r=0,n=0
4732
4715
  for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
4733
- I+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}I+="\n"}return I+="\u{1f4a1} **Tips:**\n",I+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",I+='- Use `{"branch": "main"}` to see only main branch history\n',I+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:m,versions:b.length,targetBranch:s,currentBranch:k.branch,duration:Date.now()-p}),u.incrementCounter("file_history_total",1,{success:!0,type:"file",mode:s?"single-branch":"combined"}),{content:[{type:"text",text:I}]}}catch(e){throw e}}(a,y,w,k,b,v,t,n,i,s,m))}catch(e){const t=Date.now()-m
4734
- return i.error("File/Document history operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),a({tool:"file_history",success:!1}),s.incrementCounter("file_history_errors",1),{content:[{type:"text",text:"\u274c **History Operation Failed:** "+(0,p.getErrorMessage)(e)}],isError:!0}}}
4735
- const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),f=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8850(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
4716
+ I+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}I+="\n"}return I+="\u{1f4a1} **Tips:**\n",I+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",I+='- Use `{"branch": "main"}` to see only main branch history\n',I+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:m,versions:b.length,targetBranch:s,currentBranch:k.branch,duration:Date.now()-f}),u.incrementCounter("file_history_total",1,{success:!0,type:"file",mode:s?"single-branch":"combined"}),{content:[{type:"text",text:I}]}}catch(e){throw e}}(a,y,w,k,b,v,t,n,i,s,m))}catch(e){const t=Date.now()-m
4717
+ return i.error("File/Document history operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),a({tool:"file_history",success:!1}),s.incrementCounter("file_history_errors",1),{content:[{type:"text",text:"\u274c **History Operation Failed:** "+(0,f.getErrorMessage)(e)}],isError:!0}}}
4718
+ const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),f=t(8824),p=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8850(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
4736
4719
  const r=t(6183),n=t(6891)
4737
4720
  exports.def={name:"task_file_history",description:"See all file changes made during a task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Task File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleTaskFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},8851(e,exports,t){function r(e){try{n.debug("Running cleanup before exit"),e(),n.debug("Cleanup completed")}catch(e){n.error("Error during cleanup",{error:e})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.setupParentProcessDetection=function(e){n.debug("Setting up parent process detection")
4738
4721
  const t=process.ppid,o=setInterval((()=>{try{process.kill(t,0)}catch(t){n.info("Parent process exited (detected via PPID check), shutting down"),clearInterval(o),r(e),process.exit(0)}}),5e3)
@@ -4884,37 +4867,37 @@ if(!a)throw new c.ValidationError("Could not discover current session ID. Make s
4884
4867
  return(0,h.logSessionIdentity)(""+r,"per-call-discovery",{sessionId:a}),a}function s(e){const t=[],r=e.content||{}
4885
4868
  if(t.push("**Message Code:** "+e.messageCode),t.push(`**Type:** question (${r.questionType})`),t.push("**Status:** "+e.status),t.push("**Priority:** "+e.priority),t.push("**From:** "+e.fromSessionId),t.push(e.toSessionId?"**To:** "+e.toSessionId:"**To:** (broadcast)"),t.push("**Created:** "+e.createdAt),t.push("**Expires:** "+e.expiresAt),t.push(""),t.push("**Question:** "+r.question),r.context&&t.push("**Context:** "+r.context),"alternatives"===r.questionType&&r.options){t.push(""),t.push("**Options:**")
4886
4869
  for(const e of r.options)t.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return"responded"===e.status&&e.response&&(t.push(""),t.push("---"),t.push("**Answered by:** "+e.respondedBySessionId),t.push("**Answered at:** "+e.respondedAt),e.response.text&&t.push("**Answer:** "+e.response.text),e.response.selectedOptions&&t.push("**Selected:** "+e.response.selectedOptions.join(", ")),e.response.notes&&t.push("**Notes:** "+e.response.notes)),t.join("\n")}function i(e){const t=[],r=e.content||{}
4887
- return t.push("**Status:** "+(r.reportStatus||"unknown")),t.push("**Summary:** "+(r.summary||"")),r.details&&(t.push(""),t.push("**Details:**"),t.push(r.details)),t.join("\n")}function a(e){return"question"===e.messageType?s(e):i(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSessionMessageOperations=async function(e,t,p,f,m){const y=p.child({component:"session_message_operations"})
4870
+ return t.push("**Status:** "+(r.reportStatus||"unknown")),t.push("**Summary:** "+(r.summary||"")),r.details&&(t.push(""),t.push("**Details:**"),t.push(r.details)),t.join("\n")}function a(e){return"question"===e.messageType?s(e):i(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSessionMessageOperations=async function(e,t,f,p,m){const y=f.child({component:"session_message_operations"})
4888
4871
  if(!m)throw new c.ValidationError("API client not available")
4889
4872
  const{operation:w}=e
4890
- y.info("Session message operation",{operation:w}),f.incrementCounter("session_message_operations",1,{operation:w})
4873
+ y.info("Session message operation",{operation:w}),p.incrementCounter("session_message_operations",1,{operation:w})
4891
4874
  try{switch(w){case"send":if(!e.type)throw new c.ValidationError('send operation requires type ("question" or "report")')
4892
4875
  return await async function(e,t,a,l){const{type:d}=e
4893
4876
  if(!d)throw new c.ValidationError('send operation requires type ("question" or "report")')
4894
4877
  const u=l.getSessionMessageClient()
4895
4878
  if(!u)throw new c.ValidationError("Session message client not available")
4896
- if("question"===d)return await async function(e,t,i,a,l){const{toSessionId:d,questionType:u,questionContent:h,priority:g,expiresInHours:p}=e
4879
+ if("question"===d)return await async function(e,t,i,a,l){const{toSessionId:d,questionType:u,questionContent:h,priority:g,expiresInHours:f}=e
4897
4880
  if(!u||!h?.question)throw new c.ValidationError("Question requires questionType and questionContent.question")
4898
- const f=await o(t,i,"session_message_operations",{operation:"send",send:{type:"question",questionType:u,questionContent:h}}),m=await async function(e,t,r,o){if("parent"===e){const e=await n(t,r,o)
4881
+ const p=await o(t,i,"session_message_operations",{operation:"send",send:{type:"question",questionType:u,questionContent:h}}),m=await async function(e,t,r,o){if("parent"===e){const e=await n(t,r,o)
4899
4882
  if(!e)throw new c.ValidationError("Could not find parent session. Make sure this session was spawned as a subagent.")
4900
- return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(d,f,a,i)
4883
+ return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(d,p,a,i)
4901
4884
  if(!("alternatives"!==u||h.options&&Array.isArray(h.options)))throw new c.ValidationError("Alternatives questions require options array")
4902
- i.info("Creating question",{fromSessionId:f,toSessionId:m,questionType:u})
4903
- const y=await l.createQuestion({fromSessionId:f,toSessionId:m,questionType:u,question:h.question,options:h.options,context:h.context,allowMultiple:h.allowMultiple,priority:g,expiresInHours:p})
4885
+ i.info("Creating question",{fromSessionId:p,toSessionId:m,questionType:u})
4886
+ const y=await l.createQuestion({fromSessionId:p,toSessionId:m,questionType:u,question:h.question,options:h.options,context:h.context,allowMultiple:h.allowMultiple,priority:g,expiresInHours:f})
4904
4887
  let w=""
4905
4888
  return m&&(w=await r(m,function(e){const t=e.content||{},r=["\u{1f4e8} **You have a new question!**","","**Question Code:** "+e.messageCode,"**From:** "+e.fromSessionId,"**Priority:** "+e.priority,"","**Question:** "+t.question]
4906
4889
  if(t.context&&r.push("**Context:** "+t.context),"alternatives"===t.questionType&&t.options){r.push(""),r.push("**Options:**")
4907
4890
  for(const e of t.options)r.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return r.push(""),r.push(`Use \`session_message_operations\` with \`reply\` operation and message code \`${e.messageCode}\` to respond.`),r.join("\n")}(y),t,i)?"\n\n\u{1f4ec} The target session has been notified.":"\n\n\u26a0\ufe0f Could not notify the target session (may be offline)."),{content:[{type:"text",text:`\u2705 Question created!${w}\n\n**Message Code: ${y.messageCode}**\n\nUse this code to check for answers or share with other sessions.\n\n${s(y)}`}]}}(e,t,a,l,u)
4908
- if("report"===d)return await async function(e,t,s,a,l){const{status:d,summary:u,details:h,finish:p}=e
4891
+ if("report"===d)return await async function(e,t,s,a,l){const{status:d,summary:u,details:h,finish:f}=e
4909
4892
  if(!d||!u)throw new c.ValidationError("Report requires status and summary")
4910
- const f=await o(t,s,"session_message_operations",{operation:"send",send:{type:"report",status:d,summary:u}}),m=await(async()=>{if(e.toSessionId&&"parent"!==e.toSessionId)return s.info("Using explicit toSessionId for report",{parentSessionId:e.toSessionId}),e.toSessionId
4911
- const t=await n(f,a,s)
4893
+ const p=await o(t,s,"session_message_operations",{operation:"send",send:{type:"report",status:d,summary:u}}),m=await(async()=>{if(e.toSessionId&&"parent"!==e.toSessionId)return s.info("Using explicit toSessionId for report",{parentSessionId:e.toSessionId}),e.toSessionId
4894
+ const t=await n(p,a,s)
4912
4895
  if(!t)throw new c.ValidationError("Could not find parent session. This tool should only be used by subagent sessions.")
4913
4896
  return s.info("Auto-resolved parent session",{parentSessionId:t}),t})()
4914
- s.info("Submitting report",{sessionId:f,parentSessionId:m,status:d})
4915
- const y=await l.createReport({fromSessionId:f,toSessionId:m,status:d,summary:u,details:h})
4897
+ s.info("Submitting report",{sessionId:p,parentSessionId:m,status:d})
4898
+ const y=await l.createReport({fromSessionId:p,toSessionId:m,status:d,summary:u,details:h})
4916
4899
  let w="agent"
4917
- try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(f)}/agent-type`)
4900
+ try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(p)}/agent-type`)
4918
4901
  if(e.ok){const t=await e.json()
4919
4902
  t.success&&t.agentType&&(w=t.agentType)}}catch{}const k=await r(m,function(e,t="agent"){const r=e.content||{},n=[`${{success:"\u2705",partial:"\u26a0\ufe0f",failure:"\u274c",blocked:"\u{1f6ab}"}[r.reportStatus]||"\u{1f4cb}"} **Report \u2014 ${r.reportStatus}**`,`from: ${t} (${e.fromSessionId})`,"",r.summary]
4920
4903
  return r.details&&(n.push(""),n.push(r.details)),n.join("\n")}(y,w),t,s)
@@ -4936,14 +4919,14 @@ let s=null,i=null
4936
4919
  try{s=await o(t,y,"session_message_operations",{operation:"offer-handoff"}),i=await n(s,m,y)}catch(e){y.warn("offer-handoff: could not discover parent session via HTTP",{error:(0,l.getErrorMessage)(e)})}if(!s){const e=u.sessionIdentity.getIdentity()
4937
4920
  if(e?.sessionId){if(s=e.sessionId,y.info("offer-handoff: using cached session as fallback",{sessionId:s}),!i)try{i=await n(s,m,y)}catch(e){y.warn("offer-handoff: could not resolve parent from cached session",{error:(0,l.getErrorMessage)(e)})}}else y.warn("offer-handoff: no session ID available (discovery failed, no cache)")}try{const e=m.getSessionMessageClient()
4938
4921
  if(e&&s){const t=r.requestIds?.length||0
4939
- await e.createQuestion({fromSessionId:s,toSessionId:i||void 0,questionType:"alternatives",question:"Plan ready: "+(r.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${t} request${1!==t?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:t>0?"Created requests: "+r.requestIds.join(", "):void 0,category:"action-required",priority:"high"}),y.info("offer-handoff: notification question created",{fromSessionId:s})}else y.warn("offer-handoff: skipping notification question",{hasClient:!!e,fromSessionId:s})}catch(e){y.warn("offer-handoff: failed to create notification question",{error:(0,l.getErrorMessage)(e)})}return{content:[{type:"text",text:'Handoff offered to user. STOP here and wait \u2014 the user will choose "Start Building" or "Keep Planning". You will receive their choice as a new message. Do NOT generate any further output until then.\nPLAN_HANDOFF_PENDING|'+JSON.stringify({summary:r.summary,requestIds:r.requestIds,parentSessionId:i})}],isError:!1}}case"list":return await async function(e,t,r,n){let{sessionId:o,messageType:s,direction:i,status:l,readStatus:u,reportStatus:g,limit:p,offset:f}=e
4922
+ await e.createQuestion({fromSessionId:s,toSessionId:i||void 0,questionType:"alternatives",question:"Plan ready: "+(r.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${t} request${1!==t?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:t>0?"Created requests: "+r.requestIds.join(", "):void 0,category:"action-required",priority:"high"}),y.info("offer-handoff: notification question created",{fromSessionId:s})}else y.warn("offer-handoff: skipping notification question",{hasClient:!!e,fromSessionId:s})}catch(e){y.warn("offer-handoff: failed to create notification question",{error:(0,l.getErrorMessage)(e)})}return{content:[{type:"text",text:'Handoff offered to user. STOP here and wait \u2014 the user will choose "Start Building" or "Keep Planning". You will receive their choice as a new message. Do NOT generate any further output until then.\nPLAN_HANDOFF_PENDING|'+JSON.stringify({summary:r.summary,requestIds:r.requestIds,parentSessionId:i})}],isError:!1}}case"list":return await async function(e,t,r,n){let{sessionId:o,messageType:s,direction:i,status:l,readStatus:u,reportStatus:g,limit:f,offset:p}=e
4940
4923
  const m=n.getSessionMessageClient()
4941
4924
  if(!m)throw new c.ValidationError("Session message client not available")
4942
4925
  if(!o){const e=await(0,d.getServerUrl)(t,r)
4943
4926
  if(!e)return{content:[{type:"text",text:"\u26a0\ufe0f Could not connect to OpenCode server. Unable to list messages without a session context."}]}
4944
4927
  {const t={operation:"list",list:{messageType:s,direction:i,status:l}},n=await(0,d.getAndStoreSessionId)(e,r,"session_message_operations",t)
4945
4928
  if(o=n?.sessionId,(0,h.logSessionIdentity)("session_message_operations.list",o?"per-call-discovery":"discovery-failed",{sessionId:o}),!o)return r.warn("Session discovery FAILED for list - returning empty to prevent data leak"),{content:[{type:"text",text:"\u26a0\ufe0f Could not determine current session ID. Unable to list messages without a session context."}]}}}r.debug("Listing messages",{sessionId:o,messageType:s,direction:i,status:l,readStatus:u})
4946
- const y={sessionId:o,direction:i,limit:p,offset:f}
4929
+ const y={sessionId:o,direction:i,limit:f,offset:p}
4947
4930
  s&&"all"!==s&&(y.messageType=s),l&&"all"!==l&&("report"===s?y.reportStatus=l:y.status=l),u&&"all"!==u&&(y.readStatus=u),g&&"all"!==g&&(y.reportStatus=g)
4948
4931
  const w=await m.listMessages(y)
4949
4932
  if(0===w.length)return{content:[{type:"text",text:"No messages found matching the criteria."}]}
@@ -4993,12 +4976,12 @@ let l,d
4993
4976
  try{l=await this.git.raw(["merge-base",i,c])}catch(t){return r.warn("Could not find merge-base, commits may be unrelated",{worktreeCommit:i.substring(0,8),targetCommit:c.substring(0,8),error:t}),{hasConflicts:!0,conflictedFiles:[{path:"<multiple files>",conflictType:"content",description:"Branches have diverged significantly (no merge-base found)"}],summary:"Branches have diverged significantly",resolutionInstructions:this.generateMultiAgentInstructions([{path:"<multiple files>",conflictType:"content",description:"Significant divergence"}],e.requestId,e.worktreePath,e.targetBranch),detectionMethod:"merge-tree-analysis",rawOutput:"merge-base failed: "+t}}r.debug("Commits for merge-tree analysis",{worktreeCommit:i.substring(0,8),targetCommit:c.substring(0,8),mergeBase:l.trim().substring(0,8)})
4994
4977
  let u=0
4995
4978
  try{d=await this.git.raw(["merge-tree",l.trim(),c.trim(),i.trim()]),u=0}catch(e){d=e.message||"",u=e.exitCode||1,r.debug("merge-tree failed with error",{exitCode:u,error:e.message})}r.debug("Merge-tree analysis completed",{outputLength:d.length,hasOutput:!!d.trim(),exitCode:u})
4996
- let h=!1,g="",p=null
4997
- if(0!==u?(h=!0,g="merge-tree-exit-code"):d&&d.trim()?(p=(0,s.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch),p.hasConflictMarkers?(h=!0,g="conflict-parser-detected-markers",r.warn("Git exit code 0 but conflict parser found conflict markers - treating as conflict")):(h=!1,g="clean-merge-with-changes",r.info("Git exit code 0 and conflict parser found no markers - treating as clean merge",{hasOutput:!0,outputLength:d.length}))):(h=!1,g="clean-merge-no-changes"),r.info("FINAL conflict detection result (trusting Git exit codes)",{hasConflicts:h,exitCode:u,hasOutput:!!d.trim(),outputLength:d?d.length:0,conflictReason:g,method:"git-exit-code-primary",trustedGitExitCode:0===u}),!h)return{hasConflicts:!1,conflictedFiles:[],summary:"No conflicts detected (merge-tree clean)",resolutionInstructions:"",detectionMethod:"merge-tree-analysis",rawOutput:d}
4998
- !p&&d&&d.trim()&&(p=(0,s.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch))
4999
- let f=[]
5000
- if(p&&p.filesParsed&&p.filesParsed.length>0)f=p.filesParsed.map((e=>({path:e,conflictType:"content",description:"Merge conflict detected"}))),r.debug("Successfully extracted conflict files from parsed content",{conflictedFilesCount:f.length,files:f.map((e=>e.path))})
5001
- else try{f=this.parseMergeTreeOutput(d,r),r.debug("Used fallback merge-tree parsing",{conflictedFilesCount:f.length})}catch(e){r.warn("Both conflict parsing methods failed",{parseError:e instanceof Error?e.message:e+""}),f=[{path:"<parsing failed>",conflictType:"content",description:"Git detected conflicts but parsing failed - manual inspection required"}]}return 0===f.length&&(r.warn("Git detected conflicts but no files could be determined - using fallback"),f=[{path:"<unknown files>",conflictType:"content",description:"Git detected conflicts but could not determine specific files"}]),{hasConflicts:!0,conflictedFiles:f,summary:f.length>0&&"<parsing failed>"!==f[0].path&&"<unknown files>"!==f[0].path?f.length+" file(s) have merge conflicts (detected by Git)":"Merge conflicts detected by Git (parsing details failed)",resolutionInstructions:this.generateMultiAgentInstructions(f,e.requestId,e.worktreePath,e.targetBranch),detectionMethod:"merge-tree-analysis",rawOutput:d,rawConflictContent:p?p.cleanContent:void 0}}catch(e){throw r.error("Pure multi-agent conflict detection failed",{error:e}),e}}parseMergeTreeOutput(e,t){const r=[]
4979
+ let h=!1,g="",f=null
4980
+ if(0!==u?(h=!0,g="merge-tree-exit-code"):d&&d.trim()?(f=(0,s.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch),f.hasConflictMarkers?(h=!0,g="conflict-parser-detected-markers",r.warn("Git exit code 0 but conflict parser found conflict markers - treating as conflict")):(h=!1,g="clean-merge-with-changes",r.info("Git exit code 0 and conflict parser found no markers - treating as clean merge",{hasOutput:!0,outputLength:d.length}))):(h=!1,g="clean-merge-no-changes"),r.info("FINAL conflict detection result (trusting Git exit codes)",{hasConflicts:h,exitCode:u,hasOutput:!!d.trim(),outputLength:d?d.length:0,conflictReason:g,method:"git-exit-code-primary",trustedGitExitCode:0===u}),!h)return{hasConflicts:!1,conflictedFiles:[],summary:"No conflicts detected (merge-tree clean)",resolutionInstructions:"",detectionMethod:"merge-tree-analysis",rawOutput:d}
4981
+ !f&&d&&d.trim()&&(f=(0,s.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch))
4982
+ let p=[]
4983
+ if(f&&f.filesParsed&&f.filesParsed.length>0)p=f.filesParsed.map((e=>({path:e,conflictType:"content",description:"Merge conflict detected"}))),r.debug("Successfully extracted conflict files from parsed content",{conflictedFilesCount:p.length,files:p.map((e=>e.path))})
4984
+ else try{p=this.parseMergeTreeOutput(d,r),r.debug("Used fallback merge-tree parsing",{conflictedFilesCount:p.length})}catch(e){r.warn("Both conflict parsing methods failed",{parseError:e instanceof Error?e.message:e+""}),p=[{path:"<parsing failed>",conflictType:"content",description:"Git detected conflicts but parsing failed - manual inspection required"}]}return 0===p.length&&(r.warn("Git detected conflicts but no files could be determined - using fallback"),p=[{path:"<unknown files>",conflictType:"content",description:"Git detected conflicts but could not determine specific files"}]),{hasConflicts:!0,conflictedFiles:p,summary:p.length>0&&"<parsing failed>"!==p[0].path&&"<unknown files>"!==p[0].path?p.length+" file(s) have merge conflicts (detected by Git)":"Merge conflicts detected by Git (parsing details failed)",resolutionInstructions:this.generateMultiAgentInstructions(p,e.requestId,e.worktreePath,e.targetBranch),detectionMethod:"merge-tree-analysis",rawOutput:d,rawConflictContent:f?f.cleanContent:void 0}}catch(e){throw r.error("Pure multi-agent conflict detection failed",{error:e}),e}}parseMergeTreeOutput(e,t){const r=[]
5002
4985
  if(!e||!e.trim())return t.debug("Empty merge-tree output - no conflicts to parse"),[]
5003
4986
  let n
5004
4987
  try{n=e.split("\n"),t.debug("Parsing merge-tree output",{linesCount:n.length,totalLength:e.length,firstFewLines:n.slice(0,5),hasNewlines:e.includes("\n")})}catch(r){throw t.error("Failed to split merge-tree output into lines",{error:r instanceof Error?r.message:r+"",outputLength:e.length}),Error("Failed to parse merge-tree output: "+r)}let o=!1
@@ -5050,23 +5033,23 @@ o+="## Test 3: Recent merge commits (to see actual patterns)\n",o+=`Found ${e?.a
5050
5033
  o+=`## Test 4: All commits containing "${n}" (not just merges)\n`,o+=`Found ${e?.all?.length||0} commits:\n`,e?.all?.length>0?e.all.forEach(((e,t)=>{o+=`${t+1}. ${e.hash.substring(0,8)} - ${e.message}\n`})):o+="No commits found\n",o+="\n"}catch(e){o+=`## Test 4: Error - ${(0,r.getErrorMessage)(e)}\n\n`}try{const e=await t.git.revparse(["--abbrev-ref","HEAD"])
5051
5034
  o+=`## Current branch: ${e}\n\n`}catch(e){o+=`## Current branch: Error - ${(0,r.getErrorMessage)(e)}\n\n`}try{const e=await t.git.branch()
5052
5035
  o+="## All branches:\n",e.all&&e.all.length>0?e.all.forEach((e=>{o+=`- ${e}\n`})):o+="No branches found\n",o+="\n"}catch(e){o+=`## Branches: Error - ${(0,r.getErrorMessage)(e)}\n\n`}return{content:[{type:"text",text:o}]}}catch(e){return s.error("Error in debug request file history",{error:e instanceof Error?e.stack:e+""}),{content:[{type:"text",text:"Error: "+(0,r.getErrorMessage)(e)}],isError:!0}}}
5053
- const r=t(8824)},9442(e,exports,t){function r(e){return{line:e.line,actually_matched:e.actuallyMatched,match_type:e.matchType}}async function n(e,t,n,o,s,i,a){const{path:c,documentId:d,replacements:g,fuzzy_match:p}=e,f=!!d,m=void 0!==p?p:t,y={type:f?"document":"file",path:c,documentId:d,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,externalEditDebugInfo:{detectionRan:!1,reason:f?"Skipped: Document operation":n.git?"Pending":"Skipped: No Git context"}}
5036
+ const r=t(8824)},9442(e,exports,t){function r(e){return{line:e.line,actually_matched:e.actuallyMatched,match_type:e.matchType}}async function n(e,t,n,o,s,i,a){const{path:c,documentId:d,replacements:g,fuzzy_match:f}=e,p=!!d,m=void 0!==f?f:t,y={type:p?"document":"file",path:c,documentId:d,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,externalEditDebugInfo:{detectionRan:!1,reason:p?"Skipped: Document operation":n.git?"Pending":"Skipped: No Git context"}}
5054
5037
  try{let t,o
5055
- if(f){t=await n.documentFileManager.getDocumentAsFile(d)
5038
+ if(p){t=await n.documentFileManager.getDocumentAsFile(d)
5056
5039
  const e=n.documentFileManager.getCachedDocumentInfo(d)
5057
5040
  y.filename=e?.filename,o="document:"+d}else{const e=u.validateAndNormalizePath(c,n)
5058
- o=e.normalizedPath,t=e.fullPath,y.path=o}const s=await l.default.readFile(t,"utf8"),p=[]
5041
+ o=e.normalizedPath,t=e.fullPath,y.path=o}const s=await l.default.readFile(t,"utf8"),f=[]
5059
5042
  for(const t of g){const{old:n,new:o,match_mode:i="unique"}=t,a={old:n,new:o,success:!1}
5060
5043
  try{if(n===o){a.error="No-op replacement (old and new values are identical)",a.success=!1,a.matchesFound=0,y.failedReplacements++,y.replacements.push(a)
5061
5044
  continue}const t=(0,h.findMatches)(s,n,m,100,e.path)
5062
5045
  if(a.matchesFound=t.length,0===t.length){a.error="No matches found"+(m?" (tried fuzzy matching)":""),a.success=!1
5063
5046
  const e=(0,h.findSimilarMatches)(s,n,5,.3)
5064
- e.length>0&&(a.similarMatches=e),y.failedReplacements++}else"unique"===i&&t.length>1?(a.error=`Multiple matches found (${t.length}) - expected unique match`,a.success=!1,a.details=t.map(r),y.failedReplacements++):p.push({matches:t,newText:o,matchMode:i,repResult:a})}catch(e){a.error=(0,k.getErrorMessage)(e),a.success=!1,y.failedReplacements++}y.replacements.push(a)}let w=s
5047
+ e.length>0&&(a.similarMatches=e),y.failedReplacements++}else"unique"===i&&t.length>1?(a.error=`Multiple matches found (${t.length}) - expected unique match`,a.success=!1,a.details=t.map(r),y.failedReplacements++):f.push({matches:t,newText:o,matchMode:i,repResult:a})}catch(e){a.error=(0,k.getErrorMessage)(e),a.success=!1,y.failedReplacements++}y.replacements.push(a)}let w=s
5065
5048
  const b=[]
5066
- for(const e of p)for(const t of e.matches)b.push({match:t,newText:e.newText,repResult:e.repResult})
5049
+ for(const e of f)for(const t of e.matches)b.push({match:t,newText:e.newText,repResult:e.repResult})
5067
5050
  b.sort(((e,t)=>t.match.startPos-e.match.startPos))
5068
5051
  for(const{match:e,newText:t,repResult:n}of b)w=(0,h.replaceMatch)(w,e,t),n.success?(n.lines.push(e.line),n.details.push(r(e))):(n.success=!0,n.matchType=e.matchType,n.lines=[e.line],n.details=[r(e)],y.successfulReplacements++)
5069
- y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),f&&(n.documentFileManager.markForSync(d),await n.documentFileManager.syncDocument(d))),i&&(y.externalEditWarning=i),a&&(y.externalEditDebugInfo={detectionRan:!0,...a}),y.success=0===y.failedReplacements}catch(e){y.error=(0,k.getErrorMessage)(e),y.success=!1,y.failedReplacements=g.length,y.replacements=g.map((e=>({old:e.old,new:e.new,success:!1,error:y.error})))}return y}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
5052
+ y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),p&&(n.documentFileManager.markForSync(d),await n.documentFileManager.syncDocument(d))),i&&(y.externalEditWarning=i),a&&(y.externalEditDebugInfo={detectionRan:!0,...a}),y.success=0===y.failedReplacements}catch(e){y.error=(0,k.getErrorMessage)(e),y.success=!1,y.failedReplacements=g.length,y.replacements=g.map((e=>({old:e.old,new:e.new,success:!1,error:y.error})))}return y}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
5070
5053
  var o=Object.getOwnPropertyDescriptor(t,r)
5071
5054
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[]
5072
5055
  for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
@@ -5076,7 +5059,7 @@ if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
5076
5059
  return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
5077
5060
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,t,r,o,s,i,a,c){const b=i.child({tool:"replace_in_files"}),I=Date.now()
5078
5061
  let v,C=u.FileOperationPhase.VALIDATION
5079
- try{if(e&&Array.isArray(e.operations))for(const t of e.operations)t.old&&t.new&&!t.replacements&&(t.replacements=[{old:t.old,new:t.new,match_mode:t.match_mode}],delete t.old,delete t.new,delete t.match_mode)
5062
+ try{if(e&&"string"==typeof e.operations)try{e.operations=JSON.parse(e.operations)}catch{}if(e&&Array.isArray(e.operations))for(const t of e.operations)t.old&&t.new&&!t.replacements&&(t.replacements=[{old:t.old,new:t.new,match_mode:t.match_mode}],delete t.old,delete t.new,delete t.match_mode)
5080
5063
  const i=u.validateArgs(e,d.ReplaceInFilesSchema),{taskId:_,operations:E,fuzzy_match:q=!0,comment:S}=i
5081
5064
  b.info("Replace in files batch operation",{taskId:_,operationCount:E.length,totalReplacements:E.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:q,comment:S})
5082
5065
  const T=E.filter((e=>e.documentId)).map((e=>e.documentId))
@@ -5095,26 +5078,26 @@ const n=await u.autoPromoteTaskStatus(_,x.status,O,e.request?.status,R,r,s,b,a,"
5095
5078
  n.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:_,requestId:O,previousStatus:x.status,newStatus:n.newTaskStatus}),Date.now(),P=Date.now()
5096
5079
  const o=await u.ensureCorrectWorkspaceContext({taskPromoted:n.taskPromoted,requestId:O,context:t,operation:"replace_in_files",logger:b,metrics:a,metricsPrefix:"replace_in_files"})
5097
5080
  if(!o.success){if(o.isLockConflict)return{content:[{type:"text",text:"\u274c "+o.error}],isError:!0}
5098
- throw Error(o.error)}Date.now(),$=!0}if(T.length>0&&O)try{await(0,p.validateRequestStatusForDocumentOperation)(O,s,b,a,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
5081
+ throw Error(o.error)}Date.now(),$=!0}if(T.length>0&&O)try{await(0,f.validateRequestStatusForDocumentOperation)(O,s,b,a,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
5099
5082
  throw e}P=Date.now()
5100
- const A=new Map
5083
+ const D=new Map
5101
5084
  if(b.info("\u{1f50d} Starting external edit detection",{hasFileOperations:j,hasGit:!!t.git,operationCount:E.length}),j&&t.git)for(const e of E)if(e.path&&!e.documentId)try{const r=u.validateAndNormalizePath(e.path,t),n=await l.default.readFile(r.fullPath,"utf8"),o=void 0!==e.fuzzy_match?e.fuzzy_match:q,s=[]
5102
5085
  for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
5103
5086
  s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,r.fullPath)
5104
5087
  b.info("\u{1f50d} Checking for external edits",{path:r.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
5105
5088
  const i=await(0,w.detectExternalEdits)(t.git,o,b)
5106
- b.info("\u{1f50d} External edit detection result",{path:r.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(A.set(e.path,{message:i.message,debugInfo:i.debugInfo}),b.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:r.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&A.set(e.path,{message:"",debugInfo:i.debugInfo}),b.info("\u2705 No external edit conflicts detected",{path:r.normalizedPath}))}else b.info("\u2139\ufe0f No matches found for external edit detection",{path:r.normalizedPath}),A.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){b.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),P=Date.now(),j&&t.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
5107
- const e=await(0,f.commitUserChangesBeforeToolOperation)(t.git,"replace_in_files",{requestId:O,taskId:_,workspaceManager:t.workspaceManager},b,a)
5089
+ b.info("\u{1f50d} External edit detection result",{path:r.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(D.set(e.path,{message:i.message,debugInfo:i.debugInfo}),b.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:r.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&D.set(e.path,{message:"",debugInfo:i.debugInfo}),b.info("\u2705 No external edit conflicts detected",{path:r.normalizedPath}))}else b.info("\u2139\ufe0f No matches found for external edit detection",{path:r.normalizedPath}),D.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){b.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),P=Date.now(),j&&t.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
5090
+ const e=await(0,p.commitUserChangesBeforeToolOperation)(t.git,"replace_in_files",{requestId:O,taskId:_,workspaceManager:t.workspaceManager},b,a)
5108
5091
  e.userChangesCommitted&&(b.debug("[REPLACE-IN-FILES] User changes committed",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),b.info("User changes committed before batch operation",{taskId:_,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){b.warn("Pre-tool user changes commit failed",{taskId:_,error:e instanceof Error?e.message:e+""})}Date.now(),P=Date.now(),C=u.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_in_files_phase",1,{phase:C})
5109
- const{toolRecordId:D}=await u.createFileOperationRecords(_,O,t.projectId,"replace-in-files",R,{operationCount:E.length,totalReplacements:E.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:q,userComment:S},r,o,b,a,"replace_in_files",c)
5110
- v=D,Date.now(),P=Date.now(),C=u.FileOperationPhase.STRING_REPLACEMENT,a.incrementCounter("replace_in_files_phase",1,{phase:C})
5092
+ const{toolRecordId:A}=await u.createFileOperationRecords(_,O,t.projectId,"replace-in-files",R,{operationCount:E.length,totalReplacements:E.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:q,userComment:S},r,o,b,a,"replace_in_files",c)
5093
+ v=A,Date.now(),P=Date.now(),C=u.FileOperationPhase.STRING_REPLACEMENT,a.incrementCounter("replace_in_files_phase",1,{phase:C})
5111
5094
  const F=[],N=[]
5112
- for(const e of E){const r=e.path?A.get(e.path):void 0,o=await n(e,q,t,0,0,r?.message,r?.debugInfo)
5095
+ for(const e of E){const r=e.path?D.get(e.path):void 0,o=await n(e,q,t,0,0,r?.message,r?.debugInfo)
5113
5096
  F.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&N.push(o.path)}Date.now(),P=Date.now()
5114
- const L=E.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),z=await u.handleMultiFileGitCommit(_,L,F,N.length,{operationType:"Replace in files",toolRecordId:D||v||"unknown",successField:"successfulReplacements",logger:b,metrics:a,metricsPrefix:"replace_in_files"},t),B=z.commitHash
5097
+ const L=E.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),z=await u.handleMultiFileGitCommit(_,L,F,N.length,{operationType:"Replace in files",toolRecordId:A||v||"unknown",successField:"successfulReplacements",logger:b,metrics:a,metricsPrefix:"replace_in_files"},t),B=z.commitHash
5115
5098
  Date.now(),Date.now()
5116
- const H=F.filter((e=>e.success)).length,U=F.length-H,W=F.reduce(((e,t)=>e+t.successfulReplacements),0),G=F.reduce(((e,t)=>e+t.failedReplacements),0),V=F.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,replacements:e.replacements.map((e=>({old_str:e.old,new_str:e.new,success:e.success,error:e.error,matchesFound:e.matchesFound,matchType:e.matchType,lines:e.lines})))}))),J=F.filter((e=>e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements}))),K=F.filter((e=>!e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,error:e.error,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements})))
5117
- await o.updateToolRecord(v,{metadata:{path:R,status:0===U?"completed":"partial",operationCount:E.length,operations:V,successfulFiles:J,failedFiles:K,successfulReplacements:W,failedReplacements:G,processingTime:Date.now()-I,userComment:S,...z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}}})
5099
+ const H=F.filter((e=>e.success)).length,W=F.length-H,U=F.reduce(((e,t)=>e+t.successfulReplacements),0),G=F.reduce(((e,t)=>e+t.failedReplacements),0),V=F.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,replacements:e.replacements.map((e=>({old_str:e.old,new_str:e.new,success:e.success,error:e.error,matchesFound:e.matchesFound,matchType:e.matchType,lines:e.lines})))}))),J=F.filter((e=>e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements}))),K=F.filter((e=>!e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,error:e.error,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements})))
5100
+ await o.updateToolRecord(v,{metadata:{path:R,status:0===W?"completed":"partial",operationCount:E.length,operations:V,successfulFiles:J,failedFiles:K,successfulReplacements:U,failedReplacements:G,processingTime:Date.now()-I,userComment:S,...z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}}})
5118
5101
  const Y=await async function(e,t,r,n,o,s){const i=e.filter((e=>e.success)).length,a=e.length-i,c=e.filter((e=>!e.success&&!e.error&&e.successfulReplacements>0)).length
5119
5102
  let l="## Replace In Files - Batch Results\n\n"
5120
5103
  if(o.getCurrentBranchContext)try{const e=await o.getCurrentBranchContext()
@@ -5126,10 +5109,10 @@ if(o.length>0){l+="\n**Successful Replacements:**\n"
5126
5109
  for(const e of o)l+=`- \u2705 \`${e.old.substring(0,40)}${e.old.length>40?"...":""}\` \u2192 \`${e.new.substring(0,40)}${e.new.length>40?"...":""}\``,e.matchesFound&&(l+=` (${e.matchesFound} occurrence${e.matchesFound>1?"s":""})`),e.lines&&e.lines.length>0&&3>=e.lines.length?l+=` at line${e.lines.length>1?"s":""} ${e.lines.join(", ")}`:e.lines&&e.lines.length>3&&(l+=` at ${e.lines.length} locations`),l+="\n"}const s=r.replacements.filter((e=>!e.success))
5127
5110
  if(s.length>0){l+="\n**Failed Replacement Details:**\n"
5128
5111
  for(const e of s)l+=`- \u274c \`${e.old.substring(0,40)}${e.old.length>40?"...":""}\` \u2192 \`${e.new.substring(0,40)}${e.new.length>40?"...":""}\`: ${e.error}\n`,e.details&&e.details.length>0&&(l+=" **Candidates found:**\n",l+=e.details.slice(0,5).map((e=>` - Line ${e.line}: \`${e.actually_matched.substring(0,40)}${e.actually_matched.length>40?"...":""}\` (${e.match_type})`)).join("\n")+"\n",e.details.length>5&&(l+=` ... and ${e.details.length-5} more matches\n`)),e.similarMatches&&e.similarMatches.length>0&&(l+=" **Did you mean? (Similar matches found):**\n",l+=e.similarMatches.map((e=>` - Line ${e.line}: \`${e.text.substring(0,60)}${e.text.length>60?"...":""}\` (${e.reason}, similarity: ${(100*e.similarity).toFixed(0)}%)`)).join("\n")+"\n")}l+="\n"}const d=e.filter((e=>"document"===e.type&&(e.success||e.successfulReplacements>0)))
5129
- return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(F,B,W,G,t,v)
5130
- return{content:[{type:"text",text:Y}],isError:0===W}}catch(e){const t=Date.now()-I
5112
+ return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(F,B,U,G,t,v)
5113
+ return{content:[{type:"text",text:Y}],isError:0===U}}catch(e){const t=Date.now()-I
5131
5114
  if(b.error("Replace in files batch operation failed",{error:e instanceof Error?e.stack:e+"",duration:t,phase:C}),v)try{await o.updateToolRecord(v,{metadata:{status:"failed",error:(0,k.getErrorMessage)(e),phase:C,duration:t}})}catch(e){}return a.incrementCounter("replace_in_files_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Replace In Files Failed:** "+(0,k.getErrorMessage)(e)}],isError:!0}}}
5132
- const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),p=t(5003),f=t(7478),m=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
5115
+ const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),f=t(5003),p=t(7478),m=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
5133
5116
  const t=e.trim()
5134
5117
  if(t.includes("-")){const r=t.split("-").map((e=>e.trim()))
5135
5118
  if(2!==r.length)throw Error(`Invalid line range format: "${e}". Expected format: "start-end" (e.g., "5-15")`)
@@ -5272,11 +5255,11 @@ if(!u)throw new n.ValidationError("Project ID is required for listing tasks with
5272
5255
  a.incrementCounter("list_tasks_attempts",1,{hasRequestId:!!i,hasFilters:Object.keys(d).length>0}),s.setProjectId(u)
5273
5256
  const h=s.getTaskClient(),g=d
5274
5257
  i&&(g.requestId=i),c.info("Listing tasks with filters",{projectId:u,taskFilters:g})
5275
- const p=await h.listTasks(g)
5276
- c.info("Raw tasks response data",{responseData:JSON.stringify(p)}),c.info("Tasks response structure",{type:typeof p,isArray:Array.isArray(p),hasData:null!=p,properties:p?Object.keys(p):[],dataPreview:p?JSON.stringify(p).substring(0,200)+"...":"null"})
5277
- let f=[]
5278
- p&&"object"==typeof p?"success"in p&&"data"in p?Array.isArray(p.data)?(f=p.data,c.info("Extracted tasks from success/data wrapper",{count:f.length})):p.data&&"object"==typeof p.data&&(f=[p.data],c.info("Extracted single task from success/data wrapper")):"data"in p?Array.isArray(p.data)?(f=p.data,c.info("Extracted tasks from data wrapper",{count:f.length})):p.data&&"object"==typeof p.data&&(f=[p.data],c.info("Extracted single task from data wrapper")):Array.isArray(p)?(f=p,c.info("Tasks response is direct array",{count:f.length})):(f=[p],c.info("Tasks response is single object")):(c.warn("Unexpected response format, using empty array",{responseType:typeof p}),f=[])
5279
- const m=f
5258
+ const f=await h.listTasks(g)
5259
+ c.info("Raw tasks response data",{responseData:JSON.stringify(f)}),c.info("Tasks response structure",{type:typeof f,isArray:Array.isArray(f),hasData:null!=f,properties:f?Object.keys(f):[],dataPreview:f?JSON.stringify(f).substring(0,200)+"...":"null"})
5260
+ let p=[]
5261
+ f&&"object"==typeof f?"success"in f&&"data"in f?Array.isArray(f.data)?(p=f.data,c.info("Extracted tasks from success/data wrapper",{count:p.length})):f.data&&"object"==typeof f.data&&(p=[f.data],c.info("Extracted single task from success/data wrapper")):"data"in f?Array.isArray(f.data)?(p=f.data,c.info("Extracted tasks from data wrapper",{count:p.length})):f.data&&"object"==typeof f.data&&(p=[f.data],c.info("Extracted single task from data wrapper")):Array.isArray(f)?(p=f,c.info("Tasks response is direct array",{count:p.length})):(p=[f],c.info("Tasks response is single object")):(c.warn("Unexpected response format, using empty array",{responseType:typeof f}),p=[])
5262
+ const m=p
5280
5263
  if(c.info(`Retrieved ${m.length} tasks`,{count:m.length,requestId:i,projectId:u}),0===m.length){let e=""
5281
5264
  return e=i?`No tasks found for request ${i}.`:`No tasks found for project ${u} with the specified filters.`,l({success:!0,taskCount:0}),{content:[{type:"text",text:e}]}}const y=m.map((e=>`**[${e.id}]** ${e.title}\nStatus: ${e.status}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}`)).join("\n\n")
5282
5265
  let w
@@ -5387,7 +5370,7 @@ if(null===c){n.warn("Could not read plugin source: "+e.sourceName),l.errors.push
5387
5370
  continue}const d=e.destName.startsWith("lib/")?c:["const __plugin = (function() {\n const module = { exports: {} };\n const exports = module.exports;\n (function() {",c," })();\n return module.exports.default || module.exports;\n})();\nexport default __plugin;"].join("\n"),h=i.default.createHash("md5").update(d).digest("hex"),g=r(a)
5388
5371
  if(null===g||h!==g){const t=s.default.dirname(a)
5389
5372
  t!==u&&await o.default.promises.mkdir(t,{recursive:!0}),await o.default.promises.writeFile(a,d,"utf8"),n.info("Synced plugin: "+e.destName,{reason:null===g?"not installed":"updated"}),l.synced.push(e.destName)}else l.skipped.push(e.destName)}catch(t){n.error("Failed to sync plugin: "+e.destName,{error:t instanceof Error?t.message:"Unknown error"}),l.errors.push(e.destName)}}return l}
5390
- const o=n(t(9896)),s=n(t(6928)),i=n(t(6982)),a=[{sourceName:"plugins/hooks/plugin.js",destName:"event-hooks.js"},{sourceName:"plugins/hooks/lib/condition-evaluator.js",destName:"lib/condition-evaluator.js"},{sourceName:"plugins/hooks/lib/hook-utils.js",destName:"lib/hook-utils.js"},{sourceName:"plugins/hooks/lib/dedup-utils.js",destName:"lib/dedup-utils.js"},{sourceName:"plugins/inject-session.js",destName:"inject-session.js"},{sourceName:"plugins/anthropic-auth.js",destName:"anthropic-auth.js"},{sourceName:"plugins/system-logger.js",destName:"system-logger.js"}]},9947(e,exports){function t(e,t){return e.substring(0,t).split("\n").length}function r(e){if(0===e.length)return[]
5373
+ const o=n(t(9896)),s=n(t(6928)),i=n(t(6982)),a=[{sourceName:"plugins/hooks/plugin.js",destName:"event-hooks.js"},{sourceName:"plugins/hooks/lib/condition-evaluator.js",destName:"lib/condition-evaluator.js"},{sourceName:"plugins/hooks/lib/hook-utils.js",destName:"lib/hook-utils.js"},{sourceName:"plugins/hooks/lib/dedup-utils.js",destName:"lib/dedup-utils.js"},{sourceName:"plugins/inject-session.js",destName:"inject-session.js"},{sourceName:"plugins/system-logger.js",destName:"system-logger.js"}]},9947(e,exports){function t(e,t){return e.substring(0,t).split("\n").length}function r(e){if(0===e.length)return[]
5391
5374
  const t=[...e].sort(((e,t)=>e.start-t.start)),r=[t[0]]
5392
5375
  for(let e=1;e<t.length;e++){const n=t[e],o=r[r.length-1]
5393
5376
  n.start>o.end+1?r.push(n):o.end=Math.max(o.end,n.end)}return r}function n(e,t){return e.start<=t.end&&t.start<=e.end}Object.defineProperty(exports,"__esModule",{value:!0}),exports.calculateReplacementRegion=function(e,n,o){const s=[]