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,7 +12,7 @@ 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
17
  const p=i.getTaskClient()
18
18
  u.info("Creating task with project context",{projectId:l})
@@ -26,7 +26,7 @@ w&&"object"==typeof w&&"_workingEndpoint"in w&&(E=w._workingEndpoint),u.info("Su
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:I,taskDescription:b,taskStatus:v},note:"Created task "+I})
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:I,projectId:l})
29
- let q="Created Task "+k
29
+ let q=`Created Task ${k}: ${I}`
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"})
@@ -222,6 +222,12 @@ 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)}
@@ -258,7 +264,7 @@ try{const e=u.getToolRecordClient()
258
264
  e&&(b={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:I,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:I,completionSummary:h,completionRecordId:b?.id,completedAt:t}},n=await y.updateTask(o,r)
259
265
  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:b?.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(b?.id&&(a+=`\n[RECORD:${b.id}]`),I&&(a+="\nCommit: "+I.substring(0,8)),i)try{const e=await y.listTasks({requestId:i})
263
269
  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
270
  const t=(0,s.extractArrayFromResponse)(e,{logger:p,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
@@ -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)}
@@ -820,10 +829,10 @@ if(Date.now(),Date.now(),I=Date.now(),C&&!C.readOnly)if(c?.sessionId){const e=c.
820
829
  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}))
821
830
  else{const r=await(0,d.getServerUrl)(t,m)
822
831
  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()
823
- if(e){let t,r=!1
824
- try{t=await(0,d.findMessageIdForTool)(e.serverUrl,e.sessionId,i)}catch{r=!0}if(t)_=u.sessionIdentity.buildCliOrigin(t)
825
- else if(r)_=u.sessionIdentity.buildCliOrigin()
826
- 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()
832
+ if(e){let r,n=!1
833
+ try{r=await(0,d.findMessageIdForTool)(e.serverUrl,e.sessionId,i)}catch{n=!0}if(r)_=u.sessionIdentity.buildCliOrigin(r)
834
+ else if(n)_=u.sessionIdentity.buildCliOrigin()
835
+ 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?.()
827
836
  try{const t=await(0,d.getAndStoreSessionId)(e.serverUrl,m,i)
828
837
  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)
829
838
  if(e){const t=await(0,d.getAndStoreSessionId)(e,m,i)
@@ -1004,11 +1013,10 @@ this.logger.debug("Retrieved main branch hash via direct rev-parse",{branch:n,co
1004
1013
  try{if(i=await this.git.revparse(["HEAD"]),!/^[a-f0-9]{40}$/i.test(i))throw Error("Invalid HEAD commit hash format: "+i)
1005
1014
  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
1006
1015
  this.logger.info("Starting conflict resolution workflow",{requestId:t,conflictedFiles:e.conflictedFiles.length,mode:e.mode})
1007
- try{await this.updateRequestStatus(t,"conflicted"),this.logger.info("Updated request status to conflicted",{requestId:t})
1008
- const r=await this.writeConflictMarkersToFiles(e)
1016
+ try{const r=await this.writeConflictMarkersToFiles(e)
1009
1017
  this.logger.info("Wrote conflict markers to files",{requestId:t,filesWritten:r})
1010
1018
  const n=await this.createConflictResolutionTask(e)
1011
- 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}
1019
+ 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}
1012
1020
  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
1013
1021
  this.logger.debug("Running structured merge-tree command",{requestId:e,command:t,cwd:this.workingDirectory})
1014
1022
  try{const r=await(0,c.execAsync)(t,{cwd:this.workingDirectory}),n=r.stdout.trim().split("\n").filter((e=>e.trim()))
@@ -1052,7 +1060,7 @@ if(!r)throw Error("Project ID is required for task creation but not available")
1052
1060
  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.`
1053
1061
  let s
1054
1062
  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()
1055
- 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=[]
1063
+ 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=[]
1056
1064
  for(const r of e.conflictedFiles)try{const e=i.default.resolve(this.workingDirectory,r.path)
1057
1065
  if(a.default.existsSync(e)){const n=a.default.readFileSync(e,"utf8")
1058
1066
  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})
@@ -1207,7 +1215,7 @@ try{let e
1207
1215
  try{const t=await fetch(`http://localhost:${M}/api/project-settings`)
1208
1216
  if(t.ok){const r=await t.json()
1209
1217
  if(r.data?.defaultModel){const[t,...n]=r.data.defaultModel.split("/")
1210
- 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}:{}})})
1218
+ 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)})
1211
1219
  if(!r.ok){const e=await r.text().catch((()=>"Unknown error"))
1212
1220
  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")
1213
1221
  const i=m||f?.sessionId||await(0,I.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})
@@ -1257,7 +1265,7 @@ try{let r
1257
1265
  try{const e=await fetch(`http://localhost:${M}/api/project-settings`)
1258
1266
  if(e.ok){const t=await e.json()
1259
1267
  if(t.data?.defaultModel){const[e,...n]=t.data.defaultModel.split("/")
1260
- 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}:{}})})
1268
+ 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)})
1261
1269
  if(!s.ok){const e=await s.text().catch((()=>"Unknown error"))
1262
1270
  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)
1263
1271
  if(60>t)return t+"s"
