@bridge_gpt/mcp-server 0.2.78 → 0.2.80
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.
- package/README.md +112 -7
- package/build/decision-page-template.js +360 -23
- package/build/epic-implementer-bin.js +241 -1069
- package/build/index.js +1041 -1498
- package/build/worker-guard-hook-bin.js +2 -2
- package/docs/EPIC-IMPLEMENTER-INSTALL.md +13 -0
- package/docs/EPIC-IMPLEMENTER.md +44 -0
- package/docs/epic-implementer/getting-started.md +34 -0
- package/native/windows/bin/win32-x64/bridge-windows-native.exe +0 -0
- package/native/windows/bin/win32-x64/manifest.json +3 -3
- package/package.json +10 -4
- package/pipelines/review-ticket.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{lstatSync,readFileSync,readlinkSync}from"node:fs";var DEVICE_NAMES=/^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)$/i;function isParentSegment(segment){return segment===".."}function splitSegments(text){return text.split(/[\\/]/).filter(s=>s.length>0&&s!==".")}function segmentRefusal(segment){if(segment==="..")return null;if(segment.includes(":"))return"alternate_data_stream";let base=segment.split(".")[0];return DEVICE_NAMES.test(base)?"device":/[. ]$/.test(segment)&&segment!==".."||/~[0-9]/.test(segment)?"unsupported_alias":null}function parseWindowsLiteralPath(text){if(typeof text!="string"||text.length===0)return{kind:"refused",reason:"empty"};if(/[\u0000-\u001f\u007f]/.test(text))return{kind:"refused",reason:"control_character"};if(text==="~"||text.startsWith("~/")||text.startsWith("~\\"))return{kind:"refused",reason:"home_relative"};let trailingSeparator=/[\\/]$/.test(text),volume,rest;if(/^[\\/]{2}/.test(text))return{kind:"refused",reason:/^[\\/]{2}[?.][\\/]/.test(text)?"device":"unc"};let gitBash=/^\/([A-Za-z])(?:\/(.*))?$/s.exec(text),drive=/^([A-Za-z]):(.*)$/s.exec(text);if(gitBash)volume=gitBash[1].toUpperCase(),rest=gitBash[2]??"";else if(drive){if(!/^[\\/]/.test(drive[2]))return{kind:"refused",reason:"drive_relative"};volume=drive[1].toUpperCase(),rest=drive[2]}else{if(/^[\\/]/.test(text))return{kind:"refused",reason:text.startsWith("\\")?"drive_relative":"unsupported_alias"};rest=text}let segments=splitSegments(rest);for(let segment of segments){let refusal=segmentRefusal(segment);if(refusal!==null)return{kind:"refused",reason:refusal}}return volume!==void 0?{kind:"absolute",location:{volume,segments},trailingSeparator}:{kind:"relative",segments,trailingSeparator}}function joinWindowsLocation(base,relative){return{volume:base.volume,segments:[...base.segments,...relative]}}function formatWindowsLocation(location){return`${location.volume}:\\${location.segments.join("\\")}`}var MAX_LINK_DEPTH=8;function hasCasedLetter(segment){return segment.toLowerCase()!==segment.toUpperCase()}function uncertain(reason){return{status:"uncertain",reason}}function resolveWindowsIdentity(start,intent,provider,trailingSeparator=!1){try{return walk(start,intent,provider,trailingSeparator)}catch{return uncertain("provider_error")}}function walk(start,intent,provider,trailingSeparator){let rootInspection=provider.inspect({volume:start.volume,segments:[]});if(rootInspection.status==="uncertain")return uncertain(rootInspection.reason);if(rootInspection.status!=="directory")return uncertain("resolution_failed");let volume=start.volume,current=[],ancestry=[rootInspection.identity],pending=[...start.segments],linkTargetRemaining=-1,linkDepth=0;for(;pending.length>0;){let segment=pending.shift(),isLast=pending.length===0,atLinkBoundary=linkTargetRemaining===0;if(linkTargetRemaining>=0&&(linkTargetRemaining-=1),isParentSegment(segment)){if(atLinkBoundary)return uncertain("parent_after_link");current.length>0&&(current=current.slice(0,-1),ancestry=ancestry.slice(0,-1));continue}let candidate={volume,segments:[...current,segment]},entry=provider.inspect(candidate);if(entry.status==="uncertain")return uncertain(entry.reason);if(entry.status==="missing")return intent==="directory"?uncertain("missing_directory"):pending.some(isParentSegment)?uncertain("parent_in_missing_suffix"):{status:"resolved",resolved:{ancestry,location:{volume,segments:[...current,segment,...pending]}}};if(hasCasedLetter(segment)){if(entry.caseInsensitiveLookup===!1)return uncertain("case_sensitive_directory");if(entry.caseInsensitiveLookup===void 0)return uncertain("case_behavior_unknown")}if(entry.status==="link"){if(isLast&&intent!=="directory")return trailingSeparator?uncertain("ambiguous_final_link"):entry.linkKind!=="symlink"?uncertain("unsupported_link"):{status:"resolved",resolved:{ancestry,location:{volume,segments:[...current,segment]}}};if(entry.linkKind==="other"||typeof entry.target!="string")return uncertain("unsupported_link");if(linkDepth+=1,linkDepth>MAX_LINK_DEPTH)return uncertain("link_depth_exceeded");let target=parseWindowsLiteralPath(entry.target.replace(/^\\\\\?\\(?=[A-Za-z]:\\)/,""));if(target.kind==="refused")return uncertain("unsupported_link");let targetLocation=target.kind==="absolute"?target.location:{volume,segments:[...current,...target.segments]},restart=provider.inspect({volume:targetLocation.volume,segments:[]});if(restart.status!=="directory")return uncertain("unsupported_link");volume=targetLocation.volume,current=[],ancestry=[restart.identity],pending=[...targetLocation.segments,...pending],linkTargetRemaining=targetLocation.segments.length;continue}if(entry.status==="file")return!isLast||intent==="directory"?uncertain("not_a_directory"):{status:"resolved",resolved:{ancestry,location:{volume,segments:[...current,segment]}}};current=[...current,segment],ancestry=[...ancestry,entry.identity]}return{status:"resolved",resolved:{ancestry,location:{volume,segments:current}}}}function identityContained(root,target){let rootIdentity=root.ancestry[root.ancestry.length-1];return rootIdentity===void 0?!1:target.ancestry.includes(rootIdentity)}function windowsContainment(text,base,root,intent,provider){let parsed=parseWindowsLiteralPath(text);if(parsed.kind==="refused")return{status:"refused",reason:parsed.reason};let location;if(parsed.kind==="absolute")location=parsed.location;else{if(base===void 0)return{status:"uncertain",reason:"resolution_failed"};location=joinWindowsLocation(base,parsed.segments)}let result=resolveWindowsIdentity(location,intent,provider,parsed.trailingSeparator);return result.status==="uncertain"?result:identityContained(root,result.resolved)?{status:"inside",resolved:result.resolved}:{status:"outside",resolved:result.resolved}}function resolveWindowsDirectory(text,base,provider){let parsed=parseWindowsLiteralPath(text);if(parsed.kind==="refused")return{status:"unresolved"};let location;if(parsed.kind==="absolute")location=parsed.location;else if(base!==void 0)location=joinWindowsLocation(base,parsed.segments);else return{status:"unresolved"};let result=resolveWindowsIdentity(location,"directory",provider,parsed.trailingSeparator);return result.status==="resolved"?result:{status:"unresolved"}}function flipCase(segment){let out="";for(let ch of segment){let lower=ch.toLowerCase();out+=ch===lower?ch.toUpperCase():lower}return out}function errnoCode(err){return err&&typeof err=="object"?err.code:void 0}function createHostWindowsIdentityProvider(fs){let render=location=>`${location.volume}:\\${location.segments.join("\\")}`;return{inspect(location){let p=render(location),stat;try{stat=fs.lstat(p)}catch(err){let code=errnoCode(err);return code==="ENOENT"?{status:"missing"}:code==="EACCES"||code==="EPERM"?{status:"uncertain",reason:"access_denied"}:{status:"uncertain",reason:"resolution_failed"}}let identity=`${stat.dev.toString(16)}:${stat.ino.toString(16)}`,caseInsensitiveLookup,name=location.segments[location.segments.length-1];if(name!==void 0&&hasCasedLetter(name))try{let flipped=fs.lstat(render({volume:location.volume,segments:[...location.segments.slice(0,-1),flipCase(name)]}));caseInsensitiveLookup=flipped.dev===stat.dev&&flipped.ino===stat.ino}catch(err){caseInsensitiveLookup=errnoCode(err)==="ENOENT"?!1:void 0}let withCase=caseInsensitiveLookup===void 0?{}:{caseInsensitiveLookup};if(stat.isSymbolicLink())try{return{status:"link",linkKind:"unclassified",target:fs.readlink(p),...withCase}}catch{return{status:"link",linkKind:"other",...withCase}}return stat.isDirectory()?{status:"directory",identity,...withCase}:stat.isFile()?{status:"file",identity,...withCase}:{status:"uncertain",reason:"resolution_failed"}}}}import path from"node:path";var QUALIFIED_EXECUTION_TOOLS=["Bash"],UNCOVERED_EXECUTION_TOOLS=["PowerShell"],NON_EXECUTION_TOOLS=["Read","Edit","Write","MultiEdit","NotebookEdit","Grep","Glob","Skill","Task","Agent","SlashCommand"];function classifyClaudeTool(toolName){return QUALIFIED_EXECUTION_TOOLS.includes(toolName)?"qualified_execution":UNCOVERED_EXECUTION_TOOLS.includes(toolName)?"uncovered_execution":NON_EXECUTION_TOOLS.includes(toolName)||/^mcp__/.test(toolName)?"non_execution":"unclassified"}var CODEX_CORRECTION_TOOLS=Object.freeze([{type:"namespace",name:"bridge_correction",description:"Request authorization before any command, delegation, or separate implementation workflow.",tools:[{type:"function",name:"request_operation",description:"Ask the executor to authorize a proposed effect. A refusal must be obeyed.",inputSchema:{type:"object",additionalProperties:!1,required:["effect"],properties:{effect:{type:"string",enum:["command","workflow","delegation"]},operation:{type:"string",maxLength:1e3}}}}]}]),CODEX_CORRECTION_GUARD_OVERRIDES=Object.freeze(["features.shell_tool=false","features.unified_exec=false","features.multi_agent=false","features.apps=false","features.browser_use=false","features.computer_use=false","features.skill_mcp_dependency_install=false","features.workspace_dependencies=false"]),WORKER_GUARD_REASON_PREFIX="bridge worker guard",WORKER_GUARD_MALFORMED_LINE=`${WORKER_GUARD_REASON_PREFIX}: payload could not be read; continuing fail-open`;function renderWorkerGuardReason(category,family,form,restriction){if(category==="git-push"&&restriction==="push-routing")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Push-routing changes are not allowed; use the existing origin and upstream configuration and continue.`;if(category==="environment-file")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The main checkout environment file is not available to workers. Use the files your worktree provides, or reword a textual mention of it, and continue.`;if(category==="uncovered-execution-tool")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This execution tool is not covered by the worker guard on this platform. Run the command through the Bash tool instead and continue.`;if(category==="git-ambiguous")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This shell form cannot be safely resolved: substitution, redirection, or stdin-fed arguments hide what git will run. Use literal arguments instead; for a commit message, write it to a file and run git commit -F <file>.`;if(form==="shell_form"){let pattern=category==="git-push"?"If the destination is your own branch on origin and no force is used, run git push origin HEAD:<your work branch> alone.":category==="git-reset-hard"?"If resetting your own branch, run git reset --hard origin/<your work branch> alone.":category==="filesystem-clean"?"If all pathspecs are inside your worktree, run git clean with literal worktree-contained pathspecs alone.":category==="filesystem-remove"?"If all paths are inside your worktree, run rm with literal worktree-contained paths alone.":"If arguments are read-only, run literal read-only arguments alone, without redirects or $VAR.";return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Shell form cannot be checked: redirects, pipes, substitution, or stdin-fed arguments. `+pattern}let restrictionText={"git-push":"Push only to your own branch on origin. Use HEAD:<your work branch> as the destination.","git-reset-hard":"Hard reset only against your own branch ref.","filesystem-clean":"Clean only literal paths inside your worktree.","filesystem-remove":"Remove only literal paths inside your worktree.","database-destructive":"Destructive SQL is prohibited. Use read-only database arguments.","network-mutating":"Mutating requests are prohibited. Use read-only network arguments."};return restrictionText[category]?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ${restrictionText[category]}`:category==="workflow-entry"||category==="workflow-launch-skill"||category==="workflow-launch-shell"||category==="workflow-planner-tool"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). A correction worker must not start a full workflow. Reading or editing files that mention a workflow is allowed; make the focused correction directly.`:category==="correction-context-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The correction context for this worker is not valid, so no tool call can be checked. Stop and report the launch problem.`:category==="operator-verb"&&family==="regenerate-plan"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Choosing the route a failed plan is regenerated on is the run driver's decision, made outside the worker. Do not run regenerate-plan or call its route; record the step escalated with its reason and continue.`:category==="operator-verb"&&(family==="reserve-council"||family==="record-decision")?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Convening or settling an open-decision council is the run driver's decision, made outside the worker. Do not run reserve-council or record-decision; record the open choice as an escalated step with its reason and continue.`:category==="operator-verb"&&family==="resolve-owner-work"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Resolving an owner-work item is the run owner's decision, made outside the worker. Do not run resolve-owner-work or call its route; record the unfinished work in your phase result and continue.`:category==="operator-verb"&&family==="owner-work-transfer"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Transferring owner work between tickets is the run owner's decision, made outside the worker. Do not run owner-work-transfer or call its route; record the unfinished work in your phase result and continue.`:category==="operator-verb"&&family==="credential-approval"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Approving, changing or revoking worker credential references is the repository owner's decision, made outside the worker. Do not run 'credentials references apply'; record the credential you need as an escalated step with its reason and continue.`:category==="operator-verb"&&family==="acknowledge-gaps"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Acknowledging the run's carried-gap list is the run owner's decision, made outside the worker. Do not run acknowledge-gaps or call its route; record what you could not verify in your phase result and continue.`:category==="operator-verb"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Resolving a verification hand-off is the run owner's decision, made outside the worker. Do not run resolve-handoff or call its route; record the step escalated with its hand-off and continue.`:category==="correction-payload-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The tool call could not be read as a tool name with a tool input, so it cannot be checked. Retry with a well-formed call.`:`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This command family is restricted to the worker's own branch, worktree, and read-only network access. Use a different approach and continue.`}var UNSAFE_UNQUOTED=new Set(["$","`",">","<"]),SEPARATORS=new Set([";","|","&"]);function tokenizeShellCommand(command){let commands=[],argv=[],current="",hasCurrent=!1,unsafe=!1,endToken=()=>{hasCurrent&&(argv.push(current),current="",hasCurrent=!1)},endCommand=after=>{endToken(),(argv.length>0||unsafe)&&commands.push(after===void 0?{argv,unsafe}:{argv,unsafe,after}),argv=[],unsafe=!1};for(let i=0;i<command.length;i+=1){let ch=command[i];if(ch==="\\"){let next=command[i+1];next!==void 0&&(current+=next,hasCurrent=!0,i+=1);continue}if(ch==="'"){let close=command.indexOf("'",i+1);if(close===-1){unsafe=!0,current+=command.slice(i+1),hasCurrent=!0;break}current+=command.slice(i+1,close),hasCurrent=!0,i=close;continue}if(ch==='"'){let j=i+1,body="",closed=!1;for(;j<command.length;){let c=command[j];if(c==="\\"&&j+1<command.length){let escaped=command[j+1];escaped===`
|
|
2
|
+
import{lstatSync,readFileSync,readlinkSync}from"node:fs";var DEVICE_NAMES=/^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)$/i;function isParentSegment(segment){return segment===".."}function splitSegments(text){return text.split(/[\\/]/).filter(s=>s.length>0&&s!==".")}function segmentRefusal(segment){if(segment==="..")return null;if(segment.includes(":"))return"alternate_data_stream";let base=segment.split(".")[0];return DEVICE_NAMES.test(base)?"device":/[. ]$/.test(segment)&&segment!==".."||/~[0-9]/.test(segment)?"unsupported_alias":null}function parseWindowsLiteralPath(text){if(typeof text!="string"||text.length===0)return{kind:"refused",reason:"empty"};if(/[\u0000-\u001f\u007f]/.test(text))return{kind:"refused",reason:"control_character"};if(text==="~"||text.startsWith("~/")||text.startsWith("~\\"))return{kind:"refused",reason:"home_relative"};let trailingSeparator=/[\\/]$/.test(text),volume,rest;if(/^[\\/]{2}/.test(text))return{kind:"refused",reason:/^[\\/]{2}[?.][\\/]/.test(text)?"device":"unc"};let gitBash=/^\/([A-Za-z])(?:\/(.*))?$/s.exec(text),drive=/^([A-Za-z]):(.*)$/s.exec(text);if(gitBash)volume=gitBash[1].toUpperCase(),rest=gitBash[2]??"";else if(drive){if(!/^[\\/]/.test(drive[2]))return{kind:"refused",reason:"drive_relative"};volume=drive[1].toUpperCase(),rest=drive[2]}else{if(/^[\\/]/.test(text))return{kind:"refused",reason:text.startsWith("\\")?"drive_relative":"unsupported_alias"};rest=text}let segments=splitSegments(rest);for(let segment of segments){let refusal=segmentRefusal(segment);if(refusal!==null)return{kind:"refused",reason:refusal}}return volume!==void 0?{kind:"absolute",location:{volume,segments},trailingSeparator}:{kind:"relative",segments,trailingSeparator}}function joinWindowsLocation(base,relative){return{volume:base.volume,segments:[...base.segments,...relative]}}function formatWindowsLocation(location){return`${location.volume}:\\${location.segments.join("\\")}`}var MAX_LINK_DEPTH=8;function hasCasedLetter(segment){return segment.toLowerCase()!==segment.toUpperCase()}function uncertain(reason){return{status:"uncertain",reason}}function resolveWindowsIdentity(start,intent,provider,trailingSeparator=!1){try{return walk(start,intent,provider,trailingSeparator)}catch{return uncertain("provider_error")}}function walk(start,intent,provider,trailingSeparator){let rootInspection=provider.inspect({volume:start.volume,segments:[]});if(rootInspection.status==="uncertain")return uncertain(rootInspection.reason);if(rootInspection.status!=="directory")return uncertain("resolution_failed");let volume=start.volume,current=[],ancestry=[rootInspection.identity],pending=[...start.segments],linkTargetRemaining=-1,linkDepth=0;for(;pending.length>0;){let segment=pending.shift(),isLast=pending.length===0,atLinkBoundary=linkTargetRemaining===0;if(linkTargetRemaining>=0&&(linkTargetRemaining-=1),isParentSegment(segment)){if(atLinkBoundary)return uncertain("parent_after_link");current.length>0&&(current=current.slice(0,-1),ancestry=ancestry.slice(0,-1));continue}let candidate={volume,segments:[...current,segment]},entry=provider.inspect(candidate);if(entry.status==="uncertain")return uncertain(entry.reason);if(entry.status==="missing")return intent==="directory"?uncertain("missing_directory"):pending.some(isParentSegment)?uncertain("parent_in_missing_suffix"):{status:"resolved",resolved:{ancestry,location:{volume,segments:[...current,segment,...pending]}}};if(hasCasedLetter(segment)){if(entry.caseInsensitiveLookup===!1)return uncertain("case_sensitive_directory");if(entry.caseInsensitiveLookup===void 0)return uncertain("case_behavior_unknown")}if(entry.status==="link"){if(isLast&&intent!=="directory")return trailingSeparator?uncertain("ambiguous_final_link"):entry.linkKind!=="symlink"?uncertain("unsupported_link"):{status:"resolved",resolved:{ancestry,location:{volume,segments:[...current,segment]}}};if(entry.linkKind==="other"||typeof entry.target!="string")return uncertain("unsupported_link");if(linkDepth+=1,linkDepth>MAX_LINK_DEPTH)return uncertain("link_depth_exceeded");let target=parseWindowsLiteralPath(entry.target.replace(/^\\\\\?\\(?=[A-Za-z]:\\)/,""));if(target.kind==="refused")return uncertain("unsupported_link");let targetLocation=target.kind==="absolute"?target.location:{volume,segments:[...current,...target.segments]},restart=provider.inspect({volume:targetLocation.volume,segments:[]});if(restart.status!=="directory")return uncertain("unsupported_link");volume=targetLocation.volume,current=[],ancestry=[restart.identity],pending=[...targetLocation.segments,...pending],linkTargetRemaining=targetLocation.segments.length;continue}if(entry.status==="file")return!isLast||intent==="directory"?uncertain("not_a_directory"):{status:"resolved",resolved:{ancestry,location:{volume,segments:[...current,segment]}}};current=[...current,segment],ancestry=[...ancestry,entry.identity]}return{status:"resolved",resolved:{ancestry,location:{volume,segments:current}}}}function identityContained(root,target){let rootIdentity=root.ancestry[root.ancestry.length-1];return rootIdentity===void 0?!1:target.ancestry.includes(rootIdentity)}function windowsContainment(text,base,root,intent,provider){let parsed=parseWindowsLiteralPath(text);if(parsed.kind==="refused")return{status:"refused",reason:parsed.reason};let location;if(parsed.kind==="absolute")location=parsed.location;else{if(base===void 0)return{status:"uncertain",reason:"resolution_failed"};location=joinWindowsLocation(base,parsed.segments)}let result=resolveWindowsIdentity(location,intent,provider,parsed.trailingSeparator);return result.status==="uncertain"?result:identityContained(root,result.resolved)?{status:"inside",resolved:result.resolved}:{status:"outside",resolved:result.resolved}}function resolveWindowsDirectory(text,base,provider){let parsed=parseWindowsLiteralPath(text);if(parsed.kind==="refused")return{status:"unresolved"};let location;if(parsed.kind==="absolute")location=parsed.location;else if(base!==void 0)location=joinWindowsLocation(base,parsed.segments);else return{status:"unresolved"};let result=resolveWindowsIdentity(location,"directory",provider,parsed.trailingSeparator);return result.status==="resolved"?result:{status:"unresolved"}}function flipCase(segment){let out="";for(let ch of segment){let lower=ch.toLowerCase();out+=ch===lower?ch.toUpperCase():lower}return out}function errnoCode(err){return err&&typeof err=="object"?err.code:void 0}function createHostWindowsIdentityProvider(fs){let render=location=>`${location.volume}:\\${location.segments.join("\\")}`;return{inspect(location){let p=render(location),stat;try{stat=fs.lstat(p)}catch(err){let code=errnoCode(err);return code==="ENOENT"?{status:"missing"}:code==="EACCES"||code==="EPERM"?{status:"uncertain",reason:"access_denied"}:{status:"uncertain",reason:"resolution_failed"}}let identity=`${stat.dev.toString(16)}:${stat.ino.toString(16)}`,caseInsensitiveLookup,name=location.segments[location.segments.length-1];if(name!==void 0&&hasCasedLetter(name))try{let flipped=fs.lstat(render({volume:location.volume,segments:[...location.segments.slice(0,-1),flipCase(name)]}));caseInsensitiveLookup=flipped.dev===stat.dev&&flipped.ino===stat.ino}catch(err){caseInsensitiveLookup=errnoCode(err)==="ENOENT"?!1:void 0}let withCase=caseInsensitiveLookup===void 0?{}:{caseInsensitiveLookup};if(stat.isSymbolicLink())try{return{status:"link",linkKind:"unclassified",target:fs.readlink(p),...withCase}}catch{return{status:"link",linkKind:"other",...withCase}}return stat.isDirectory()?{status:"directory",identity,...withCase}:stat.isFile()?{status:"file",identity,...withCase}:{status:"uncertain",reason:"resolution_failed"}}}}import path from"node:path";var QUALIFIED_EXECUTION_TOOLS=["Bash"],UNCOVERED_EXECUTION_TOOLS=["PowerShell"],NON_EXECUTION_TOOLS=["Read","Edit","Write","MultiEdit","NotebookEdit","Grep","Glob","Skill","Task","Agent","SlashCommand"];function classifyClaudeTool(toolName){return QUALIFIED_EXECUTION_TOOLS.includes(toolName)?"qualified_execution":UNCOVERED_EXECUTION_TOOLS.includes(toolName)?"uncovered_execution":NON_EXECUTION_TOOLS.includes(toolName)||/^mcp__/.test(toolName)?"non_execution":"unclassified"}var CODEX_CORRECTION_TOOLS=Object.freeze([{type:"namespace",name:"bridge_correction",description:"Request authorization before any command, delegation, or separate implementation workflow.",tools:[{type:"function",name:"request_operation",description:"Ask the executor to authorize a proposed effect. A refusal must be obeyed.",inputSchema:{type:"object",additionalProperties:!1,required:["effect"],properties:{effect:{type:"string",enum:["command","workflow","delegation"]},operation:{type:"string",maxLength:1e3}}}}]}]),CODEX_CORRECTION_GUARD_OVERRIDES=Object.freeze(["features.shell_tool=false","features.unified_exec=false","features.multi_agent=false","features.apps=false","features.browser_use=false","features.computer_use=false","features.skill_mcp_dependency_install=false","features.workspace_dependencies=false"]),WORKER_GUARD_REASON_PREFIX="bridge worker guard",WORKER_GUARD_MALFORMED_LINE=`${WORKER_GUARD_REASON_PREFIX}: payload could not be read; continuing fail-open`;function renderWorkerGuardReason(category,family,form,restriction){if(category==="git-push"&&restriction==="push-routing")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Push-routing changes are not allowed; use the existing origin and upstream configuration and continue.`;if(category==="environment-file")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The main checkout environment file is not available to workers. Use the files your worktree provides, or reword a textual mention of it, and continue.`;if(category==="uncovered-execution-tool")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This execution tool is not covered by the worker guard on this platform. Run the command through the Bash tool instead and continue.`;if(category==="git-commit-ci-skip")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). CI-skip markers are not allowed. Remove the skip marker and commit again.`;if(category==="git-ambiguous")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This shell form cannot be safely resolved: substitution, redirection, or stdin-fed arguments hide what git will run. Use literal arguments instead; for a commit message, write it to a file and run git commit -F <file>.`;if(form==="shell_form"){let pattern=category==="git-push"?"If the destination is your own branch on origin and no force is used, run git push origin HEAD:<your work branch> alone.":category==="git-reset-hard"?"If resetting your own branch, run git reset --hard origin/<your work branch> alone.":category==="filesystem-clean"?"If all pathspecs are inside your worktree, run git clean with literal worktree-contained pathspecs alone.":category==="filesystem-remove"?"If all paths are inside your worktree, run rm with literal worktree-contained paths alone.":"If arguments are read-only, run literal read-only arguments alone, without redirects or $VAR.";return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Shell form cannot be checked: redirects, pipes, substitution, or stdin-fed arguments. `+pattern}let restrictionText={"git-push":"Push only to your own branch on origin. Use HEAD:<your work branch> as the destination.","git-reset-hard":"Hard reset only against your own branch ref.","filesystem-clean":"Clean only literal paths inside your worktree.","filesystem-remove":"Remove only literal paths inside your worktree.","database-destructive":"Destructive SQL is prohibited. Use read-only database arguments.","network-mutating":"Mutating requests are prohibited. Use read-only network arguments."};return restrictionText[category]?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ${restrictionText[category]}`:category==="workflow-entry"||category==="workflow-launch-skill"||category==="workflow-launch-shell"||category==="workflow-planner-tool"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). A correction worker must not start a full workflow. Reading or editing files that mention a workflow is allowed; make the focused correction directly.`:category==="correction-context-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The correction context for this worker is not valid, so no tool call can be checked. Stop and report the launch problem.`:category==="operator-verb"&&family==="regenerate-plan"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Choosing the route a failed plan is regenerated on is the run driver's decision, made outside the worker. Do not run regenerate-plan or call its route; record the step escalated with its reason and continue.`:category==="operator-verb"&&(family==="reserve-council"||family==="record-decision")?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Convening or settling an open-decision council is the run driver's decision, made outside the worker. Do not run reserve-council or record-decision; record the open choice as an escalated step with its reason and continue.`:category==="operator-verb"&&family==="resolve-owner-work"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Resolving an owner-work item is the run owner's decision, made outside the worker. Do not run resolve-owner-work or call its route; record the unfinished work in your phase result and continue.`:category==="operator-verb"&&family==="owner-work-transfer"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Transferring owner work between tickets is the run owner's decision, made outside the worker. Do not run owner-work-transfer or call its route; record the unfinished work in your phase result and continue.`:category==="operator-verb"&&family==="credential-approval"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Approving, changing or revoking worker credential references is the repository owner's decision, made outside the worker. Do not run 'credentials references apply'; record the credential you need as an escalated step with its reason and continue.`:category==="operator-verb"&&family==="acknowledge-gaps"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Acknowledging the run's carried-gap list is the run owner's decision, made outside the worker. Do not run acknowledge-gaps or call its route; record what you could not verify in your phase result and continue.`:category==="operator-verb"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Resolving a verification hand-off is the run owner's decision, made outside the worker. Do not run resolve-handoff or call its route; record the step escalated with its hand-off and continue.`:category==="correction-payload-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The tool call could not be read as a tool name with a tool input, so it cannot be checked. Retry with a well-formed call.`:`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This command family is restricted to the worker's own branch, worktree, and read-only network access. Use a different approach and continue.`}var UNSAFE_UNQUOTED=new Set(["$","`",">","<"]),SEPARATORS=new Set([";","|","&"]);function tokenizeShellCommand(command){let commands=[],argv=[],current="",hasCurrent=!1,unsafe=!1,endToken=()=>{hasCurrent&&(argv.push(current),current="",hasCurrent=!1)},endCommand=after=>{endToken(),(argv.length>0||unsafe)&&commands.push(after===void 0?{argv,unsafe}:{argv,unsafe,after}),argv=[],unsafe=!1};for(let i=0;i<command.length;i+=1){let ch=command[i];if(ch==="\\"){let next=command[i+1];next!==void 0&&(current+=next,hasCurrent=!0,i+=1);continue}if(ch==="'"){let close=command.indexOf("'",i+1);if(close===-1){unsafe=!0,current+=command.slice(i+1),hasCurrent=!0;break}current+=command.slice(i+1,close),hasCurrent=!0,i=close;continue}if(ch==='"'){let j=i+1,body="",closed=!1;for(;j<command.length;){let c=command[j];if(c==="\\"&&j+1<command.length){let escaped=command[j+1];escaped===`
|
|
3
3
|
`||(escaped==="$"||escaped==="`"||escaped==='"'||escaped==="\\"?body+=escaped:body+=c+escaped),j+=2;continue}if(c==='"'){closed=!0;break}(c==="$"||c==="`")&&(unsafe=!0),body+=c,j+=1}closed||(unsafe=!0),current+=body,hasCurrent=!0,i=j;continue}if(UNSAFE_UNQUOTED.has(ch)){unsafe=!0,current+=ch,hasCurrent=!0;continue}if(SEPARATORS.has(ch)){(ch==="&"||ch==="|")&&command[i+1]===ch?(i+=1,endCommand(ch==="&"?"&&":"||")):endCommand(ch===";"?";":ch==="|"?"|":"&");continue}if(ch===`
|
|
4
4
|
`){endCommand(";");continue}if(ch===" "||ch===" "||ch==="\r"){endToken();continue}current+=ch,hasCurrent=!0}return endCommand(),commands}function diagnosticProjections(command){if(command.length>WORKER_GUARD_MAX_PAYLOAD_BYTES)return[];let result=[],start=0,masked="",quote="",uncertain2=!1,finish=end=>{let original=tokenizeShellCommand(command.slice(start,end)),projected=tokenizeShellCommand(masked),value=!uncertain2&&projected.length===1?{argv:projected[0].argv,complete:!projected[0].unsafe}:void 0;result.push(...original.map((_,i)=>i===0?value:void 0)),masked="",uncertain2=!1,start=end+1};for(let i=0;i<command.length;i+=1){let ch=command[i];if(ch==="\\"&"e!=="'"){masked+=command.slice(i,i+2),i+=1;continue}if(quote){masked+=ch,ch===quote&&(quote="");continue}if(ch==="'"||ch==='"'){quote=ch,masked+=ch;continue}if(ch===">"||ch==="<"){masked=masked.replace(/(^|\s)\d+$/,"$1");let j=i+1;for(command[j]===ch&&(j+=1),command[j]==="&"&&(j+=1);/[ \t]/.test(command[j]??"")&&j<command.length;)j+=1;let operandStart=j,operandQuote="";for(;j<command.length;){let c=command[j];if(c==="\\"&&operandQuote!=="'"){j+=2;continue}if(operandQuote){c===operandQuote&&(operandQuote=""),j+=1;continue}if(c==="'"||c==='"'){operandQuote=c,j+=1;continue}if(/[\s;|&<>]/.test(c))break;j+=1}(j===operandStart||operandQuote||command.slice(i,j).startsWith("<<"))&&(uncertain2=!0),masked+=" ",i=j-1;continue}if(SEPARATORS.has(ch)||ch===`
|
|
5
|
-
`){finish(i);continue}masked+=ch}return quote&&(uncertain2=!0),finish(command.length),result}var WORKER_GUARD_MAX_PAYLOAD_BYTES=1e6;function asRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function isInside(root,candidate){let rel=path.relative(root,candidate);return rel===""?!0:rel===".."||rel.startsWith(`..${path.sep}`)?!1:!path.isAbsolute(rel)}function windowsPolicy(ctx){return ctx.platformPolicy==="win32"}function windowsRoot(ctx){let root=ctx.worktreePath,provider=ctx.identityProvider;if(typeof root!="string"||provider===void 0||parseWindowsLiteralPath(root).kind!=="absolute")return;let resolved=resolveWindowsDirectory(root,void 0,provider);return resolved.status==="resolved"?resolved.resolved:void 0}function windowsLocationOf(dir){let parsed=parseWindowsLiteralPath(dir);return parsed.kind==="absolute"?parsed.location:void 0}function resolveEffectiveCwd(ctx,payloadCwd){let root=ctx.worktreePath;if(windowsPolicy(ctx)){let rootResolved=windowsRoot(ctx),provider=ctx.identityProvider;if(rootResolved===void 0||provider===void 0)return;if(payloadCwd===void 0)return formatWindowsLocation(rootResolved.location);if(typeof payloadCwd!="string"||payloadCwd.length===0)return;let contained=windowsContainment(payloadCwd,rootResolved.location,rootResolved,"directory",provider);return contained.status==="inside"?formatWindowsLocation(contained.resolved.location):void 0}if(typeof root!="string"||!path.isAbsolute(root))return;let normalizedRoot=path.resolve(root);if(payloadCwd===void 0)return normalizedRoot;if(typeof payloadCwd!="string"||payloadCwd.length===0)return;let resolved=path.isAbsolute(payloadCwd)?path.resolve(payloadCwd):path.resolve(normalizedRoot,payloadCwd);return isInside(normalizedRoot,resolved)?resolved:void 0}function allTargetsContained(ctx,cwd,targets,intent="remove_target"){let root=ctx.worktreePath;if(cwd===void 0)return!1;if(windowsPolicy(ctx)){let rootResolved=windowsRoot(ctx),provider=ctx.identityProvider,base=windowsLocationOf(cwd);return rootResolved===void 0||provider===void 0||base===void 0?!1:targets.every(target=>windowsContainment(target,base,rootResolved,intent,provider).status==="inside")}if(typeof root!="string"||!path.isAbsolute(root))return!1;let normalizedRoot=path.resolve(root);return targets.every(target=>{if(target.length===0||target==="~"||target.startsWith("~/"))return!1;let resolved=path.isAbsolute(target)?path.resolve(target):path.resolve(cwd,target);return isInside(normalizedRoot,resolved)})}function parseGitInvocation(argv,baseCwd,ctx){let cwd=baseCwd,unsafe=!1,i=1;for(;i<argv.length;){let token=argv[i];if(token==="-C"){let dir=argv[i+1];dir===void 0||cwd===void 0?(unsafe=!0,cwd=void 0):ctx!==void 0&&windowsPolicy(ctx)?cwd=resolveWindowsDirectoryString(ctx,dir,cwd):cwd=path.isAbsolute(dir)?path.resolve(dir):path.resolve(cwd,dir),i+=2;continue}if(token==="-c"||token==="--namespace"||token==="--git-dir"||token==="--work-tree"){unsafe=!0,i+=2;continue}if(token.startsWith("-")){i+=1;continue}break}return{subcommand:argv[i]??"",args:argv.slice(i+1),cwd,unsafe}}function resolveWindowsDirectoryString(ctx,dir,base){let provider=ctx.identityProvider;if(provider===void 0)return;let baseLocation=base===void 0?void 0:windowsLocationOf(base),resolved=resolveWindowsDirectory(dir,baseLocation,provider);return resolved.status==="resolved"?formatWindowsLocation(resolved.resolved.location):void 0}function isOwnBranchDestination(destination,workerBranch){let colon=destination.indexOf(":"),dst=colon===-1?destination:destination.slice(colon+1);if(dst.length===0)return!1;let bare=dst.startsWith("+")?dst.slice(1):dst;return bare===workerBranch||bare===`refs/heads/${workerBranch}`}function evaluateGitPush(args,ctx){let deny={kind:"deny",category:"git-push",family:"git"},workerBranch=ctx.workerBranch;if(typeof workerBranch!="string"||workerBranch.trim().length===0)return deny;let positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}if(token.startsWith("-")){if(token==="--tags"||token==="--delete"||token==="-d"||token==="--mirror"||token==="--all"||token==="--branches"||token==="--prune"||token==="--follow-tags"||token.startsWith("--repo"))return deny;(token==="-o"||token==="--push-option"||token==="--receive-pack"||token==="--exec")&&(i+=1);continue}positional.push(token)}if(positional.length>0&&positional[0]!=="origin")return deny;if(positional.length<=1)return{kind:"allow"};let destinations=positional.slice(1);for(let refspec of destinations)if((refspec.startsWith("+")?refspec.slice(1):refspec).startsWith(":"))return deny;return destinations.every(d=>isOwnBranchDestination(d,workerBranch))?{kind:"allow"}:deny}var ROUTING_DENY={kind:"deny",category:"git-push",family:"git",restriction:"push-routing"},REMOTE_MUTATIONS=new Set(["add","set-url","rename","remove","rm","set-head","set-branches"]);function isRemoteMutation(args){let sub=args.find(t=>!t.startsWith("-"));return sub!==void 0&&REMOTE_MUTATIONS.has(sub)}function isUpstreamMutation(args){for(let token of args){if(token==="--")break;if(token.startsWith("--set-upstream")||token==="--unset-upstream"||/^-[^-]/.test(token)&&token.includes("u"))return!0}return!1}function isRoutingConfigKey(key){let k=key.toLowerCase();return k.startsWith("remote.")||/^branch\..+\.(?:remote|pushremote|merge)$/.test(k)||/^url\..+\.(?:insteadof|pushinsteadof)$/.test(k)?!0:k==="push.default"}function isRoutingConfigSection(name){let first=name.toLowerCase().split(".")[0];return first==="remote"||first==="branch"||first==="url"||first==="push"}var CONFIG_VALUE_OPTIONS=new Set(["-f","--file","--blob","--type","--default","--comment"]),CONFIG_READ_OPTIONS=new Set(["--get","--get-all","--get-regexp","--get-urlmatch","-l","--list","--get-color","--get-colorbool","--name-only","--show-origin","--show-scope"]),CONFIG_KEY_MUTATIONS=new Set(["--add","--unset","--unset-all","--replace-all"]);function isConfigRoutingMutation(args){let positional=[],options=new Set;for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}if(token.startsWith("-")&&token.length>1){options.add(token.split("=")[0]),CONFIG_VALUE_OPTIONS.has(token)&&(i+=1);continue}positional.push(token)}if(options.has("-e")||options.has("--edit"))return!0;let sub;if(positional.length>0&&["get","set","unset","list","edit","remove-section","rename-section"].includes(positional[0])&&(sub=positional[0]),sub==="edit")return!0;if(sub==="set"||sub==="unset"){let key=positional[1];return key!==void 0&&isRoutingConfigKey(key)}if(sub==="remove-section"){let name=positional[1];return name!==void 0&&isRoutingConfigSection(name)}if(sub==="rename-section")return positional.slice(1,3).some(isRoutingConfigSection);if(sub==="get"||sub==="list")return!1;if(options.has("--remove-section")||options.has("--rename-section"))return positional.slice(0,2).some(isRoutingConfigSection);for(let opt of options)if(CONFIG_KEY_MUTATIONS.has(opt))return positional[0]!==void 0&&isRoutingConfigKey(positional[0]);for(let opt of options)if(CONFIG_READ_OPTIONS.has(opt))return!1;return positional.length>=2?isRoutingConfigKey(positional[0]):!1}function evaluateGitRouting(subcommand,args){return subcommand==="remote"&&isRemoteMutation(args)||subcommand==="branch"&&isUpstreamMutation(args)||subcommand==="config"&&isConfigRoutingMutation(args)?ROUTING_DENY:{kind:"allow"}}function evaluateGitReset(args,ctx){let deny={kind:"deny",category:"git-reset-hard",family:"git"};if(!args.includes("--hard"))return{kind:"allow"};let positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}token.startsWith("-")||positional.push(token)}if(positional.length===0)return{kind:"allow"};let workerBranch=ctx.workerBranch;if(typeof workerBranch!="string"||workerBranch.length===0)return deny;let allowed=new Set([workerBranch,`origin/${workerBranch}`,`refs/heads/${workerBranch}`,`refs/remotes/origin/${workerBranch}`]);return positional.every(ref=>allowed.has(ref))?{kind:"allow"}:deny}function evaluateGitClean(args,ctx,cwd){let deny={kind:"deny",category:"filesystem-clean",family:"git"};if(cwd===void 0||!allTargetsContained(ctx,cwd,[cwd],"directory"))return deny;let pathspecs=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){pathspecs.push(...args.slice(i+1));break}if(token==="-e"||token==="--exclude"){i+=1;continue}token.startsWith("-")||pathspecs.push(token)}return pathspecs.length===0?{kind:"allow"}:windowsPolicy(ctx)&&pathspecs.some(p=>p.startsWith(":"))?deny:allTargetsContained(ctx,cwd,pathspecs,"pathspec")?{kind:"allow"}:deny}function isRecursiveForcedRemove(args){let recursive=!1,force=!1;for(let token of args){if(token==="--")break;if(token==="--recursive")recursive=!0;else if(token==="--force")force=!0;else{if(token.startsWith("--"))continue;if(token.startsWith("-")&&token.length>1)for(let flag of token.slice(1))(flag==="r"||flag==="R")&&(recursive=!0),flag==="f"&&(force=!0)}}return recursive&&force}function evaluateRemove(argv,ctx,cwd){let deny={kind:"deny",category:"filesystem-remove",family:"rm"},args=argv.slice(1);if(!isRecursiveForcedRemove(args))return{kind:"allow"};let targets=[],sawDoubleDash=!1;for(let token of args){if(!sawDoubleDash&&token==="--"){sawDoubleDash=!0;continue}!sawDoubleDash&&token.startsWith("-")&&token.length>1||targets.push(token)}return targets.length===0?deny:allTargetsContained(ctx,cwd,targets,"remove_target")?{kind:"allow"}:deny}function isDatabaseCommand(executable){let base=path.basename(executable);return base==="psql"||base.startsWith("pg_")}var DESTRUCTIVE_SQL=/\b(?:DROP|TRUNCATE)\b/i;function evaluateDatabase(argv){let deny={kind:"deny",category:"database-destructive",family:"psql"};return argv.slice(1).some(arg=>DESTRUCTIVE_SQL.test(arg))?deny:{kind:"allow"}}var MUTATING_METHODS=new Set(["POST","PUT","PATCH","DELETE"]);function evaluateNetwork(argv,ctx){let deny={kind:"deny",category:"network-mutating",family:"curl"},base=executableName(argv[0]??"",ctx),args=argv.slice(1);for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="-X"||token==="--request"||token==="--method"){let value=args[i+1];if(value===void 0||MUTATING_METHODS.has(value.toUpperCase()))return deny;i+=1;continue}if(token.startsWith("-X")&&token.length>2){if(MUTATING_METHODS.has(token.slice(2).toUpperCase()))return deny;continue}if(token.startsWith("--request=")||token.startsWith("--method=")){let value=token.slice(token.indexOf("=")+1);if(MUTATING_METHODS.has(value.toUpperCase()))return deny;continue}if(token==="--data"||token.startsWith("--data=")||token.startsWith("--data-")||token==="--form"||token==="-F"||token==="--upload-file"||token==="-T"||token==="--post-data"||token.startsWith("--post-data=")||token==="--post-file"||token.startsWith("--post-file=")||token==="--body-data"||token.startsWith("--body-data=")||token==="--body-file"||token.startsWith("--body-file=")||base==="curl"&&token==="-d")return deny}return{kind:"allow"}}function executableName(executable,ctx){if(ctx===void 0||!windowsPolicy(ctx))return path.basename(executable);let base=path.win32.basename(executable).toLowerCase();return base.endsWith(".exe")?base.slice(0,-4):base}function classify(executable,ctx){let base=executableName(executable,ctx);return base==="git"?"git":base==="rm"?"rm":isDatabaseCommand(base)?"database":base==="curl"||base==="wget"?"network":null}function unsafeGitCategory(argv){let{subcommand}=parseGitInvocation(argv,void 0);return subcommand==="push"?"git-push":subcommand==="reset"?"git-reset-hard":subcommand==="clean"?"filesystem-clean":"git-ambiguous"}function diagnosticPushForce(args){return args.some(t=>t==="--force"||t==="-f"||t==="--force-with-lease"||t.startsWith("--force-with-lease=")||t.startsWith("+"))}function diagnosticViolation(family,diagnostic,ctx,cwd){let full=unwrapTransparentPrefixes(diagnostic.argv,ctx),unknown=diagnostic.complete?-1:full.findIndex(t=>/[$`]/.test(t)),argv=unknown<0?full:full.slice(0,unknown);if(family==="database")return evaluateDatabase(argv).kind==="deny";if(family==="network")return evaluateNetwork(argv,ctx).kind==="deny";let git=parseGitInvocation(argv,cwd,ctx);return family==="git"&&git.subcommand==="push"&&diagnosticPushForce(git.args)?!0:diagnostic.complete?family==="rm"?evaluateRemove(argv,ctx,cwd).kind==="deny":git.unsafe?!0:git.subcommand==="push"?evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1:family==="rm"?argv.slice(1).some(t=>!t.startsWith("-"))&&evaluateRemove(argv,ctx,cwd).kind==="deny":git.subcommand==="push"?git.args.filter(t=>!t.startsWith("-")).length>=2&&evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?git.args.some(t=>!t.startsWith("-"))&&evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1}function unsafeSegmentDecision(family,argv,ctx,cwd,diagnostic){let category=family==="git"?unsafeGitCategory(argv):family==="rm"?"filesystem-remove":family==="database"?"database-destructive":"network-mutating",decision={kind:"deny",category,family:family==="database"?"psql":family==="network"?"curl":family};return diagnostic&&category!=="git-ambiguous"&&!diagnosticViolation(family,diagnostic,ctx,cwd)?{...decision,form:"shell_form"}:decision}var TRANSPARENT_PREFIXES=new Set(["sudo","env","command","nohup","time","nice","exec"]),STDIN_ARGUMENT_PREFIXES=new Set(["xargs"]),SHELL_EXECUTABLES=new Set(["sh","bash","zsh","dash","ksh"]),EVAL_BUILTINS=new Set(["eval"]);function unwrapTransparentPrefixes(argv,ctx){let rest=argv;for(let depth=0;depth<8;depth+=1){let head=rest[0];if(head===void 0||!TRANSPARENT_PREFIXES.has(executableName(head,ctx)))return rest;let i=1;for(;i<rest.length;){let token=rest[i];if(executableName(head,ctx)==="env"&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){i+=1;continue}if(token.startsWith("-")){i+=1;continue}break}rest=rest.slice(i)}return rest}function stripStdinPrefixOptions(argv){let VALUE_OPTS=new Set(["-I","-i","-L","-n","-P","-s","-d","-E","-e","-a","--replace","--max-lines","--max-args","--max-procs","--max-chars","--delimiter","--eof","--arg-file"]),i=1;for(;i<argv.length;){let token=argv[i];if(token==="--"){i+=1;break}if(!token.startsWith("-"))break;if(token.includes("=")){i+=1;continue}i+=VALUE_OPTS.has(token)?2:1}return argv.slice(i)}var WORKFLOW_NAMES="implement-ticket|plan-ticket|idea-to-pr|review-and-implement",WORKFLOW_SLASH_LAUNCH=new RegExp(`(?:^|\\s)/(?:bridge-)?(?:${WORKFLOW_NAMES})(?=\\s|$)`,"i"),WORKFLOW_NAME_EXACT=new RegExp(`^/?(?:[A-Za-z0-9_-]+:)?(?:bridge-)?(?:${WORKFLOW_NAMES})$`,"i"),CLAUDE_PACKAGE_TOKEN=/^(?:@anthropic-ai\/)?claude(?:-code)?(?:@\S+)?$/;function claudeLaunchArgs(argv){let base=path.basename(argv[0]??"");if(base==="claude")return argv.slice(1);if(base==="npx"){let index=argv.findIndex((token,i)=>i>0&&CLAUDE_PACKAGE_TOKEN.test(token));return index===-1?void 0:argv.slice(index+1)}}function isClaudeWorkflowPrintLaunch(segment){let args=claudeLaunchArgs(segment.argv);return args===void 0||!args.some(token=>token==="-p"||token==="--print"||token.startsWith("--print="))?!1:segment.unsafe?!0:args.some(token=>{let value=token.startsWith("--print=")?token.slice(8):token;return WORKFLOW_SLASH_LAUNCH.test(value)})}var OPERATOR_ONLY_VERBS=["resolve-handoff","regenerate-plan","acknowledge-gaps","reserve-council","record-decision","resolve-owner-work","owner-work-transfer"],SEGMENT_ROUTE_VERBS=OPERATOR_ONLY_VERBS.filter(verb=>verb!=="resolve-owner-work"&&verb!=="owner-work-transfer"),OWNER_WORK_ROUTES=[{verb:"resolve-owner-work",pattern:/\/jira\/epic-runs\/runs\/[^/?#\s]+\/owner-work\/[^/?#\s]+\/resolve\/?(?=$|[^A-Za-z0-9_\-.~%/])/},{verb:"owner-work-transfer",pattern:/\/jira\/epic-runs\/epics\/[^/?#\s]+\/owner-work\/transfers\/?(?=$|[^A-Za-z0-9_\-.~%/])/}],BRIDGE_PACKAGE_TOKEN=/^@bridge_gpt\/mcp-server(?:@\S+)?$/,PACKAGE_RUNNERS=new Set(["npx","pnpx","bunx"]),BRIDGE_SERVER_BINS=new Set(["mcp-server","bridge-api-mcp-server"]),ROUTE_TEXT_ONLY_EXECUTABLES=new Set(["grep","egrep","fgrep","rg","ag","cat","echo","printf","head","tail","wc","diff","less","more","ls","sort","uniq","tr","cut","jq"]);function isTextOnlyInvocation(argv){let executable=path.basename(argv[0]??"");return ROUTE_TEXT_ONLY_EXECUTABLES.has(executable)?!0:executable==="git"?!argv.some(token=>/alias\.[^=]*=\s*!/i.test(token)):executable==="find"?!argv.some(token=>["-exec","-execdir","-ok","-okdir"].includes(token)):!1}function namedOperatorOnlyRoute(token){let decoded=token;for(let i=0;i<3;i+=1){let next;try{next=decodeURIComponent(decoded)}catch{break}if(next===decoded)break;decoded=next}let haystacks=[decoded.toLowerCase(),token.toLowerCase()];for(let text of haystacks){let council=/\/driver-councils(\/[^/?#\s"'`]+)?/.exec(text);if(council)return council[1]?"record-decision":"reserve-council"}for(let route of OWNER_WORK_ROUTES)if(haystacks.some(text=>route.pattern.test(text)))return route.verb;return SEGMENT_ROUTE_VERBS.find(verb=>haystacks.some(text=>text.includes(`/${verb}`)))}var NODE_VALUE_OPTIONS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--input-type","--title","--stack-size","--max-old-space-size"]),NPM_EXEC_SUBCOMMANDS=new Set(["exec","x"]);function runnerPackageIndex(argv,start){for(let i=start;i<argv.length;i+=1){let token=argv[i];if(BRIDGE_PACKAGE_TOKEN.test(token))return{index:i,inline:!1};let inline=/^(?:--package|-p)=(.*)$/.exec(token);if(inline&&BRIDGE_PACKAGE_TOKEN.test(inline[1]))return{index:i,inline:!0}}}function firstOperand(args){return args.find(token=>!token.startsWith("-"))}function epicImplementerArgs(argv){return packagedCliArgs(argv,"epic-implementer",{bin:"epic-implementer",script:"epic-implementer-bin.js"})}function packagedCliArgs(argv,subcommand,dedicated){let base=path.basename(argv[0]??""),afterEpicImplementer=rest=>rest.length===0?[]:rest[0]===subcommand?rest.slice(1):void 0;if(dedicated&&base===dedicated.bin)return argv.slice(1);if(BRIDGE_SERVER_BINS.has(base))return afterEpicImplementer(argv.slice(1));let runnerStart=PACKAGE_RUNNERS.has(base)?1:base==="npm"&&NPM_EXEC_SUBCOMMANDS.has(argv[1]??"")?2:-1;if(runnerStart!==-1){let operands=from=>argv.slice(from).filter(t=>t!=="--"),found=runnerPackageIndex(argv,runnerStart);if(found!==void 0){let rest=operands(found.index+1),commandAt=rest.findIndex(t=>!t.startsWith("-"));return afterEpicImplementer(commandAt===-1?[]:rest.slice(commandAt))}let first=argv.slice(runnerStart).find(t=>!t.startsWith("-"));return dedicated&&first===dedicated.bin?operands(argv.indexOf(first,runnerStart)+1):void 0}if(base==="node"||base==="nodejs"){let scriptIndex=-1;for(let i=1;i<argv.length;i+=1){let token=argv[i];if(NODE_VALUE_OPTIONS.has(token)){i+=1;continue}if(!token.startsWith("-")){scriptIndex=i;break}}if(scriptIndex===-1)return;let script=argv[scriptIndex].replace(/\\/g,"/"),rest=argv.slice(scriptIndex+1);if(dedicated&&path.posix.basename(script)===dedicated.script)return rest;if(/(?:^|\/)build\/index\.js$/.test(script))return afterEpicImplementer(rest)}}function operatorVerbDecision(segment,stdinFed){let denyFor=family=>({kind:"deny",category:"operator-verb",family}),argv=segment.argv,credentialArgs=packagedCliArgs(argv,"credentials");if(credentialArgs!==void 0){let referencesAt=credentialArgs.indexOf("references");if(referencesAt!==-1&&credentialArgs.slice(referencesAt+1).includes("apply")||credentialArgs.length===0&&stdinFed||segment.unsafe&&credentialArgs.some(t=>/[$`]/.test(t)))return denyFor("credential-approval")}let cliArgs=epicImplementerArgs(argv);if(cliArgs!==void 0){let verb=firstOperand(cliArgs),named=OPERATOR_ONLY_VERBS.find(v=>verb===v||cliArgs.includes(v));if(named!==void 0)return denyFor(named);if(verb===void 0&&stdinFed||segment.unsafe&&(verb===void 0||/[$`]/.test(verb)))return denyFor("resolve-handoff")}if(!isTextOnlyInvocation(argv))for(let token of argv){let routeVerb=namedOperatorOnlyRoute(token);if(routeVerb!==void 0)return denyFor(routeVerb)}return null}var ENV_DENY={kind:"deny",category:"environment-file",family:"environment-file"};function liveDirs(state){return state.known?[state.dir,...state.alternates??[]]:[]}function makeDirState(live,pending,pendingUnknown){let uniqueLive=[...new Set(live)];if(uniqueLive.length===0)return{known:!1};let livePool=new Set(uniqueLive),uniquePending=[...new Set(pending)].filter(dir=>!livePool.has(dir)),state={known:!0,dir:uniqueLive[0]};return uniqueLive.length>1&&(state.alternates=uniqueLive.slice(1)),uniquePending.length>0&&(state.pending=uniquePending),pendingUnknown&&(state.pendingUnknown=!0),state}function settleChain(state,after){return after==="&&"||!state.known?state:state.pendingUnknown?{known:!1}:makeDirState([...liveDirs(state),...state.pending??[]],[],!1)}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rawCommandNamesProtectedEnvPath(command,paths){return paths.some(protectedPath=>new RegExp(`(?<![A-Za-z0-9_.~/-])${escapeRegExp(protectedPath)}(?=$|[\\s'"\`<>;|&()])`).test(command))}function argvNamesProtectedEnvPath(argv,scope,protectedPaths,ctx){let api=windowsPolicy(ctx)?path.win32:path,protectedSet=new Set(protectedPaths);for(let token of argv){let candidates=[token],eq=token.indexOf("=");eq>0&&candidates.push(token.slice(eq+1));for(let raw of candidates){let candidate=raw.replace(/[)}]+$/,"");if(!(candidate.length===0||candidate.startsWith("~")||/[$`]/.test(candidate))){if(api.isAbsolute(candidate)){if(protectedSet.has(api.resolve(candidate)))return!0;continue}if(scope.known){if(protectedSet.has(api.resolve(scope.dir,candidate)))return!0}else if(candidate.split(/[\\/]/).pop()===".env")return!0}}}return!1}function initialDirState(ctx,payloadCwd){let root=ctx.worktreePath;if(payloadCwd!==void 0&&payloadCwd.length===0)return{known:!1};if(windowsPolicy(ctx)){let rootResolved=windowsRoot(ctx),rootDir=rootResolved===void 0?void 0:formatWindowsLocation(rootResolved.location);if(payloadCwd===void 0)return rootDir===void 0?{known:!1}:{known:!0,dir:rootDir};let dir=resolveWindowsDirectoryString(ctx,payloadCwd,rootDir);return dir===void 0?{known:!1}:{known:!0,dir}}let rootKnown=typeof root=="string"&&path.isAbsolute(root);return payloadCwd!==void 0?path.isAbsolute(payloadCwd)?{known:!0,dir:path.resolve(payloadCwd)}:rootKnown?{known:!0,dir:path.resolve(root,payloadCwd)}:{known:!1}:rootKnown?{known:!0,dir:path.resolve(root)}:{known:!1}}function effectiveCwd(ctx,state){return state.known?resolveEffectiveCwd(ctx,state.dir):void 0}var GROUPING_WORDS=new Set(["!","{","(","}",")","if","then","else","elif","do","while","until"]);function stripShellGrouping(argv){let grouped=!1,rest=[...argv];for(;rest.length>0;){let head=rest[0];if(GROUPING_WORDS.has(head)){grouped=!0,rest=rest.slice(1);continue}/^[({]+./.test(head)&&(grouped=!0,rest=[head.replace(/^[({]+/,""),...rest.slice(1)]);break}for(;rest.length>0&&/^[)}]+$|^;;$/.test(rest[rest.length-1]);)grouped=!0,rest=rest.slice(0,-1);return grouped&&rest.length>0&&/[)}]$/.test(rest[rest.length-1])&&(rest=[...rest.slice(0,-1),rest[rest.length-1].replace(/[)}]+$/,"")]),{argv:rest,grouped}}function groupDelta(argv){let delta=0;for(let token of argv){let open=/^\(+/.exec(token);open&&(delta+=open[0].length);let close=/\)+$/.exec(token);close&&(delta-=close[0].length)}return delta}function isSequential(prevAfter,after){return(prevAfter===void 0||prevAfter===";"||prevAfter==="&&")&&(after===void 0||after===";"||after==="&&")}function nextDirState(segment,prevAfter,state,ctx,insideGroup,depth=0){let stripped=stripShellGrouping(segment.argv),argv=unwrapTransparentPrefixes(stripped.argv,ctx);argv[0]!==void 0&&executableName(argv[0],ctx)==="builtin"&&(argv=argv.slice(1));let head=executableName(argv[0]??"",ctx),isEval=EVAL_BUILTINS.has(head);if(head!=="cd"&&head!=="pushd"&&head!=="popd"&&!isEval)return settleChain(state,segment.after);if(!isSequential(prevAfter,segment.after))return prevAfter==="||"||segment.after==="||"?{known:!1}:settleChain(state,segment.after);if(stripped.grouped||insideGroup)return{known:!1};if(isEval){if(segment.unsafe||depth>=4)return{known:!1};let current=state,innerPrev;for(let inner of tokenizeShellCommand(argv.slice(1).join(" ")))current=nextDirState(inner,innerPrev,current,ctx,!1,depth+1),innerPrev=inner.after;return settleChain(current,segment.after)}if(head!=="cd")return{known:!1};let operands=[],afterDoubleDash=!1;for(let token of argv.slice(1)){if(!afterDoubleDash&&token==="--"){afterDoubleDash=!0;continue}!afterDoubleDash&&token.startsWith("-")&&token.length>1||operands.push(token)}if(operands.length!==1||segment.unsafe)return{known:!1};let target=operands[0];if(target==="-"||target.startsWith("~")||/[$`*?[(){}]/.test(target))return{known:!1};let before=liveDirs(state),moved=[];if(windowsPolicy(ctx))for(let base of state.known?before:[void 0]){let dir=resolveWindowsDirectoryString(ctx,target,base);if(dir===void 0)return{known:!1};moved.push(dir)}else if(path.isAbsolute(target))moved.push(path.resolve(target));else{if(!state.known)return{known:!1};for(let base of before)moved.push(path.resolve(base,target))}let fallbackUnknown=!state.known||state.pendingUnknown===!0,fallback=[...before,...state.known?state.pending??[]:[]];return segment.after==="&&"?makeDirState(moved,fallback,fallbackUnknown):fallbackUnknown?{known:!1}:makeDirState([...moved,...fallback],[],!1)}function evaluateCommandSequence(segments,ctx,state,depth,stdinFed,projections){let current=state,prevAfter,openGroups=0;for(let[i,segment]of segments.entries()){let decision=evaluateSimpleCommand(segment,ctx,current,depth,stdinFed,projections[i]);if(decision.kind==="deny")return decision;let delta=groupDelta(segment.argv);current=nextDirState(segment,prevAfter,current,ctx,openGroups>0||delta!==0),openGroups=Math.max(0,openGroups+delta),prevAfter=segment.after}return{kind:"allow"}}function evaluateSimpleCommand(segment,ctx,state,depth=0,stdinFed=!1,diagnostic){if(state.known&&state.alternates!==void 0&&state.alternates.length>0){for(let dir of liveDirs(state)){let decision=evaluateSimpleCommand(segment,ctx,{known:!0,dir},depth,stdinFed,diagnostic);if(decision.kind==="deny")return decision}return{kind:"allow"}}if(state.known&&(state={known:!0,dir:state.dir}),ctx.mainCheckoutEnvPaths&&ctx.mainCheckoutEnvPaths.length>0&&argvNamesProtectedEnvPath(segment.argv,state,ctx.mainCheckoutEnvPaths,ctx))return ENV_DENY;let argv=unwrapTransparentPrefixes(stripShellGrouping(segment.argv).argv,ctx),executable=argv[0];if(executable===void 0)return{kind:"allow"};let name=executableName(executable,ctx);if(SHELL_EXECUTABLES.has(name)&&depth<4){let cIndex=argv.findIndex(t=>t==="-c"),inner=cIndex===-1?void 0:argv[cIndex+1];if(inner!==void 0){let projections=diagnostic?.complete?diagnosticProjections(inner):[];return evaluateCommandSequence(tokenizeShellCommand(inner),ctx,state,depth+1,stdinFed,projections)}}if(EVAL_BUILTINS.has(name)&&depth<4){let inner=argv.slice(1).join(" "),projections=diagnostic?.complete?diagnosticProjections(inner):[];return evaluateCommandSequence(tokenizeShellCommand(inner),ctx,state,depth+1,stdinFed,projections)}if(STDIN_ARGUMENT_PREFIXES.has(name)&&depth<4){let rest=stripStdinPrefixOptions(argv);return rest.length===0?{kind:"allow"}:evaluateSimpleCommand({argv:rest,unsafe:segment.unsafe},ctx,state,depth+1,!0,diagnostic?{argv:stripStdinPrefixOptions(unwrapTransparentPrefixes(diagnostic.argv,ctx)),complete:!1}:void 0)}segment={argv,unsafe:segment.unsafe};let operatorVerb=operatorVerbDecision(segment,stdinFed);if(operatorVerb!==null)return operatorVerb;if(ctx.correctionEnforced&&isClaudeWorkflowPrintLaunch(segment))return{kind:"deny",category:"workflow-launch-shell",family:"workflow"};let family=classify(executable,ctx);if(family===null)return{kind:"allow"};let cwd=effectiveCwd(ctx,state);if(stdinFed||segment.unsafe)return unsafeSegmentDecision(family,segment.argv,ctx,cwd,diagnostic);if(family==="rm")return evaluateRemove(segment.argv,ctx,cwd);if(family==="database")return evaluateDatabase(segment.argv);if(family==="network")return evaluateNetwork(segment.argv,ctx);let git=parseGitInvocation(segment.argv,cwd,ctx);return git.subcommand==="remote"||git.subcommand==="branch"||git.subcommand==="config"?evaluateGitRouting(git.subcommand,git.args):git.subcommand==="push"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitPush(git.args,ctx):git.subcommand==="reset"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitReset(git.args,ctx):git.subcommand==="clean"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitClean(git.args,ctx,git.cwd):{kind:"allow"}}function workflowDeny(category){return{kind:"deny",category,family:"workflow"}}var FILE_TOOLS=new Set(["Read","Edit","Write","MultiEdit","NotebookEdit","Grep","Glob"]),INVOCATION_FIELDS={Skill:["skill","args"],Task:["prompt","description"],Agent:["prompt","description"],SlashCommand:["command"]},PLANNER_TOOL_NAME=/(?:request_plan_generation|get_pipeline_recipe|plan_ticket|implement_ticket)/i;function evaluateCorrectionToolRole(toolName,input){if(FILE_TOOLS.has(toolName))return{kind:"allow"};if(toolName==="Bash")return;let fields=INVOCATION_FIELDS[toolName];if(fields!==void 0){for(let field of fields){let value=input[field];if(value===void 0)continue;if(typeof value!="string")return workflowDeny("workflow-launch-skill");let nameField=toolName==="Skill"?field==="skill":toolName==="SlashCommand";if(WORKFLOW_SLASH_LAUNCH.test(value)||nameField&&WORKFLOW_NAME_EXACT.test(value.trim().split(/\s+/)[0]??""))return workflowDeny("workflow-launch-skill")}return{kind:"allow"}}if(/^mcp__/i.test(toolName)&&PLANNER_TOOL_NAME.test(toolName))return workflowDeny("workflow-planner-tool");let args=Object.values(input).filter(v=>typeof v=="string").join(" ");return WORKFLOW_SLASH_LAUNCH.test(args)?workflowDeny("workflow-entry"):void 0}function evaluateWorkerGuardPayload(payload,ctx){if(ctx.correctionContextInvalid)return workflowDeny("correction-context-invalid");let root=asRecord(payload);if(root===void 0)return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let toolName=root.tool_name??root.toolName;if(typeof toolName!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let input=asRecord(root.tool_input??root.toolInput),correctionDecision;if(ctx.correctionEnforced){if(input===void 0)return workflowDeny("correction-payload-invalid");if(correctionDecision=evaluateCorrectionToolRole(toolName,input),correctionDecision!==void 0&&correctionDecision.kind==="deny")return correctionDecision}if(windowsPolicy(ctx)&&classifyClaudeTool(toolName)==="uncovered_execution")return{kind:"deny",category:"uncovered-execution-tool",family:"execution-tool"};if(correctionDecision!==void 0)return correctionDecision;if(toolName!=="Bash")return{kind:"allow"};if(input===void 0)return{kind:"malformed"};let command=input.command;if(typeof command!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let rawCwd=root.cwd??input.cwd,payloadCwd=typeof rawCwd=="string"?rawCwd:void 0;if(ctx.mainCheckoutEnvPaths&&ctx.mainCheckoutEnvPaths.length>0&&rawCommandNamesProtectedEnvPath(command,ctx.mainCheckoutEnvPaths))return ENV_DENY;let projections=diagnosticProjections(command);return evaluateCommandSequence(tokenizeShellCommand(command),ctx,initialDirState(ctx,payloadCwd),0,!1,projections)}function evaluateWorkerGuardInput(raw,ctx){let unreadable=()=>ctx.correctionContextInvalid?workflowDeny("correction-context-invalid"):ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};if(typeof raw!="string"||raw.length>WORKER_GUARD_MAX_PAYLOAD_BYTES||raw.trim().length===0)return unreadable();let parsed;try{parsed=JSON.parse(raw)}catch{return unreadable()}try{return evaluateWorkerGuardPayload(parsed,ctx)}catch{return unreadable()}}var WORKER_GUARD_ROOT_FLAG="--worktree-root",WORKER_GUARD_ENV_PATH_FLAG="--main-checkout-env-path";function resolveWorkerGuardContext(env,cwd,argv=[],trusted={}){let ctx={},win=trusted.platform==="win32";win&&(ctx.platformPolicy="win32",trusted.identityProvider!==void 0&&(ctx.identityProvider=trusted.identityProvider));let api=win?path.win32:path,root;for(let i=0;i<argv.length;i+=1){if(argv[i]===WORKER_GUARD_ROOT_FLAG){root=argv[i+1];break}if(argv[i].startsWith(`${WORKER_GUARD_ROOT_FLAG}=`)){root=argv[i].slice(WORKER_GUARD_ROOT_FLAG.length+1);break}}root===void 0&&typeof cwd=="string"&&(root=cwd),win?typeof root=="string"&&parseWindowsLiteralPath(root).kind==="absolute"&&(ctx.worktreePath=root):typeof root=="string"&&path.isAbsolute(root)&&(ctx.worktreePath=path.resolve(root));let envPaths=[];for(let i=0;i<argv.length;i+=1){let value;if(argv[i]===WORKER_GUARD_ENV_PATH_FLAG?(value=argv[i+1],i+=1):argv[i].startsWith(`${WORKER_GUARD_ENV_PATH_FLAG}=`)&&(value=argv[i].slice(WORKER_GUARD_ENV_PATH_FLAG.length+1)),typeof value!="string"||value.length===0||!api.isAbsolute(value)||/[\u0000-\u001f\u007f]/.test(value))continue;let normalized=api.resolve(value);envPaths.includes(normalized)||envPaths.push(normalized)}envPaths.length>0&&(ctx.mainCheckoutEnvPaths=envPaths);let branch=env.BAPI_WORKER_BRANCH;typeof branch=="string"&&branch.trim().length>0&&(ctx.workerBranch=branch.trim());let flagIndex=argv.indexOf("--correction-intent-version"),flagValue=flagIndex>=0?argv[flagIndex+1]:void 0,envValue=env.BAPI_CORRECTION_INTENT_VERSION;return ctx.correctionEnforced=flagValue==="1"||envValue==="1",ctx.correctionContextInvalid=flagIndex>=0&&flagValue!=="1"||envValue!==void 0&&envValue!=="1"||flagIndex>=0&&envValue!==void 0&&envValue!==flagValue,ctx}function runWorkerGuardHook(io){let exitCode=0,correctionRequested=io.argv.includes("--correction-intent-version")||io.env.BAPI_CORRECTION_INTENT_VERSION!==void 0;try{let raw=io.readStdin(),ctx=resolveWorkerGuardContext(io.env,io.cwd,io.argv,{...io.platform!==void 0?{platform:io.platform}:{},...io.identityProvider!==void 0?{identityProvider:io.identityProvider}:{}}),decision=evaluateWorkerGuardInput(raw,ctx);decision.kind==="deny"?(io.writeStderr(renderWorkerGuardReason(decision.category,decision.family,decision.form,decision.restriction)),exitCode=2):decision.kind==="malformed"&&(io.writeStderr(WORKER_GUARD_MALFORMED_LINE),exitCode=0)}catch{try{io.writeStderr(correctionRequested?renderWorkerGuardReason("correction-payload-invalid","workflow"):WORKER_GUARD_MALFORMED_LINE)}catch{}exitCode=correctionRequested?2:0}return exitCode}function readStdinSync(){return readFileSync(0,"utf-8")}process.exit(runWorkerGuardHook({readStdin:readStdinSync,env:process.env,cwd:process.cwd(),argv:process.argv.slice(2),writeStderr:text=>{process.stderr.write(`${text}
|
|
5
|
+
`){finish(i);continue}masked+=ch}return quote&&(uncertain2=!0),finish(command.length),result}var WORKER_GUARD_MAX_PAYLOAD_BYTES=1e6;function asRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function isInside(root,candidate){let rel=path.relative(root,candidate);return rel===""?!0:rel===".."||rel.startsWith(`..${path.sep}`)?!1:!path.isAbsolute(rel)}function windowsPolicy(ctx){return ctx.platformPolicy==="win32"}function windowsRoot(ctx){let root=ctx.worktreePath,provider=ctx.identityProvider;if(typeof root!="string"||provider===void 0||parseWindowsLiteralPath(root).kind!=="absolute")return;let resolved=resolveWindowsDirectory(root,void 0,provider);return resolved.status==="resolved"?resolved.resolved:void 0}function windowsLocationOf(dir){let parsed=parseWindowsLiteralPath(dir);return parsed.kind==="absolute"?parsed.location:void 0}function resolveEffectiveCwd(ctx,payloadCwd){let root=ctx.worktreePath;if(windowsPolicy(ctx)){let rootResolved=windowsRoot(ctx),provider=ctx.identityProvider;if(rootResolved===void 0||provider===void 0)return;if(payloadCwd===void 0)return formatWindowsLocation(rootResolved.location);if(typeof payloadCwd!="string"||payloadCwd.length===0)return;let contained=windowsContainment(payloadCwd,rootResolved.location,rootResolved,"directory",provider);return contained.status==="inside"?formatWindowsLocation(contained.resolved.location):void 0}if(typeof root!="string"||!path.isAbsolute(root))return;let normalizedRoot=path.resolve(root);if(payloadCwd===void 0)return normalizedRoot;if(typeof payloadCwd!="string"||payloadCwd.length===0)return;let resolved=path.isAbsolute(payloadCwd)?path.resolve(payloadCwd):path.resolve(normalizedRoot,payloadCwd);return isInside(normalizedRoot,resolved)?resolved:void 0}function allTargetsContained(ctx,cwd,targets,intent="remove_target"){let root=ctx.worktreePath;if(cwd===void 0)return!1;if(windowsPolicy(ctx)){let rootResolved=windowsRoot(ctx),provider=ctx.identityProvider,base=windowsLocationOf(cwd);return rootResolved===void 0||provider===void 0||base===void 0?!1:targets.every(target=>windowsContainment(target,base,rootResolved,intent,provider).status==="inside")}if(typeof root!="string"||!path.isAbsolute(root))return!1;let normalizedRoot=path.resolve(root);return targets.every(target=>{if(target.length===0||target==="~"||target.startsWith("~/"))return!1;let resolved=path.isAbsolute(target)?path.resolve(target):path.resolve(cwd,target);return isInside(normalizedRoot,resolved)})}function parseGitInvocation(argv,baseCwd,ctx){let cwd=baseCwd,unsafe=!1,i=1;for(;i<argv.length;){let token=argv[i];if(token==="-C"){let dir=argv[i+1];dir===void 0||cwd===void 0?(unsafe=!0,cwd=void 0):ctx!==void 0&&windowsPolicy(ctx)?cwd=resolveWindowsDirectoryString(ctx,dir,cwd):cwd=path.isAbsolute(dir)?path.resolve(dir):path.resolve(cwd,dir),i+=2;continue}if(token==="-c"||token==="--namespace"||token==="--git-dir"||token==="--work-tree"){unsafe=!0,i+=2;continue}if(token.startsWith("-")){i+=1;continue}break}return{subcommand:argv[i]??"",args:argv.slice(i+1),cwd,unsafe}}function resolveWindowsDirectoryString(ctx,dir,base){let provider=ctx.identityProvider;if(provider===void 0)return;let baseLocation=base===void 0?void 0:windowsLocationOf(base),resolved=resolveWindowsDirectory(dir,baseLocation,provider);return resolved.status==="resolved"?formatWindowsLocation(resolved.resolved.location):void 0}function isOwnBranchDestination(destination,workerBranch){let colon=destination.indexOf(":"),dst=colon===-1?destination:destination.slice(colon+1);if(dst.length===0)return!1;let bare=dst.startsWith("+")?dst.slice(1):dst;return bare===workerBranch||bare===`refs/heads/${workerBranch}`}function evaluateGitPush(args,ctx){let deny={kind:"deny",category:"git-push",family:"git"},workerBranch=ctx.workerBranch;if(typeof workerBranch!="string"||workerBranch.trim().length===0)return deny;let positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}if(token.startsWith("-")){if(token==="--tags"||token==="--delete"||token==="-d"||token==="--mirror"||token==="--all"||token==="--branches"||token==="--prune"||token==="--follow-tags"||token.startsWith("--repo"))return deny;(token==="-o"||token==="--push-option"||token==="--receive-pack"||token==="--exec")&&(i+=1);continue}positional.push(token)}if(positional.length>0&&positional[0]!=="origin")return deny;if(positional.length<=1)return{kind:"allow"};let destinations=positional.slice(1);for(let refspec of destinations)if((refspec.startsWith("+")?refspec.slice(1):refspec).startsWith(":"))return deny;return destinations.every(d=>isOwnBranchDestination(d,workerBranch))?{kind:"allow"}:deny}var ROUTING_DENY={kind:"deny",category:"git-push",family:"git",restriction:"push-routing"},REMOTE_MUTATIONS=new Set(["add","set-url","rename","remove","rm","set-head","set-branches"]);function isRemoteMutation(args){let sub=args.find(t=>!t.startsWith("-"));return sub!==void 0&&REMOTE_MUTATIONS.has(sub)}function isUpstreamMutation(args){for(let token of args){if(token==="--")break;if(token.startsWith("--set-upstream")||token==="--unset-upstream"||/^-[^-]/.test(token)&&token.includes("u"))return!0}return!1}function isRoutingConfigKey(key){let k=key.toLowerCase();return k.startsWith("remote.")||/^branch\..+\.(?:remote|pushremote|merge)$/.test(k)||/^url\..+\.(?:insteadof|pushinsteadof)$/.test(k)?!0:k==="push.default"}function isRoutingConfigSection(name){let first=name.toLowerCase().split(".")[0];return first==="remote"||first==="branch"||first==="url"||first==="push"}var CONFIG_VALUE_OPTIONS=new Set(["-f","--file","--blob","--type","--default","--comment"]),CONFIG_READ_OPTIONS=new Set(["--get","--get-all","--get-regexp","--get-urlmatch","-l","--list","--get-color","--get-colorbool","--name-only","--show-origin","--show-scope"]),CONFIG_KEY_MUTATIONS=new Set(["--add","--unset","--unset-all","--replace-all"]);function isConfigRoutingMutation(args){let positional=[],options=new Set;for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}if(token.startsWith("-")&&token.length>1){options.add(token.split("=")[0]),CONFIG_VALUE_OPTIONS.has(token)&&(i+=1);continue}positional.push(token)}if(options.has("-e")||options.has("--edit"))return!0;let sub;if(positional.length>0&&["get","set","unset","list","edit","remove-section","rename-section"].includes(positional[0])&&(sub=positional[0]),sub==="edit")return!0;if(sub==="set"||sub==="unset"){let key=positional[1];return key!==void 0&&isRoutingConfigKey(key)}if(sub==="remove-section"){let name=positional[1];return name!==void 0&&isRoutingConfigSection(name)}if(sub==="rename-section")return positional.slice(1,3).some(isRoutingConfigSection);if(sub==="get"||sub==="list")return!1;if(options.has("--remove-section")||options.has("--rename-section"))return positional.slice(0,2).some(isRoutingConfigSection);for(let opt of options)if(CONFIG_KEY_MUTATIONS.has(opt))return positional[0]!==void 0&&isRoutingConfigKey(positional[0]);for(let opt of options)if(CONFIG_READ_OPTIONS.has(opt))return!1;return positional.length>=2?isRoutingConfigKey(positional[0]):!1}function evaluateGitRouting(subcommand,args){return subcommand==="remote"&&isRemoteMutation(args)||subcommand==="branch"&&isUpstreamMutation(args)||subcommand==="config"&&isConfigRoutingMutation(args)?ROUTING_DENY:{kind:"allow"}}function evaluateGitReset(args,ctx){let deny={kind:"deny",category:"git-reset-hard",family:"git"};if(!args.includes("--hard"))return{kind:"allow"};let positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}token.startsWith("-")||positional.push(token)}if(positional.length===0)return{kind:"allow"};let workerBranch=ctx.workerBranch;if(typeof workerBranch!="string"||workerBranch.length===0)return deny;let allowed=new Set([workerBranch,`origin/${workerBranch}`,`refs/heads/${workerBranch}`,`refs/remotes/origin/${workerBranch}`]);return positional.every(ref=>allowed.has(ref))?{kind:"allow"}:deny}function evaluateGitClean(args,ctx,cwd){let deny={kind:"deny",category:"filesystem-clean",family:"git"};if(cwd===void 0||!allTargetsContained(ctx,cwd,[cwd],"directory"))return deny;let pathspecs=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){pathspecs.push(...args.slice(i+1));break}if(token==="-e"||token==="--exclude"){i+=1;continue}token.startsWith("-")||pathspecs.push(token)}return pathspecs.length===0?{kind:"allow"}:windowsPolicy(ctx)&&pathspecs.some(p=>p.startsWith(":"))?deny:allTargetsContained(ctx,cwd,pathspecs,"pathspec")?{kind:"allow"}:deny}function isRecursiveForcedRemove(args){let recursive=!1,force=!1;for(let token of args){if(token==="--")break;if(token==="--recursive")recursive=!0;else if(token==="--force")force=!0;else{if(token.startsWith("--"))continue;if(token.startsWith("-")&&token.length>1)for(let flag of token.slice(1))(flag==="r"||flag==="R")&&(recursive=!0),flag==="f"&&(force=!0)}}return recursive&&force}function evaluateRemove(argv,ctx,cwd){let deny={kind:"deny",category:"filesystem-remove",family:"rm"},args=argv.slice(1);if(!isRecursiveForcedRemove(args))return{kind:"allow"};let targets=[],sawDoubleDash=!1;for(let token of args){if(!sawDoubleDash&&token==="--"){sawDoubleDash=!0;continue}!sawDoubleDash&&token.startsWith("-")&&token.length>1||targets.push(token)}return targets.length===0?deny:allTargetsContained(ctx,cwd,targets,"remove_target")?{kind:"allow"}:deny}function isDatabaseCommand(executable){let base=path.basename(executable);return base==="psql"||base.startsWith("pg_")}var DESTRUCTIVE_SQL=/\b(?:DROP|TRUNCATE)\b/i;function evaluateDatabase(argv){let deny={kind:"deny",category:"database-destructive",family:"psql"};return argv.slice(1).some(arg=>DESTRUCTIVE_SQL.test(arg))?deny:{kind:"allow"}}var MUTATING_METHODS=new Set(["POST","PUT","PATCH","DELETE"]);function evaluateNetwork(argv,ctx){let deny={kind:"deny",category:"network-mutating",family:"curl"},base=executableName(argv[0]??"",ctx),args=argv.slice(1);for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="-X"||token==="--request"||token==="--method"){let value=args[i+1];if(value===void 0||MUTATING_METHODS.has(value.toUpperCase()))return deny;i+=1;continue}if(token.startsWith("-X")&&token.length>2){if(MUTATING_METHODS.has(token.slice(2).toUpperCase()))return deny;continue}if(token.startsWith("--request=")||token.startsWith("--method=")){let value=token.slice(token.indexOf("=")+1);if(MUTATING_METHODS.has(value.toUpperCase()))return deny;continue}if(token==="--data"||token.startsWith("--data=")||token.startsWith("--data-")||token==="--form"||token==="-F"||token==="--upload-file"||token==="-T"||token==="--post-data"||token.startsWith("--post-data=")||token==="--post-file"||token.startsWith("--post-file=")||token==="--body-data"||token.startsWith("--body-data=")||token==="--body-file"||token.startsWith("--body-file=")||base==="curl"&&token==="-d")return deny}return{kind:"allow"}}function executableName(executable,ctx){if(ctx===void 0||!windowsPolicy(ctx))return path.basename(executable);let base=path.win32.basename(executable).toLowerCase();return base.endsWith(".exe")?base.slice(0,-4):base}function classify(executable,ctx){let base=executableName(executable,ctx);return base==="git"?"git":base==="rm"?"rm":isDatabaseCommand(base)?"database":base==="curl"||base==="wget"?"network":null}function unsafeGitCategory(argv){let{subcommand}=parseGitInvocation(argv,void 0);return subcommand==="push"?"git-push":subcommand==="reset"?"git-reset-hard":subcommand==="clean"?"filesystem-clean":"git-ambiguous"}function diagnosticPushForce(args){return args.some(t=>t==="--force"||t==="-f"||t==="--force-with-lease"||t.startsWith("--force-with-lease=")||t.startsWith("+"))}function diagnosticViolation(family,diagnostic,ctx,cwd){let full=unwrapTransparentPrefixes(diagnostic.argv,ctx),unknown=diagnostic.complete?-1:full.findIndex(t=>/[$`]/.test(t)),argv=unknown<0?full:full.slice(0,unknown);if(family==="database")return evaluateDatabase(argv).kind==="deny";if(family==="network")return evaluateNetwork(argv,ctx).kind==="deny";let git=parseGitInvocation(argv,cwd,ctx);return family==="git"&&git.subcommand==="push"&&diagnosticPushForce(git.args)?!0:diagnostic.complete?family==="rm"?evaluateRemove(argv,ctx,cwd).kind==="deny":git.unsafe?!0:git.subcommand==="push"?evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1:family==="rm"?argv.slice(1).some(t=>!t.startsWith("-"))&&evaluateRemove(argv,ctx,cwd).kind==="deny":git.subcommand==="push"?git.args.filter(t=>!t.startsWith("-")).length>=2&&evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?git.args.some(t=>!t.startsWith("-"))&&evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1}function unsafeSegmentDecision(family,argv,ctx,cwd,diagnostic){let category=family==="git"?unsafeGitCategory(argv):family==="rm"?"filesystem-remove":family==="database"?"database-destructive":"network-mutating",decision={kind:"deny",category,family:family==="database"?"psql":family==="network"?"curl":family};return diagnostic&&category!=="git-ambiguous"&&!diagnosticViolation(family,diagnostic,ctx,cwd)?{...decision,form:"shell_form"}:decision}var TRANSPARENT_PREFIXES=new Set(["sudo","env","command","nohup","time","nice","exec"]),STDIN_ARGUMENT_PREFIXES=new Set(["xargs"]),SHELL_EXECUTABLES=new Set(["sh","bash","zsh","dash","ksh"]),EVAL_BUILTINS=new Set(["eval"]);function unwrapTransparentPrefixes(argv,ctx){let rest=argv;for(let depth=0;depth<8;depth+=1){let head=rest[0];if(head===void 0||!TRANSPARENT_PREFIXES.has(executableName(head,ctx)))return rest;let i=1;for(;i<rest.length;){let token=rest[i];if(executableName(head,ctx)==="env"&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){i+=1;continue}if(token.startsWith("-")){i+=1;continue}break}rest=rest.slice(i)}return rest}function stripStdinPrefixOptions(argv){let VALUE_OPTS=new Set(["-I","-i","-L","-n","-P","-s","-d","-E","-e","-a","--replace","--max-lines","--max-args","--max-procs","--max-chars","--delimiter","--eof","--arg-file"]),i=1;for(;i<argv.length;){let token=argv[i];if(token==="--"){i+=1;break}if(!token.startsWith("-"))break;if(token.includes("=")){i+=1;continue}i+=VALUE_OPTS.has(token)?2:1}return argv.slice(i)}var WORKFLOW_NAMES="implement-ticket|plan-ticket|idea-to-pr|review-and-implement",WORKFLOW_SLASH_LAUNCH=new RegExp(`(?:^|\\s)/(?:bridge-)?(?:${WORKFLOW_NAMES})(?=\\s|$)`,"i"),WORKFLOW_NAME_EXACT=new RegExp(`^/?(?:[A-Za-z0-9_-]+:)?(?:bridge-)?(?:${WORKFLOW_NAMES})$`,"i"),CLAUDE_PACKAGE_TOKEN=/^(?:@anthropic-ai\/)?claude(?:-code)?(?:@\S+)?$/;function claudeLaunchArgs(argv){let base=path.basename(argv[0]??"");if(base==="claude")return argv.slice(1);if(base==="npx"){let index=argv.findIndex((token,i)=>i>0&&CLAUDE_PACKAGE_TOKEN.test(token));return index===-1?void 0:argv.slice(index+1)}}function isClaudeWorkflowPrintLaunch(segment){let args=claudeLaunchArgs(segment.argv);return args===void 0||!args.some(token=>token==="-p"||token==="--print"||token.startsWith("--print="))?!1:segment.unsafe?!0:args.some(token=>{let value=token.startsWith("--print=")?token.slice(8):token;return WORKFLOW_SLASH_LAUNCH.test(value)})}var OPERATOR_ONLY_VERBS=["resolve-handoff","regenerate-plan","acknowledge-gaps","reserve-council","record-decision","resolve-owner-work","owner-work-transfer"],SEGMENT_ROUTE_VERBS=OPERATOR_ONLY_VERBS.filter(verb=>verb!=="resolve-owner-work"&&verb!=="owner-work-transfer"),OWNER_WORK_ROUTES=[{verb:"resolve-owner-work",pattern:/\/jira\/epic-runs\/runs\/[^/?#\s]+\/owner-work\/[^/?#\s]+\/resolve\/?(?=$|[^A-Za-z0-9_\-.~%/])/},{verb:"owner-work-transfer",pattern:/\/jira\/epic-runs\/epics\/[^/?#\s]+\/owner-work\/transfers\/?(?=$|[^A-Za-z0-9_\-.~%/])/}],BRIDGE_PACKAGE_TOKEN=/^@bridge_gpt\/mcp-server(?:@\S+)?$/,PACKAGE_RUNNERS=new Set(["npx","pnpx","bunx"]),BRIDGE_SERVER_BINS=new Set(["mcp-server","bridge-api-mcp-server"]),ROUTE_TEXT_ONLY_EXECUTABLES=new Set(["grep","egrep","fgrep","rg","ag","cat","echo","printf","head","tail","wc","diff","less","more","ls","sort","uniq","tr","cut","jq"]);function isTextOnlyInvocation(argv){let executable=path.basename(argv[0]??"");return ROUTE_TEXT_ONLY_EXECUTABLES.has(executable)?!0:executable==="git"?!argv.some(token=>/alias\.[^=]*=\s*!/i.test(token)):executable==="find"?!argv.some(token=>["-exec","-execdir","-ok","-okdir"].includes(token)):!1}function namedOperatorOnlyRoute(token){let decoded=token;for(let i=0;i<3;i+=1){let next;try{next=decodeURIComponent(decoded)}catch{break}if(next===decoded)break;decoded=next}let haystacks=[decoded.toLowerCase(),token.toLowerCase()];for(let text of haystacks){let council=/\/driver-councils(\/[^/?#\s"'`]+)?/.exec(text);if(council)return council[1]?"record-decision":"reserve-council"}for(let route of OWNER_WORK_ROUTES)if(haystacks.some(text=>route.pattern.test(text)))return route.verb;return SEGMENT_ROUTE_VERBS.find(verb=>haystacks.some(text=>text.includes(`/${verb}`)))}var NODE_VALUE_OPTIONS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--input-type","--title","--stack-size","--max-old-space-size"]),NPM_EXEC_SUBCOMMANDS=new Set(["exec","x"]);function runnerPackageIndex(argv,start){for(let i=start;i<argv.length;i+=1){let token=argv[i];if(BRIDGE_PACKAGE_TOKEN.test(token))return{index:i,inline:!1};let inline=/^(?:--package|-p)=(.*)$/.exec(token);if(inline&&BRIDGE_PACKAGE_TOKEN.test(inline[1]))return{index:i,inline:!0}}}function firstOperand(args){return args.find(token=>!token.startsWith("-"))}function epicImplementerArgs(argv){return packagedCliArgs(argv,"epic-implementer",{bin:"epic-implementer",script:"epic-implementer-bin.js"})}function packagedCliArgs(argv,subcommand,dedicated){let base=path.basename(argv[0]??""),afterEpicImplementer=rest=>rest.length===0?[]:rest[0]===subcommand?rest.slice(1):void 0;if(dedicated&&base===dedicated.bin)return argv.slice(1);if(BRIDGE_SERVER_BINS.has(base))return afterEpicImplementer(argv.slice(1));let runnerStart=PACKAGE_RUNNERS.has(base)?1:base==="npm"&&NPM_EXEC_SUBCOMMANDS.has(argv[1]??"")?2:-1;if(runnerStart!==-1){let operands=from=>argv.slice(from).filter(t=>t!=="--"),found=runnerPackageIndex(argv,runnerStart);if(found!==void 0){let rest=operands(found.index+1),commandAt=rest.findIndex(t=>!t.startsWith("-"));return afterEpicImplementer(commandAt===-1?[]:rest.slice(commandAt))}let first=argv.slice(runnerStart).find(t=>!t.startsWith("-"));return dedicated&&first===dedicated.bin?operands(argv.indexOf(first,runnerStart)+1):void 0}if(base==="node"||base==="nodejs"){let scriptIndex=-1;for(let i=1;i<argv.length;i+=1){let token=argv[i];if(NODE_VALUE_OPTIONS.has(token)){i+=1;continue}if(!token.startsWith("-")){scriptIndex=i;break}}if(scriptIndex===-1)return;let script=argv[scriptIndex].replace(/\\/g,"/"),rest=argv.slice(scriptIndex+1);if(dedicated&&path.posix.basename(script)===dedicated.script)return rest;if(/(?:^|\/)build\/index\.js$/.test(script))return afterEpicImplementer(rest)}}function operatorVerbDecision(segment,stdinFed){let denyFor=family=>({kind:"deny",category:"operator-verb",family}),argv=segment.argv,credentialArgs=packagedCliArgs(argv,"credentials");if(credentialArgs!==void 0){let referencesAt=credentialArgs.indexOf("references");if(referencesAt!==-1&&credentialArgs.slice(referencesAt+1).includes("apply")||credentialArgs.length===0&&stdinFed||segment.unsafe&&credentialArgs.some(t=>/[$`]/.test(t)))return denyFor("credential-approval")}let cliArgs=epicImplementerArgs(argv);if(cliArgs!==void 0){let verb=firstOperand(cliArgs),named=OPERATOR_ONLY_VERBS.find(v=>verb===v||cliArgs.includes(v));if(named!==void 0)return denyFor(named);if(verb===void 0&&stdinFed||segment.unsafe&&(verb===void 0||/[$`]/.test(verb)))return denyFor("resolve-handoff")}if(!isTextOnlyInvocation(argv))for(let token of argv){let routeVerb=namedOperatorOnlyRoute(token);if(routeVerb!==void 0)return denyFor(routeVerb)}return null}var ENV_DENY={kind:"deny",category:"environment-file",family:"environment-file"};function liveDirs(state){return state.known?[state.dir,...state.alternates??[]]:[]}function makeDirState(live,pending,pendingUnknown){let uniqueLive=[...new Set(live)];if(uniqueLive.length===0)return{known:!1};let livePool=new Set(uniqueLive),uniquePending=[...new Set(pending)].filter(dir=>!livePool.has(dir)),state={known:!0,dir:uniqueLive[0]};return uniqueLive.length>1&&(state.alternates=uniqueLive.slice(1)),uniquePending.length>0&&(state.pending=uniquePending),pendingUnknown&&(state.pendingUnknown=!0),state}function settleChain(state,after){return after==="&&"||!state.known?state:state.pendingUnknown?{known:!1}:makeDirState([...liveDirs(state),...state.pending??[]],[],!1)}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rawCommandNamesProtectedEnvPath(command,paths){return paths.some(protectedPath=>new RegExp(`(?<![A-Za-z0-9_.~/-])${escapeRegExp(protectedPath)}(?=$|[\\s'"\`<>;|&()])`).test(command))}function argvNamesProtectedEnvPath(argv,scope,protectedPaths,ctx){let api=windowsPolicy(ctx)?path.win32:path,protectedSet=new Set(protectedPaths);for(let token of argv){let candidates=[token],eq=token.indexOf("=");eq>0&&candidates.push(token.slice(eq+1));for(let raw of candidates){let candidate=raw.replace(/[)}]+$/,"");if(!(candidate.length===0||candidate.startsWith("~")||/[$`]/.test(candidate))){if(api.isAbsolute(candidate)){if(protectedSet.has(api.resolve(candidate)))return!0;continue}if(scope.known){if(protectedSet.has(api.resolve(scope.dir,candidate)))return!0}else if(candidate.split(/[\\/]/).pop()===".env")return!0}}}return!1}function initialDirState(ctx,payloadCwd){let root=ctx.worktreePath;if(payloadCwd!==void 0&&payloadCwd.length===0)return{known:!1};if(windowsPolicy(ctx)){let rootResolved=windowsRoot(ctx),rootDir=rootResolved===void 0?void 0:formatWindowsLocation(rootResolved.location);if(payloadCwd===void 0)return rootDir===void 0?{known:!1}:{known:!0,dir:rootDir};let dir=resolveWindowsDirectoryString(ctx,payloadCwd,rootDir);return dir===void 0?{known:!1}:{known:!0,dir}}let rootKnown=typeof root=="string"&&path.isAbsolute(root);return payloadCwd!==void 0?path.isAbsolute(payloadCwd)?{known:!0,dir:path.resolve(payloadCwd)}:rootKnown?{known:!0,dir:path.resolve(root,payloadCwd)}:{known:!1}:rootKnown?{known:!0,dir:path.resolve(root)}:{known:!1}}function effectiveCwd(ctx,state){return state.known?resolveEffectiveCwd(ctx,state.dir):void 0}var GROUPING_WORDS=new Set(["!","{","(","}",")","if","then","else","elif","do","while","until"]);function stripShellGrouping(argv){let grouped=!1,rest=[...argv];for(;rest.length>0;){let head=rest[0];if(GROUPING_WORDS.has(head)){grouped=!0,rest=rest.slice(1);continue}/^[({]+./.test(head)&&(grouped=!0,rest=[head.replace(/^[({]+/,""),...rest.slice(1)]);break}for(;rest.length>0&&/^[)}]+$|^;;$/.test(rest[rest.length-1]);)grouped=!0,rest=rest.slice(0,-1);return grouped&&rest.length>0&&/[)}]$/.test(rest[rest.length-1])&&(rest=[...rest.slice(0,-1),rest[rest.length-1].replace(/[)}]+$/,"")]),{argv:rest,grouped}}function groupDelta(argv){let delta=0;for(let token of argv){let open=/^\(+/.exec(token);open&&(delta+=open[0].length);let close=/\)+$/.exec(token);close&&(delta-=close[0].length)}return delta}function isSequential(prevAfter,after){return(prevAfter===void 0||prevAfter===";"||prevAfter==="&&")&&(after===void 0||after===";"||after==="&&")}function nextDirState(segment,prevAfter,state,ctx,insideGroup,depth=0){let stripped=stripShellGrouping(segment.argv),argv=unwrapTransparentPrefixes(stripped.argv,ctx);argv[0]!==void 0&&executableName(argv[0],ctx)==="builtin"&&(argv=argv.slice(1));let head=executableName(argv[0]??"",ctx),isEval=EVAL_BUILTINS.has(head);if(head!=="cd"&&head!=="pushd"&&head!=="popd"&&!isEval)return settleChain(state,segment.after);if(!isSequential(prevAfter,segment.after))return prevAfter==="||"||segment.after==="||"?{known:!1}:settleChain(state,segment.after);if(stripped.grouped||insideGroup)return{known:!1};if(isEval){if(segment.unsafe||depth>=4)return{known:!1};let current=state,innerPrev;for(let inner of tokenizeShellCommand(argv.slice(1).join(" ")))current=nextDirState(inner,innerPrev,current,ctx,!1,depth+1),innerPrev=inner.after;return settleChain(current,segment.after)}if(head!=="cd")return{known:!1};let operands=[],afterDoubleDash=!1;for(let token of argv.slice(1)){if(!afterDoubleDash&&token==="--"){afterDoubleDash=!0;continue}!afterDoubleDash&&token.startsWith("-")&&token.length>1||operands.push(token)}if(operands.length!==1||segment.unsafe)return{known:!1};let target=operands[0];if(target==="-"||target.startsWith("~")||/[$`*?[(){}]/.test(target))return{known:!1};let before=liveDirs(state),moved=[];if(windowsPolicy(ctx))for(let base of state.known?before:[void 0]){let dir=resolveWindowsDirectoryString(ctx,target,base);if(dir===void 0)return{known:!1};moved.push(dir)}else if(path.isAbsolute(target))moved.push(path.resolve(target));else{if(!state.known)return{known:!1};for(let base of before)moved.push(path.resolve(base,target))}let fallbackUnknown=!state.known||state.pendingUnknown===!0,fallback=[...before,...state.known?state.pending??[]:[]];return segment.after==="&&"?makeDirState(moved,fallback,fallbackUnknown):fallbackUnknown?{known:!1}:makeDirState([...moved,...fallback],[],!1)}function evaluateCommandSequence(segments,ctx,state,depth,stdinFed,projections){let current=state,prevAfter,openGroups=0;for(let[i,segment]of segments.entries()){let decision=evaluateSimpleCommand(segment,ctx,current,depth,stdinFed,projections[i]);if(decision.kind==="deny")return decision;let delta=groupDelta(segment.argv);current=nextDirState(segment,prevAfter,current,ctx,openGroups>0||delta!==0),openGroups=Math.max(0,openGroups+delta),prevAfter=segment.after}return{kind:"allow"}}function evaluateSimpleCommand(segment,ctx,state,depth=0,stdinFed=!1,diagnostic){if(state.known&&state.alternates!==void 0&&state.alternates.length>0){for(let dir of liveDirs(state)){let decision=evaluateSimpleCommand(segment,ctx,{known:!0,dir,ambiguousDir:!0},depth,stdinFed,diagnostic);if(decision.kind==="deny")return decision}return{kind:"allow"}}if(state.known&&(state=state.ambiguousDir?{known:!0,dir:state.dir,ambiguousDir:!0}:{known:!0,dir:state.dir}),ctx.mainCheckoutEnvPaths&&ctx.mainCheckoutEnvPaths.length>0&&argvNamesProtectedEnvPath(segment.argv,state,ctx.mainCheckoutEnvPaths,ctx))return ENV_DENY;let argv=unwrapTransparentPrefixes(stripShellGrouping(segment.argv).argv,ctx),executable=argv[0];if(executable===void 0)return{kind:"allow"};let name=executableName(executable,ctx);if(SHELL_EXECUTABLES.has(name)&&depth<4){let cIndex=argv.findIndex(t=>t==="-c"),inner=cIndex===-1?void 0:argv[cIndex+1];if(inner!==void 0){let projections=diagnostic?.complete?diagnosticProjections(inner):[];return evaluateCommandSequence(tokenizeShellCommand(inner),ctx,state,depth+1,stdinFed,projections)}}if(EVAL_BUILTINS.has(name)&&depth<4){let inner=argv.slice(1).join(" "),projections=diagnostic?.complete?diagnosticProjections(inner):[];return evaluateCommandSequence(tokenizeShellCommand(inner),ctx,state,depth+1,stdinFed,projections)}if(STDIN_ARGUMENT_PREFIXES.has(name)&&depth<4){let rest=stripStdinPrefixOptions(argv);return rest.length===0?{kind:"allow"}:evaluateSimpleCommand({argv:rest,unsafe:segment.unsafe},ctx,state,depth+1,!0,diagnostic?{argv:stripStdinPrefixOptions(unwrapTransparentPrefixes(diagnostic.argv,ctx)),complete:!1}:void 0)}segment={argv,unsafe:segment.unsafe};let operatorVerb=operatorVerbDecision(segment,stdinFed);if(operatorVerb!==null)return operatorVerb;if(ctx.correctionEnforced&&isClaudeWorkflowPrintLaunch(segment))return{kind:"deny",category:"workflow-launch-shell",family:"workflow"};let family=classify(executable,ctx);if(family===null)return{kind:"allow"};let cwd=effectiveCwd(ctx,state);if(stdinFed||segment.unsafe)return unsafeSegmentDecision(family,segment.argv,ctx,cwd,diagnostic);if(family==="rm")return evaluateRemove(segment.argv,ctx,cwd);if(family==="database")return evaluateDatabase(segment.argv);if(family==="network")return evaluateNetwork(segment.argv,ctx);let git=parseGitInvocation(segment.argv,cwd,ctx);if(git.subcommand==="remote"||git.subcommand==="branch"||git.subcommand==="config")return evaluateGitRouting(git.subcommand,git.args);if(git.subcommand==="push")return git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitPush(git.args,ctx);if(git.subcommand==="reset")return git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitReset(git.args,ctx);if(git.subcommand==="clean")return git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitClean(git.args,ctx,git.cwd);if(git.subcommand==="commit"){let provenDirectory=git.unsafe||state.known&&state.ambiguousDir===!0?void 0:git.cwd;return evaluateGitCommit(git.args,ctx,provenDirectory)}return{kind:"allow"}}var CI_SKIP_MARKERS=["[skip ci]","[ci skip]","[no ci]","[skip actions]","[actions skip]","skip-checks: true"];function carriesCiSkipMarker(text){let lower=text.toLowerCase();return CI_SKIP_MARKERS.some(marker=>lower.includes(marker))}var COMMIT_SHORT_VALUE_OPTIONS=new Set(["m","F","C","c","t"]),COMMIT_SHORT_ATTACHED_ONLY=new Set(["S","u"]),COMMIT_LONG_VALUE_OPTIONS=["message","file","reuse-message","reedit-message","fixup","squash","author","date","template","cleanup","pathspec-from-file","trailer"],MAX_COMMIT_MESSAGE_FILES=32;function commitLongValueOption(name){if(COMMIT_LONG_VALUE_OPTIONS.includes(name))return name;if(name.length<3)return;let matches=COMMIT_LONG_VALUE_OPTIONS.filter(option=>option.startsWith(name));return matches.length===1?matches[0]:void 0}function parseCommitMessageInputs(args){let inline=[],files=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--")break;if(token.startsWith("--")){let eq=token.indexOf("="),option=commitLongValueOption(eq===-1?token.slice(2):token.slice(2,eq));if(option===void 0)continue;let value;if(eq!==-1?value=token.slice(eq+1):(value=args[i+1],i+=1),value===void 0)continue;option==="message"?inline.push(value):option==="file"&&files.push(value);continue}if(token.length>1&&token.startsWith("-"))for(let j=1;j<token.length;j+=1){let letter=token[j];if(COMMIT_SHORT_VALUE_OPTIONS.has(letter)){let attached=token.slice(j+1),value;attached.length>0?value=attached:(value=args[i+1],i+=1),value!==void 0&&(letter==="m"?inline.push(value):letter==="F"&&files.push(value));break}if(COMMIT_SHORT_ATTACHED_ONLY.has(letter))break}}return{inline,files}}function isLiteralMessageFileOperand(operand){return operand.length>0&&operand!=="-"&&!/[$`*?[\]{}\x00-\x1f]/.test(operand)&&!operand.startsWith("~")}function evaluateGitCommit(args,ctx,directory){let deny={kind:"deny",category:"git-commit-ci-skip",family:"git"},inputs;try{inputs=parseCommitMessageInputs(args)}catch{return{kind:"allow"}}if(inputs.inline.some(carriesCiSkipMarker))return deny;let read=ctx.readCommitMessageFile;if(read===void 0||directory===void 0)return{kind:"allow"};for(let operand of inputs.files.slice(0,MAX_COMMIT_MESSAGE_FILES)){if(!isLiteralMessageFileOperand(operand))continue;let text;try{text=read({directory,operand})}catch{continue}if(typeof text=="string"&&carriesCiSkipMarker(text))return deny}return{kind:"allow"}}function workflowDeny(category){return{kind:"deny",category,family:"workflow"}}var FILE_TOOLS=new Set(["Read","Edit","Write","MultiEdit","NotebookEdit","Grep","Glob"]),INVOCATION_FIELDS={Skill:["skill","args"],Task:["prompt","description"],Agent:["prompt","description"],SlashCommand:["command"]},PLANNER_TOOL_NAME=/(?:request_plan_generation|get_pipeline_recipe|plan_ticket|implement_ticket)/i;function evaluateCorrectionToolRole(toolName,input){if(FILE_TOOLS.has(toolName))return{kind:"allow"};if(toolName==="Bash")return;let fields=INVOCATION_FIELDS[toolName];if(fields!==void 0){for(let field of fields){let value=input[field];if(value===void 0)continue;if(typeof value!="string")return workflowDeny("workflow-launch-skill");let nameField=toolName==="Skill"?field==="skill":toolName==="SlashCommand";if(WORKFLOW_SLASH_LAUNCH.test(value)||nameField&&WORKFLOW_NAME_EXACT.test(value.trim().split(/\s+/)[0]??""))return workflowDeny("workflow-launch-skill")}return{kind:"allow"}}if(/^mcp__/i.test(toolName)&&PLANNER_TOOL_NAME.test(toolName))return workflowDeny("workflow-planner-tool");let args=Object.values(input).filter(v=>typeof v=="string").join(" ");return WORKFLOW_SLASH_LAUNCH.test(args)?workflowDeny("workflow-entry"):void 0}function evaluateWorkerGuardPayload(payload,ctx){if(ctx.correctionContextInvalid)return workflowDeny("correction-context-invalid");let root=asRecord(payload);if(root===void 0)return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let toolName=root.tool_name??root.toolName;if(typeof toolName!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let input=asRecord(root.tool_input??root.toolInput),correctionDecision;if(ctx.correctionEnforced){if(input===void 0)return workflowDeny("correction-payload-invalid");if(correctionDecision=evaluateCorrectionToolRole(toolName,input),correctionDecision!==void 0&&correctionDecision.kind==="deny")return correctionDecision}if(windowsPolicy(ctx)&&classifyClaudeTool(toolName)==="uncovered_execution")return{kind:"deny",category:"uncovered-execution-tool",family:"execution-tool"};if(correctionDecision!==void 0)return correctionDecision;if(toolName!=="Bash")return{kind:"allow"};if(input===void 0)return{kind:"malformed"};let command=input.command;if(typeof command!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let rawCwd=root.cwd??input.cwd,payloadCwd=typeof rawCwd=="string"?rawCwd:void 0;if(ctx.mainCheckoutEnvPaths&&ctx.mainCheckoutEnvPaths.length>0&&rawCommandNamesProtectedEnvPath(command,ctx.mainCheckoutEnvPaths))return ENV_DENY;let projections=diagnosticProjections(command);return evaluateCommandSequence(tokenizeShellCommand(command),ctx,initialDirState(ctx,payloadCwd),0,!1,projections)}function evaluateWorkerGuardInput(raw,ctx){let unreadable=()=>ctx.correctionContextInvalid?workflowDeny("correction-context-invalid"):ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};if(typeof raw!="string"||raw.length>WORKER_GUARD_MAX_PAYLOAD_BYTES||raw.trim().length===0)return unreadable();let parsed;try{parsed=JSON.parse(raw)}catch{return unreadable()}try{return evaluateWorkerGuardPayload(parsed,ctx)}catch{return unreadable()}}var WORKER_GUARD_ROOT_FLAG="--worktree-root",WORKER_GUARD_ENV_PATH_FLAG="--main-checkout-env-path";function resolveWorkerGuardContext(env,cwd,argv=[],trusted={}){let ctx={},win=trusted.platform==="win32";win&&(ctx.platformPolicy="win32",trusted.identityProvider!==void 0&&(ctx.identityProvider=trusted.identityProvider));let api=win?path.win32:path,root;for(let i=0;i<argv.length;i+=1){if(argv[i]===WORKER_GUARD_ROOT_FLAG){root=argv[i+1];break}if(argv[i].startsWith(`${WORKER_GUARD_ROOT_FLAG}=`)){root=argv[i].slice(WORKER_GUARD_ROOT_FLAG.length+1);break}}root===void 0&&typeof cwd=="string"&&(root=cwd),win?typeof root=="string"&&parseWindowsLiteralPath(root).kind==="absolute"&&(ctx.worktreePath=root):typeof root=="string"&&path.isAbsolute(root)&&(ctx.worktreePath=path.resolve(root));let envPaths=[];for(let i=0;i<argv.length;i+=1){let value;if(argv[i]===WORKER_GUARD_ENV_PATH_FLAG?(value=argv[i+1],i+=1):argv[i].startsWith(`${WORKER_GUARD_ENV_PATH_FLAG}=`)&&(value=argv[i].slice(WORKER_GUARD_ENV_PATH_FLAG.length+1)),typeof value!="string"||value.length===0||!api.isAbsolute(value)||/[\u0000-\u001f\u007f]/.test(value))continue;let normalized=api.resolve(value);envPaths.includes(normalized)||envPaths.push(normalized)}envPaths.length>0&&(ctx.mainCheckoutEnvPaths=envPaths);let branch=env.BAPI_WORKER_BRANCH;typeof branch=="string"&&branch.trim().length>0&&(ctx.workerBranch=branch.trim());let flagIndex=argv.indexOf("--correction-intent-version"),flagValue=flagIndex>=0?argv[flagIndex+1]:void 0,envValue=env.BAPI_CORRECTION_INTENT_VERSION;return ctx.correctionEnforced=flagValue==="1"||envValue==="1",ctx.correctionContextInvalid=flagIndex>=0&&flagValue!=="1"||envValue!==void 0&&envValue!=="1"||flagIndex>=0&&envValue!==void 0&&envValue!==flagValue,ctx}import{constants as fsConstants}from"node:fs";import*as nodeFs from"node:fs";import path3 from"node:path";import path2 from"path";var PUBLICATION_TEMP_PREFIX=".bridge-fill-",PUBLICATION_TEMP_SUFFIX=".tmp",PUBLICATION_TEMP_PATTERN=`${PUBLICATION_TEMP_PREFIX}*${PUBLICATION_TEMP_SUFFIX}`;function publicationPathApi(platform){return platform==="win32"?path2.win32:path2.posix}function isCaseInsensitivePlatform(platform){return platform==="win32"||platform==="darwin"}function isContained(parent,child,platform){let api=publicationPathApi(platform),fold=value=>isCaseInsensitivePlatform(platform)?value.toLowerCase():value,relative=api.relative(fold(api.normalize(parent)),fold(api.normalize(child)));return relative===""||!relative.startsWith("..")&&!api.isAbsolute(relative)}var COMMIT_MESSAGE_FILE_BYTE_CAP=65536;function createNodeMessageFileFs(){let noBlock=typeof fsConstants.O_NONBLOCK=="number"?fsConstants.O_NONBLOCK:0,noFollow=typeof fsConstants.O_NOFOLLOW=="number"?fsConstants.O_NOFOLLOW:0;return{realpath:filePath=>nodeFs.realpathSync.native(filePath),openReadOnly:filePath=>nodeFs.openSync(filePath,fsConstants.O_RDONLY|noBlock|noFollow),fstat:fd=>nodeFs.fstatSync(fd,{bigint:!0}),stat:filePath=>nodeFs.statSync(filePath,{bigint:!0}),read:(fd,buffer,offset,length)=>nodeFs.readSync(fd,buffer,offset,length,null),close:fd=>nodeFs.closeSync(fd)}}var WINDOWS_DEVICE_NAME=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i;function isReadableOperandForm(operand,platform){if(operand.length===0||operand.length>4096||operand==="-"||/[\x00-\x1f\x7f]/.test(operand))return!1;let segments=operand.split(/[\\/]+/);if(segments.some(segment=>segment===".."))return!1;if(platform==="win32"){if(operand.startsWith("\\\\")||operand.startsWith("//"))return!1;let withoutDrive=operand.replace(/^[A-Za-z]:/,"");if(withoutDrive.includes(":")||/[<>"|?*]/.test(withoutDrive)||segments.some(segment=>/[. ]$/.test(segment)&&segment!=="."||WINDOWS_DEVICE_NAME.test(segment)))return!1}return!0}function createTrustedMessageFileReader(options){let{root,platform}=options,api=platform==="win32"?path3.win32:path3.posix;if(typeof root!="string"||!api.isAbsolute(root))return;let fs=options.fs??createNodeMessageFileFs(),cap=options.byteCap??COMMIT_MESSAGE_FILE_BYTE_CAP;return({directory,operand})=>{if(typeof directory!="string"||typeof operand!="string"||!api.isAbsolute(directory)||!isReadableOperandForm(operand,platform))return;let fd;try{let realRoot=fs.realpath(root),realDirectory=fs.realpath(directory);if(!isContained(realRoot,realDirectory,platform))return;let target=api.isAbsolute(operand)?operand:api.join(realDirectory,operand);fd=fs.openReadOnly(target);let opened=fs.fstat(fd);if(!opened.isFile()||Number(opened.ino)===0)return;let physical=fs.realpath(target);if(!isContained(realRoot,physical,platform))return;let identity=fs.stat(physical);if(!identity.isFile()||identity.dev!==opened.dev||identity.ino!==opened.ino)return;let buffer=Buffer.alloc(cap+1),total=0;for(;total<=cap;){let count=fs.read(fd,buffer,total,cap+1-total);if(count<=0)break;total+=count}return total>cap||fs.realpath(target)!==physical?void 0:buffer.subarray(0,total).toString("utf-8")}catch{return}finally{if(fd!==void 0)try{fs.close(fd)}catch{}}}}function runWorkerGuardHook(io){let exitCode=0,correctionRequested=io.argv.includes("--correction-intent-version")||io.env.BAPI_CORRECTION_INTENT_VERSION!==void 0;try{let raw=io.readStdin(),ctx=resolveWorkerGuardContext(io.env,io.cwd,io.argv,{...io.platform!==void 0?{platform:io.platform}:{},...io.identityProvider!==void 0?{identityProvider:io.identityProvider}:{}}),reader=createTrustedMessageFileReader({root:ctx.worktreePath??"",platform:io.platform==="win32"?"win32":"linux",...io.messageFileFs!==void 0?{fs:io.messageFileFs}:{}});reader!==void 0&&(ctx.readCommitMessageFile=reader);let decision=evaluateWorkerGuardInput(raw,ctx);decision.kind==="deny"?(io.writeStderr(renderWorkerGuardReason(decision.category,decision.family,decision.form,decision.restriction)),exitCode=2):decision.kind==="malformed"&&(io.writeStderr(WORKER_GUARD_MALFORMED_LINE),exitCode=0)}catch{try{io.writeStderr(correctionRequested?renderWorkerGuardReason("correction-payload-invalid","workflow"):WORKER_GUARD_MALFORMED_LINE)}catch{}exitCode=correctionRequested?2:0}return exitCode}function readStdinSync(){return readFileSync(0,"utf-8")}process.exit(runWorkerGuardHook({readStdin:readStdinSync,env:process.env,cwd:process.cwd(),argv:process.argv.slice(2),writeStderr:text=>{process.stderr.write(`${text}
|
|
6
6
|
`)},platform:process.platform,...process.platform==="win32"?{identityProvider:createHostWindowsIdentityProvider({lstat:p=>lstatSync(p,{bigint:!0}),readlink:p=>readlinkSync(p)})}:{}}));
|
|
@@ -14,6 +14,19 @@ The one first-run guide is
|
|
|
14
14
|
`docs/install/epic-implementer-install.md`. Run it again at any time to refresh
|
|
15
15
|
the file.
|
|
16
16
|
|
|
17
|
+
## For agents: the merge question
|
|
18
|
+
|
|
19
|
+
Setup asks "How should Epic Implementer merge finished work into the epic
|
|
20
|
+
branch?" The options are `gh_login` (the person's GitHub sign-in, when offered),
|
|
21
|
+
`reference` (a dedicated token), `off` (set up without unattended merges), and
|
|
22
|
+
`decline`. Propose the recommendation, then relay the question with the account
|
|
23
|
+
and repository it names, and wait for the person's own answer.
|
|
24
|
+
|
|
25
|
+
An agent never accepts personal-login consent on the person's behalf. An agent
|
|
26
|
+
never runs `install epic-implementer --use-gh-login`. That command is the
|
|
27
|
+
person's approval, and it fails closed outside an interactive terminal. Relay
|
|
28
|
+
the command for the person to run instead.
|
|
29
|
+
|
|
17
30
|
The first run has four steps: install, set up (`npx -y @bridge_gpt/mcp-server
|
|
18
31
|
install conductor`), define the epic (`/define-tickets`), and launch it
|
|
19
32
|
(`/drive-epic-run <EPIC>`). For every option and command, read
|
package/docs/EPIC-IMPLEMENTER.md
CHANGED
|
@@ -889,6 +889,50 @@ uniquely named temporary file plus rename.
|
|
|
889
889
|
verification is unchanged.
|
|
890
890
|
- **Remediation:** the warning tells the operator to inspect the worktree before
|
|
891
891
|
trusting its staged changes.
|
|
892
|
+
### Package-only Bridge fills in executor worktrees
|
|
893
|
+
|
|
894
|
+
Right before the copy-settle-and-scrub step, the executor fills the running
|
|
895
|
+
package's workflow files into the prepared worktree for the host **this spawn**
|
|
896
|
+
launches (`fillWorktreeBridgeFiles` in `executor/worktree-bridge-fills.ts`). The
|
|
897
|
+
fill is package-only: Claude gets `.claude/commands/*` and `.claude/agents/*`,
|
|
898
|
+
Cursor gets `.cursor/commands/*`, Codex gets `.agents/skills/*` and
|
|
899
|
+
`.codex/agents/*`, and every host gets the shared documents (`.bridge/procedures/**`,
|
|
900
|
+
`.bridge/README.md`, `docs/install/**`, and the top-level reference docs) plus
|
|
901
|
+
`AGENTS.md` and, for Claude, a `CLAUDE.md` pointer. It never copies project
|
|
902
|
+
config, instructions, pipelines, permissions, settings, MCP registrations, install
|
|
903
|
+
state, or credentials; the unchanged scrub still removes copied project files.
|
|
904
|
+
|
|
905
|
+
- **Which paths join the clone's excludes.** Only absent, untracked destinations
|
|
906
|
+
that passed candidate validation get a root-anchored, escaped literal line in the
|
|
907
|
+
clone's common `info/exclude`, plus the reserved temp pattern
|
|
908
|
+
(`.bridge-fill-*.tmp`). A path that already exists or is tracked is kept and gets
|
|
909
|
+
no line. The tracked `.gitignore` is never edited.
|
|
910
|
+
- **Positive ignore evidence.** A file is written only when `git check-ignore
|
|
911
|
+
--no-index` confirms both the destination and its parent's temp probe as ignored.
|
|
912
|
+
A negating rule or an unknown answer skips that one path.
|
|
913
|
+
- **Warn and continue.** An incomplete or failed fill logs exactly one warning with
|
|
914
|
+
closed reason codes, the safe affected paths (or the fixed label `package`), the
|
|
915
|
+
packaged `repair-assets` command, and a statement that the job continues. It ends
|
|
916
|
+
with `commit the Bridge files, or run repair for the named path`. It never parks
|
|
917
|
+
the job, sets a failure kind, or reports to the server. A hard publish failure
|
|
918
|
+
rolls back only this attempt's own files; if removal cannot be confirmed the
|
|
919
|
+
warning says so and the existing dirty-worktree check stays authoritative.
|
|
920
|
+
- **Existing notes files.** Fill-only setup cannot add a Bridge region to an
|
|
921
|
+
`AGENTS.md` or `CLAUDE.md` the project already owns; it leaves those bytes alone.
|
|
922
|
+
A new `CLAUDE.md` pointer is written only when a usable `AGENTS.md` physically
|
|
923
|
+
exists (written by this fill or already present), so the pointer never dangles.
|
|
924
|
+
Otherwise the pointer is deferred and named in the warning.
|
|
925
|
+
- **`repair-assets`.** The warning names the packaged command so an operator can
|
|
926
|
+
repair the named path in a checkout; it is a hint for a person, not something the
|
|
927
|
+
executor runs.
|
|
928
|
+
|
|
929
|
+
The same release adds a worker-guard rule: a Bash `git commit` whose message holds a
|
|
930
|
+
CI-skip marker (`[skip ci]`, `[ci skip]`, `[no ci]`, `[skip actions]`,
|
|
931
|
+
`[actions skip]`, `skip-checks: true`) is denied with a fixed rephrase instruction.
|
|
932
|
+
Messages are read from the parsed commit options only (`-m`, `--message`, `-F`,
|
|
933
|
+
`--file`, bundles such as `-am`), and a `-F` file is read through a trusted,
|
|
934
|
+
bounded, worktree-contained reader. Anything the guard cannot read is allowed.
|
|
935
|
+
|
|
892
936
|
# Local cleanup commands
|
|
893
937
|
|
|
894
938
|
- `npx -y @bridge_gpt/mcp-server executor uninstall-service [--executor-id <id>] [--dry-run]`: list home-scoped units or remove one after interactive consent. Logs are retained; repository locator cleanup is limited to the current checkout's repository.
|
|
@@ -74,6 +74,7 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
|
|
|
74
74
|
- **Additional readiness diagnostics** (`server.diagnostics`) — Extra readiness diagnostics from the server are clear. Fix: Read the diagnostic text; each names its own fix.
|
|
75
75
|
- **Command versions** (`conductor.command-drift`) — The installed Epic Implementer commands match this package's version. Fix: Run `npx -y @bridge_gpt/mcp-server install` to refresh them.
|
|
76
76
|
- **Escalation delivery** (`escalation-reachability`) — An escalation can actually be delivered. Fix: Verify your account email or fix the webhook, then run setup again.
|
|
77
|
+
- **Project settings complete** (`server.project-config-complete`) — The project has the settings a run needs: a project description, a working-in value, an owning account, an account model policy, a model provider, and a ticket key prefix that points only to this project. Checked at launch until a finished run records the current project facts. A proven gap blocks the launch; a setting that could not be read is a warning. Fix: Follow the fix printed for each named setting, then launch again.
|
|
77
78
|
|
|
78
79
|
## 1. Install
|
|
79
80
|
|
|
@@ -153,6 +154,39 @@ An old copy of the command line tool can print old wording or miss a flag such a
|
|
|
153
154
|
4. Run setup again: `npx -y @bridge_gpt/mcp-server@latest install epic-implementer`.
|
|
154
155
|
5. If the output is still wrong, email info@bridgegpt.ai with the `Bridge MCP version:` line from step 1 and the setup output, with any secret removed.
|
|
155
156
|
|
|
157
|
+
### Choose how finished work is merged
|
|
158
|
+
|
|
159
|
+
Setup asks one question: "How should Epic Implementer merge finished work into the epic branch?" You answer it yourself. An agent can recommend an option, but it can never answer for you.
|
|
160
|
+
|
|
161
|
+
- **Merge with your GitHub sign-in** (offered only when no dedicated token is configured and your `gh` account can push to the repository). It is a method to try. Setup runs a write check with a throwaway branch and records your approval only if the check passes. Merges then appear under your GitHub account.
|
|
162
|
+
- **Use a dedicated token**. Setup reads a token you name, write-checks it, and stores it for this repository only.
|
|
163
|
+
- **Set up without unattended merges**. Nothing is recorded. Unattended runs cannot merge until you enable a credential later.
|
|
164
|
+
|
|
165
|
+
You can also approve or withdraw the sign-in directly, in your own terminal:
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
npx -y @bridge_gpt/mcp-server install epic-implementer --use-gh-login [--repo owner/repo] [--dry-run]
|
|
169
|
+
npx -y @bridge_gpt/mcp-server install epic-implementer --forget-gh-login [--repo owner/repo] [--dry-run]
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`--use-gh-login` needs an interactive terminal. Running it is your approval, so it asks no second question. It refuses before any write check when a dedicated token is configured, and it records nothing unless the write check passes. On success it names the approved account. `--forget-gh-login` removes only that repository's sign-in approval and its proof. A dedicated token is left alone. With nothing recorded, it says so and exits 0. `--dry-run` only describes what would happen.
|
|
173
|
+
|
|
174
|
+
The approval covers child merges into the epic branch, recovery of those merges, `sync_base` (merging the base branch into the epic branch), and the first-run write probe. It never covers the final merge into your base branch.
|
|
175
|
+
|
|
176
|
+
**Which credential a local merge uses.** The first match wins:
|
|
177
|
+
|
|
178
|
+
1. An invalid `GITHUB_MERGE_TOKEN` (or `BAPI_LOCAL_MERGE_TOKEN`) value refuses the merge. Nothing else is tried.
|
|
179
|
+
2. A usable token stored for this repository (`--store-merge-token`).
|
|
180
|
+
3. `GITHUB_MERGE_TOKEN`.
|
|
181
|
+
4. `BAPI_LOCAL_MERGE_TOKEN`.
|
|
182
|
+
5. Your GitHub sign-in, only when no explicit token is configured at all. A blank stored entry, or a credential store that cannot be read, blocks this step.
|
|
183
|
+
|
|
184
|
+
Machine-user mode reads only `BAPI_MACHINE_MERGE_TOKEN` and never uses your sign-in.
|
|
185
|
+
|
|
186
|
+
**If the account changed.** When `gh` is signed in as a different account than the one you approved, merges stop with a one-line fix. Run `gh auth switch` and choose the approved account, or run `--use-gh-login` again to approve the active account. If `gh` is signed out, sign in with `gh auth login`.
|
|
187
|
+
|
|
188
|
+
**If the sign-in cannot be read.** A locked keychain, a missing `gh`, or a GitHub outage makes the sign-in unavailable. Merges retry within the usual limit. A dedicated token (`--store-merge-token`) does not depend on the keychain.
|
|
189
|
+
|
|
156
190
|
## 3. Define the epic
|
|
157
191
|
|
|
158
192
|
In Claude Code, run:
|
|
Binary file
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"schema": "bridge.windows-native-manifest.v1",
|
|
3
3
|
"target": "win32-x64",
|
|
4
4
|
"executable": "bridge-windows-native.exe",
|
|
5
|
-
"executable_sha256": "
|
|
6
|
-
"source_sha": "
|
|
7
|
-
"bridge_version": "0.2.
|
|
5
|
+
"executable_sha256": "7d8a99e74eb0f135d8f8d0c4c30541f2ad0ddc3687af32f1ef8884ac411e93a0",
|
|
6
|
+
"source_sha": "e0e3791a28c641423b6f9437cdcddc9f5b8c3038",
|
|
7
|
+
"bridge_version": "0.2.80",
|
|
8
8
|
"helper_version": "1.3.0",
|
|
9
9
|
"protocol_version": 4
|
|
10
10
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bridge_gpt/mcp-server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.80",
|
|
4
4
|
"description": "Bridge API MCP server — exposes Jira endpoints as MCP tools for Claude Code agents",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"native/windows/bin/win32-x64/manifest.json"
|
|
34
34
|
],
|
|
35
35
|
"//test": "The `test` script delegates to the bounded launcher (scripts/run-unit-tests.js → src/run-unit-tests-launcher.ts, BAPI-683), which discovers build/*.test.js at runtime and spawns them in size-bounded batches so the argv never exceeds Windows' ~8191-char command-line limit. Two determinism rules from the pre-launcher script are preserved INSIDE the launcher: (1) multi-file batches run WITHOUT --test-force-exit, because that flag makes node:test exit before aggregating per-subprocess summaries and the tally becomes nondeterministic (failures still surface and still set exit 1, but the count cannot be trusted as a completeness signal); (2) build/secret-safety.test.js leaks a handle that holds the event loop ~60s after its tests finish (they run in ~147ms), so the launcher quarantines it into its own single-file --test-force-exit invocation (FORCE_EXIT_QUARANTINE in src/run-unit-tests-launcher.ts) where the tally stays exact. Do NOT add --test-force-exit to batched invocations, and do NOT remove the quarantine, until the underlying handle leak is fixed.",
|
|
36
|
-
"//prepublishOnly": "Laptop release path (the Windows release hold from BAPI-1847 is lifted). `npm publish` from a clean checkout at the release commit (after `npm version`) runs: bundle-assets -> build -> build-windows-native (cross-compiles the Windows helper with MinGW, stamped with this commit and version) -> build-windows-native --release-verify (refuses a missing or mismatched helper) -> verify-shebang -> assert:release-identity (refuses a dirty or untagged tree) -> check-package-contents --public-package (packs with --ignore-scripts and refuses a package without the helper). The helper must be built here, at the release commit, because the runtime refuses a helper whose bridge_version or source_sha does not match the package. Customer installs run no lifecycle script. See docs/claude/runbooks/mcp-release.md.",
|
|
36
|
+
"//prepublishOnly": "Laptop release path (the Windows release hold from BAPI-1847 is lifted). `npm publish` from a clean checkout at the release commit (after `npm version`) runs: stamp-package-build recover (restores, or refuses, a pack stamp an interrupted publish left behind; BAPI-1925) -> bundle-assets -> build (through `stamp-package-build.mjs with-release-origin`, which sets BRIDGE_BUILD_ORIGIN=release without a POSIX-only `VAR=x` prefix, so the generated BUILD_ORIGIN is `release`) -> build-windows-native (cross-compiles the Windows helper with MinGW, stamped with this commit and version) -> build-windows-native --release-verify (refuses a missing or mismatched helper) -> verify-shebang -> assert:release-identity (refuses a dirty or untagged tree) -> check-package-contents --public-package (packs with --ignore-scripts and refuses a package without the helper). The helper must be built here, at the release commit, because the runtime refuses a helper whose bridge_version or source_sha does not match the package. Then npm runs prepack (stamps bridgeBuild.commit with the BUILD_COMMIT compiled into the build, so the published version document carries it), postpack (keeps the stamp under `npm publish`, because npm re-reads package.json after postpack to build the registry document; restores it for any other pack) and postpublish (restores package.json to its exact original bytes). The backup lives in .bridge-pack-stamp/ (gitignored, never packed). Customer installs run no lifecycle script. See docs/claude/runbooks/mcp-release.md.",
|
|
37
37
|
"//version": "BAPI-930: fired by `npm version <level>` AFTER npm rewrites package.json's version field, so the bumped version, repinned README and version-rendered command mirrors land in the SAME commit. A bump performed by hand-editing package.json instead of running `npm version` bypasses this hook entirely and must repin manually via `node scripts/sync-readme-host-examples.js` and `node ../commands/build.js` — the `--check` wired into `build` below is the backstop that catches that case.",
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "node scripts/generate-readiness-prerequisites.mjs && node scripts/generate-first-run-findings.mjs && node scripts/generate-language-catalog.mjs && node scripts/bundle-version.js && node scripts/sync-readme-host-examples.js --check && node scripts/validate-packaged-command-references.js && node scripts/bundle-readme.js && node scripts/bundle-pipelines.js && node scripts/bundle-commands.js && node scripts/bundle-agents.js && node scripts/bundle-docs.js && node scripts/bundle-agent-guidance.js && node -e \"require('node:fs').rmSync('build', { recursive: true, force: true })\" && tsc && node scripts/sync-readme-merge-workflow.js --check && node scripts/sync-agent-mirrors.js && node scripts/sync-codex-operator-assets.mjs && node scripts/bundle-esbuild.js",
|
|
@@ -56,7 +56,10 @@
|
|
|
56
56
|
"acceptance:kit": "node scripts/build-windows-acceptance-kit.mjs",
|
|
57
57
|
"acceptance:validate": "node scripts/run-windows-product-validation.mjs",
|
|
58
58
|
"acceptance:check": "node scripts/check-windows-product-qualification.mjs",
|
|
59
|
-
"prepublishOnly": "node scripts/bundle-assets.js && npm run build && node scripts/build-windows-native.mjs && node scripts/build-windows-native.mjs --release-verify --expected-version \"$npm_package_version\" --expected-source-sha \"$(git rev-parse HEAD)\" && node scripts/verify-shebang.cjs && npm run assert:release-identity && node scripts/check-package-contents.js --public-package --expected-source-sha \"$(git rev-parse HEAD)\""
|
|
59
|
+
"prepublishOnly": "node scripts/stamp-package-build.mjs recover && node scripts/bundle-assets.js && node scripts/stamp-package-build.mjs with-release-origin -- npm run build && node scripts/build-windows-native.mjs && node scripts/build-windows-native.mjs --release-verify --expected-version \"$npm_package_version\" --expected-source-sha \"$(git rev-parse HEAD)\" && node scripts/verify-shebang.cjs && npm run assert:release-identity && node scripts/check-package-contents.js --public-package --expected-source-sha \"$(git rev-parse HEAD)\"",
|
|
60
|
+
"prepack": "node scripts/stamp-package-build.mjs prepack",
|
|
61
|
+
"postpack": "node scripts/stamp-package-build.mjs postpack",
|
|
62
|
+
"postpublish": "node scripts/stamp-package-build.mjs postpublish"
|
|
60
63
|
},
|
|
61
64
|
"dependencies": {
|
|
62
65
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
@@ -94,5 +97,8 @@
|
|
|
94
97
|
"claude",
|
|
95
98
|
"ai-tools"
|
|
96
99
|
],
|
|
97
|
-
"homepage": "https://bridgegpt-api.com"
|
|
100
|
+
"homepage": "https://bridgegpt-api.com",
|
|
101
|
+
"bridgeBuild": {
|
|
102
|
+
"commit": "e0e3791a28c6"
|
|
103
|
+
}
|
|
98
104
|
}
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
{
|
|
31
31
|
"type": "agent_task",
|
|
32
32
|
"id": "wait-for-ticket-review",
|
|
33
|
-
"instruction": "FIRST, check whether a review was actually submitted. The previous step runs with `on_error: warn_and_continue`, so a rejected submission (a 402, 403 or 500 from the generate endpoint, or a dropped connection) lets the pipeline continue into this step. If that step returned an error envelope \u2014 a JSON object with a string `error`, a numeric `status`, and an `operation` field (for example `status: 403` with `error: \"ENTITLEMENT_REQUIRED\"`, or `status: 422` for too little ticket detail) \u2014 rather than its submission confirmation or a `recovery_get` envelope, do NOT wait: nothing is running, and `wait_for_ticket_review` cannot tell \"never submitted\" from \"still running\" \u2014 it would read `pending` in every window until the caller's own timeout. Treat a failed submission as a terminal failure, report the `status`, `error`, and `message` the previous step gave, and take the verdict contract's `revise` path.\n\nONE EXCEPTION \u2014 a review 409 (BAPI-1868). A `status: 409` envelope may carry a `review_conflict` object: another review of this ticket is already running. NEVER submit again after a 409: a second submission is a second paid review. Read `review_conflict.recovery`:\n- `follow_named_operation` (the active kind is `review` and `active_operation` names the running review): follow THAT review instead of failing. Show it as progress: \"A review is already running for this ticket (operation <active_operation>); waiting for it.\" The generation seen at the 409 is kept as the freshness baseline. Wait with `wait_for_ticket_review` exactly as described below. Before you accept a `ready` result, call `get_ticket_state` once and confirm that `ticket_review.public_reference` equals `active_operation` and `ticket_review.state` is `succeeded`. Accept only a `freshness_basis: \"generation\"` result whose legs advanced past that baseline, for this same repository, ticket, and operation. A `terminality_only` result, a different `public_reference`, a `failed` state, a missing `ticket_review`, or an `error` state means the review stays UNRESOLVED.\n- `unresolved_do_not_resubmit` (no operation was named \u2014 an older server or the direct-dispatch lock \u2014 or the active kind is `clarify` or `critique`): do not wait and do not submit. Report the review as unresolved, with the active kind and the detail text, and take the verdict contract's `revise` path.\nA 409 without `review_conflict` (an older server) is reported the same way: unresolved, never resubmitted. An unresolved review is never reported as passed. Continue only work that does not need its verdict.\n\nOtherwise, wait for the review submitted by the previous step to finish, using repeated BOUNDED windows.\n\nCall `wait_for_ticket_review` with `ticket_number` set to the ticket key. Each call uses the default 20-second window (set `budget_ms: 20000` explicitly if needed); do not use a longer window, because some MCP clients time out before a pending result arrives. The tool returns a JSON body with a `state` field:\n\n- `state: \"pending\"` \u2014 NORMAL and expected. The review is still running. Call the tool again immediately. Do NOT sleep, do NOT poll in a shell loop, and do NOT re-run `request_ticket_review`: re-submitting starts a second billable multi-model review and abandons the one already in flight. If the pending result carries `parse_wait: true`, the review is waiting for the repository parse to finish: show its `message` as normal progress and keep calling the tool on this same review, with no cap on pending windows of your own. A parse wait is not a failure or a timeout, and never a reason to submit again.\n- Any result may end with a stale-index line (the work used the last good code index, so the latest code may be missing). Include the one from the final result once in this session's final report. Do not carry an earlier pending line into a later result that has none.\n- `state: \"ready\"` \u2014 the review is over. BAPI-1121: a ready result has ALREADY persisted exactly the accepted documents and reconciled the canonical source files \u2014 it writes every leg in `saved_legs` to its canonical path and removes the stale canonical file for every leg in `withheld_legs`. Do NOT call `get_clarifying_questions` or `get_ticket_critique` after a ready result; those retrieval calls were removed from this recipe because reading them again could reintroduce exactly the stale content the wait just withheld. Treat `saved_legs` as the authoritative source set for the next steps, not file presence.\n - `freshness_basis: \"generation\"` is the normal case: `advanced_legs`/`saved_legs` are current-review evidence, proven newer than the submission. Any leg in `withheld_legs` was delivered but NOT proven current \u2014 surface its `reason` (`generation_not_advanced` or `
|
|
33
|
+
"instruction": "FIRST, check whether a review was actually submitted. The previous step runs with `on_error: warn_and_continue`, so a rejected submission (a 402, 403 or 500 from the generate endpoint, or a dropped connection) lets the pipeline continue into this step. If that step returned an error envelope \u2014 a JSON object with a string `error`, a numeric `status`, and an `operation` field (for example `status: 403` with `error: \"ENTITLEMENT_REQUIRED\"`, or `status: 422` for too little ticket detail) \u2014 rather than its submission confirmation or a `recovery_get` envelope, do NOT wait: nothing is running, and `wait_for_ticket_review` cannot tell \"never submitted\" from \"still running\" \u2014 it would read `pending` in every window until the caller's own timeout. Treat a failed submission as a terminal failure, report the `status`, `error`, and `message` the previous step gave, and take the verdict contract's `revise` path.\n\nONE EXCEPTION \u2014 a review 409 (BAPI-1868). A `status: 409` envelope may carry a `review_conflict` object: another review of this ticket is already running. NEVER submit again after a 409: a second submission is a second paid review. Read `review_conflict.recovery`:\n- `follow_named_operation` (the active kind is `review` and `active_operation` names the running review): follow THAT review instead of failing. Show it as progress: \"A review is already running for this ticket (operation <active_operation>); waiting for it.\" The generation seen at the 409 is kept as the freshness baseline. Wait with `wait_for_ticket_review` exactly as described below. Before you accept a `ready` result, call `get_ticket_state` once and confirm that `ticket_review.public_reference` equals `active_operation` and `ticket_review.state` is `succeeded`. Accept only a `freshness_basis: \"generation\"` result whose legs advanced past that baseline, for this same repository, ticket, and operation. A `terminality_only` result, a different `public_reference`, a `failed` state, a missing `ticket_review`, or an `error` state means the review stays UNRESOLVED.\n- `unresolved_do_not_resubmit` (no operation was named \u2014 an older server or the direct-dispatch lock \u2014 or the active kind is `clarify` or `critique`): do not wait and do not submit. Report the review as unresolved, with the active kind and the detail text, and take the verdict contract's `revise` path.\nA 409 without `review_conflict` (an older server) is reported the same way: unresolved, never resubmitted. An unresolved review is never reported as passed. Continue only work that does not need its verdict.\n\nOtherwise, wait for the review submitted by the previous step to finish, using repeated BOUNDED windows.\n\nCall `wait_for_ticket_review` with `ticket_number` set to the ticket key. Each call uses the default 20-second window (set `budget_ms: 20000` explicitly if needed); do not use a longer window, because some MCP clients time out before a pending result arrives. The tool returns a JSON body with a `state` field:\n\n- `state: \"pending\"` \u2014 NORMAL and expected. The review is still running, or its job just finished and the wait is confirming once more that nothing new landed. Call the tool again immediately. Do NOT sleep, do NOT poll in a shell loop, and do NOT re-run `request_ticket_review`: re-submitting starts a second billable multi-model review and abandons the one already in flight. If the pending result carries `parse_wait: true`, the review is waiting for the repository parse to finish: show its `message` as normal progress and keep calling the tool on this same review, with no cap on pending windows of your own. A parse wait is not a failure or a timeout, and never a reason to submit again.\n- Any result may end with a stale-index line (the work used the last good code index, so the latest code may be missing). Include the one from the final result once in this session's final report. Do not carry an earlier pending line into a later result that has none.\n- `state: \"ready\"` \u2014 the review is over. BAPI-1121: a ready result has ALREADY persisted exactly the accepted documents and reconciled the canonical source files \u2014 it writes every leg in `saved_legs` to its canonical path and removes the stale canonical file for every leg in `withheld_legs`. Do NOT call `get_clarifying_questions` or `get_ticket_critique` after a ready result; those retrieval calls were removed from this recipe because reading them again could reintroduce exactly the stale content the wait just withheld. Treat `saved_legs` as the authoritative source set for the next steps, not file presence.\n - `freshness_basis: \"generation\"` is the normal case: `advanced_legs`/`saved_legs` are current-review evidence, proven newer than the submission. Any leg in `withheld_legs` was delivered but NOT proven current \u2014 surface its `reason` (`generation_not_advanced`, `identity_unchanged`, `identity_unreadable`, or `baseline_unobserved`) as a visible warning; do not describe the result as an ordinary cost-saved one-leg review when a withholding occurred. A leg in `absent_legs` with `reason: \"not_delivered\"` is an ordinary policy omission (e.g. an Easy-ticket clarify-only review) unless its status also flags it as policy-expected, in which case call that out too.\n - `freshness_basis: \"terminality_only\"` means no submission baseline was available (e.g. a resumed session) \u2014 `advanced_legs` is empty by construction and `saved_legs` was accepted on terminal delivery alone. Surface this prominently as a DEGRADED-freshness warning: the saved artifact(s) may be indistinguishable from a prior attachment, and the downstream identity-footer agreement check is the remaining backstop. Retain this warning when reporting to the next steps rather than treating a `terminality_only` ready result as equivalent to a `generation`-backed one.\n - If the result instead carries `state: \"error\"` alongside a persistence failure (an `ARTIFACT_PERSISTENCE_FAILED` `error`/`status`/`message` envelope), HALT rather than proceeding with whatever files happen to exist on disk \u2014 report the failure; the accepted legs already on disk before the failure are named in the envelope and are not lost, but nothing new was persisted for this window.\n- `state: \"error\"` \u2014 terminal. Report the `reason` and stop; the review will not complete on its own. `UPSTREAM_TERMINAL` means the review failed or expired server-side \u2014 take the verdict contract's `revise` path; do NOT open another wait window and do NOT re-run `request_ticket_review`. `NO_REVIEW_REQUESTED` means no review was submitted from this session and none is running; `NO_REVIEW_RUNNING` means the submitted review is no longer running on the server \u2014 treat both like `UPSTREAM_TERMINAL`. `INVALID_RESPONSE` means the delivered document could not be read. `REVIEW_COMPLETED_NOT_ADVANCED` (BAPI-1923) means the submitted review finished on the server, but no review document could be proven new for this submission: report the review as UNRESOLVED, quoting each entry of the result's `legs` array (`leg`, `delivered`, `baseline_generation`, `baseline_source`, `observed_generation`, `not_accepted_reason`) and its `review_operation`, and take the verdict contract's `revise` path. Do NOT open another wait window and do NOT call `request_ticket_review` again \u2014 a second submission is a second paid review. An unresolved review is never reported as passed.\n\nKeep looping on `pending` for as long as this session's own budget allows. There is no iteration cap here: the bound is the caller's \u2014 for the conductor's spec-review worker that is the existing 120-minute job timeout, which produces the ordinary liveness outcome if the review never lands. Never fabricate a verdict or a review result from a pending state.",
|
|
34
34
|
"description": "Wait for the submitted review in repeated bounded windows; a ready result has already persisted the accepted documents and reconciled the canonical files (BAPI-1121). Resumable: a pending result is a normal observation, not a failure.",
|
|
35
35
|
"on_error": "halt"
|
|
36
36
|
},
|