@bridge_gpt/mcp-server 0.2.71 → 0.2.72
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 +55 -17
- package/build/agent-launchers/claude-executor-adapter.js +19 -3
- package/build/agent-notes.js +171 -95
- package/build/agents.generated.js +4 -4
- package/build/bridge-permissions.js +4 -0
- package/build/bridge-worktree-inspection.js +237 -0
- package/build/check-evidence.js +6 -0
- package/build/claude-review-workflow.js +1 -1
- package/build/cli-help.js +6 -0
- package/build/codex-auto-recovery.js +126 -0
- package/build/codex-skill-adapter.js +2 -0
- package/build/commands.generated.js +5 -5
- package/build/conductor/bridge-api-client.js +518 -23
- package/build/conductor/doctor.js +84 -10
- package/build/conductor/epic-implementer-cli.js +51 -2
- package/build/conductor/gate-discovery.js +136 -10
- package/build/conductor/gate-settings-review.js +305 -5
- package/build/conductor/git-hooks-uninstall.js +112 -0
- package/build/conductor/git-hooks.js +81 -15
- package/build/conductor/guided-repair.js +10 -1
- package/build/conductor/install-doctor.js +2 -4
- package/build/conductor/launch-plan.js +42 -2
- package/build/conductor/local-merge.js +12 -1
- package/build/conductor/merge-execution-contract.js +1 -1
- package/build/conductor/merged-child-check.js +2 -1
- package/build/conductor/prerequisite-inputs.js +379 -0
- package/build/conductor/readiness-assessment.js +78 -0
- package/build/conductor/readiness-cli.js +10 -0
- package/build/conductor/readiness-prerequisites.js +53 -0
- package/build/conductor/readiness-sections.js +21 -8
- package/build/conductor/readiness.js +20 -2
- package/build/conductor/recovery-cli.js +223 -13
- package/build/conductor/recovery-operations.js +34 -4
- package/build/conductor/repair-contract.js +33 -0
- package/build/conductor/tools.js +34 -3
- package/build/conductor/wait-run-attention.js +115 -0
- package/build/conductor/wait-run-cli.js +96 -3
- package/build/conductor/worker-database-doctor-inspector.js +1 -0
- package/build/credential-store.js +25 -20
- package/build/dependency-install-declarations.js +157 -0
- package/build/docs.generated.js +4 -4
- package/build/doctor.js +37 -5
- package/build/drive-epic-help.js +2 -2
- package/build/drive-epic.js +52 -11
- package/build/epic-implementer-bin.js +118 -43
- package/build/epic-launch-profile.js +1 -1
- package/build/executor/cli.js +2 -0
- package/build/executor/completion-contract.js +16 -0
- package/build/executor/credentials.js +1 -1
- package/build/executor/delivery-observations.js +113 -0
- package/build/executor/delivery-outcome.js +30 -0
- package/build/executor/dependency-refresh-runner.js +132 -0
- package/build/executor/dependency-refresh.js +530 -0
- package/build/executor/deps.js +4 -0
- package/build/executor/env.js +67 -2
- package/build/executor/harness-coverage.js +19 -0
- package/build/executor/http-client.js +35 -1
- package/build/executor/index.js +2 -1
- package/build/executor/install-preflight.js +1 -1
- package/build/executor/job-runner.js +246 -28
- package/build/executor/likely-tests.js +94 -97
- package/build/executor/prompt-spec.js +13 -3
- package/build/executor/required-verification.js +28 -0
- package/build/executor/required-work-diagnostics.js +30 -0
- package/build/executor/required-work-ledger.js +19 -1
- package/build/executor/results.js +42 -0
- package/build/executor/service-discovery.js +42 -0
- package/build/executor/service-lifecycle.js +109 -2
- package/build/executor/service-uninstall.js +205 -0
- package/build/executor/service-unit.js +5 -3
- package/build/executor/test-clock.js +3 -0
- package/build/executor/verification-hints.js +179 -0
- package/build/executor/worker-command.js +54 -2
- package/build/executor/worker-database.js +271 -31
- package/build/executor/worker-finalization.js +65 -10
- package/build/executor/worker-guard-hook.js +10 -2
- package/build/executor/worker-verification-guidance.js +37 -2
- package/build/executor/worktree-inspection.js +42 -0
- package/build/github-sign-in.js +1 -1
- package/build/index.js +679 -278
- package/build/init.js +3 -3
- package/build/install-bridge-conductor-gate.js +236 -42
- package/build/install-bridge-conductor-setup.js +115 -26
- package/build/install-bridge-conductor.js +448 -350
- package/build/install-bridge.js +418 -123
- package/build/install-maintenance.js +104 -0
- package/build/install-reexec.js +1 -1
- package/build/local-cleanup.js +59 -0
- package/build/mcp-install-state.js +68 -2
- package/build/merge-workflow-install.js +2 -2
- package/build/package-script-semantics.js +10 -0
- package/build/pipeline-utils.js +1 -1
- package/build/pipelines.generated.js +5 -5
- package/build/plan-execution-ledger.js +148 -2
- package/build/plane/plane-freshness.js +6 -7
- package/build/plane/terminal-run-cleanup.js +5 -1
- package/build/plane/terminal-run-status.js +4 -0
- package/build/printed-remedy-commands.js +24 -4
- package/build/readiness-check.js +1 -78
- package/build/readiness-prerequisites.generated.js +199 -0
- package/build/readme.generated.js +1 -1
- package/build/repository-toolchains.js +50 -8
- package/build/setup-change-policy.js +32 -0
- package/build/setup-epic.js +2 -2
- package/build/setup-question.js +62 -0
- package/build/start-tickets.js +4 -0
- package/build/test-command-detection.js +32 -88
- package/build/test-support/notes-fs.js +40 -0
- package/build/ticket-delivery-enrollment.js +21 -8
- package/build/ticket-delivery-run-scope.js +128 -0
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktrees.js +105 -0
- package/docs/EPIC-IMPLEMENTER.md +5 -0
- package/docs/epic-implementer/getting-started.md +40 -15
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync}from"node:fs";import path from"node:path";var 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){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 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 restriction={"git-push":"Push only to your own branch, without force. 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 restriction[category]?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ${restriction[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"?`${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=()=>{endToken(),(argv.length>0||unsafe)&&commands.push({argv,unsafe}),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){body+=command[j+1],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)){endCommand();continue}if(ch===`
|
|
2
|
+
import{readFileSync}from"node:fs";import path from"node:path";var 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){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 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 restriction={"git-push":"Push only to your own branch, without force. 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 restriction[category]?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ${restriction[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==="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=()=>{endToken(),(argv.length>0||unsafe)&&commands.push({argv,unsafe}),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){body+=command[j+1],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)){endCommand();continue}if(ch===`
|
|
3
3
|
`){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="",uncertain=!1,finish=end=>{let original=tokenizeShellCommand(command.slice(start,end)),projected=tokenizeShellCommand(masked),value=!uncertain&&projected.length===1?{argv:projected[0].argv,complete:!projected[0].unsafe}:void 0;result.push(...original.map((_,i)=>i===0?value:void 0)),masked="",uncertain=!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("<<"))&&(uncertain=!0),masked+=" ",i=j-1;continue}if(SEPARATORS.has(ch)||ch===`
|
|
4
|
-
`){finish(i);continue}masked+=ch}return quote&&(uncertain=!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.startsWith("..")?!1:!path.isAbsolute(rel)}function resolveEffectiveCwd(ctx,payloadCwd){let root=ctx.worktreePath;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){let root=ctx.worktreePath;if(typeof root!="string"||!path.isAbsolute(root)||cwd===void 0)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){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):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 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"},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==="--follow-tags"||token.startsWith("--repo"))return deny;(token==="-o"||token==="--push-option"||token==="--receive-pack"||token==="--exec")&&(i+=1);continue}positional.push(token)}let workerBranch=ctx.workerBranch;return typeof workerBranch!="string"||workerBranch.length===0?deny:positional.length<=1?{kind:"allow"}:positional.slice(1).every(d=>isOwnBranchDestination(d,workerBranch))?{kind:"allow"}:deny}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]))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"}:allTargetsContained(ctx,cwd,pathspecs)?{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)?{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){let deny={kind:"deny",category:"network-mutating",family:"curl"},base=path.basename(argv[0]??""),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 classify(executable){let base=path.basename(executable);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),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).kind==="deny";let git=parseGitInvocation(argv,cwd);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){let rest=argv;for(let depth=0;depth<8;depth+=1){let head=rest[0];if(head===void 0||!TRANSPARENT_PREFIXES.has(path.basename(head)))return rest;let i=1;for(;i<rest.length;){let token=rest[i];if(path.basename(head)==="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"],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}return OPERATOR_ONLY_VERBS.find(verb=>decoded.toLowerCase().includes(`/${verb}`)||token.toLowerCase().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){let base=path.basename(argv[0]??""),afterEpicImplementer=rest=>rest.length===0?[]:rest[0]==="epic-implementer"?rest.slice(1):void 0;if(base==="epic-implementer")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 first==="epic-implementer"?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(path.posix.basename(script)==="epic-implementer-bin.js")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,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}function evaluateSimpleCommand(segment,ctx,payloadCwd,depth=0,stdinFed=!1,diagnostic){let argv=unwrapTransparentPrefixes(segment.argv),executable=argv[0];if(executable===void 0)return{kind:"allow"};if(SHELL_EXECUTABLES.has(path.basename(executable))&&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):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}}if(EVAL_BUILTINS.has(path.basename(executable))&&depth<4){let inner=argv.slice(1).join(" "),projections=diagnostic?.complete?diagnosticProjections(inner):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}if(STDIN_ARGUMENT_PREFIXES.has(path.basename(executable))&&depth<4){let rest=stripStdinPrefixOptions(argv);return rest.length===0?{kind:"allow"}:evaluateSimpleCommand({argv:rest,unsafe:segment.unsafe},ctx,payloadCwd,depth+1,!0,diagnostic?{argv:stripStdinPrefixOptions(unwrapTransparentPrefixes(diagnostic.argv)),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);if(family===null)return{kind:"allow"};if(stdinFed||segment.unsafe)return unsafeSegmentDecision(family,segment.argv,ctx,resolveEffectiveCwd(ctx,payloadCwd),diagnostic);let cwd=resolveEffectiveCwd(ctx,payloadCwd);if(family==="rm")return evaluateRemove(segment.argv,ctx,cwd);if(family==="database")return evaluateDatabase(segment.argv);if(family==="network")return evaluateNetwork(segment.argv);let git=parseGitInvocation(segment.argv,cwd);return 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);if(ctx.correctionEnforced){if(input===void 0)return workflowDeny("correction-payload-invalid");let decision=evaluateCorrectionToolRole(toolName,input);if(decision!==void 0)return decision}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,projections=diagnosticProjections(command);for(let[i,segment]of tokenizeShellCommand(command).entries()){let decision=evaluateSimpleCommand(segment,ctx,payloadCwd,0,!1,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}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";function resolveWorkerGuardContext(env,cwd,argv=[]){let ctx={},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),typeof root=="string"&&path.isAbsolute(root)&&(ctx.worktreePath=path.resolve(root));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),decision=evaluateWorkerGuardInput(raw,ctx);decision.kind==="deny"?(io.writeStderr(renderWorkerGuardReason(decision.category,decision.family,decision.form)),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}
|
|
4
|
+
`){finish(i);continue}masked+=ch}return quote&&(uncertain=!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.startsWith("..")?!1:!path.isAbsolute(rel)}function resolveEffectiveCwd(ctx,payloadCwd){let root=ctx.worktreePath;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){let root=ctx.worktreePath;if(typeof root!="string"||!path.isAbsolute(root)||cwd===void 0)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){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):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 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"},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==="--follow-tags"||token.startsWith("--repo"))return deny;(token==="-o"||token==="--push-option"||token==="--receive-pack"||token==="--exec")&&(i+=1);continue}positional.push(token)}let workerBranch=ctx.workerBranch;return typeof workerBranch!="string"||workerBranch.length===0?deny:positional.length<=1?{kind:"allow"}:positional.slice(1).every(d=>isOwnBranchDestination(d,workerBranch))?{kind:"allow"}:deny}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]))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"}:allTargetsContained(ctx,cwd,pathspecs)?{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)?{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){let deny={kind:"deny",category:"network-mutating",family:"curl"},base=path.basename(argv[0]??""),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 classify(executable){let base=path.basename(executable);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),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).kind==="deny";let git=parseGitInvocation(argv,cwd);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){let rest=argv;for(let depth=0;depth<8;depth+=1){let head=rest[0];if(head===void 0||!TRANSPARENT_PREFIXES.has(path.basename(head)))return rest;let i=1;for(;i<rest.length;){let token=rest[i];if(path.basename(head)==="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"],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}return OPERATOR_ONLY_VERBS.find(verb=>decoded.toLowerCase().includes(`/${verb}`)||token.toLowerCase().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){let base=path.basename(argv[0]??""),afterEpicImplementer=rest=>rest.length===0?[]:rest[0]==="epic-implementer"?rest.slice(1):void 0;if(base==="epic-implementer")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 first==="epic-implementer"?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(path.posix.basename(script)==="epic-implementer-bin.js")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,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}function evaluateSimpleCommand(segment,ctx,payloadCwd,depth=0,stdinFed=!1,diagnostic){let argv=unwrapTransparentPrefixes(segment.argv),executable=argv[0];if(executable===void 0)return{kind:"allow"};if(SHELL_EXECUTABLES.has(path.basename(executable))&&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):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}}if(EVAL_BUILTINS.has(path.basename(executable))&&depth<4){let inner=argv.slice(1).join(" "),projections=diagnostic?.complete?diagnosticProjections(inner):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}if(STDIN_ARGUMENT_PREFIXES.has(path.basename(executable))&&depth<4){let rest=stripStdinPrefixOptions(argv);return rest.length===0?{kind:"allow"}:evaluateSimpleCommand({argv:rest,unsafe:segment.unsafe},ctx,payloadCwd,depth+1,!0,diagnostic?{argv:stripStdinPrefixOptions(unwrapTransparentPrefixes(diagnostic.argv)),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);if(family===null)return{kind:"allow"};if(stdinFed||segment.unsafe)return unsafeSegmentDecision(family,segment.argv,ctx,resolveEffectiveCwd(ctx,payloadCwd),diagnostic);let cwd=resolveEffectiveCwd(ctx,payloadCwd);if(family==="rm")return evaluateRemove(segment.argv,ctx,cwd);if(family==="database")return evaluateDatabase(segment.argv);if(family==="network")return evaluateNetwork(segment.argv);let git=parseGitInvocation(segment.argv,cwd);return 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);if(ctx.correctionEnforced){if(input===void 0)return workflowDeny("correction-payload-invalid");let decision=evaluateCorrectionToolRole(toolName,input);if(decision!==void 0)return decision}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,projections=diagnosticProjections(command);for(let[i,segment]of tokenizeShellCommand(command).entries()){let decision=evaluateSimpleCommand(segment,ctx,payloadCwd,0,!1,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}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";function resolveWorkerGuardContext(env,cwd,argv=[]){let ctx={},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),typeof root=="string"&&path.isAbsolute(root)&&(ctx.worktreePath=path.resolve(root));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),decision=evaluateWorkerGuardInput(raw,ctx);decision.kind==="deny"?(io.writeStderr(renderWorkerGuardReason(decision.category,decision.family,decision.form)),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
5
|
`)}}));
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** Read-only listing and separately consented, non-forcing worktree pruning. */
|
|
2
|
+
import { confirmLocalCleanup, runLocalCommand } from "./local-cleanup.js";
|
|
3
|
+
import { inspectBridgeWorktrees, buildBridgeWorktreePrunePlan, formatBridgeWorktreeSummary, formatWorktreeStatusCommand, validCleanupBranch } from "./bridge-worktree-inspection.js";
|
|
4
|
+
export function getWorktreesUsage() {
|
|
5
|
+
return "Usage: mcp-server worktrees [--prune] [--base <branch>] [--dry-run] [--fetch]\nLists every registered worktree. --prune offers only proven safe Bridge worktrees.\n--fetch explicitly runs one git fetch --prune origin; incompatible with --dry-run.\nPruning requires interactive consent; logs and uncommitted work are retained.";
|
|
6
|
+
}
|
|
7
|
+
export async function runWorktreesCli(argv, overrides = {}) {
|
|
8
|
+
const deps = { cwd: process.cwd(), isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY), log: text => process.stderr.write(text + "\n"), prompt: confirmLocalCleanup, inspect: inspectBridgeWorktrees, run: runLocalCommand, ...overrides };
|
|
9
|
+
let prune = false, dryRun = false, fetch = false, base;
|
|
10
|
+
for (let i = 0; i < argv.length; i++) {
|
|
11
|
+
const arg = argv[i];
|
|
12
|
+
if (arg === "--help" || arg === "-h") {
|
|
13
|
+
deps.log(getWorktreesUsage());
|
|
14
|
+
return 0;
|
|
15
|
+
}
|
|
16
|
+
if (arg === "--prune")
|
|
17
|
+
prune = true;
|
|
18
|
+
else if (arg === "--dry-run")
|
|
19
|
+
dryRun = true;
|
|
20
|
+
else if (arg === "--fetch")
|
|
21
|
+
fetch = true;
|
|
22
|
+
else if (arg === "--base" && !base && argv[i + 1] && validCleanupBranch(argv[i + 1]))
|
|
23
|
+
base = argv[++i];
|
|
24
|
+
else {
|
|
25
|
+
deps.log("Invalid worktrees arguments.\n" + getWorktreesUsage());
|
|
26
|
+
return 1;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (fetch && dryRun) {
|
|
30
|
+
deps.log("--fetch and --dry-run cannot be combined.");
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
if (fetch && (await deps.run("git", ["fetch", "--prune", "origin"], deps.cwd)).exitCode !== 0) {
|
|
35
|
+
deps.log("Fetch failed; pruning prohibited. Retry manually: git fetch --prune origin");
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
const options = { cwd: deps.cwd, base };
|
|
39
|
+
const observation = await deps.inspect(options);
|
|
40
|
+
for (const wt of observation.worktrees) {
|
|
41
|
+
deps.log(`${wt.path}\n branch: ${wt.branch ?? "detached/bare"}; size: ${wt.size ? `${wt.size.bytes} bytes${wt.size.complete ? "" : " (partial)"}` : "unknown"}; status: ${wt.status}; Bridge: ${wt.evidence.join(", ") || "none"}`);
|
|
42
|
+
if (wt.branch)
|
|
43
|
+
deps.log(` Git will refuse to check out this branch elsewhere until this holding worktree is removed.`);
|
|
44
|
+
if (wt.retained.length)
|
|
45
|
+
deps.log(` retained: ${wt.retained.join("; ")}. Inspect: ${formatWorktreeStatusCommand(wt)}`);
|
|
46
|
+
}
|
|
47
|
+
deps.log(formatBridgeWorktreeSummary(observation));
|
|
48
|
+
if (observation.state === "unavailable") {
|
|
49
|
+
deps.log("Worktree inspection unavailable; run git worktree list and inspect local refs.");
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
if (!prune)
|
|
53
|
+
return 0;
|
|
54
|
+
const selected = buildBridgeWorktreePrunePlan(observation);
|
|
55
|
+
for (const wt of selected)
|
|
56
|
+
deps.log(`Offered: ${wt.path}; ${wt.branch}; ${wt.evidence.join(", ")}; tip proven merged into ${observation.baseRef}.`);
|
|
57
|
+
if (dryRun) {
|
|
58
|
+
deps.log("dry run — nothing was removed");
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
if (!selected.length) {
|
|
62
|
+
deps.log("No proven safe prune candidates.");
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
if (!deps.isTTY || !await deps.prompt(`Remove these ${selected.length} worktrees and safely delete their branches?`)) {
|
|
66
|
+
deps.log("declined — nothing was removed");
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
let failed = false;
|
|
70
|
+
for (const approved of selected) {
|
|
71
|
+
const fresh = await deps.inspect(options);
|
|
72
|
+
const current = buildBridgeWorktreePrunePlan(fresh).find(wt => wt.path === approved.path && wt.branch === approved.branch && wt.head === approved.head);
|
|
73
|
+
if (!current || fresh.baseTip !== observation.baseTip) {
|
|
74
|
+
deps.log(`Retained changed or unsafe worktree: ${approved.path}`);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const remove = await deps.run("git", ["worktree", "remove", "--", approved.path], deps.cwd);
|
|
78
|
+
if (remove.exitCode !== 0) {
|
|
79
|
+
failed = true;
|
|
80
|
+
deps.log(`Failed to remove ${approved.path}; inspect: ${formatWorktreeStatusCommand(approved)}`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
deps.log(`Removed worktree: ${approved.path}`);
|
|
84
|
+
// The branch can move between removal and deletion: recheck its exact tip.
|
|
85
|
+
const ref = await deps.run("git", ["rev-parse", "--verify", "--quiet", `refs/heads/${approved.branch}^{commit}`], deps.cwd);
|
|
86
|
+
const ancestor = await deps.run("git", ["merge-base", "--is-ancestor", approved.head, approved.status === "remote-gone" ? "HEAD" : observation.baseTip], deps.cwd);
|
|
87
|
+
if (ref.exitCode !== 0 || ref.stdout.trim() !== approved.head || ancestor.exitCode !== 0) {
|
|
88
|
+
deps.log(`Retained branch: ${approved.branch}; preservation changed.`);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const branch = await deps.run("git", ["branch", "-d", "--", approved.branch], deps.cwd);
|
|
92
|
+
if (branch.exitCode !== 0) {
|
|
93
|
+
failed = true;
|
|
94
|
+
deps.log(`Retained branch: ${approved.branch}; Git safe deletion refused.`);
|
|
95
|
+
}
|
|
96
|
+
else
|
|
97
|
+
deps.log(`Deleted branch: ${approved.branch}`);
|
|
98
|
+
}
|
|
99
|
+
return failed ? 1 : 0;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
deps.log("Worktree cleanup unavailable; remaining work retained.");
|
|
103
|
+
return 1;
|
|
104
|
+
}
|
|
105
|
+
}
|
package/docs/EPIC-IMPLEMENTER.md
CHANGED
|
@@ -805,3 +805,8 @@ uniquely named temporary file plus rename.
|
|
|
805
805
|
verification is unchanged.
|
|
806
806
|
- **Remediation:** the warning tells the operator to inspect the worktree before
|
|
807
807
|
trusting its staged changes.
|
|
808
|
+
# Local cleanup commands
|
|
809
|
+
|
|
810
|
+
- `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.
|
|
811
|
+
- `epic-implementer uninstall-git-hooks [--dry-run]`: remove managed blocks from shared hooks, preserving user text and modes.
|
|
812
|
+
- `npx -y @bridge_gpt/mcp-server worktrees [--prune] [--base <branch>] [--dry-run] [--fetch]`: inspect linked checkouts and consentedly remove proven safe Bridge worktrees. Local refs reflect the last fetch; `--fetch` performs one explicit origin refresh and is incompatible with dry-run. Unknown sizes, incomplete observations, and retained resources are reported. Remote-gone eligibility requires upstream history and surviving-tip evidence.
|
|
@@ -11,15 +11,15 @@ In every command below, `npx -y @bridge_gpt/mcp-server` is the launcher. Keep th
|
|
|
11
11
|
Setup checks every item below for you, fixes what it can, and prints the one step it cannot fix. Read this list only when setup reports an item. Each bullet gives the item's name, its id, what it means, and the fix.
|
|
12
12
|
|
|
13
13
|
- **Unattended posture (Setup page)** (`server.unattended-posture`) — Bridge allows unattended runs for this repository. Fix: Turn on **Allow unattended Epic Implementer runs** on the repository Setup page, or launch with `--attended`.
|
|
14
|
-
- **Resolved merge mode** (`server.resolved-merge-mode`) — Bridge knows how child pull requests will be merged (your computer, a machine token, or GitHub Actions). Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
14
|
+
- **Resolved merge mode** (`server.resolved-merge-mode`) — Bridge knows how child pull requests will be merged (your computer, a machine token, or GitHub Actions). Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
15
15
|
- **Provider repository** (`server.provider-repository`) — Bridge knows the GitHub `owner/name` of this repository. Fix: Run `npx -y @bridge_gpt/mcp-server connect-github`, then run setup again.
|
|
16
|
-
- **Supervisor setup** (`server.supervisor-setup`) — The repository has a stored supervisor record. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
17
|
-
- **Supervisor configuration** (`server.supervisor-config`) — The supervisor record is complete: the test gate and the safe defaults are stored. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
16
|
+
- **Supervisor setup** (`server.supervisor-setup`) — The repository has a stored supervisor record. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
17
|
+
- **Supervisor configuration** (`server.supervisor-config`) — The supervisor record is complete: the test gate and the safe defaults are stored. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
18
18
|
- **Supervisor required CI checks** (`server.supervisor-required-checks`) — The CI checks a child pull request must pass before it merges are stored. Fix: Run setup and confirm the gate it proposes, or name a check with `--required-check <name>`.
|
|
19
19
|
- **Review policy** (`server.review-policy`) — The review policy for child pull requests is known. AI review is an opt-in choice by the repository admin. Fix: Nothing is needed unless you want AI review. Choose a policy at launch with `--review-policy`.
|
|
20
20
|
- **GitHub App credentials** (`server.github-credentials`) — Bridge's GitHub App is connected and can read this repository. Fix: Run `npx -y @bridge_gpt/mcp-server connect-github`, then run setup again.
|
|
21
21
|
- **GitHub App actions permission** (`server.github-actions-permission`) — The GitHub App may start workflow runs. Only needed when merges go through GitHub Actions. Fix: Accept the updated permission on the GitHub App's installation page, then run setup again.
|
|
22
|
-
- **Merge workflow eligibility** (`server.merge-execution-workflow`) — The merge workflow file is on the default branch and current. Only needed when merges go through GitHub Actions. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
22
|
+
- **Merge workflow eligibility** (`server.merge-execution-workflow`) — The merge workflow file is on the default branch and current. Only needed when merges go through GitHub Actions. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer --merge-workflow --codeowner <@org/team|@user>`, merge the pull request it opens, then run setup again.
|
|
23
23
|
- **Merge branch policy** (`server.merge-execution-branch-policy`) — The default branch rules let the merge workflow do its job. Only needed when merges go through GitHub Actions. Fix: Adjust the branch rule or ruleset as setup describes, then run setup again.
|
|
24
24
|
- **Executor server observation** (`server.executor-readiness`) — Bridge has seen a heartbeat from an executor for this repository. Before your first run this can be missing: `drive-epic` starts the executor for each run. Fix: Launch the epic with `npx -y @bridge_gpt/mcp-server drive-epic <EPIC>`.
|
|
25
25
|
- **Review workflow protocol** (`server.review-workflow`) — The review workflow on the default branch matches the review policy. Only needed with AI review. Fix: Run setup; it names the workflow change to make.
|
|
@@ -27,7 +27,7 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
|
|
|
27
27
|
- **Escalation channel (webhook or email)** (`server.unattended-notify-default`) — Bridge has somewhere to send an escalation: a verified notify webhook, or your account email. Fix: Declare a notify webhook, or verify your account email.
|
|
28
28
|
- **Repository workflow readiness** (`server.repository-workflow-readiness`) — The CI and review workflows are confirmed on the default branch. Fix: Run setup, merge the setup pull request, then run setup again.
|
|
29
29
|
- **Workflows at indexed commit** (`server.indexed-workflows`) — The repository index includes the workflow files on the default branch. Fix: Merge the setup pull request, then run setup again. It starts the re-index and reports this item as pending until the index reaches that commit.
|
|
30
|
-
- **Known test command** (`server.test-command`) — Bridge knows the command that runs this repository's tests. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
30
|
+
- **Known test command** (`server.test-command`) — Bridge knows the command that runs this repository's tests. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer --test-command "<command>"`, replacing `<command>` with the one command that runs your tests, or run setup and answer its test command question.
|
|
31
31
|
- **Service availability** (`server.service-availability`) — Bridge could read this repository's readiness from the server. Fix: Retry in a few minutes. If it keeps failing, email info@bridgegpt.ai.
|
|
32
32
|
- **Claude login** (`install.claude-login`) — Claude Code is signed in on this computer. Fix: Run `claude` and sign in, then run setup again.
|
|
33
33
|
- **Repository identity** (`install.identity`) — Bridge knows which repository this folder is. Fix: Run setup from the repository root, or pass `--repo <name>`.
|
|
@@ -49,12 +49,12 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
|
|
|
49
49
|
- **Claude login** (`conductor.claude-login`) — Claude Code is signed in for the workers. Fix: Run `claude` and sign in, then run setup again.
|
|
50
50
|
- **Merge credential capability** (`conductor.merge-credential-capability`) — The merge token can push to the repository and read pull requests. Fix: Replace the token (setup offers to), then run setup again.
|
|
51
51
|
- **Worktree preparation** (`conductor.worktree-preparation`) — The executor's clone can keep its working files out of git (`.git/info/exclude` exists or can be written). Fix: Make `.git/info/exclude` writable in this clone.
|
|
52
|
-
- **Supervisor gate profile** (`conductor.install-section-supervisor-gate-profile`) — The repository's test gate profile is stored and valid. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
53
|
-
- **Supervisor required CI checks** (`conductor.install-section-supervisor-required-checks`) — The required CI checks in the gate match checks the provider reports. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
54
|
-
- **Supervisor review-policy alignment** (`conductor.install-section-supervisor-review-alignment`) — The review policy and the review workflow agree. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
52
|
+
- **Supervisor gate profile** (`conductor.install-section-supervisor-gate-profile`) — The repository's test gate profile is stored and valid. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
53
|
+
- **Supervisor required CI checks** (`conductor.install-section-supervisor-required-checks`) — The required CI checks in the gate match checks the provider reports. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
54
|
+
- **Supervisor review-policy alignment** (`conductor.install-section-supervisor-review-alignment`) — The review policy and the review workflow agree. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
55
55
|
- **GitHub App actions permission** (`conductor.install-section-github-actions-permission`) — The GitHub App may start workflow runs. Only needed when merges go through GitHub Actions. Fix: Accept the updated permission on the GitHub App's installation page.
|
|
56
|
-
- **Merge execution eligibility** (`conductor.install-section-merge-execution-eligibility`) — This repository can use GitHub Actions merges. Only needed for that merge mode. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
57
|
-
- **Epic Implementer MCP profile token** (`conductor.install-section-epic-implementer-profile-token`) — The Bridge key used by the Epic Implementer tool profile is stored. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
56
|
+
- **Merge execution eligibility** (`conductor.install-section-merge-execution-eligibility`) — This repository can use GitHub Actions merges. Only needed for that merge mode. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer --merge-workflow --codeowner <@org/team|@user>` and merge its pull request.
|
|
57
|
+
- **Epic Implementer MCP profile token** (`conductor.install-section-epic-implementer-profile-token`) — The Bridge key used by the Epic Implementer tool profile is stored. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
58
58
|
- **Conductor hook targets** (`conductor.install-section-conductor-hook-targets`) — The git hook targets are in place for this clone. Fix: Run `npx -y @bridge_gpt/mcp-server epic-implementer install-git-hooks`.
|
|
59
59
|
- **GitHub Actions merge: local observation prerequisites** (`conductor.install-section-gh-actions-merge-auth`) — This computer can observe GitHub Actions merges. Only needed for that merge mode. Fix: Sign in with `gh auth login` and rerun setup.
|
|
60
60
|
- **GitHub Actions merge: capability observability** (`conductor.install-section-gh-actions-merge-observable`) — Bridge can observe the outcome of GitHub Actions merges. Only needed for that merge mode. Fix: Rerun setup and follow the step it prints.
|
|
@@ -63,9 +63,9 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
|
|
|
63
63
|
- **Launch evidence: unattended consent** (`server.admission-unattended-consent`) — Launch check: unattended runs are allowed. Fix: Turn on **Allow unattended Epic Implementer runs** on the Setup page, or launch with `--attended`.
|
|
64
64
|
- **Launch evidence: notification destination** (`server.admission-notify-webhook`) — Launch check: an escalation destination is verified. Fix: Declare a notify webhook, or verify your account email.
|
|
65
65
|
- **Launch evidence: repository workflows** (`server.admission-repository-readiness`) — Launch check: the CI and review workflows are confirmed. Fix: Run setup, merge the setup pull request, then run setup again.
|
|
66
|
-
- **Launch evidence: required CI checks** (`server.admission-required-checks`) — Launch check: the required CI checks are stored. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
66
|
+
- **Launch evidence: required CI checks** (`server.admission-required-checks`) — Launch check: the required CI checks are stored. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
67
67
|
- **Launch evidence: indexed repository** (`server.admission-index-provenance`) — Launch check: the index reaches the commit that holds the workflows. Fix: Merge the setup pull request, then run setup again.
|
|
68
|
-
- **Repository test gate** (`server.gate-profile`) — The repository's test gate is stored. Fix: Run `npx -y @bridge_gpt/mcp-server install
|
|
68
|
+
- **Repository test gate** (`server.gate-profile`) — The repository's test gate is stored. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
|
|
69
69
|
- **Repository test gate warnings** (`server.gate-profile-warnings`) — The stored test gate has no unresolved warnings. Fix: Read the warnings setup prints and confirm or edit the gate.
|
|
70
70
|
- **Effective review mode** (`server.effective-review-mode`) — Bridge shows which review mode child pull requests will use. Fix: Choose a review policy at launch with `--review-policy` if you want a different one.
|
|
71
71
|
- **Epic branch CI** (`server.epic-branch-ci-decision`) — Someone has decided whether CI runs on pull requests into the epic branch. Fix: Run setup and answer the epic-branch CI question, or pass `--epic-branch-ci-decision include|decline`.
|
|
@@ -89,7 +89,7 @@ It writes this guide to `docs/install/epic-implementer-install.md` in your proje
|
|
|
89
89
|
Run this once per repository, from the repository root, in your own terminal:
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
npx -y @bridge_gpt/mcp-server install
|
|
92
|
+
npx -y @bridge_gpt/mcp-server install epic-implementer
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
`install-bridge conductor` is the same command with another spelling. Setup checks everything first (read-only), fixes only what is missing, checks again, and ends with one verdict: "Ready for your first epic" or "Not ready: N steps left", with the fix for each step. It asks before anything that writes, and without a terminal every question is a "no".
|
|
@@ -107,7 +107,7 @@ Test command: `npm test` (stored). Change it with --test-command "...".
|
|
|
107
107
|
To save or replace it, pass the command yourself:
|
|
108
108
|
|
|
109
109
|
```bash
|
|
110
|
-
npx -y @bridge_gpt/mcp-server install
|
|
110
|
+
npx -y @bridge_gpt/mcp-server install epic-implementer --test-command "npm run lint && npm run build"
|
|
111
111
|
```
|
|
112
112
|
|
|
113
113
|
The flag is your consent for that one write, so setup asks no command question. It checks the command first (one line, no `${{`, at most 500 characters), saves it once, and reads it back. It reports success only when the stored value matches. Passing the same command again says "Test command unchanged" and writes nothing. With `--dry-run`, nothing is saved.
|
|
@@ -149,7 +149,7 @@ An old copy of the command line tool can print old wording or miss a flag such a
|
|
|
149
149
|
1. See which version ran: `npx -y @bridge_gpt/mcp-server doctor`. Its `Bridge MCP version:` line gives the installed version and the latest one, and says when an upgrade is available.
|
|
150
150
|
2. Fetch the newest release by running through `@latest`: `npx -y @bridge_gpt/mcp-server@latest doctor`. The `Bridge MCP version:` line should now show the latest version.
|
|
151
151
|
3. Refresh the installed command files: `npx -y @bridge_gpt/mcp-server@latest install`.
|
|
152
|
-
4. Run setup again: `npx -y @bridge_gpt/mcp-server@latest install
|
|
152
|
+
4. Run setup again: `npx -y @bridge_gpt/mcp-server@latest install epic-implementer`.
|
|
153
153
|
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.
|
|
154
154
|
|
|
155
155
|
## 3. Define the epic
|
|
@@ -185,3 +185,28 @@ Add `--dry-run` for a read-only preview, or `--attended` to opt out of unattende
|
|
|
185
185
|
## If something goes wrong
|
|
186
186
|
|
|
187
187
|
Every refusal names the missing item and its fix, and creates nothing. Run setup again after you fix an item. To stop a run that is already active, run `npx -y @bridge_gpt/mcp-server epic-implementer abandon-run --epic-run-id <id>`, replacing `<id>` with the run ID that `drive-epic` printed when it started the run. Abandoning a run is final. For a read-only report of every item, run `npx -y @bridge_gpt/mcp-server epic-implementer readiness --json`. If you are stuck, email info@bridgegpt.ai.
|
|
188
|
+
# Uninstall / clean up
|
|
189
|
+
|
|
190
|
+
Inspect before removing local resources:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
npx -y @bridge_gpt/mcp-server executor uninstall-service
|
|
194
|
+
npx -y @bridge_gpt/mcp-server executor uninstall-service --executor-id builder-01 --dry-run
|
|
195
|
+
epic-implementer uninstall-git-hooks --dry-run
|
|
196
|
+
npx -y @bridge_gpt/mcp-server worktrees
|
|
197
|
+
npx -y @bridge_gpt/mcp-server worktrees --prune --dry-run
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Remove `--dry-run` to approve the displayed plan at an interactive `(y/N)` prompt. Declined and noninteractive requests remove nothing. Executor service removal affects this user's home-scoped service; install-state locator cleanup affects only the current repository. Stopping may interrupt jobs and does not certify termination of all child processes: finish or stop work through the supported executor or plane workflow first. Darwin stdout/stderr logs are retained at `~/Library/Logs/com.bridge-gpt.executor.<id>.{out,err}.log`; Linux logs remain in the user journald journal. If a later phase fails, the command reports completed and retained stages; retry the same command after correcting the reported condition, then confirm with `doctor`.
|
|
201
|
+
|
|
202
|
+
Hook removal targets only Bridge's managed text in the common hooks directory shared by linked worktrees. Mixed user hook bytes and modes are preserved; unsafe or ambiguous content is retained for owner repair.
|
|
203
|
+
|
|
204
|
+
Worktree observations use local refs as of the last fetch. `worktrees --fetch` explicitly performs one `git fetch --prune origin`; it cannot be combined with `--dry-run`. `--base <branch>` selects the comparison base. Pruning retains protected, dirty, active, locked, or uncertain worktrees. Unknown and partial sizes are labelled explicitly; incomplete inspection offers no candidates. A remote-gone branch needs prior origin-upstream and surviving-tip evidence. Partial cleanup reports retained resources; reconcile them with the repository owner or support. Avoid forced removal or deletion.
|
|
205
|
+
|
|
206
|
+
For the other local permissions surfaces use `npx -y @bridge_gpt/mcp-server install --remove-bridge-permissions` and `npx -y @bridge_gpt/mcp-server install epic-implementer --remove-merge-token`.
|
|
207
|
+
|
|
208
|
+
## “Already checked out at” troubleshooting
|
|
209
|
+
|
|
210
|
+
Start with `npx -y @bridge_gpt/mcp-server worktrees`. Git holds a branch in the checkout named in the error and refuses a second checkout until that holding worktree is removed. Use `worktrees --prune` only for proven eligible resources; preserve retained work and reconcile it with the repository owner.
|
|
211
|
+
|
|
212
|
+
For unexpected commits, use `npx -y @bridge_gpt/mcp-server doctor --stale-branch PROJ-123 --stale-branch-base main`. Opt into prevention with `start-tickets --guard-stale-branch`. Those diagnose or prevent stale reuse; neither releases a branch held by another worktree.
|