@@ -1347,7 +1355,7 @@ var t={}
1347
1355
  if(null!=e)for(var r=p(e),n=0;n<r.length;n++)"default"!==r[n]&&f(t,e,r[n])
1348
1356
  return m(t,e),t})
1349
1357
  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")
1350
- 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)
1358
+ 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)
1351
1359
  const r=_.validateArgs(e,C.SubagentOperationsSchema),{sessionId:d,operation:p}=r
1352
1360
  let f
1353
1361
  switch(c.info("Processing subagent_operations",{operation:p,sessionId:d}),p){case"spawn":f=await o(r.spawn,t,c,i,a)
@@ -1534,7 +1542,9 @@ const u=await s.proxyGet(`/api/projects/${o.projectId}/requests/${d}/test-runs`)
1534
1542
  if(!p)return c({success:!1,error:"no_test_run"}),{content:[{type:"text",text:`No test run found for request ${d}.`}],isError:!0}
1535
1543
  const f=p.id
1536
1544
  await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${f}`,{status:e.status,results:e.results})
1537
- 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}`
1545
+ const m="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f"
1546
+ try{const t=s.getRequestClient()
1547
+ "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}`
1538
1548
  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
1539
1549
  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'}]}}
1540
1550
  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`
@@ -2339,31 +2349,7 @@ exports.defaultLogger=o.default
2339
2349
  const s=t(6540)
2340
2350
  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
2341
2351
  const r=t(6183),n=t(8317)
2342
- 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")
2343
- try{const{requestId:n}=e
2344
- if(!n)throw(0,r.createValidationError)("Request ID is required")
2345
- let o,c
2346
- d.info("Starting request finalization",{requestId:n})
2347
- try{const e=await a.proxyPost(`/api/projects/${t.projectId}/requests/${n}/validate-completion`,{})
2348
- o=e?.data||e}catch(e){const t=(0,i.getErrorMessage)(e)
2349
- 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`
2350
- 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")
2351
- let l="workspace-manager"
2352
- try{const e=a.getRequestClient(),r=await e.getRequest(n),o=r?.title||"Request "+n
2353
- if("conflicted"===r?.status){d.info("Request is conflicted, attempting fast-path merge",{requestId:n})
2354
- const e=t.workspaceManager.getCurrentContext()
2355
- let r=e?.basePath||process.cwd()
2356
- if("multi-agent"===e?.mode)try{const e=await t.workspaceManager.getWorktreeInfo(n)
2357
- e?.worktreePath&&(r=e.worktreePath)}catch{}const i=(0,s.createConflictResolutionManager)(d,a,r,t.git),h=await i.validateMarkersRemoved(n)
2358
- 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.`}]}
2359
- const g=await i.hasMainBranchChanged(n)
2360
- 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)
2361
- return u({success:!1,reason:"merge_conflicts"}),{content:[{type:"text",text:i.userMessage}],isError:!1}}const r=(0,i.getErrorMessage)(e)
2362
- 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)
2363
- 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"
2364
- 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})
2365
- 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}}}
2366
- const r=t(9860),n=t(1569),o=t(8616),s=t(1651),i=t(8824)},3611(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2352
+ 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)}}},3611(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2367
2353
  Object.defineProperty(exports,"__esModule",{value:!0})
2368
2354
  const n=r(t(6928)),o=r(t(7252)),s=r(t(8577)),i=t(184),a=t(1213),c=t(3444),l=t(9955),d=t(5218),u=t(2568),h=t(3102),g=t(1152),p=t(3884),f=t(7888),m=t(4139),y=t(6800),w=t(6539),k=t(8824),I=t(6975),b=t(1253),v=process.argv.slice(2),C=v[0]||process.cwd(),_=n.default.resolve(C),E=parseInt(process.env.LOCAL_SERVER_PORT||v[1]||"3002",10),q=(0,c.createEnvLogger)({serviceName:"mcp-http-server"});(0,c.isDebugToolsEnabled)()?q.info("HTTP server initializing",{baseDir:_,preferredPort:E,debugLogging:process.env.DEBUG_LOGGING,debugLevel:process.env.DEBUG_LEVEL}):q.info("HTTP server starting",{port:E})
2369
2355
  const S=(0,g.createMetricsCollector)(!0),T=(process.env.REMOTE_SERVER_PORT,process.env.REMOTE_SERVER_HOST,process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com")
@@ -2496,21 +2482,22 @@ e.userChangesCommitted?f.info("Committed user changes to main before quick-edit
2496
2482
  f.debug("Creating task")
2497
2483
  const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+b})
2498
2484
  if(!e||!e.id)throw Error("Failed to create task")
2499
- let l
2500
- 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,I,y,h,g,p)
2501
- else if("replace"===t)l=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,I,y,h,g,p)
2485
+ let v
2486
+ if(T=e.id,f.info("Created task",{taskId:T}),f.debug("Executing file operation",{operationType:t}),"write"===t)v=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,I,y,h,g,p)
2487
+ else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,I,y,h,g,p)
2502
2488
  else{if("manage"!==t)throw new r.ValidationError("Unsupported operation type: "+t)
2503
- l=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||b},d,w,I,y,u,h,g,p)}if(l.isError){f.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
2504
- 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")
2505
- q?f.warn("File operation completed with partial failures",{requestId:S}):f.info("File operation completed successfully"),f.debug("Completing task")
2506
- try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${b}${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})
2489
+ v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||b},d,w,I,y,u,h,g,p)}if(v.isError){f.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
2490
+ 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${v.content[0].text}\n\nThe request (${S}) and task have been canceled and cleaned up.`}],isError:!0}}const q=v.content[0].text,P=q.includes("\u26a0\ufe0f Partial Success")||q.includes("\u274c Failed")||q.includes("\u274c 0 successful")
2491
+ P?f.warn("File operation completed with partial failures",{requestId:S}):f.info("File operation completed successfully"),f.debug("Completing task")
2492
+ try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${b}${P?" (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})
2507
2493
  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")
2508
- const P=q?`Quick change completed with partial success: ${b}. Some replacements failed - see details below.`:"Quick change completed: "+b,M=q?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
2509
- let R=!1
2510
- try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:P,acceptanceEvidence:[{evidence:M}],testVerification:void 0},d,u,h,g,p)
2511
- e.isError?f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text}):(R=!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(!R)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:P}),R=!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 j=Date.now()-m
2512
- let x
2513
- return f.info("Quick fix completed",{requestId:S,duration:j,hasPartialFailure:q}),x=q?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${b}\n**Operation:** ${t}\n**Duration:** ${j}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:** ${b}\n**Operation:** ${t}\n**Duration:** ${j}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&&(x+="\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:x}]}}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
2494
+ const M=P?`Quick change completed with partial success: ${b}. Some replacements failed - see details below.`:"Quick change completed: "+b,R=P?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
2495
+ let j=!1
2496
+ try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:M,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,p)
2497
+ if(e.isError)f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
2498
+ else{try{await y.updateRequest(S,{status:"completed",completionSummary:M}),f.info("Request finalized to completed",{requestId:S})}catch(e){f.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}j=!0,f.info("Request completed successfully",{requestId:S})}}catch(e){f.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!j)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:M}),j=!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
2499
+ let O
2500
+ return f.info("Quick fix completed",{requestId:S,duration:x,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${b}\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`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${b}\n**Operation:** ${t}\n**Duration:** ${x}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&&(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
2514
2501
  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}}}
2515
2502
  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")},3884(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.middleware=exports.validateRequest=exports.authenticate=exports.corsOptions=exports.errorHandler=exports.requestLogger=void 0
2516
2503
  const r=t(9860),n=t(5674)
@@ -2626,7 +2613,7 @@ return w.info("Write operation completed successfully",{duration:X-I,path:R?j:"d
2626
2613
  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}}}
2627
2614
  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
2628
2615
  const r=t(6183),n=t(4648)
2629
- 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
2616
+ 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
2630
2617
  const r=t(7163)
2631
2618
  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)})
2632
2619
  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")
@@ -2687,7 +2674,26 @@ if(!h)return{content:[{type:"text",text:"\u274c Unsupported image type: ."+u}],i
2687
2674
  if("svg"===u)return{content:[{type:"text",text:`**Asset: ${r}**\n\n\`\`\`svg\n${await i.readFile(c,"utf-8")}\n\`\`\``}]}
2688
2675
  const g=await i.readFile(c),p=g.toString("base64")
2689
2676
  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}}}
2690
- 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)
2677
+ 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
2678
+ try{if(!u)throw(0,r.createValidationError)("requestId is required")
2679
+ l.info("Starting merge request",{requestId:u,verificationCount:h.length})
2680
+ const e=i.getRequestClient(),o=await e.getRequest(u)
2681
+ 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}
2682
+ 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)
2683
+ l.warn("Criteria verification failed, continuing with merge",{requestId:u,error:t})}let a,c
2684
+ try{const e=await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/validate-completion`,{})
2685
+ a=e?.data||e}catch(e){const t=(0,s.getErrorMessage)(e)
2686
+ 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`
2687
+ 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")
2688
+ let g="workspace-manager"
2689
+ const p=await e.getRequest(u),f=p?.title||"Request "+u,m="resolving_conflicts"===p?.status
2690
+ try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,f,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,f),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)
2691
+ 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)
2692
+ 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:p?.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)
2693
+ 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)
2694
+ l.error("Merge request failed",{error:r})
2695
+ 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}}}
2696
+ 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)
2691
2697
  if(a)return t.debug("Reusing existing HealthCheckManager instance",{baseUrl:i,totalInstances:n.size}),a
2692
2698
  t.info("Creating new HealthCheckManager instance",{baseUrl:i,totalInstancesBefore:n.size})
2693
2699
  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})
@@ -2727,7 +2733,7 @@ var t={}
2727
2733
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2728
2734
  return o(t,e),t})
2729
2735
  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")
2730
- 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)
2736
+ 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)
2731
2737
  const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:p,sessionId:f}=r
2732
2738
  let m
2733
2739
  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"
@@ -2791,27 +2797,24 @@ let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
2791
2797
  return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&b&&(S+=`**Backup created:** ${c.basename(b)}\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
2792
2798
  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}}}
2793
2799
  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"})
2794
- 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)
2795
- const d=e?.complete?.acceptanceEvidence
2796
- Array.isArray(d)&&(e.complete.acceptanceEvidence=d.map((e=>"object"==typeof e&&e.evidence?e.evidence:e)))
2797
- const m=r.RequestOperationsSchema.parse(e),{requestId:y,operation:w}=m
2798
- switch(f.info("Processing request operation",{requestId:y,operation:w}),w){case"complete":{f.info("Routing to complete-request handler")
2799
- const e={requestId:y,summary:m.complete.summary,acceptanceEvidence:m.complete.acceptanceEvidence.map((e=>"string"==typeof e?{evidence:e}:e)),testVerification:m.complete.testVerification}
2800
- return await(0,n.handleCompleteRequest)(e,t,u,h,g,p)}case"finalize":{f.info("Routing to finalize-request handler")
2801
- const e={requestId:y}
2802
- return await(0,c.handleFinalizeRequest)(e,t,u,h,g,p)}case"approve":{f.info("Routing to approve-request handler")
2803
- const e={requestId:y}
2804
- return await(0,l.handleApproveRequest)(e,t,u,h,g,p)}case"revert":{f.info("Routing to revert-request handler")
2805
- const e={requestId:y,reason:m.revert.reason,confirmDestructive:m.revert.confirmDestructive}
2800
+ 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)
2801
+ const d=r.RequestOperationsSchema.parse(e),{requestId:m,operation:y}=d
2802
+ switch(f.info("Processing request operation",{requestId:m,operation:y}),y){case"complete":{f.info("Routing to complete-request handler")
2803
+ const e={requestId:m,summary:d.complete.summary}
2804
+ return await(0,n.handleCompleteRequest)(e,t,u,h,g,p)}case"merge":return f.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:m,verifications:d.merge?.verifications||[]},t,u,h,g,p)
2805
+ case"approve":{f.info("Routing to approve-request handler")
2806
+ const e={requestId:m}
2807
+ return await(0,c.handleApproveRequest)(e,t,u,h,g,p)}case"revert":{f.info("Routing to revert-request handler")
2808
+ const e={requestId:m,reason:d.revert.reason,confirmDestructive:d.revert.confirmDestructive}
2806
2809
  return await(0,o.handleRevertRequest)(e,t,u,h,g)}case"get-info":{f.info("Routing to get-request-information handler")
2807
- const e={requestId:y}
2810
+ const e={requestId:m}
2808
2811
  return await(0,s.handleGetRequestInformation)(e,t,u,h,g)}case"list":{f.info("Routing to list-requests handler")
2809
- const e={filters:m.list?.filters}
2812
+ const e={filters:d.list?.filters}
2810
2813
  return await(0,i.handleListRequests)(e,t,u,h,g)}case"search":{f.info("Routing to search-requests handler")
2811
- const e={search:m.search}
2812
- return await(0,a.handleSearchRequests)(e,t,u,h,g)}default:{const e="Unknown operation type: "+w
2814
+ const e={search:d.search}
2815
+ return await(0,a.handleSearchRequests)(e,t,u,h,g)}default:{const e="Unknown operation type: "+y
2813
2816
  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}}}
2814
- 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}}
2817
+ 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}}
2815
2818
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClient=void 0
2816
2819
  const n=r(t(9896)),o=r(t(6928)),s=t(7645),i=t(2161),a=t(1058),c=t(8824)
2817
2820
  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")
@@ -3016,7 +3019,7 @@ const r=t(6183),n=t(4592)
3016
3019
  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"})
3017
3020
  try{a.info("Validating request status for document operation",{requestId:e})
3018
3021
  const r=await t.getRequest(e)
3019
- 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`
3022
+ 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`
3020
3023
  a.warn("Document operation blocked on terminal request",{requestId:e,requestStatus:r.status,reason:"completed"===r.status?"request_completed":"request_canceled"})
3021
3024
  const c="completed"===r.status?i+"_blocked_completed_request":i+"_blocked_canceled_request"
3022
3025
  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
@@ -3146,48 +3149,57 @@ var t={}
3146
3149
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3147
3150
  return o(t,e),t})
3148
3151
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlanRead=async function(e,t,r,n,o){const s=n.child({tool:"plan_read"})
3149
- try{const n=a.validateArgs(e,i.PlanReadSchema),{operation:d}=n
3150
- switch(s.info("Processing plan_read",{operation:d}),d){case"get":{const e=await(0,c.handleGetPlan)(n.get,t,r,s,o)
3151
- 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)
3152
- 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)
3152
+ 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)
3153
+ const n=a.validateArgs(e,i.PlanReadSchema),{operation:d,planId:u}=n
3154
+ switch(s.info("Processing plan_read",{operation:d}),d){case"get":{const e=await(0,c.handleGetPlan)({planId:u},t,r,s,o)
3155
+ 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)
3156
+ 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)
3153
3157
  o.incrementCounter("plan_read_total",1,{operation:"get-history",success:!0})
3154
- let i=""
3155
- 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"
3156
- let a=""
3157
- 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
3158
+ let n=""
3159
+ 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"
3160
+ let s=""
3161
+ 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
3158
3162
  if(!n)return{content:[{type:"text",text:"\u274c No project context available."}],isError:!0}
3159
3163
  const i=await e.getProject(n)
3160
3164
  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."}]}
3161
3165
  const a=await(0,c.handleGetPlan)({planId:i.activePlanId},t,r,s,o)
3162
- 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})
3163
- 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}.`}]}
3164
- let i=`## Requests Linked to ${e} (${s.length})\n\n`
3165
- 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`
3166
- 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}}}
3167
- 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")
3166
+ 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})
3167
+ 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}.`}]}
3168
+ let n=`## Requests Linked to ${u} (${t.length})\n\n`
3169
+ 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`
3170
+ 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}}}
3171
+ 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")
3168
3172
  try{const{requestId:t}=e
3169
3173
  if(!t)throw new r.ValidationError("Request ID is required")
3170
3174
  if(!/^req\d{6}$/.test(t))throw new r.ValidationError(`Invalid request ID format: ${t}. Expected format: req######`)
3171
- l.info("Getting information for request "+t)
3172
- const n=i.getRequestClient(),s=i.getTaskClient(),[a,c]=await Promise.all([n.getRequest(t),s.listTasks({requestId:t})])
3173
- 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"})
3174
- const u=(0,o.extractDataFromResponse)(a,{logger:l,operationName:"getRequestInformation",throwOnNoData:!0}),h="data"in u?u.data:u
3175
- 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"})
3176
- const g=(0,o.extractArrayFromResponse)(c,{logger:l,operationName:"listTasksForRequest",defaultValue:[]})
3177
- l.info(`Successfully extracted ${g.length} tasks using data extraction utility`)
3178
- const p={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:g.length}
3179
- g.forEach((e=>{const t=e.status
3180
- t in p&&p[t]++}))
3181
- const f=h.acceptanceCriteria||[],m={unverified:0,partial:0,verified:0,partially_verified:0,total:f.length}
3182
- f.forEach((e=>{const t=e.status||"unverified"
3183
- t in m&&m[t]++}))
3184
- let y=h.testVerification||null
3185
- const w=h.title,k=h.type
3186
- let I=`# ${"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`
3187
- 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===g.length?I+="No tasks found for this request.\n":g.forEach((e=>{I+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),l.info(`Added task listing with ${g.length} tasks`),I+="\n## Acceptance Criteria\n",0===f.length?I+="No acceptance criteria defined.\n":f.forEach(((e,t)=>{const r=e.status||"unverified"
3188
- I+=`${t}. [${r.toUpperCase()}] ${e.description}\n`})),y&&(I+=`\n## Test Coverage\n- Test Cases: ${y.totalTestCases||0}\n- Criteria Tested: ${y.criteriaTestedCount||0}/${m.total}\n`,y.criterionCoverage&&Array.isArray(y.criterionCoverage)&&(I+="\n### Detailed Test Coverage:\n",y.criterionCoverage.forEach((e=>{I+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),h.recentActivity&&Array.isArray(h.recentActivity)&&(I+="\n## Recent Activity\n",h.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
3189
- I+=`- ${t}: ${e.description}\n`}))),d({success:!0}),{content:[{type:"text",text:I}]}}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}}}
3190
- 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
3175
+ d.info("Getting information for request "+t)
3176
+ const n=a.getRequestClient(),s=a.getTaskClient(),[c,l]=await Promise.all([n.getRequest(t),s.listTasks({requestId:t})])
3177
+ 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"})
3178
+ const h=(0,o.extractDataFromResponse)(c,{logger:d,operationName:"getRequestInformation",throwOnNoData:!0}),g="data"in h?h.data:h
3179
+ 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"})
3180
+ const p=(0,o.extractArrayFromResponse)(l,{logger:d,operationName:"listTasksForRequest",defaultValue:[]})
3181
+ d.info(`Successfully extracted ${p.length} tasks using data extraction utility`)
3182
+ const f={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:p.length}
3183
+ p.forEach((e=>{const t=e.status
3184
+ t in f&&f[t]++}))
3185
+ const m=g.acceptanceCriteria||[],y={unverified:0,partial:0,verified:0,partially_verified:0,total:m.length}
3186
+ m.forEach((e=>{const t=e.status||"unverified"
3187
+ t in y&&y[t]++}))
3188
+ let w=g.testVerification||null
3189
+ const k=g.title,I=g.type
3190
+ let b=`# ${"feature"===I?"Feature":"quick-edit"===I?"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: ${f.completed}/${f.total} completed (${Math.round(f.completed/f.total*100)||0}%)\n- Acceptance Criteria: ${y.verified}/${y.total} verified (${Math.round(y.verified/y.total*100)||0}%)\n`
3191
+ return b+=`\n## Task Status\n- Pending: ${f.pending}\n- In Progress: ${f.in_progress}\n- Blocked: ${f.blocked}\n- Ready for Review: ${f.ready_for_review}\n- Completed: ${f.completed}\n- Reverted: ${f.reverted}\n`,b+="\n## Tasks\n",0===p.length?b+="No tasks found for this request.\n":p.forEach((e=>{b+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),d.info(`Added task listing with ${p.length} tasks`),b+="\n## Acceptance Criteria\n",b+=(0,i.formatCriteriaWithHashes)(m)+"\n","ready_for_review"===g.status&&m.some((e=>"verified"!==e.status))&&(b+="\n> **Status: ready_for_review** \u2014 Use the merge operation to verify criteria and merge to main.\n"),w&&(b+=`\n## Test Coverage\n- Test Cases: ${w.totalTestCases||0}\n- Criteria Tested: ${w.criteriaTestedCount||0}/${y.total}\n`,w.criterionCoverage&&Array.isArray(w.criterionCoverage)&&(b+="\n### Detailed Test Coverage:\n",w.criterionCoverage.forEach((e=>{b+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),g.recentActivity&&Array.isArray(g.recentActivity)&&(b+="\n## Recent Activity\n",g.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
3192
+ b+=`- ${t}: ${e.description}\n`}))),u({success:!0}),{content:[{type:"text",text:b}]}}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}}}
3193
+ 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
3194
+ for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t)|0
3195
+ return`${t+1}${String.fromCharCode(97+Math.abs(r)%26)}`}function r(e){const r=new Map
3196
+ for(let n=0;n<e.length;n++){const o=t(e[n].id,n)
3197
+ r.set(o,e[n])}return r}function n(e){if(0===e.length)return"No acceptance criteria defined."
3198
+ const t=r(e),n=[]
3199
+ for(const[e,r]of t){const t=(r.status||"unverified").toUpperCase()
3200
+ n.push(`[${e}] [${t}] ${r.description}`)}return n.join("\n")}function o(e){const t=r(e),o=[]
3201
+ for(const[e,r]of t)o.push(` {"key": "${e}", "evidence": "<your evidence for: ${r.description}>"}`)
3202
+ 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
3191
3203
  const r=t(6183),n=t(2414)
3192
3204
  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)
3193
3205
  var o=Object.getOwnPropertyDescriptor(t,r)
@@ -3198,35 +3210,37 @@ var t={}
3198
3210
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3199
3211
  return o(t,e),t})
3200
3212
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDocumentOperations=async function(e,t,r,n,o,s,u){const h=n.child({tool:"document_operations"})
3201
- try{const n=a.validateArgs(e,i.DocumentOperationsSchema),{operation:d}=n
3202
- switch(h.info("Processing document_operations",{operation:d}),d){case"create":{h.info("Routing to create-document handler")
3203
- const e=await(0,c.handleCreateDocument)(n.create,t,r,h,o,s,u)
3213
+ try{const n=["create","search","createSnapshot","getHistory","getVersion","restoreVersion","listAnnotations","createAnnotation","replyToAnnotation","resolveAnnotation"]
3214
+ for(const t of n)e?.[t]&&"object"==typeof e[t]&&(Object.assign(e,e[t]),delete e[t])
3215
+ const d=a.validateArgs(e,i.DocumentOperationsSchema),{operation:g}=d,p=d.documentId
3216
+ switch(h.info("Processing document_operations",{operation:g}),g){case"create":{h.info("Routing to create-document handler")
3217
+ 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)
3204
3218
  return o.incrementCounter("document_operations_total",1,{operation:"create",success:!e.isError}),e}case"search":{h.info("Routing to search-documents handler")
3205
- const e=await(0,l.handleSearchDocuments)(n.search,t,r,h,o,s)
3219
+ 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)
3206
3220
  return o.incrementCounter("document_operations_total",1,{operation:"search",success:!e.isError}),e}case"create-snapshot":{h.info("Creating version snapshot")
3207
- const{documentId:e,versionLabel:t,changeSummary:s}=n.createSnapshot,i=r.getDocumentClient(),a=await i.createVersionSnapshot(e,t,s)
3208
- 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")
3209
- const{documentId:e}=n.getHistory,t=r.getDocumentClient(),s=await t.getVersionHistory(e)
3210
- 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})
3211
- let i=""
3212
- 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"
3213
- let a=""
3214
- 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")
3215
- const{documentId:e,versionNumber:t}=n.getVersion,s=r.getDocumentClient(),i=await s.getVersion(e,t)
3216
- 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")
3217
- const{documentId:e,versionNumber:t}=n.restoreVersion,s=r.getDocumentClient(),i=await s.restoreToVersion(e,t)
3218
- 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")
3219
- const{documentId:e}=n.listAnnotations,t=r.getDocumentClient(),s=await t.listAnnotations(e)
3220
- 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}.`}]}
3221
- let i=`## Annotations on ${e} (${s.length})\n\n`
3222
- 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`
3223
- 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")
3224
- 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})
3225
- 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")
3226
- 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})
3227
- 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")
3228
- const{documentId:e,annotationId:t}=n.resolveAnnotation,s=r.getDocumentClient()
3229
- 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}}}
3221
+ const{versionLabel:e,changeSummary:t}=d,n=r.getDocumentClient(),s=await n.createVersionSnapshot(p,e,t)
3222
+ return o.incrementCounter("document_operations_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Version Snapshot Created**\n\n**Document:** ${p}\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")
3223
+ const e=r.getDocumentClient(),t=await e.getVersionHistory(p)
3224
+ 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})
3225
+ let n=""
3226
+ 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"
3227
+ let s=""
3228
+ 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 ${p}\n\n${n}${s}`}]}}case"get-version":{h.info("Retrieving specific version")
3229
+ const e=r.getDocumentClient(),t=await e.getVersion(p,d.versionNumber)
3230
+ return o.incrementCounter("document_operations_total",1,{operation:"get-version",success:!0}),{content:[{type:"text",text:`## Version ${d.versionNumber} of ${p}\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")
3231
+ const e=r.getDocumentClient(),t=await e.restoreToVersion(p,d.versionNumber)
3232
+ return o.incrementCounter("document_operations_total",1,{operation:"restore-version",success:!0}),{content:[{type:"text",text:`\u2705 **Document Restored**\n\n**Document:** ${p}\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")
3233
+ const e=r.getDocumentClient(),t=await e.listAnnotations(p)
3234
+ 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 ${p}.`}]}
3235
+ let n=`## Annotations on ${p} (${t.length})\n\n`
3236
+ 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`
3237
+ 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")
3238
+ 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(p,{selectedText:e,prefixContext:n,suffixContext:s,lineHint:i,body:t,createdByAgent:c,createdBySessionId:l})
3239
+ 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:** ${p}\n**Selected text:** "${e.substring(0,60)}"\n**Comment:** `+t}]}}case"reply-to-annotation":{h.info("Replying to annotation")
3240
+ const e=d.annotationId,t=d.body,n=r.getDocumentClient(),s=await n.replyToAnnotation(p,e,{body:t,createdByAgent:u?"agent":void 0,createdBySessionId:u?.sessionId})
3241
+ 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")
3242
+ const e=d.annotationId,t=r.getDocumentClient()
3243
+ return await t.resolveAnnotation(p,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}}}
3230
3244
  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("/")
3231
3245
  return{provider:t||"anthropic",modelId:r.join("/")||e}}function n(e){const t={anthropic:!1,openai:!1}
3232
3246
  try{const n=(0,a.join)(e,"opencode.json")
@@ -3273,55 +3287,25 @@ if(t){const e=Date.now()-t
3273
3287
  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()
3274
3288
  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
3275
3289
  const r=t(6183),n=t(2965)
3276
- 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")
3277
- try{const{requestId:o,summary:s,acceptanceEvidence:d}=e
3290
+ 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"}),p=d.startTimer("tool_execution_time")
3291
+ try{const{requestId:o,summary:s}=e
3278
3292
  if(!o)throw(0,r.createValidationError)("Request ID is required")
3279
3293
  if(!s)throw(0,r.createValidationError)("Summary is required")
3280
- if(!d||!Array.isArray(d)||0===d.length)throw(0,r.createValidationError)("Acceptance evidence is required and must be a non-empty array")
3281
- const h=d.map((e=>{if("object"!=typeof e||!e.evidence)throw(0,r.createValidationError)('Each evidence item must have an "evidence" property')
3282
- return e.evidence}))
3283
- p.info("Starting request completion",{requestId:o,evidenceCount:h.length})
3284
- const m=g?.sessionId||(0,n.getCachedSession)()?.sessionId
3285
- let y,w
3286
- try{const e=await l.proxyPost(`/api/projects/${t.projectId}/requests/${o}/validate-completion`,{sessionId:m})
3287
- y=e?.data||e}catch(e){const t=(0,c.getErrorMessage)(e)
3288
- 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`
3289
- 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})
3290
- try{const e=l.getRequestClient()
3291
- let t
3292
- 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)
3293
- 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})
3294
- 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)
3295
- 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:""}
3296
- 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)
3297
- 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()
3298
- await t.git.reset(["--hard",e])
3299
- const r=await t.git.revparse(["HEAD"])
3300
- if(r.trim()!==e)throw Error(`Git reset verification failed: expected ${e.substring(0,8)}, got ${r.substring(0,8)}`)
3301
- 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)
3302
- return f({success:!1,reason:"revert_removal_failed"}),{content:[{type:"text",text:"Failed to re-complete reverted request: "+t}],isError:!0}}}const I=l.getRequestClient(),b=await I.getRequest(o)
3303
- if(!w&&"conflicted"===b?.status){p.info("Request is conflicted, attempting fast-path merge",{requestId:o})
3304
- const e=t.workspaceManager?.getCurrentContext()
3305
- let r=e?.basePath||process.cwd()
3306
- if("multi-agent"===e?.mode&&t.workspaceManager)try{const e=await t.workspaceManager.getWorktreeInfo(o)
3307
- e?.worktreePath&&(r=e.worktreePath)}catch{}const n=(0,i.createConflictResolutionManager)(p,l,r,t.git),s=await n.validateMarkersRemoved(o)
3308
- 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.`}]}
3309
- const a=await n.hasMainBranchChanged(o)
3310
- 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)})
3311
- else try{const e=await async function(e,t,r){r.info("Executing branch-version merge for resolved conflicts",{requestId:e})
3312
- 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)
3313
- 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)
3314
- 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}
3315
- const e=t.workspaceManager.getCurrentContext()
3316
- 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)
3317
- let a
3318
- if("conflicted"===b?.status)try{a=await s.updateConflictResolution(o,r)}catch{a=await s.handleConflicts(r)}else a=await s.handleConflicts(r)
3319
- return f({success:!1,reason:"merge_conflicts_handled"}),{content:[{type:"text",text:a.userMessage}],isError:!1}}const r=(0,c.getErrorMessage)(e)
3320
- 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)
3321
- 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=""
3322
- 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})
3323
- 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}}}
3324
- 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
3294
+ g.info("Starting request completion",{requestId:o})
3295
+ const l=h?.sessionId||(0,n.getCachedSession)()?.sessionId
3296
+ let d
3297
+ try{const e=await c.proxyPost(`/api/projects/${t.projectId}/requests/${o}/validate-completion`,{sessionId:l})
3298
+ d=e?.data||e}catch(e){const t=(0,i.getErrorMessage)(e)
3299
+ return g.error("Server validation failed",{requestId:o,error:t}),p({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`
3300
+ 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`}))),p({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}const u=c.getRequestClient(),f="auto-test-then-merge"===d.completionMode,m=f?"ready_for_review":"ready_for_merge"
3301
+ try{await u.updateRequest(o,{status:m,completionSummary:s})}catch(e){const t=(0,i.getErrorMessage)(e)
3302
+ return p({success:!1,error:"status_transition_failed"}),{content:[{type:"text",text:"Failed to transition request: "+t}],isError:!0}}let y
3303
+ try{y=await u.getRequest(o)}catch(e){const t=(0,i.getErrorMessage)(e)
3304
+ return p({success:!1,error:"fetch_request_failed"}),{content:[{type:"text",text:"Failed to fetch request criteria: "+t}],isError:!0}}const w=y?.acceptanceCriteria||[]
3305
+ return p({success:!0}),f?{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=""
3306
+ 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})
3307
+ 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}}}
3308
+ 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
3325
3309
  const r=t(6183),n=t(6285)
3326
3310
  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())}))})
3327
3311
  return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
@@ -3455,21 +3439,19 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
3455
3439
  if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
3456
3440
  const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
3457
3441
  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
3458
- 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)"})
3459
- 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
3460
- return"get-info"===e.operation?!t&&r&&!n:"list"===e.operation&&!r&&n}),{message:"Invalid operation data"})
3442
+ 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)"})
3443
+ 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" }'})}))
3461
3444
  const a=r.z.string().min(1).describe("OpenCode session ID")
3462
3445
  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
3463
3446
  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
3464
3447
  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
3465
- 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"})
3448
+ 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"})}))
3466
3449
  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)"})
3467
- 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]))
3468
- 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]
3469
- if(!t)return!1
3470
- const r=["create","update","append","replace","createSnapshot","restore","setActive"].filter((e=>e!==t)).some((t=>void 0!==e[t]))
3471
- 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
3472
- 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")})
3450
+ 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
3451
+ "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
3452
+ if(["complete","merge","approve","revert","get-info"].includes(n)&&!r)return void t.addIssue({code:"custom",message:`requestId is required for '${n}' operation`})
3453
+ 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]
3454
+ 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")})
3473
3455
  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)")})
3474
3456
  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
3475
3457
  const r=t(6183),n=t(405)
@@ -3482,7 +3464,7 @@ var t={}
3482
3464
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3483
3465
  return o(t,e),t})
3484
3466
  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")
3485
- 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
3467
+ 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
3486
3468
  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)
3487
3469
  const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:w,sessionId:k}=n
3488
3470
  let I
@@ -4077,7 +4059,7 @@ i.appendFileSync(o,`[${s}] ${e} | ${t}${c}\n`)}catch(e){}}
4077
4059
  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"})
4078
4060
  p.info("Creating new request",{args:e})
4079
4061
  const f=u.startTimer("tool_handler_duration")
4080
- 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)
4062
+ 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)
4081
4063
  throw new n.ValidationError("Invalid input: "+(0,i.getErrorMessage)(e))}}(e)
4082
4064
  u.incrementCounter("create_request_attempts",1,{type:d.type,criteriaCounts:d.acceptanceCriteria.length})
4083
4065
  const m=t.projectId
@@ -4466,8 +4448,9 @@ const e=this.worktreeManager.getWorktreeInfo(n)
4466
4448
  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"})
4467
4449
  const r=await this.worktreeManager.ensureWorktreeExists(n,void 0,void 0)
4468
4450
  if(!r.success)throw Error("Failed to create worktree: "+r.message)
4469
- 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}))
4470
- const s=Date.now()-t
4451
+ 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
4452
+ 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"])
4453
+ 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
4471
4454
  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
4472
4455
  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})
4473
4456
  const r=Date.now(),n=this.getCurrentContext()
@@ -4500,7 +4483,7 @@ try{this.currentRequestId===r&&await this.switchToMain()
4500
4483
  const e=await this.worktreeManager.removeWorktree(r,!1)
4501
4484
  if(!e.success)throw Error(e.message||"Failed to remove worktree")
4502
4485
  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"}
4503
- return this.logger.debug("getCurrentContext returning",{context:e}),e}async getWorkspaceInfo(e){try{const t=a.WorkspaceValidation.validateRequestId(e)
4486
+ 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)
4504
4487
  if(!t.isValid)return null
4505
4488
  const r=t.sanitized,n=await this.getWorktreeInfo(r)
4506
4489
  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\/(.+)$/)
@@ -5299,7 +5282,7 @@ if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
5299
5282
  return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
5300
5283
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,t,r,o,s,i,a,c){const I=i.child({tool:"replace_in_files"}),b=Date.now()
5301
5284
  let v,C=u.FileOperationPhase.VALIDATION
5302
- 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)
5285
+ 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)
5303
5286
  const i=u.validateArgs(e,d.ReplaceInFilesSchema),{taskId:_,operations:E,fuzzy_match:q=!0,comment:S}=i
5304
5287
  I.info("Replace in files batch operation",{taskId:_,operationCount:E.length,totalReplacements:E.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:q,comment:S})
5305
5288
  const T=E.filter((e=>e.documentId)).map((e=>e.documentId))