@code-partner/codepipe 0.3.3-dev.95.g49a6768 → 0.3.3-dev.96.gbcb185c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +38 -37
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- var me="0.3.3-dev.95.g49a6768",Te="https://hub.dev.codepipe.dev";var Ie=4,mu=4;function Lr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=mu&&t<=Ie}var je=".codepipe-context.yaml",lr=".devpipe-context.yaml",ci=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",je]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[je]}];function Dr(t=2){return`# CodePipe Context Repo format version.
2
+ var me="0.3.3-dev.96.gbcb185c",Te="https://hub.dev.codepipe.dev";var Ie=4,mu=4;function Lr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=mu&&t<=Ie}var je=".codepipe-context.yaml",lr=".devpipe-context.yaml",ci=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",je]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[je]}];function Dr(t=2){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function li(t){if(!t)return 0;let e=/^\s*template_version:\s*(\d+)\s*$/m.exec(t),r=e?parseInt(e[1]??"",10):NaN;return Number.isFinite(r)&&r>=0?r:0}function ui(t,e=ci){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function pi(t,e=ci){return e.filter(r=>r.version>t)}var di=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","analysis","chat"];function pt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var qe="opus",Br="sonnet",gu="haiku",Kn=[qe,Br,gu],fi={analyze:qe,implement:qe,"resolve-conflict":qe,rework:qe,estimate:Br,build:Br,draft:Br,index:qe,analysis:qe,chat:qe};var hu=[{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Kn],help:"Overrides the recommended defaults for every role not listed below."},...di.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Kn],help:`recommended: ${fi[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function mi(t=hu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...mi(r.groups));return e}function yu(t,e){let r=JSON.stringify(e);return mi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function gi(t){let e=yu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":return typeof r!="string"?{ok:!1,error:`${e.id} must be a string`}:{ok:!0,field:e,value:r.trim()};case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var dt=/^[a-z][a-z0-9-]{1,30}$/,wu="-codepipe-ctx";function Ge(t){return`${t}${wu}`}var ku=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Gr(t){for(let e of ku){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ur={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Ct(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var ft="x-bitbucket-api-token-auth";function Mr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var hi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Ah}from"commander";import{homedir as $i}from"node:os";import{mkdirSync as ju,readFileSync as Pu,writeFileSync as Eu,existsSync as qn}from"node:fs";import{dirname as xi,join as Kr,resolve as Au}from"node:path";import{fileURLToPath as _u}from"node:url";import{existsSync as Fr,readFileSync as wi,readdirSync as $u,writeFileSync as vu}from"node:fs";import{dirname as xu,join as Ye}from"node:path";import{parse as Su}from"yaml";import{existsSync as yi,renameSync as bu}from"node:fs";function mt(t,e,r=n=>console.error(n)){if(yi(e)||!yi(t))return!1;try{return bu(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Pe=".codepipe",Wn=".devpipe";function Cu(t=process.cwd()){let e=t;for(;;){if(Fr(Ye(e,Pe,"project.yaml")))return e;if(Fr(Ye(e,Wn,"project.yaml")))return mt(Ye(e,Wn),Ye(e,Pe))&&Tu(e),e;let r=xu(e);if(r===e)return null;e=r}}function Ru(t){let e=Ye(t,Pe);return Fr(e)?e:Ye(t,Wn)}function Tu(t){let e=Ye(t,".gitignore");if(!Fr(e))return;let r=wi(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
6
- `);n!==r&&vu(e,n)}function ge(t=process.cwd()){let e=Cu(t);if(!e)return null;let r=Ru(e),n=Iu(wi(Ye(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function ki(t,e,r){return $u(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function Hr(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Iu(t){let e=Su(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,f=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function bi(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var vi=Au(xi(_u(import.meta.url)),"..");function Si(t){let e=Kr(vi,".env");if(qn(e)&&process.loadEnvFile(e),t){let r=Kr(vi,"profiles",t,".env");qn(r)&&process.loadEnvFile(r)}}function Rt(t){let e=L("CONFIG");return e||(t?Kr($i(),".codepipe","profiles",t,"config.json"):Kr($i(),".codepipe","config.json"))}function $e(t){let e=Rt(t);if(!qn(e))return null;let r=Pu(e,"utf-8");return JSON.parse(r)}function Me(t,e){let r=Rt(e);ju(xi(r),{recursive:!0}),Eu(r,JSON.stringify(t,null,2)+`
5
+ `}function li(t){if(!t)return 0;let e=/^\s*template_version:\s*(\d+)\s*$/m.exec(t),r=e?parseInt(e[1]??"",10):NaN;return Number.isFinite(r)&&r>=0?r:0}function ui(t,e=ci){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function pi(t,e=ci){return e.filter(r=>r.version>t)}var di=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","analysis","chat"];function pt(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var qe="opus",Br="sonnet",gu="haiku",Kn=[qe,Br,gu],fi={analyze:qe,implement:qe,"resolve-conflict":qe,rework:qe,estimate:Br,build:Br,draft:Br,index:qe,analysis:qe,chat:qe};var hu=[{id:"branch",label:"Branch",help:"Task-branch naming.",fields:[{id:"branch.pattern",file:"project.yaml",path:["branch","pattern"],type:"string",label:"Task-branch pattern",nullable:!0,mustContain:"<TASK_ID>",help:"Template for the per-task branch name. Must contain the <TASK_ID> placeholder. Empty \u21D2 default codepipe/<TASK_ID>."}]},{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Kn],help:"Overrides the recommended defaults for every role not listed below."},...di.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Kn],help:`recommended: ${fi[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function mi(t=hu){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...mi(r.groups));return e}function yu(t,e){let r=JSON.stringify(e);return mi().find(n=>n.file===t&&JSON.stringify(n.path)===r)}function gi(t){let e=yu(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,n=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||n&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.type==="string"&&e.mustContain&&!i.includes(e.mustContain)?{ok:!1,error:`${e.id} must contain "${e.mustContain}"`}:{ok:!0,field:e,value:i}}case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var dt=/^[a-z][a-z0-9-]{1,30}$/,wu="-codepipe-ctx";function Ge(t){return`${t}${wu}`}var bu=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Gr(t){for(let e of bu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ur={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Ct(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var ft="x-bitbucket-api-token-auth";function Mr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var hi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Ah}from"commander";import{homedir as $i}from"node:os";import{mkdirSync as ju,readFileSync as Pu,writeFileSync as Eu,existsSync as qn}from"node:fs";import{dirname as xi,join as Kr,resolve as Au}from"node:path";import{fileURLToPath as _u}from"node:url";import{existsSync as Fr,readFileSync as wi,readdirSync as $u,writeFileSync as vu}from"node:fs";import{dirname as xu,join as Ye}from"node:path";import{parse as Su}from"yaml";import{existsSync as yi,renameSync as ku}from"node:fs";function mt(t,e,r=n=>console.error(n)){if(yi(e)||!yi(t))return!1;try{return ku(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var Pe=".codepipe",Wn=".devpipe";function Cu(t=process.cwd()){let e=t;for(;;){if(Fr(Ye(e,Pe,"project.yaml")))return e;if(Fr(Ye(e,Wn,"project.yaml")))return mt(Ye(e,Wn),Ye(e,Pe))&&Tu(e),e;let r=xu(e);if(r===e)return null;e=r}}function Ru(t){let e=Ye(t,Pe);return Fr(e)?e:Ye(t,Wn)}function Tu(t){let e=Ye(t,".gitignore");if(!Fr(e))return;let r=wi(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
6
+ `);n!==r&&vu(e,n)}function ge(t=process.cwd()){let e=Cu(t);if(!e)return null;let r=Ru(e),n=Iu(wi(Ye(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function bi(t,e,r){return $u(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function Hr(t,e=process.cwd()){try{let r=ge(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Iu(t){let e=Su(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,f=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function ki(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var vi=Au(xi(_u(import.meta.url)),"..");function Si(t){let e=Kr(vi,".env");if(qn(e)&&process.loadEnvFile(e),t){let r=Kr(vi,"profiles",t,".env");qn(r)&&process.loadEnvFile(r)}}function Rt(t){let e=L("CONFIG");return e||(t?Kr($i(),".codepipe","profiles",t,"config.json"):Kr($i(),".codepipe","config.json"))}function $e(t){let e=Rt(t);if(!qn(e))return null;let r=Pu(e,"utf-8");return JSON.parse(r)}function Me(t,e){let r=Rt(e);ju(xi(r),{recursive:!0}),Eu(r,JSON.stringify(t,null,2)+`
7
7
  `,{mode:384})}function Wr(t){if(t)return{cfg:he(t),profile:t};let e;try{e=ge()?.spec.projectId||void 0}catch{}if(e){let r=$e(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:he(void 0),profile:void 0}}function he(t){let e=$e(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${Rt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Ci}from"node:os";import{join as Ri}from"node:path";function Ti(){mt(Ri(Ci(),".devpipe"),Ri(Ci(),".codepipe"))}import{homedir as Ii}from"node:os";import{existsSync as ji,mkdirSync as Pi,readFileSync as Ei,writeFileSync as Ai}from"node:fs";import{dirname as _i,join as Oi}from"node:path";function qr(t,e,r){let n=U(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,V(n),"pinned")}function Ni(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],V(r),!0):!1}function Ee(t){return Oi(Ii(),".codepipe","secrets",`${t}.json`)}function U(t){let e=Ee(t);return ji(e)?JSON.parse(Ei(e,"utf-8")):null}function V(t){let e=Ee(t.projectId);Pi(_i(e),{recursive:!0}),Ai(e,JSON.stringify(t,null,2)+`
8
8
  `,{mode:384})}function Yr(){return Oi(Ii(),".codepipe","shared.json")}function Yn(){let t=Yr();return ji(t)?JSON.parse(Ei(t,"utf-8")):null}function Ui(t){let e=Yr();Pi(_i(e),{recursive:!0}),Ai(e,JSON.stringify(t,null,2)+`
9
9
  `,{mode:384})}function Tt(t){let e=U(t)?.claude?.oauthToken;return e||Yn()?.claude?.oauthToken}function pr(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function It(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Li(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=$e(e);r&&!t.force&&(console.error(`already configured at ${Rt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");Me({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};V(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${Rt(e)}`)}import{homedir as Co}from"node:os";import{join as vr}from"node:path";import{appendFileSync as Ou,existsSync as Di,mkdirSync as Nu,renameSync as Bi,statSync as Uu,unlinkSync as Lu}from"node:fs";import{Writable as Du}from"node:stream";import{join as Bu}from"node:path";var Gi={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},jt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Nu(e.dir,{recursive:!0}),this.currentPath=Bu(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
@@ -16,7 +16,7 @@ template_version: ${t}
16
16
  `).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;At(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await eo(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function Qn(t){let e=new Map;for(let r of Et){let n=Ae(t,r);Ve(n)&&e.set(r,Xn(n))}return e}function Zn(t,e){Wi(t,{recursive:!0});for(let[r,n]of e){let o=Ae(t,r);Ve(o)||Pt(o,n)}}var Vi=3,cp=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function _t(t,e,r){if(!op(Ji(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Je(t,i.path);ip(sp(s),{recursive:!0}),i.encoding==="base64"?Yi(s,Buffer.from(i.content,"base64")):Yi(s,i.content)}let n=zi(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...Et]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await eo(t))}async function eo(t){let e=zi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=Vi;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await lp(e);if(i.length>0&&i.every(s=>cp.has(s)))await e.raw(["checkout","--theirs","--",...i]),await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"]);else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${Vi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function lp(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
17
  `).map(r=>r.trim()).filter(Boolean)}function Je(t,e){if(ap(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=to(Ji(t,e)),n=to(t+"/");if(r!==to(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var dp=/^(\d{4})-(.+)\.md$/,fp="0000-template.md";function mp(t){let e=t.split(`
18
18
  `),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function gp(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex($=>$.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],f="",p=null,g=a>=0?a+1:0;for(let $=g;$<s.length;$++){let y=(s[$]??"").trim();if(y===""){g=$+1;continue}let b=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!b)break;let v=(b[1]??"").trim().toLowerCase(),O=(b[2]??"").trim(),P=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);P&&(p=parseInt(P[1]??"",10)),v==="tasks"&&(f=O),l.has(v)||u.push(y),g=$+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,h=s.slice(g).join(`
19
+ `),a=s.findIndex($=>$.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],f="",p=null,g=a>=0?a+1:0;for(let $=g;$<s.length;$++){let y=(s[$]??"").trim();if(y===""){g=$+1;continue}let k=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!k)break;let v=(k[1]??"").trim().toLowerCase(),O=(k[2]??"").trim(),P=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);P&&(p=parseInt(P[1]??"",10)),v==="tasks"&&(f=O),l.has(v)||u.push(y),g=$+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,h=s.slice(g).join(`
20
20
  `).replace(/^\n+/,""),C=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${d}`,...u,"",h].join(`
21
21
  `);return{content:C.endsWith(`
22
22
  `)?C:C+`
@@ -24,7 +24,7 @@ template_version: ${t}
24
24
 
25
25
  - **Status:** superseded by ADR-${r}`):n}function yp(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
26
26
  `)+`
27
- `}async function es(t,e,r,n=new Date().toISOString().slice(0,10)){try{await pp(t).pull(void 0,void 0,["--rebase"])}catch{}let o=[],i=[];for(let d of r){let h=Je(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!Xi(h)){i.push(d);continue}o.push({slug:d,content:Qi(h,"utf-8")})}let s=Zi(t,"adr"),a=new Map;if(Xi(s))for(let d of up(s)){let h=dp.exec(d);!h||d===fp||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Qi(Zi(s,d),"utf-8")})}let c=Math.max(0,...[...a.values()].map(d=>d.num))+1,l=new Map,u=[],f=[];for(let d of o){if([...a.entries()].find(([,v])=>v.slug===d.slug&&v.content.includes(e))){f.push(d.slug);continue}let C=c++,$=`${String(C).padStart(4,"0")}-${d.slug}.md`,{content:y,supersedes:b}=gp(d.content,C,d.slug,e,n);if(l.set($,y),a.set($,{num:C,slug:d.slug,content:y}),u.push(`adr/${$}`),b!==null){let v=[...a.keys()].find(O=>O.startsWith(`${String(b).padStart(4,"0")}-`));if(v&&v!==$){let O=hp(l.get(v)??a.get(v).content,C);l.set(v,O),a.set(v,{...a.get(v),content:O})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:mp(h.content)}));l.set("INDEX.md",yp(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await _t(t,g,`adr(${e}): promote ${o.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as ts,readFileSync as kp}from"node:fs";import{join as rs}from"node:path";function bp(t){for(let e of[je,lr]){let r=rs(t,e);if(ts(r))try{return li(kp(r,"utf-8"))}catch{return 0}}return 0}function $p(t,e,r,n=2){let o=e<n,i=o?ui(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Qr(t,e){return $p(e,bp(t),r=>ts(rs(t,r)))}import{existsSync as ss,mkdirSync as Up,mkdtempSync as Lp,rmSync as as,writeFileSync as cs}from"node:fs";import{tmpdir as Dp}from"node:os";import{dirname as Bp,join as en}from"node:path";import{simpleGit as so}from"simple-git";var ht=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function ns(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
27
+ `}async function es(t,e,r,n=new Date().toISOString().slice(0,10)){try{await pp(t).pull(void 0,void 0,["--rebase"])}catch{}let o=[],i=[];for(let d of r){let h=Je(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!Xi(h)){i.push(d);continue}o.push({slug:d,content:Qi(h,"utf-8")})}let s=Zi(t,"adr"),a=new Map;if(Xi(s))for(let d of up(s)){let h=dp.exec(d);!h||d===fp||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:Qi(Zi(s,d),"utf-8")})}let c=Math.max(0,...[...a.values()].map(d=>d.num))+1,l=new Map,u=[],f=[];for(let d of o){if([...a.entries()].find(([,v])=>v.slug===d.slug&&v.content.includes(e))){f.push(d.slug);continue}let C=c++,$=`${String(C).padStart(4,"0")}-${d.slug}.md`,{content:y,supersedes:k}=gp(d.content,C,d.slug,e,n);if(l.set($,y),a.set($,{num:C,slug:d.slug,content:y}),u.push(`adr/${$}`),k!==null){let v=[...a.keys()].find(O=>O.startsWith(`${String(k).padStart(4,"0")}-`));if(v&&v!==$){let O=hp(l.get(v)??a.get(v).content,C);l.set(v,O),a.set(v,{...a.get(v),content:O})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:mp(h.content)}));l.set("INDEX.md",yp(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await _t(t,g,`adr(${e}): promote ${o.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as ts,readFileSync as bp}from"node:fs";import{join as rs}from"node:path";function kp(t){for(let e of[je,lr]){let r=rs(t,e);if(ts(r))try{return li(bp(r,"utf-8"))}catch{return 0}}return 0}function $p(t,e,r,n=2){let o=e<n,i=o?ui(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Qr(t,e){return $p(e,kp(t),r=>ts(rs(t,r)))}import{existsSync as ss,mkdirSync as Up,mkdtempSync as Lp,rmSync as as,writeFileSync as cs}from"node:fs";import{tmpdir as Dp}from"node:os";import{dirname as Bp,join as en}from"node:path";import{simpleGit as so}from"simple-git";var ht=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function ns(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
28
  `+t.slice(t.length-e)}async function ze(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function Zr(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Xe(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await vp(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function vp(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Qe(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function is(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var ro=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new ht(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,n){if(n&&n.length>0){let i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},no=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new ht(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let f of u.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let f of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${o}/actions/runs/${f.id}/jobs?per_page=50`,{headers:n});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!h.ok)continue;let C=await h.text();u.push(`### CI job: ${d.name}
29
29
 
30
30
  ${ns(C,8e3)}`)}}return u.length===0?void 0:ns(u.join(`
@@ -309,7 +309,8 @@ apply:
309
309
  # into local clones for apply.mode: local). No per-project knob to configure.
310
310
 
311
311
  # Task-branch name template. <TASK_ID> \u2192 lower-cased tracker key (e.g.
312
- # codepipe/dev-109).
312
+ # codepipe/dev-109). Also editable from the dashboard: project card \u2192 Settings \u2192
313
+ # Branch (must keep the <TASK_ID> placeholder).
313
314
  branch:
314
315
  pattern: codepipe/<TASK_ID>
315
316
 
@@ -432,21 +433,21 @@ llm:
432
433
  `)}async function ls(t,e,r,n){let o=so(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Qr(t,e);if(!i.outdated)return i;let s=Gp(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Fp(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Fe(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Mp(i)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function Fp(t,e,r,n,o,i,s){let a=so(t),c=Lp(en(Dp(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(Ot(l,u).map(h=>[h.path,h.content])),p=0;for(let h of n.missingPaths){if(h===je)continue;let C=f.get(h);if(C==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let $=en(c,h);ss($)||(Up(Bp($),{recursive:!0}),cs($,C),p++)}cs(en(c,je),Dr(n.currentVersion)),p++;let g=en(c,lr);ss(g)&&(as(g,{force:!0}),p++);let d=so(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await d.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),as(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{existsSync as Hp,readFileSync as Kp,writeFileSync as Wp}from"node:fs";import{homedir as qp}from"node:os";import{join as us}from"node:path";import{parseDocument as Yp}from"yaml";function Vp(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Jp(t,e){let r=Yp(t);return r.set("repos",e.map(Vp)),r.toString()}function zp(t,e){let r=[us(qp(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(us(e,"project.yaml")),r}function fr(t,e,r){let n=[],o=[];for(let i of zp(t,r))if(Hp(i))try{let s=Kp(i,"utf-8"),a=Jp(s,e);a!==s&&(Wp(i,a),n.push(i))}catch(s){o.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:n,errors:o}}import{homedir as Xp}from"node:os";import{existsSync as Qp,mkdirSync as Zp}from"node:fs";import{join as ao}from"node:path";import{simpleGit as fs}from"simple-git";var ps=t=>console.log(t);function ds(t){ps=t}function mr(t,e="info"){ps(t,e)}function ve(t,e,r){let n=r??ao(Xp(),".codepipe","repos");return ao(n,t,e)}async function tn(t,e,r={}){let n=ve(t,e.name,r.baseDir),o=r.cloneUrlOverride??co(e);if(!Qp(ao(n,".git"))){Zp(n,{recursive:!0});let a=fs();mr(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
433
434
  ${l.trim()}`)}}let i=fs(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
434
435
  ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function gr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ms=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function rn(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&mr(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await gr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await gr(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...ms,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function gs(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await gr(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await gr(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function hs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await gs(t,i,()=>rn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await gr(t,g)||(g=`origin/${u??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,p]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...ms,"cherry-pick",p])}catch($){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=$ instanceof Error?$.message:String($);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
435
- ${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),C=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(C),await t.push([n,"--delete",o]).catch(()=>{}),{commit:h}}async function ys(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await gs(t,i,()=>rn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function ws(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function co(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as ed,createDecipheriv as td,createHash as rd,createPrivateKey as nd,createPublicKey as lo,diffieHellman as ks,generateKeyPairSync as bs,hkdfSync as $s,randomBytes as od}from"node:crypto";var vs=Buffer.from("devpipe-sealedbox-v1","utf-8");function nn(){let{publicKey:t,privateKey:e}=bs("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ae(t){let e=Buffer.from(t,"base64");return(rd("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function He(t,e){let r=lo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=bs("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=ks({privateKey:o,publicKey:r}),c=Buffer.from($s("sha256",a,Buffer.concat([i,s]),vs,32)),l=od(12),u=ed("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(f),u.final()]),g=u.getAuthTag(),d={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(d),"utf-8").toString("base64")}function on(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=nd({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=lo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=lo(n).export({type:"spki",format:"der"}),a=ks({privateKey:n,publicKey:o}),c=Buffer.from($s("sha256",a,Buffer.concat([i,s]),vs,32)),l=td("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}function id(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function xs(t,e,r,n){let o=id(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=qr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=He(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as Rs}from"node:crypto";import{readFileSync as sd}from"node:fs";import Ze from"node:tls";var Ts=typeof Ze.getCACertificates=="function"&&typeof Ze.setDefaultCACertificates=="function",Ss=!1,Cs=new Map,Is=t=>console.warn(t);function ad(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function js(t=Is){if(Ss)return;Ss=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Ts))try{let r=ad(sd(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ze.setDefaultCACertificates([...Ze.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function Ps(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function cd(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
436
- `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function ld(t,e,r){return new Promise((n,o)=>{let i=Ze.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new Rs(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function uo(t,e,r){return new Promise(n=>{let o=Ze.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function ud(t){try{let e=await fetch(t);return e.ok?new Rs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Es(t,e=443,r=Is){let n=`${t}:${e}`,o=Cs.get(n);if(o)return o;let i=pd(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Cs.set(n,i),i}async function pd(t,e,r){if(!Ts)return!1;let n=8e3;if(await uo(t,e,n))return!0;let o=await ld(t,e,n),i=Ze.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=cd(o);if(!c)break;let l=await ud(c);if(!l)break;if(s.push(l.toString()),Ze.setDefaultCACertificates([...i,...s]),await uo(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return uo(t,e,n)}function Oe(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ye(t,e,r){js();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(Ps(s)&&await Es(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var As=t=>new Promise(e=>setTimeout(e,t));function dd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fd(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function po(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=fd(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ye(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&dd(l.status,u)){await As(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await As(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function et(t){let e;try{e=await ye(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Ns(t){try{let e=await ye(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var hr="Stage",_s=new Map;async function md(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=_s.get(o);if(i)return i;let s=await ye(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return _s.set(o,l.id),l.id}async function Us(t,e,r,n=hr){let o=await md(t,e,r,n);await po(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Ls(t,e,r){return await(await po(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ds(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await po(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var Os=new Map;async function Bs(t,e){let r=Os.get(e);if(r)return r;let n=await ye(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Os.set(e,i.id),i.id}async function Gs(t,e,r,n,o,i=hr){let s=await Bs(t,e),a=await ye(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ms(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ye(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}var Fs="attachments(id,name,url,size,mimeType)",gd="links(direction,linkType(name),issues(idReadable))",Hs=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Fs},${gd}`,hd=`id,text,created,author(login),${Fs}`;function Ks(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Ws(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function sn(t,e){let r=e.stageField??hr,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Hs}&$top=200`,s=await ye(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ys(c,r))}async function an(t,e,r=hr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Hs}`,o=await ye(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ys(await o.json(),r)}async function qs(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${hd}&$top=500`,o=await ye(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Ks(s.attachments);return c&&(a.attachments=c),a})}function yd(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Ys(t,e=hr){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Ks(t.attachments);a&&(s.attachments=a);let c=yd(t.links);return c&&(s.links=c),s}async function Vs(t,e){let r=await wd(t,e);return r.length>0?r:kd(t,e)}async function wd(t,e){let r=await Bs(t,e),n=await ye(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Js(s.bundle)});return i}async function kd(t,e){let r=`project: ${e}`,n=await ye(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Js(s.projectCustomField?.bundle)});return i}function Js(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function xe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function zs(t,e){let r=U(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await et({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:xe(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await ze(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:xe(c)}),o.push({kind:"github",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Xe(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:xe(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Qe(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:xe(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Zr(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(f){n.push({name:`repo:${u.name}`,ok:!1,detail:xe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Zr(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:xe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Zr(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:xe(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Tt(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await fo(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function fo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function yr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function wr(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function kr(t,e=process.env){if(!t)return!1;let r=`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function mo(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Xs(t,e=process.env){return mo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>yr(t,e),e)}function Qs(t,e=process.env){return mo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>wr(t,e),e)}function Zs(t,e=process.env){return mo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,()=>kr(t,e),e)}function ea(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=nn();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ae(e.sealKey.publicKey)}}async function ta(t,e,r,n){let o;try{o=JSON.parse(on(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await ze(o.token);return i.github={token:o.token},Nt(i,()=>{process.env.GH_TOKEN=o.token,Xs(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Qe(o.token);return i.gitlab={token:o.token},Nt(i,()=>{process.env.GITLAB_TOKEN=o.token,Qs(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Xe(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Nt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Zs(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await et({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Nt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await fo(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Nt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Nt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Nt(t,e){V(t),e()}import{existsSync as bd,readFileSync as $d,statSync as ra}from"node:fs";var na=2*1024*1024;function vd(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function oa(t,e){let r=Je(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!bd(r)||!ra(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=ra(r);if(n>na)throw new Error(`file too large: ${e} is ${n} bytes (limit ${na})`);let o=$d(r);return vd(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as xd,readFileSync as Sd,writeFileSync as Cd}from"node:fs";import{join as Rd}from"node:path";import{parseDocument as Td}from"yaml";async function ia(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=gi(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=Rd(t,o);if(!xd(s))throw new Error(`${o} not found in context repo (${t})`);let a=Td(Sd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Cd(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as go,readFileSync as ho,writeFileSync as Id}from"node:fs";import{join as cn}from"node:path";import{parseDocument as yo}from"yaml";async function sa(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=cn(t,"project.yaml");if(!go(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=yo(ho(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=cn(t,"regimen.yaml");if(!go(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=yo(ho(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)Id(cn(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ln(t){if(!t)return"Stage";try{let e=cn(t,"project.yaml");if(!go(e))return"Stage";let n=yo(ho(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as aa,readFileSync as jd,readdirSync as Pd}from"node:fs";function Ed(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Nd(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Ad(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Od(_d(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function un(t,e,r){if(r.length===0)return;let n=Ed(t,e,r),o=r.map(i=>i.issue.key);await _t(t,n,`sync(${o.join(", ")}): task data`)}function Ad(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
436
+ ${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),C=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(C),await t.push([n,"--delete",o]).catch(()=>{}),{commit:h}}async function ys(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await gs(t,i,()=>rn(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function ws(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function co(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{createCipheriv as ed,createDecipheriv as td,createHash as rd,createPrivateKey as nd,createPublicKey as lo,diffieHellman as bs,generateKeyPairSync as ks,hkdfSync as $s,randomBytes as od}from"node:crypto";var vs=Buffer.from("devpipe-sealedbox-v1","utf-8");function nn(){let{publicKey:t,privateKey:e}=ks("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ae(t){let e=Buffer.from(t,"base64");return(rd("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function He(t,e){let r=lo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=ks("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=bs({privateKey:o,publicKey:r}),c=Buffer.from($s("sha256",a,Buffer.concat([i,s]),vs,32)),l=od(12),u=ed("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(f),u.final()]),g=u.getAuthTag(),d={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(d),"utf-8").toString("base64")}function on(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=nd({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=lo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=lo(n).export({type:"spki",format:"der"}),a=bs({privateKey:n,publicKey:o}),c=Buffer.from($s("sha256",a,Buffer.concat([i,s]),vs,32)),l=td("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}function id(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function xs(t,e,r,n){let o=id(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=qr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=He(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as Rs}from"node:crypto";import{readFileSync as sd}from"node:fs";import Ze from"node:tls";var Ts=typeof Ze.getCACertificates=="function"&&typeof Ze.setDefaultCACertificates=="function",Ss=!1,Cs=new Map,Is=t=>console.warn(t);function ad(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function js(t=Is){if(Ss)return;Ss=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Ts))try{let r=ad(sd(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ze.setDefaultCACertificates([...Ze.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function Ps(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function cd(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
437
+ `)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function ld(t,e,r){return new Promise((n,o)=>{let i=Ze.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new Rs(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function uo(t,e,r){return new Promise(n=>{let o=Ze.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function ud(t){try{let e=await fetch(t);return e.ok?new Rs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Es(t,e=443,r=Is){let n=`${t}:${e}`,o=Cs.get(n);if(o)return o;let i=pd(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Cs.set(n,i),i}async function pd(t,e,r){if(!Ts)return!1;let n=8e3;if(await uo(t,e,n))return!0;let o=await ld(t,e,n),i=Ze.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=cd(o);if(!c)break;let l=await ud(c);if(!l)break;if(s.push(l.toString()),Ze.setDefaultCACertificates([...i,...s]),await uo(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return uo(t,e,n)}function Oe(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ye(t,e,r){js();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(Ps(s)&&await Es(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var As=t=>new Promise(e=>setTimeout(e,t));function dd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fd(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function po(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=fd(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await ye(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&dd(l.status,u)){await As(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await As(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function et(t){let e;try{e=await ye(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Ns(t){try{let e=await ye(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var hr="Stage",_s=new Map;async function md(t,e,r,n){let o=`${e.split("-")[0]}:${n}:${r}`,i=_s.get(o);if(i)return i;let s=await ye(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===n);if(!c)throw new Error(`yt: issue ${e} has no ${n} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${n} bundle for ${e}`);return _s.set(o,l.id),l.id}async function Us(t,e,r,n=hr){let o=await md(t,e,r,n);await po(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:n,$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Ls(t,e,r){return await(await po(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ds(t,e,r){let n={};r.summary!==void 0&&(n.summary=r.summary),r.description!==void 0&&(n.description=r.description),await po(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(n)})}var Os=new Map;async function Bs(t,e){let r=Os.get(e);if(r)return r;let n=await ye(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Os.set(e,i.id),i.id}async function Gs(t,e,r,n,o,i=hr){let s=await Bs(t,e),a=await ye(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:n,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:o,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ms(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await ye(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}var Fs="attachments(id,name,url,size,mimeType)",gd="links(direction,linkType(name),issues(idReadable))",Hs=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Fs},${gd}`,hd=`id,text,created,author(login),${Fs}`;function Ks(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Ws(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function sn(t,e){let r=e.stageField??hr,n=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");n.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);n.push(`updated: ${c} .. *`)}e.assignee?n.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&n.push("has: Assignee");let o=n.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Hs}&$top=200`,s=await ye(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ys(c,r))}async function an(t,e,r=hr){let n=`/api/issues/${encodeURIComponent(e)}?fields=${Hs}`,o=await ye(t,n);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ys(await o.json(),r)}async function qs(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${hd}&$top=500`,o=await ye(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Ks(s.attachments);return c&&(a.attachments=c),a})}function yd(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Ys(t,e=hr){let r=t.customFields??[],n=r.find(l=>l.name===e),o=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:n?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),o?.value?.login&&(s.assignee=o.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Ks(t.attachments);a&&(s.attachments=a);let c=yd(t.links);return c&&(s.links=c),s}async function Vs(t,e){let r=await wd(t,e);return r.length>0?r:bd(t,e)}async function wd(t,e){let r=await Bs(t,e),n=await ye(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!n.ok)return[];let o=await n.json(),i=[];for(let s of o)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Js(s.bundle)});return i}async function bd(t,e){let r=`project: ${e}`,n=await ye(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!n.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${n.status} ${await n.text()}`);let o=await n.json(),i=[];for(let s of o[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Js(s.projectCustomField?.bundle)});return i}function Js(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function xe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function zs(t,e){let r=U(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await et({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:xe(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await ze(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:xe(c)}),o.push({kind:"github",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Xe(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:xe(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Qe(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:xe(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Zr(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(f){n.push({name:`repo:${u.name}`,ok:!1,detail:xe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Zr(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:xe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Zr(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:xe(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Tt(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await fo(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function fo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function yr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function wr(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function br(t,e=process.env){if(!t)return!1;let r=`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function mo(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Xs(t,e=process.env){return mo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>yr(t,e),e)}function Qs(t,e=process.env){return mo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>wr(t,e),e)}function Zs(t,e=process.env){return mo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ft}:${encodeURIComponent(t)}@bitbucket.org/`,()=>br(t,e),e)}function ea(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=nn();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ae(e.sealKey.publicKey)}}async function ta(t,e,r,n){let o;try{o=JSON.parse(on(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await ze(o.token);return i.github={token:o.token},Nt(i,()=>{process.env.GH_TOKEN=o.token,Xs(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Qe(o.token);return i.gitlab={token:o.token},Nt(i,()=>{process.env.GITLAB_TOKEN=o.token,Qs(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Xe(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},Nt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,Zs(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await et({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},Nt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await fo(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},Nt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},Nt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Nt(t,e){V(t),e()}import{existsSync as kd,readFileSync as $d,statSync as ra}from"node:fs";var na=2*1024*1024;function vd(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function oa(t,e){let r=Je(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!kd(r)||!ra(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=ra(r);if(n>na)throw new Error(`file too large: ${e} is ${n} bytes (limit ${na})`);let o=$d(r);return vd(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as xd,readFileSync as Sd,writeFileSync as Cd}from"node:fs";import{join as Rd}from"node:path";import{parseDocument as Td}from"yaml";async function ia(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let o of e){let i=gi(o);if(!i.ok)throw new Error(i.error);let s=r.get(o.file)??[];s.push({path:i.field.path,value:i.value}),r.set(o.file,s)}let n=[];for(let[o,i]of r){let s=Rd(t,o);if(!xd(s))throw new Error(`${o} not found in context repo (${t})`);let a=Td(Sd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);Cd(s,a.toString()),n.push(o)}return{files:n}}import{existsSync as go,readFileSync as ho,writeFileSync as Id}from"node:fs";import{join as cn}from"node:path";import{parseDocument as yo}from"yaml";async function sa(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0||e.backlogScope!==void 0){let i=cn(t,"project.yaml");if(!go(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=yo(ho(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),e.backlogScope!==void 0&&(e.backlogScope==="personal"?s.setIn(["youtrack","backlog_scope"],"personal"):e.backlogScope==="shared"?s.setIn(["youtrack","backlog_scope"],"shared"):s.deleteIn(["youtrack","backlog_scope"])),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=cn(t,"regimen.yaml");if(!go(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=yo(ho(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)Id(cn(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ln(t){if(!t)return"Stage";try{let e=cn(t,"project.yaml");if(!go(e))return"Stage";let n=yo(ho(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof n=="string"&&n.trim().length>0?n.trim():"Stage"}catch{return"Stage"}}import{existsSync as aa,readFileSync as jd,readdirSync as Pd}from"node:fs";function Ed(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=Nd(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:Ad(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:Od(_d(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function un(t,e,r){if(r.length===0)return;let n=Ed(t,e,r),o=r.map(i=>i.issue.key);await _t(t,n,`sync(${o.join(", ")}): task data`)}function Ad(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
437
438
  `)}function _d(t,e,r){let n=new Map,o=Je(t,`tasks/${e}/comments.jsonl`);if(aa(o))for(let i of jd(o,"utf-8").split(`
438
439
  `)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Gr(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function Od(t){return t.map(e=>JSON.stringify(e)).join(`
439
440
  `)+(t.length>0?`
440
- `:"")}function Nd(t,e,r){let n=[],o=Je(t,`tasks/${e}/attachments`);if(aa(o))for(let i of Pd(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var pn=new Map;async function wo(t,e){let n=(pn.get(t)??Promise.resolve()).catch(()=>{}).then(e);pn.set(t,n);try{return await n}finally{pn.get(t)===n&&pn.delete(t)}}async function ca(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;mr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c}=await hs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await ys(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Fe(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await ws(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return te({stub:!0});case"tracker_status":{let i=Oe();return i?t.trackerIssueId?(await Us(i,t.trackerIssueId,e.newStatus,ln(t.contextDir)),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await Ls(i,t.trackerIssueId,e.body);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Gs(i,e.projectKey,e.title,e.body,e.targetStatus,ln(t.contextDir));return te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ms(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await ia(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return q("no context repo clone on this CLI");let s=ln(t.contextDir);await Ds(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await an(i,e.issueKey,s);return a&&await un(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await sa(t.contextDir,e);return te({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=oa(t.contextDir,e.path);return te({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as Ca,readFileSync as Ra}from"node:fs";import{join as Ta}from"node:path";import{homedir as Ud}from"node:os";import{existsSync as Ld,mkdirSync as Dd,readFileSync as Bd,writeFileSync as Gd}from"node:fs";import{dirname as Md,join as Fd}from"node:path";function ko(){return L("FARM_PINS")??Fd(Ud(),".codepipe","farm-pins.json")}function la(){let t=ko();if(!Ld(t))return{};try{return JSON.parse(Bd(t,"utf-8"))}catch{return{}}}function Hd(t){let e=ko();Dd(Md(e),{recursive:!0}),Gd(e,JSON.stringify(t,null,2)+`
441
- `,{mode:384})}function Kd(t){return la()[t]}function dn(t,e){let r=la();r[t]=e,Hd(r)}function fn(t,e){let r=ae(e),n=Kd(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${ko()}.`);return r}import Wd from"ws";function mn(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Wd(r)}var A=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function tt(t,e,r){return Se(t,e,"/projects",r)}async function ua(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function gn(t,e,r,n){return Se(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function pa(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function da(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function fa(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function hn(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function ma(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var br=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ga(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new br(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ha(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ya(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function wa(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function ka(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function ba(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function $a(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function va(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function yn(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function bo(t,e,r,n){await Se(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function xa(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Sa(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new A(o.status,s,a)}return s}async function M(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Se(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new A(o.status,s,a)}return s}async function Ia(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ae(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");fn(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await M(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Ta(r,"project.yaml"),g=Ta(r,"regimen.yaml");Ca(p)&&Ca(g)?c={projectYaml:Ra(p,"utf-8"),regimenYaml:Ra(g,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=He(e.farmPublicKey,JSON.stringify(l));dn(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await gn(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}import{homedir as qd}from"node:os";import{existsSync as Yd,mkdirSync as Vd,readFileSync as Jd,writeFileSync as zd}from"node:fs";import{dirname as Xd,join as Qd}from"node:path";function $o(){return L("RUNNER_PINS")??Qd(qd(),".codepipe","runner-pins.json")}function ja(){let t=$o();if(!Yd(t))return{};try{return JSON.parse(Jd(t,"utf-8"))}catch{return{}}}function Zd(t){let e=$o();Vd(Xd(e),{recursive:!0}),zd(e,JSON.stringify(t,null,2)+`
442
- `,{mode:384})}function ef(t){return ja()[t]}function vo(t,e){let r=ja();r[t]=e,Zd(r)}function Pa(t,e){let r=ae(e),n=ef(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${$o()}.`);return r}var Aa=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Ea(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Aa(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var tf={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Aa(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Ea(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Ea(t,e,r,"remove-token")},_a={api:tf,fetchProject:M,provisionOnRunner:pa,teardownOnRunner:da};async function Oa(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ae(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Pa(e.runnerId,e.runnerPublicKey);let i=U(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function Na(t,e,r,n=_a){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Oa(t,e,n),a=[];for(let p of s)await n.api.repoHasAdmin(i,p.owner,p.repoName)||a.push(`${p.owner}/${p.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let p of s)c.push({owner:p.owner,repo:p.repoName,regToken:await n.api.mintRegistrationToken(i,p.owner,p.repoName)});let l={projectId:t.projectId,runners:c},u=He(e.runnerPublicKey,JSON.stringify(l));vo(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let f=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:u});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:f.ok,...f.runners?{runners:f.runners}:{},...f.error?{error:f.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Ua(t,e,r,n=_a){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Oa(t,e,n),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(p){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=He(e.runnerPublicKey,JSON.stringify(c));vo(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var wn=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Fe(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof ht){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Fe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=rf(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function rf(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var kn=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let e=Oe();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let b=e.stageField?{stageField:e.stageField}:{},v=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{};if((e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn){let x=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[]])],[m,R]=await Promise.all([x.length>0?sn(r,{projectKey:e.projectKey,columns:x,...b,...v}):Promise.resolve([]),sn(r,{projectKey:e.projectKey,columns:[e.backlogColumn],...b})]),w=new Map;for(let S of[...m,...R])w.set(S.id,S);o=[...w.values()]}else{let x=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await sn(r,{projectKey:e.projectKey,columns:x,...b,...v})}}catch(b){this.log.warn(`[yt-sync] listIssues failed: ${b instanceof Error?b.message:String(b)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let b of o){if(s.add(b.id),a.has(b.status))continue;let v=await Da(r,b.id,e.sinceMs,this.log);v&&i.set(b.id,v)}let c=[];for(let b of e.offBoardIssueIds){if(s.has(b))continue;let v=await Da(r,b,e.sinceMs,this.log);if(v&&v.length>0&&i.set(b,v),e.requireAssignee||v&&v.length>0){let O=await sf(r,b,e.stageField,this.log);if(O)c.push(O);else if(v&&v.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(b=>!a.has(b.status)),{attachmentsByIssue:u,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(b=>({issue:b,comments:i.get(b.id)??[],attachments:u.get(b.id)??[]}));try{await un(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let b of f)this.shippedAttachments.add(b)}catch(b){let v=b instanceof Error?b.message:String(b);this.abandonTick(`context task sync failed: ${v}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[b,v]of i){let O=v.filter(x=>!g(x.id));if(O.length===0)continue;d.push({issueId:b,comments:O.map(nf)});let P=O.flatMap(x=>{let m=Gr(x.body);return m?[{commentId:x.id,author:x.author,name:m.name,args:m.args,createdAt:x.createdAt}]:[]});P.length>0&&h.push({issueId:b,commands:P})}let C={type:"youtrack_observation",projectId:e.projectId,issues:o.map(La),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(La)}:{},observedAtMs:n};this.send(C);let $=d.reduce((b,v)=>b+v.comments.length,0),y=h.reduce((b,v)=>b+v.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Ws(n,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=of(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function La(t){let{description:e,...r}=t;return r}function nf(t){let{body:e,...r}=t;return r}function of(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function sf(t,e,r,n){try{return await an(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Da(t,e,r,n){try{return await qs(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var xo="npm i -g @code-partner/codepipe@latest";function bn(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${me} (protocol ${Ie})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&qi(o.contextDir,r);let i=Ba("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ba("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,u=new Set,f=new Set,p=g();function g(){let d=mn(t.hubUrl,t.cliToken),h=null,C=new wn(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),$=new kn(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:o?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,b=async()=>{try{let m;try{let S=await M(t.hubUrl,t.cliToken,t.projectId);m={repos:S.repos,contextRepo:S.contextRepo}}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let R=await zs(t.projectId,m);if(d.readyState!==d.OPEN)return;let w={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,checkedAt:R.checkedAt};if(d.send(JSON.stringify(w)),R.ready)r.info("[readiness] ready");else{let S=R.checks.filter(j=>!j.ok).map(j=>`${j.name}(${j.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},v=()=>{b(),y=setInterval(()=>void b(),a),typeof y.unref=="function"&&y.unref()},O=()=>{y&&(clearInterval(y),y=null)},P=o?.contextDir?new zr(o.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,x=async()=>{let m=o?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let R;try{R=(await M(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let w=await ls(m,t.projectId,R,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(w)),w};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let m=Fi(t.projectId),R=L("ORIGIN")==="farm"?"farm":"local",w=L("FARM_ID"),S=t.accountEmail??m.email,j;try{let I=ea(t.projectId);I&&(j=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let k={type:"register",projectId:t.projectId,platformVersion:me,protocolVersion:Ie,accountId:m.accountId,accountLabel:m.label,origin:R,inFlightActionIds:[...u],...S?{accountEmail:S}:{},...R==="farm"&&w?{farmId:w}:{},...j?{sealPublicKey:j}:{}};d.send(JSON.stringify(k))}),d.on("message",async m=>{let R=m.toString("utf-8");if(R==="pong"||R==="ping")return;let w;try{w=JSON.parse(R)}catch{return}if(!w||typeof w!="object")return;let S=w.type;if(S==="registered"){let k=w;if(k.ok){if(r.info(`[ws] registered for project ${k.projectId}`),n({kind:"registered",projectId:k.projectId??t.projectId}),C.start(),P?.start(),v(),So(t,o,r),o?.contextDir)try{let I=Qr(o.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,x().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}else r.warn(`[ws] register rejected: ${k.reason??"unknown"}`),n({kind:"register_rejected",reason:k.reason??"unknown"}),c=!0,d.close();return}if(S==="hello"){let k=w;h=Lr(k.protocolVersion);let I=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${k.platformVersion} (protocol ${k.protocolVersion}) \u2014 ${I}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${me}, protocol ${Ie}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${xo}`),n({kind:"incompatible",hubVersion:typeof k.platformVersion=="string"?k.platformVersion:null,hubProtocol:typeof k.protocolVersion=="number"?k.protocolVersion:null,updateCommand:xo}));return}if(S==="tracking_targets"){C.setTargets(w.targets);return}if(S==="youtrack_sync_request"){$.setRequest(w);return}if(S==="youtrack_force_sync"){$.forceSync();return}if(S==="sync_local"){await pf(w,o,d,r);return}if(S==="provision_repo"){let k=w;r.info(`[repo] provision_repo: ${k.repo.name} (${k.repo.host}:${k.repo.owner}/${k.repo.repoName})`),await lf(t,o,k.repo,r),await So(t,o,r);return}if(S==="remove_repo"){let k=w;r.info(`[repo] remove_repo: ${k.repoName}${k.purge?" (purge)":""}`),await So(t,o,r),k.purge&&uf(t,o,k.repoName,r);return}if(S==="context_write"){await df(w,o,d,r);return}if(S==="adr_promote"){await ff(w,o,d,r);return}if(S==="cred_update"){let k=w,I=U(t.projectId),B=I?.sealKey?await ta(t.projectId,k.kind,k.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},K={type:"cred_update_result",updateId:k.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(K)),B.ok?(r.info(`[cred] ${k.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),b()):r.warn(`[cred] ${k.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(S==="move_to_farm"){let k=w;r.info(`[farm-move] request to move ${t.projectId} onto farm ${k.farmName} (${k.farmId})`);let I=await Ia(t,k,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(S==="gh_runner_setup"){let k=w;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${k.runnerName} (${k.runnerId})`);let I=await Na(t,k,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${k.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(S==="gh_runner_teardown"){let k=w;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${k.runnerName} (${k.runnerId})`);let I=await Ua(t,k,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${k.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(S==="tracker_fields_request"){let k=w,I={type:"tracker_fields_result",requestId:k.requestId,projectId:t.projectId,ok:!1},B=Oe();if(!B)I.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{I.fields=await Vs(B,k.projectKey),I.ok=!0}catch(K){I.error=K instanceof Error?K.message:String(K)}d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(S==="sandbox_keys"){let k=U(t.projectId);if(!k){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Tt(t.projectId),B=xs(w,k,I,r);for(let K of B)d.readyState===d.OPEN&&d.send(JSON.stringify(K));return}if(S!=="dispatch_action")return;let j=w;if(h===!1){let k=`refused: HUB protocol incompatible with CLI v${me} (protocol ${Ie})`;d.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:k})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${k}`),r.warn(`[exec] update the CLI to clear this: ${xo}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:k});return}u.add(j.actionId);try{let k=await ca({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?x:void 0}).catch(K=>({status:"failed",error:K instanceof Error?K.message:String(K)}));j.action.type==="tracker_comment"&&k.status==="done"&&"result"in k&&typeof k.result?.commentId=="string"&&f.add(k.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:j.actionId,...k}));let I=k.status!=="failed",B=!I&&"error"in k?k.error:void 0;I?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${B??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:I,...B?{error:B}:{}})}finally{u.delete(j.actionId)}}),d.on("close",(m,R)=>{let w=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${w?` reason=${w}`:""}`),C.stop(),$.stop(),P?.stop(),O(),w==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function So(t,e,r){try{let n=await M(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=fr(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function lf(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?$r(e.root,o):ve(t.projectId,r.name);if(Ga($r(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await cf().clone(co(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function uf(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,o):ve(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ga($r(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{af(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function pf(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=$r(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Hi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function df(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await _t(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function ff(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=await es(e.contextDir,t.taskKey,t.slugs);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${s}`),o("failed",s);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Ba(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ya,mkdirSync as Va}from"node:fs";import{dirname as Ja}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as mf}from"node:child_process";import{mkdtempSync as gf,mkdirSync as hf,readFileSync as Ma,rmSync as yf,writeFileSync as wf}from"node:fs";import{tmpdir as kf}from"node:os";import{dirname as bf,join as Fa}from"node:path";function Ha(t="codepipe-context"){let e=gf(Fa(kf(),"codepipe-ssh-")),r=Fa(e,"id_ed25519");try{return mf("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ma(r,"utf-8"),publicKey:Ma(`${r}.pub`,"utf-8").trim()}}finally{yf(e,{recursive:!0,force:!0})}}async function Ka(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Wa(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function qa(t,e){hf(bf(t),{recursive:!0});let r=e.endsWith(`
441
+ `:"")}function Nd(t,e,r){let n=[],o=Je(t,`tasks/${e}/attachments`);if(aa(o))for(let i of Pd(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var pn=new Map;async function wo(t,e){let n=(pn.get(t)??Promise.resolve()).catch(()=>{}).then(e);pn.set(t,n);try{return await n}finally{pn.get(t)===n&&pn.delete(t)}}async function ca(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;mr(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c}=await hs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{commit:c,pushed:l}=await ys(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return q("no repo spec");let i=Fe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return q("no repo spec");let i=Fe(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return q("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return wo(`${i}/${r.name}`,async()=>{let s=await tn(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=ve(i,r.name,t.baseDir),{mergedSha:c}=await ws(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return te({stub:!0});case"tracker_status":{let i=Oe();return i?t.trackerIssueId?(await Us(i,t.trackerIssueId,e.newStatus,ln(t.contextDir)),te({issueId:t.trackerIssueId,newStatus:e.newStatus})):q("no tracker_issue_id provided"):q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return q("no tracker_issue_id provided");let s=await Ls(i,t.trackerIssueId,e.body);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return q("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Gs(i,e.projectKey,e.title,e.body,e.targetStatus,ln(t.contextDir));return te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ms(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return q(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return te({applied:s})}case"set_project_setting":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await ia(t.contextDir,e.edits);return te({files:i.files})}case"tracker_edit":{let i=Oe();if(!i)return q("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return q("no context repo clone on this CLI");let s=ln(t.contextDir);await Ds(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await an(i,e.issueKey,s);return a&&await un(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),te({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=await sa(t.contextDir,e);return te({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):q("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return q("no context repo clone on this CLI");let i=await t.refreshContextStatus();return te({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return q("no context repo clone on this CLI");let i=oa(t.contextDir,e.path);return te({path:e.path,...i})}default:return q(`unsupported action type: ${e.type}`)}}catch(i){return q(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function q(t){return{status:"failed",error:t}}import{existsSync as Ca,readFileSync as Ra}from"node:fs";import{join as Ta}from"node:path";import{homedir as Ud}from"node:os";import{existsSync as Ld,mkdirSync as Dd,readFileSync as Bd,writeFileSync as Gd}from"node:fs";import{dirname as Md,join as Fd}from"node:path";function bo(){return L("FARM_PINS")??Fd(Ud(),".codepipe","farm-pins.json")}function la(){let t=bo();if(!Ld(t))return{};try{return JSON.parse(Bd(t,"utf-8"))}catch{return{}}}function Hd(t){let e=bo();Dd(Md(e),{recursive:!0}),Gd(e,JSON.stringify(t,null,2)+`
442
+ `,{mode:384})}function Kd(t){return la()[t]}function dn(t,e){let r=la();r[t]=e,Hd(r)}function fn(t,e){let r=ae(e),n=Kd(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${bo()}.`);return r}import Wd from"ws";function mn(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Wd(r)}var A=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function tt(t,e,r){return Se(t,e,"/projects",r)}async function ua(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function gn(t,e,r,n){return Se(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function pa(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners`,n)}async function da(t,e,r,n){return Se(t,e,`/runners/${encodeURIComponent(r)}/gh-runners/teardown`,n)}async function fa(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function hn(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function ma(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var kr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ga(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new kr(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ha(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ya(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function wa(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function ba(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function ka(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function $a(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function va(t,e,r,n,o){return Se(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function yn(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function ko(t,e,r,n){await Se(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function xa(t,e,r,n){return Se(t,e,`/projects/${encodeURIComponent(r)}/repos`,n)}async function Sa(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(n)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new A(o.status,s,a)}return s}async function M(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Se(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new A(o.status,s,a)}return s}async function Ia(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ae(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");fn(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await M(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Ta(r,"project.yaml"),g=Ta(r,"regimen.yaml");Ca(p)&&Ca(g)?c={projectYaml:Ra(p,"utf-8"),regimenYaml:Ra(g,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=He(e.farmPublicKey,JSON.stringify(l));dn(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await gn(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}import{homedir as qd}from"node:os";import{existsSync as Yd,mkdirSync as Vd,readFileSync as Jd,writeFileSync as zd}from"node:fs";import{dirname as Xd,join as Qd}from"node:path";function $o(){return L("RUNNER_PINS")??Qd(qd(),".codepipe","runner-pins.json")}function ja(){let t=$o();if(!Yd(t))return{};try{return JSON.parse(Jd(t,"utf-8"))}catch{return{}}}function Zd(t){let e=$o();Vd(Xd(e),{recursive:!0}),zd(e,JSON.stringify(t,null,2)+`
443
+ `,{mode:384})}function ef(t){return ja()[t]}function vo(t,e){let r=ja();r[t]=e,Zd(r)}function Pa(t,e){let r=ae(e),n=ef(t);if(n&&n!==r)throw new Error(`runner host ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the runner host was re-registered intentionally, remove its entry from ${$o()}.`);return r}var Aa=t=>({Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"});async function Ea(t,e,r,n){let o=await fetch(`https://api.github.com/repos/${e}/${r}/actions/runners/${n}`,{method:"POST",headers:Aa(t)});if(!o.ok)throw new Error(`github ${n} for ${e}/${r}: HTTP ${o.status}`);let i=await o.json();if(!i.token)throw new Error(`github ${n} for ${e}/${r}: no token in response`);return i.token}var tf={async repoHasAdmin(t,e,r){let n=await fetch(`https://api.github.com/repos/${e}/${r}`,{headers:Aa(t)});if(!n.ok)throw new Error(`github GET /repos/${e}/${r}: HTTP ${n.status}`);return(await n.json()).permissions?.admin===!0},mintRegistrationToken:(t,e,r)=>Ea(t,e,r,"registration-token"),mintRemoveToken:(t,e,r)=>Ea(t,e,r,"remove-token")},_a={api:tf,fetchProject:M,provisionOnRunner:pa,teardownOnRunner:da};async function Oa(t,e,r){if(e.projectId!==t.projectId)throw new Error(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);if(ae(e.runnerPublicKey)!==e.fingerprint)throw new Error("runner host key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Pa(e.runnerId,e.runnerPublicKey);let i=U(t.projectId)?.github?.token;if(!i)throw new Error("no GitHub token stored for this project on this CLI");let a=((await r.fetchProject(t.hubUrl,t.cliToken,t.projectId)).repos??[]).filter(c=>c.host==="github");if(a.length===0)throw new Error("the project has no GitHub repositories \u2014 nothing to connect a runner to");return{githubToken:i,repos:a}}async function Na(t,e,r,n=_a){let o=i=>({type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Oa(t,e,n),a=[];for(let p of s)await n.api.repoHasAdmin(i,p.owner,p.repoName)||a.push(`${p.owner}/${p.repoName}`);if(a.length>0)return o(`the GitHub token lacks admin access on ${a.join(", ")} \u2014 replace it (project page \u2192 Tokens \u2192 Replace) with a token that has admin rights on every repository`);let c=[];for(let p of s)c.push({owner:p.owner,repo:p.repoName,regToken:await n.api.mintRegistrationToken(i,p.owner,p.repoName)});let l={projectId:t.projectId,runners:c},u=He(e.runnerPublicKey,JSON.stringify(l));vo(e.runnerId,e.fingerprint),r.info(`[ghr] ${c.length} registration token(s) sealed for runner host ${e.runnerName} \u2014 handing off`);let f=await n.provisionOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:u});return{type:"gh_runner_setup_result",requestId:e.requestId,projectId:t.projectId,ok:f.ok,...f.runners?{runners:f.runners}:{},...f.error?{error:f.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}async function Ua(t,e,r,n=_a){let o=i=>({type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{let{githubToken:i,repos:s}=await Oa(t,e,n),a=[];for(let f of s)try{a.push({owner:f.owner,repo:f.repoName,removeToken:await n.api.mintRemoveToken(i,f.owner,f.repoName)})}catch(p){r.warn(`[ghr] remove-token for ${f.owner}/${f.repoName} failed (${p instanceof Error?p.message:p}) \u2014 the runner host will force-remove`),a.push({owner:f.owner,repo:f.repoName})}let c={projectId:t.projectId,runners:a},l=He(e.runnerPublicKey,JSON.stringify(c));vo(e.runnerId,e.fingerprint),r.info(`[ghr] removal bundle sealed for runner host ${e.runnerName} \u2014 handing off`);let u=await n.teardownOnRunner(t.hubUrl,t.cliToken,e.runnerId,{projectId:t.projectId,sealedBundle:l});return{type:"gh_runner_teardown_result",requestId:e.requestId,projectId:t.projectId,ok:u.ok,...u.error?{error:u.error}:{}}}catch(i){return o(i instanceof Error?i.message:String(i))}}var wn=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Fe(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof ht){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Fe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=rf(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function rf(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var bn=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let e=Oe();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let k=e.stageField?{stageField:e.stageField}:{},v=e.requireAssignee&&e.assignee?{assignee:e.assignee}:e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{};if((e.backlogScope??"shared")==="shared"&&!!e.requireAssignee&&!!e.backlogColumn){let x=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[]])],[m,R]=await Promise.all([x.length>0?sn(r,{projectKey:e.projectKey,columns:x,...k,...v}):Promise.resolve([]),sn(r,{projectKey:e.projectKey,columns:[e.backlogColumn],...k})]),w=new Map;for(let S of[...m,...R])w.set(S.id,S);o=[...w.values()]}else{let x=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await sn(r,{projectKey:e.projectKey,columns:x,...k,...v})}}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let v=await Da(r,k.id,e.sinceMs,this.log);v&&i.set(k.id,v)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let v=await Da(r,k,e.sinceMs,this.log);if(v&&v.length>0&&i.set(k,v),e.requireAssignee||v&&v.length>0){let O=await sf(r,k,e.stageField,this.log);if(O)c.push(O);else if(v&&v.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.status)),{attachmentsByIssue:u,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(k=>({issue:k,comments:i.get(k.id)??[],attachments:u.get(k.id)??[]}));try{await un(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let v=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${v}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[k,v]of i){let O=v.filter(x=>!g(x.id));if(O.length===0)continue;d.push({issueId:k,comments:O.map(nf)});let P=O.flatMap(x=>{let m=Gr(x.body);return m?[{commentId:x.id,author:x.author,name:m.name,args:m.args,createdAt:x.createdAt}]:[]});P.length>0&&h.push({issueId:k,commands:P})}let C={type:"youtrack_observation",projectId:e.projectId,issues:o.map(La),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(La)}:{},observedAtMs:n};this.send(C);let $=d.reduce((k,v)=>k+v.comments.length,0),y=h.reduce((k,v)=>k+v.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${$} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Ws(n,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=of(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function La(t){let{description:e,...r}=t;return r}function nf(t){let{body:e,...r}=t;return r}function of(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function sf(t,e,r,n){try{return await an(t,e,r)}catch(o){return n.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Da(t,e,r,n){try{return await qs(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var xo="npm i -g @code-partner/codepipe@latest";function kn(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${me} (protocol ${Ie})`);let n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&qi(o.contextDir,r);let i=Ba("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ba("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,u=new Set,f=new Set,p=g();function g(){let d=mn(t.hubUrl,t.cliToken),h=null,C=new wn(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),$=new bn(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:o?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,k=async()=>{try{let m;try{let S=await M(t.hubUrl,t.cliToken,t.projectId);m={repos:S.repos,contextRepo:S.contextRepo}}catch(S){r.warn(`[readiness] could not fetch project summary for push checks: ${S instanceof Error?S.message:String(S)}`)}let R=await zs(t.projectId,m);if(d.readyState!==d.OPEN)return;let w={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,checkedAt:R.checkedAt};if(d.send(JSON.stringify(w)),R.ready)r.info("[readiness] ready");else{let S=R.checks.filter(j=>!j.ok).map(j=>`${j.name}(${j.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${S.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},v=()=>{k(),y=setInterval(()=>void k(),a),typeof y.unref=="function"&&y.unref()},O=()=>{y&&(clearInterval(y),y=null)},P=o?.contextDir?new zr(o.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,x=async()=>{let m=o?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let R;try{R=(await M(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let w=await ls(m,t.projectId,R,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(w)),w};return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let m=Fi(t.projectId),R=L("ORIGIN")==="farm"?"farm":"local",w=L("FARM_ID"),S=t.accountEmail??m.email,j;try{let I=ea(t.projectId);I&&(j=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let b={type:"register",projectId:t.projectId,platformVersion:me,protocolVersion:Ie,accountId:m.accountId,accountLabel:m.label,origin:R,inFlightActionIds:[...u],...S?{accountEmail:S}:{},...R==="farm"&&w?{farmId:w}:{},...j?{sealPublicKey:j}:{}};d.send(JSON.stringify(b))}),d.on("message",async m=>{let R=m.toString("utf-8");if(R==="pong"||R==="ping")return;let w;try{w=JSON.parse(R)}catch{return}if(!w||typeof w!="object")return;let S=w.type;if(S==="registered"){let b=w;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),n({kind:"registered",projectId:b.projectId??t.projectId}),C.start(),P?.start(),v(),So(t,o,r),o?.contextDir)try{let I=Qr(o.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,x().catch(()=>{})))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),n({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,d.close();return}if(S==="hello"){let b=w;h=Lr(b.protocolVersion);let I=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${I}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${me}, protocol ${Ie}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${xo}`),n({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:xo}));return}if(S==="tracking_targets"){C.setTargets(w.targets);return}if(S==="youtrack_sync_request"){$.setRequest(w);return}if(S==="youtrack_force_sync"){$.forceSync();return}if(S==="sync_local"){await pf(w,o,d,r);return}if(S==="provision_repo"){let b=w;r.info(`[repo] provision_repo: ${b.repo.name} (${b.repo.host}:${b.repo.owner}/${b.repo.repoName})`),await lf(t,o,b.repo,r),await So(t,o,r);return}if(S==="remove_repo"){let b=w;r.info(`[repo] remove_repo: ${b.repoName}${b.purge?" (purge)":""}`),await So(t,o,r),b.purge&&uf(t,o,b.repoName,r);return}if(S==="context_write"){await df(w,o,d,r);return}if(S==="adr_promote"){await ff(w,o,d,r);return}if(S==="cred_update"){let b=w,I=U(t.projectId),B=I?.sealKey?await ta(t.projectId,b.kind,b.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},K={type:"cred_update_result",updateId:b.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(K)),B.ok?(r.info(`[cred] ${b.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),k()):r.warn(`[cred] ${b.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(S==="move_to_farm"){let b=w;r.info(`[farm-move] request to move ${t.projectId} onto farm ${b.farmName} (${b.farmId})`);let I=await Ia(t,b,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(S==="gh_runner_setup"){let b=w;r.info(`[ghr] runner setup for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let I=await Na(t,b,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners connected on ${b.runnerName}`):r.warn(`[ghr] setup failed: ${I.error??"see per-repo statuses"}`);return}if(S==="gh_runner_teardown"){let b=w;r.info(`[ghr] runner teardown for ${t.projectId} on runner host ${b.runnerName} (${b.runnerId})`);let I=await Ua(t,b,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[ghr] runners disconnected from ${b.runnerName}`):r.warn(`[ghr] teardown failed: ${I.error??"unknown error"}`);return}if(S==="tracker_fields_request"){let b=w,I={type:"tracker_fields_result",requestId:b.requestId,projectId:t.projectId,ok:!1},B=Oe();if(!B)I.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{I.fields=await Vs(B,b.projectKey),I.ok=!0}catch(K){I.error=K instanceof Error?K.message:String(K)}d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok||r.warn(`[yt-fields] listing failed: ${I.error??"unknown"}`);return}if(S==="sandbox_keys"){let b=U(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=Tt(t.projectId),B=xs(w,b,I,r);for(let K of B)d.readyState===d.OPEN&&d.send(JSON.stringify(K));return}if(S!=="dispatch_action")return;let j=w;if(h===!1){let b=`refused: HUB protocol incompatible with CLI v${me} (protocol ${Ie})`;d.send(JSON.stringify({type:"action_result",actionId:j.actionId,status:"failed",error:b})),r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${xo}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:!1,error:b});return}u.add(j.actionId);try{let b=await ca({action:j.action,repo:j.repo,trackerIssueId:j.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:P?()=>P.reportNow():void 0,refreshContextStatus:o?.contextDir?x:void 0}).catch(K=>({status:"failed",error:K instanceof Error?K.message:String(K)}));j.action.type==="tracker_comment"&&b.status==="done"&&"result"in b&&typeof b.result?.commentId=="string"&&f.add(b.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:j.actionId,...b}));let I=b.status!=="failed",B=!I&&"error"in b?b.error:void 0;I?r.info(`[exec] ${j.actionId} (${j.action.type}) \u2192 done`):r.warn(`[exec] ${j.actionId} (${j.action.type}) \u2192 FAILED: ${B??"?"}`),n({kind:"action",actionId:j.actionId,actionType:j.action.type,ok:I,...B?{error:B}:{}})}finally{u.delete(j.actionId)}}),d.on("close",(m,R)=>{let w=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${w?` reason=${w}`:""}`),C.stop(),$.stop(),P?.stop(),O(),w==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),n({kind:"replaced"});return}n({kind:"disconnected",code:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function So(t,e,r){try{let n=await M(t.hubUrl,t.cliToken,t.projectId),{updated:o,errors:i}=fr(t.projectId,n.repos,e?.contextDir);for(let s of o)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(n){r.warn(`[repo] repo-set reconcile skipped: ${n instanceof Error?n.message:String(n)}`)}}async function lf(t,e,r,n){let o=r.mountAs??r.name;if(o==="."){n.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?$r(e.root,o):ve(t.projectId,r.name);if(Ga($r(i,".git"))){n.info(`[repo] ${r.name} already present at ${i}`);return}try{await cf().clone(co(r),i),n.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){n.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function uf(t,e,r,n){let o=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,o):ve(t.projectId,r);if(e&&i===e.root){n.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Ga($r(i,".git"))){n.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{af(i,{recursive:!0,force:!0}),n.info(`[repo] purged local clone ${i}`)}catch(s){n.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function pf(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=$r(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await Hi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function df(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await _t(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function ff(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=await es(e.contextDir,t.taskKey,t.slugs);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${s}`),o("failed",s);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Ba(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ya,mkdirSync as Va}from"node:fs";import{dirname as Ja}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as mf}from"node:child_process";import{mkdtempSync as gf,mkdirSync as hf,readFileSync as Ma,rmSync as yf,writeFileSync as wf}from"node:fs";import{tmpdir as bf}from"node:os";import{dirname as kf,join as Fa}from"node:path";function Ha(t="codepipe-context"){let e=gf(Fa(bf(),"codepipe-ssh-")),r=Fa(e,"id_ed25519");try{return mf("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ma(r,"utf-8"),publicKey:Ma(`${r}.pub`,"utf-8").trim()}}finally{yf(e,{recursive:!0,force:!0})}}async function Ka(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function Wa(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function qa(t,e){hf(kf(t),{recursive:!0});let r=e.endsWith(`
443
444
  `)?e:e+`
444
- `;return wf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function $f(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function vf(t,e){return e?.contextWrite?.token?{user:Mr(t),secret:e.contextWrite.token}:t===ur.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ur.bitbucket?e?.bitbucket?.apiToken?{user:ft,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function $n(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await M(e.hubUrl,e.cliToken,e.projectId)}catch(c){return o.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=vf(Ct(s.cloneUrl),r);if(a){let c=await xf({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Sf({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function xf(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=$f(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Qn(r);await l.reset(["--hard",`origin/${s}`]),Zn(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Va(Ja(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await za(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Sf(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=qa(i,n),a=Wa(e.cloneUrl),c=e.branch;try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Qn(r);await l.reset(["--hard",`origin/${c}`]),Zn(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Va(Ja(r),{recursive:!0}),await Ut().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ut(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await za(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function za(t){let e=Ut(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Xa(t={profile:void 0}){let{cfg:e,profile:r}=Wr(t.profile),n=U(e.projectId);n&&pr(n),yr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),wr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),kr(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=vr(Co(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Vr("CLI_LOG",i,o);if(s.enabled){let p=new jt(s);Jr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Hr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let p=vr(Co(),".codepipe",r?vr("profiles",r,"context"):"context");if(await bo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await $n({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await bo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=vr(Co(),".codepipe",r?vr("profiles",r,"context-config"):"context-config");Xr(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=bn(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function f(p){u||(u=!0,console.log(`
445
+ `;return wf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function $f(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function vf(t,e){return e?.contextWrite?.token?{user:Mr(t),secret:e.contextWrite.token}:t===ur.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ur.bitbucket?e?.bitbucket?.apiToken?{user:ft,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function $n(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await M(e.hubUrl,e.cliToken,e.projectId)}catch(c){return o.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=vf(Ct(s.cloneUrl),r);if(a){let c=await xf({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Sf({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function xf(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=$f(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Qn(r);await l.reset(["--hard",`origin/${s}`]),Zn(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Va(Ja(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await za(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Sf(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=qa(i,n),a=Wa(e.cloneUrl),c=e.branch;try{if(Ya(`${r}/.git`)){let l=Ut(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Qn(r);await l.reset(["--hard",`origin/${c}`]),Zn(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Va(Ja(r),{recursive:!0}),await Ut().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ut(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await za(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function za(t){let e=Ut(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Xa(t={profile:void 0}){let{cfg:e,profile:r}=Wr(t.profile),n=U(e.projectId);n&&pr(n),yr(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),wr(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),br(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=vr(Co(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Vr("CLI_LOG",i,o);if(s.enabled){let p=new jt(s);Jr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Hr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let p=vr(Co(),".codepipe",r?vr("profiles",r,"context"):"context");if(await ko(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await $n({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await ko(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=vr(Co(),".codepipe",r?vr("profiles",r,"context-config"):"context-config");Xr(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=kn(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function f(p){u||(u=!0,console.log(`
445
446
  [${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as Af}from"node:os";import{spawnSync as Cf}from"node:child_process";function Rf(){try{return Cf("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Qa(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Rf(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Lt}from"node:os";import{mkdirSync as Tf,readFileSync as Za,writeFileSync as If,existsSync as Ro}from"node:fs";import{dirname as jf,join as rt}from"node:path";Ro(".env")&&process.loadEnvFile(".env");function Pf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function Ce(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=rt(Lt(),".codepipe","worker");return t?rt(r,"profiles",t,"config.json"):rt(r,"config.json")}function ec(){return rt(Lt(),".devpipe-sandbox","config.json")}function vn(){mt(rt(Lt(),".devpipe"),rt(Lt(),".codepipe")),L("SANDBOX_CONFIG")||mt(rt(Lt(),".devpipe-sandbox"),rt(Lt(),".codepipe-sandbox"))}function ie(t){let e=Ce(t),r=null;return Ro(e)?r=JSON.parse(Za(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&Ro(ec())&&(r=JSON.parse(Za(ec(),"utf-8"))),r?(r.planningLane=Pf(),r):null}function tc(t,e){let r=Ce(e);Tf(jf(r),{recursive:!0}),If(r,JSON.stringify(t,null,2)+`
446
447
  `,{mode:384})}import Ef from"ws";var Dt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(n.signal=e);let o=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(o,n)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Ef(e)}};async function yt(t){vn();let e=ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ce(t.profile)}.`),process.exit(1));let r=t.name??Af(),n=Qa({projects:t.projects??[],llm:t.llm??null}),o=new Dt(t.hub.replace(/\/$/,"")),i=nn(),s=ae(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});tc({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Ce(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as xm,readFileSync as Oo,readdirSync as Sm,writeFileSync as Cm}from"node:fs";import{dirname as Rm,join as Rr,resolve as Tm}from"node:path";import{spawn as Df}from"node:child_process";import{existsSync as Bf}from"node:fs";import{spawn as _f}from"node:child_process";var rc=16e3,nc=5e3,oc=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),Of="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function To(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function Nf(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}function Uf(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function wt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Io(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
447
- `}async function ic(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ke;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let f=c.message;for(let p of f?.content??[]){let g=p.type;if(g==="text"){let d=String(p.text??"").trim();d&&o({ts:l,kind:"text",author:"agent",text:To(d,rc)})}else if(g==="tool_use"){let d=String(p.name??""),h=p.input?.file_path??p.input?.path,C=Nf(h,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:d,...C?{file:C}:{}})}}return}if(u==="user"){let f=c.message;for(let p of f?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,d=g?To(Uf(p.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...d?{text:d}:{}})}return}if(u==="result"){s=c;let f=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(u==="system"){let f=String(c.subtype??"").trim();f&&o({ts:l,kind:"system",author:"agent",text:f})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=_f(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let f=!1,p=!1,g=null,d=()=>{f=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,C=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${oc}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)},oc)},$=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},y=!0,b=P=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(P)}catch{}};b(Io(e.prompt)),C(),(async()=>{try{for await(let P of e.interactive.inbox){if(f||!y)break;if(C(),P.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:To(P.text,rc)}),b(Io(P.text));else{b(Io(Of)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let v="",O=P=>{let x;try{x=JSON.parse(P)}catch{return}a(x)};u.stdout.on("data",P=>{i.push(P),C(),v+=P;let x;for(;(x=v.indexOf(`
448
+ `}async function ic(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Ke;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let n=e.onActivity,o=c=>{if(n)try{n(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let f=c.message;for(let p of f?.content??[]){let g=p.type;if(g==="text"){let d=String(p.text??"").trim();d&&o({ts:l,kind:"text",author:"agent",text:To(d,rc)})}else if(g==="tool_use"){let d=String(p.name??""),h=p.input?.file_path??p.input?.path,C=Nf(h,e.workspaceDir);o({ts:l,kind:"tool",author:"agent",tool:d,...C?{file:C}:{}})}}return}if(u==="user"){let f=c.message;for(let p of f?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,d=g?To(Uf(p.content),200):"";o({ts:l,kind:"tool_result",author:"agent",isError:g,...d?{text:d}:{}})}return}if(u==="result"){s=c;let f=String(c.subtype??"").trim();o({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(u==="system"){let f=String(c.subtype??"").trim();f&&o({ts:l,kind:"system",author:"agent",text:f})}};return o({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=_f(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let f=!1,p=!1,g=null,d=()=>{f=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,C=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${oc}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),nc)},oc)},$=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},y=!0,k=P=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(P)}catch{}};k(Io(e.prompt)),C(),(async()=>{try{for await(let P of e.interactive.inbox){if(f||!y)break;if(C(),P.kind==="user")o({ts:Date.now(),kind:"text",author:"user",text:To(P.text,rc)}),k(Io(P.text));else{k(Io(Of)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let v="",O=P=>{let x;try{x=JSON.parse(P)}catch{return}a(x)};u.stdout.on("data",P=>{i.push(P),C(),v+=P;let x;for(;(x=v.indexOf(`
448
449
  `))!==-1;){let m=v.slice(0,x).trim();v=v.slice(x+1),m&&O(m)}}),u.stderr.on("data",P=>{i.push(P);for(let x of P.split(`
449
- `)){let m=x.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",P=>{$(),l(P)}),u.on("close",P=>{if($(),f){l(new Ke);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}v.trim()&&O(v.trim()),console.log(`[claude:chat] exit code=${P}`),c({artifactPaths:[],log:i.join(""),usage:Lf(s)})})})}function Lf(t){let e=pt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=wt(r.input_tokens),e.outputTokens=wt(r.output_tokens),e.cacheReadInputTokens=wt(r.cache_read_input_tokens),e.cacheCreationInputTokens=wt(r.cache_creation_input_tokens)),e.totalCostUsd=wt(t.total_cost_usd),e.numTurns=wt(t.num_turns),e.durationMs=wt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ke=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Gf=5e3,xr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ic(this.binary,e);if(e.signal?.aborted)throw new Ke;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let h=Kf(d.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(d.type==="assistant"){let h=d.message;typeof h?.model=="string"&&(c=h.model);let C=h?.usage;C&&(a+=1,s.input+=ce(C.input_tokens),s.output+=ce(C.output_tokens),s.cacheRead+=ce(C.cache_read_input_tokens),s.cacheCreate+=ce(C.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of qf(d,e.workspaceDir))try{p(h)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((d,h)=>{let C=Df(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});C.stdout.setEncoding("utf-8"),C.stderr.setEncoding("utf-8");let $=!1,y=null,b=()=>{$=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),C.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),C.kill("SIGKILL")},Gf)};e.signal?.addEventListener("abort",b,{once:!0});let v=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",b)},O="";C.stdout.on("data",P=>{n.push(P),O+=P;let x;for(;(x=O.indexOf(`
450
+ `)){let m=x.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",P=>{$(),l(P)}),u.on("close",P=>{if($(),f){l(new Ke);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}v.trim()&&O(v.trim()),console.log(`[claude:chat] exit code=${P}`),c({artifactPaths:[],log:i.join(""),usage:Lf(s)})})})}function Lf(t){let e=pt();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=wt(r.input_tokens),e.outputTokens=wt(r.output_tokens),e.cacheReadInputTokens=wt(r.cache_read_input_tokens),e.cacheCreationInputTokens=wt(r.cache_creation_input_tokens)),e.totalCostUsd=wt(t.total_cost_usd),e.numTurns=wt(t.num_turns),e.durationMs=wt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Ke=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Gf=5e3,xr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return ic(this.binary,e);if(e.signal?.aborted)throw new Ke;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let h=Kf(d.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(d.type==="assistant"){let h=d.message;typeof h?.model=="string"&&(c=h.model);let C=h?.usage;C&&(a+=1,s.input+=ce(C.input_tokens),s.output+=ce(C.output_tokens),s.cacheRead+=ce(C.cache_read_input_tokens),s.cacheCreate+=ce(C.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of qf(d,e.workspaceDir))try{p(h)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((d,h)=>{let C=Df(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});C.stdout.setEncoding("utf-8"),C.stderr.setEncoding("utf-8");let $=!1,y=null,k=()=>{$=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),C.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),C.kill("SIGKILL")},Gf)};e.signal?.addEventListener("abort",k,{once:!0});let v=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",k)},O="";C.stdout.on("data",P=>{n.push(P),O+=P;let x;for(;(x=O.indexOf(`
450
451
  `))!==-1;){let m=O.slice(0,x).trim();if(O=O.slice(x+1),m){let R=sc(m);u(R),R&&g(R)}}}),C.stderr.on("data",P=>{n.push(P),o.push(P);for(let x of P.split(`
451
452
  `)){let m=x.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),C.on("error",P=>{v(),h(P)}),C.on("close",P=>{if(v(),$){h(new Ke);return}if(O.trim()){let m=sc(O.trim());u(m),m&&g(m)}let x=i?.is_error===!0;if(P!==0||x){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,R=typeof i?.subtype=="string"?i.subtype:void 0,w=typeof i?.result=="string"?i.result:void 0;h(new Bt(Mf(P,i,o.join("")),{code:P,apiErrorStatus:m,subtype:R,resultText:w,retryAfterMs:Ff(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:Wf(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&Bf(n))}};function sc(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${nt(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Hf(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=cc(o.content);console.log(`[claude] tool_result (error)${i?`: ${nt(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${nt(JSON.stringify(e),200)}`),e}function Mf(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(nt(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(nt(r.trim().split(`
452
453
  `).slice(-5).join(`
@@ -536,17 +537,17 @@ ${r?`
536
537
  `)+`
537
538
  `,{mode:384}),hc(o,`[credential]
538
539
  helper = store --file=${n}
539
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{am(r,{recursive:!0,force:!0})}catch{}}}}function Po(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(lm)),t.bitbucket?.apiToken&&(e.push(`https://${ft}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(um)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(pm)),yc(e,r)}function wc(t,e){if(t.contextWrite?.token){let r=Ct(e)??"github.com",n=Mr(r);return yc([`https://${n}:${t.contextWrite.token}@${r}`],[Sn(r)])}return Po(t)}import{spawn as bc}from"node:child_process";import{existsSync as Cn,mkdirSync as Rn,readFileSync as dm,rmSync as Eo,symlinkSync as fm}from"node:fs";import{homedir as mm}from"node:os";import{dirname as Tn,join as kt}from"node:path";function $c(){return kt(mm(),".codepipe-sandbox","repos")}var Ft=new Map;function vc(t,e){let n=(Ft.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ft.get(t)===o&&Ft.delete(t)},()=>{Ft.get(t)===o&&Ft.delete(t)});return Ft.set(t,o),n}function kc(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}async function xc(t,e,r,n,o){if(Cn(kt(t,".git"))){let i=async s=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],o),await Y(t,["reset","--hard",`origin/${s}`],o),await Y(t,["clean","-fdx"],o)};try{return await i(r),r}catch(s){if(!n||n===r||!kc(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}}Cn(t)&&Eo(t,{recursive:!0,force:!0}),Rn(Tn(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(i){if(!n||n===r||!kc(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Cn(t)&&Eo(t,{recursive:!0,force:!0}),Rn(Tn(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}}async function Sc(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Ht="CodePipe Agent",Kt="codepipe@codepartner.ee";async function Cc(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let n=(await oe(r,["write-tree"])).trim(),o=(await oe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};return(await oe(r,["commit-tree",n,"-m",e],i)).trim()}async function Rc(t,e,r,n,o){try{await Y(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ct(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Tc(t,e){return oe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ic(t,e,r,n,o){await Y(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await Y(t.workspacePath,["checkout","--force",r])}async function jc(t,e,r,n,o,i){let s=t.workspacePath;await Y(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await oe(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=d=>oe(s,["rev-parse","-q","--verify",`${d}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await oe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await Y(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt},u=(await oe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await oe(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await Y(s,["cherry-pick","--quit"],l).catch(()=>{});let p=null;try{await Y(s,["cherry-pick","--no-commit",f],l)}catch(d){p=d instanceof Error?d.message:String(d)}let g=(await oe(s,["diff","--name-only","--diff-filter=U"])).split(`
540
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{am(r,{recursive:!0,force:!0})}catch{}}}}function Po(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(lm)),t.bitbucket?.apiToken&&(e.push(`https://${ft}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(um)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(pm)),yc(e,r)}function wc(t,e){if(t.contextWrite?.token){let r=Ct(e)??"github.com",n=Mr(r);return yc([`https://${n}:${t.contextWrite.token}@${r}`],[Sn(r)])}return Po(t)}import{spawn as kc}from"node:child_process";import{existsSync as Cn,mkdirSync as Rn,readFileSync as dm,rmSync as Eo,symlinkSync as fm}from"node:fs";import{homedir as mm}from"node:os";import{dirname as Tn,join as bt}from"node:path";function $c(){return bt(mm(),".codepipe-sandbox","repos")}var Ft=new Map;function vc(t,e){let n=(Ft.get(t)??Promise.resolve()).then(e,e),o=n.then(()=>{Ft.get(t)===o&&Ft.delete(t)},()=>{Ft.get(t)===o&&Ft.delete(t)});return Ft.set(t,o),n}function bc(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}async function xc(t,e,r,n,o){if(Cn(bt(t,".git"))){let i=async s=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],o),await Y(t,["reset","--hard",`origin/${s}`],o),await Y(t,["clean","-fdx"],o)};try{return await i(r),r}catch(s){if(!n||n===r||!bc(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}}Cn(t)&&Eo(t,{recursive:!0,force:!0}),Rn(Tn(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(i){if(!n||n===r||!bc(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Cn(t)&&Eo(t,{recursive:!0,force:!0}),Rn(Tn(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}}async function Sc(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Ht="CodePipe Agent",Kt="codepipe@codepartner.ee";async function Cc(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let n=(await oe(r,["write-tree"])).trim(),o=(await oe(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};return(await oe(r,["commit-tree",n,"-m",e],i)).trim()}async function Rc(t,e,r,n,o){try{await Y(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ct(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Tc(t,e){return oe(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ic(t,e,r,n,o){await Y(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await Y(t.workspacePath,["checkout","--force",r])}async function jc(t,e,r,n,o,i){let s=t.workspacePath;await Y(s,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await oe(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=d=>oe(s,["rev-parse","-q","--verify",`${d}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(n)&&((await oe(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(n)||await Y(s,["fetch","origin",n],i).catch(()=>{}),!await c(n)))throw new Error(`moved-base apply: delivery base ${n.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt},u=(await oe(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await oe(s,["commit-tree",u,"-p",n,"-m","delivery"],l)).trim();await Y(s,["cherry-pick","--quit"],l).catch(()=>{});let p=null;try{await Y(s,["cherry-pick","--no-commit",f],l)}catch(d){p=d instanceof Error?d.message:String(d)}let g=(await oe(s,["diff","--name-only","--diff-filter=U"])).split(`
540
541
  `).map(d=>d.trim()).filter(d=>d.length>0);if(p&&g.length===0)throw await Y(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${p}`);return g}async function Ao(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};(await oe(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await Y(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Y(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await oe(n,["diff","--name-only","--diff-filter=U"])).split(`
541
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await oe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Y(t,e,r){return new Promise((n,o)=>{let i=bc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
542
- ${s.join("").trim()||"(no stderr)"}`))})})}function oe(t,e,r){return new Promise((n,o)=>{let i=bc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
543
- ${a.join("").trim()||"(no stderr)"}`))})})}function Pc(t,e){Cn(t)&&Eo(t,{recursive:!0,force:!0}),Rn(Tn(t),{recursive:!0}),fm(e,t,"dir")}async function Ec(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Rn(Tn(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ac(t,e,r,n="worktree",o){return r.length===0?[]:vc(e,async()=>{let i=[];for(let s of r){let a=kt($c(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await xc(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await oe(a,["rev-parse","HEAD"])).trim(),u=kt(t,"code",s.name);n==="direct"?(Pc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Ec(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i})}async function _c(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return vc(e,async()=>{let s=kt($c(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await xc(s,i.cloneUrl,i.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=kt(t,"context");n==="direct"?(Pc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Ec(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await oe(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Oc(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await Y(r,["add","-A",...n]).catch(()=>{});let o;try{o=await oe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
544
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=dm(kt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as gm}from"node:fs";import{join as hm}from"node:path";var _o=8*1024,Wt=class extends Error{},Cr="meta/build-result.json";function Nc(t){let e=hm(t,Cr),r;try{r=gm(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${Cr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Wt(`${Cr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Wt(`${Cr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Wt(`${Cr}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let f=u,p=typeof f.name=="string"?f.name:null,g=typeof f.exitCode=="number"?f.exitCode:null;if(p===null||g===null)return[];let d={name:p,exitCode:g};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof o.logTail=="string"?ym(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function ym(t){let e=Buffer.from(t,"utf-8");return e.length<=_o?t:`\u2026 [${e.length-_o} bytes elided] \u2026
545
- `+e.subarray(e.length-_o).toString("utf-8")}import{lstatSync as wm,mkdtempSync as km,readFileSync as bm,readdirSync as Lc,rmSync as Uc}from"node:fs";import{tmpdir as $m}from"node:os";import{join as In,relative as vm}from"node:path";var Dc=new Set(["code","context"]);function Bc(t){let e=km(In($m(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Uc(e,{recursive:!0,force:!0}),listFiles:()=>Gc(e,e),readFile:r=>bm(In(e,r),"utf-8"),clean:()=>{for(let r of Lc(e))Dc.has(r)||Uc(In(e,r),{recursive:!0,force:!0})}}}function Gc(t,e){let r=[];for(let n of Lc(e)){let o=In(e,n),i=wm(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Dc.has(n))continue;r.push(...Gc(t,o))}else r.push(vm(t,o))}return r}var jn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Im=new Set(["implement","resolve-conflict"]);function jm(t){let e=Buffer.from(t,"utf-8");if(e.length<=jn)return t;let r=Math.floor(jn/4),n=jn-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
542
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await oe(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Y(t,e,r){return new Promise((n,o)=>{let i=kc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
543
+ ${s.join("").trim()||"(no stderr)"}`))})})}function oe(t,e,r){return new Promise((n,o)=>{let i=kc("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
544
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Pc(t,e){Cn(t)&&Eo(t,{recursive:!0,force:!0}),Rn(Tn(t),{recursive:!0}),fm(e,t,"dir")}async function Ec(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Rn(Tn(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ac(t,e,r,n="worktree",o){return r.length===0?[]:vc(e,async()=>{let i=[];for(let s of r){let a=bt($c(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await xc(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await oe(a,["rev-parse","HEAD"])).trim(),u=bt(t,"code",s.name);n==="direct"?(Pc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Ec(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i})}async function _c(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=r;return vc(e,async()=>{let s=bt($c(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await xc(s,i.cloneUrl,i.ref,void 0,o)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=bt(t,"context");n==="direct"?(Pc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await Ec(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await oe(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Oc(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await Y(r,["add","-A",...n]).catch(()=>{});let o;try{o=await oe(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
545
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=dm(bt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as gm}from"node:fs";import{join as hm}from"node:path";var _o=8*1024,Wt=class extends Error{},Cr="meta/build-result.json";function Nc(t){let e=hm(t,Cr),r;try{r=gm(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${Cr} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Wt(`${Cr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Wt(`${Cr} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Wt(`${Cr}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let f=u,p=typeof f.name=="string"?f.name:null,g=typeof f.exitCode=="number"?f.exitCode:null;if(p===null||g===null)return[];let d={name:p,exitCode:g};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof o.logTail=="string"?ym(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function ym(t){let e=Buffer.from(t,"utf-8");return e.length<=_o?t:`\u2026 [${e.length-_o} bytes elided] \u2026
546
+ `+e.subarray(e.length-_o).toString("utf-8")}import{lstatSync as wm,mkdtempSync as bm,readFileSync as km,readdirSync as Lc,rmSync as Uc}from"node:fs";import{tmpdir as $m}from"node:os";import{join as In,relative as vm}from"node:path";var Dc=new Set(["code","context"]);function Bc(t){let e=bm(In($m(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Uc(e,{recursive:!0,force:!0}),listFiles:()=>Gc(e,e),readFile:r=>km(In(e,r),"utf-8"),clean:()=>{for(let r of Lc(e))Dc.has(r)||Uc(In(e,r),{recursive:!0,force:!0})}}}function Gc(t,e){let r=[];for(let n of Lc(e)){let o=In(e,n),i=wm(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Dc.has(n))continue;r.push(...Gc(t,o))}else r.push(vm(t,o))}return r}var jn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Im=new Set(["implement","resolve-conflict"]);function jm(t){let e=Buffer.from(t,"utf-8");if(e.length<=jn)return t;let r=Math.floor(jn/4),n=jn-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
546
547
 
547
548
  \u2026 [${s} bytes elided \u2014 log capped at ${jn} bytes for upload] \u2026
548
549
 
549
- ${i}`}function Pm(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Tr(t={}){vn();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Vr("SANDBOX_LOG","sandbox",Tm("./logs"));if(n.enabled){let x=new jt(n);Jr(x),console.log(`[log] file logging \u2192 ${x.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${me} (protocol ${Ie})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=uc(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=fc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,f=null,p=!1,g=()=>{let x=s.openControlSocket();return u=x,x.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Ie};x.send(JSON.stringify(m))}),x.on("message",m=>{let R=m.toString("utf-8"),w=null;try{let S=JSON.parse(R);S&&typeof S=="object"&&(w=S)}catch{}if(w&&w.type==="hello"){let S=w;f=Lr(S.protocolVersion);let j=f?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${j}`),f&&(p=!1);return}if(w&&w.type==="pause_job"){let S=typeof w.jobId=="string"?w.jobId:"",j=S?l.get(S):void 0;j?(console.warn(`[ws] pause_job ${S} \u2014 aborting agent`),j.paused=!0,j.abort.abort()):console.log(`[ws] pause_job ${S} \u2014 not a running job, ignoring`),S&&x.send(JSON.stringify({type:"job_paused",jobId:S}));return}if(w&&(w.type==="chat_user_message"||w.type==="chat_finalize")){let S=typeof w.jobId=="string"?w.jobId:"",j=S?l.get(S):void 0;if(j?.chatInbox)if(w.type==="chat_user_message"){let k=typeof w.text=="string"?w.text:"";k.trim()&&j.chatInbox.push({kind:"user",text:k})}else j.chatInbox.finalize();else console.log(`[ws] ${String(w.type)} ${S} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${R}`)}),x.on("close",(m,R)=>{console.log(`[ws] closed code=${m} reason=${R?.toString()||""}`),u===x&&(u=null),!a&&setTimeout(g,2e3)}),x.on("error",m=>console.warn(`[ws] error: ${m.message}`)),x},d=g(),h=async x=>{for(;!a;){if(f===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${me}, protocol ${Ie}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,x);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${x}] ${m.status} \u2014 backoff 5s`),await new Promise(w=>setTimeout(w,5e3));continue}let R=await m.json();await C(s,R)}catch(m){if(c.signal.aborted)break;let R=m instanceof Error?m.message:String(m);console.warn(`[claim:${x}] error: ${R} \u2014 backoff 5s`),await new Promise(w=>setTimeout(w,5e3))}}};async function C(x,m){let R={abort:new AbortController,paused:!1};m.role==="chat"&&(R.chatInbox=Pm()),l.set(m.jobId,R);let w=!1,S=null,j=null,k=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),I=async()=>{try{await x.heartbeat(m.jobId)==="claim_lost"&&(w=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(F){let be=F instanceof Error?F.message:String(F);console.warn(`[job] ${m.jobId} heartbeat error: ${be}`)}};I();let B=setInterval(()=>{I()},k),K=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let Re=[],ct=null,E=400,de=25,We=500,Ue=()=>{if(ct&&(clearTimeout(ct),ct=null),Re.length===0)return;let F=Re.splice(0,Re.length),be=u;if(!be||be.readyState!==be.OPEN)return;let Le={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:F};try{be.send(JSON.stringify(Le))}catch{}},Ln=F=>{Re.push(F),Re.length>We&&Re.shift(),Re.length>=de?Ue():ct||(ct=setTimeout(Ue,E))},lt=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,ee=new Set,Dn=null;try{if(!o){w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:K,finishedAt:new Date().toISOString()});return}let F=Bc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let be=$(m,r);S=be.gitCreds,j=be.contextGitCreds;let Le=S?.env,ri=be.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:be.claudeOauthToken}:void 0,De=[],ir=null,Bn=null;try{let _="worktree";De=await Ac(F.dir,m.projectId,m.projectRepos,_,Le);let N=await _c(F.dir,m.projectId,m.contextRepo,_,Le);Bn=N,ir=N?.workspacePath??null}catch(_){let N=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} materialize failed: ${N}`),w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${N}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let ni=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let _=m.contextRepo?.cloneUrl;if(!_||!Le)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let N=[];for(let G of m.deliveries){let H=De.find(fe=>fe.name===G.name);if(H){if(m.role==="implement"&&G.baseSha&&G.baseSha!==H.baseSha){let fe=await jc(H,G.deliveryRef,G.deliverySha,G.baseSha,_,Le);console.log(`[job] ${m.jobId} ${H.name}: base moved ${G.baseSha.slice(0,10)} \u2192 ${H.baseSha.slice(0,10)} \u2014 re-applied delivery ${G.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&N.push(`- **${H.name}**:`,...fe.map(sr=>` - \`${sr}\``));continue}await Ic(H,G.deliveryRef,G.deliverySha,_,Le),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${G.deliverySha.slice(0,10)} for ${m.role}`)}}return N},Gn=[];if(m.role==="build"||m.role==="implement")try{Gn=await ni()}catch(_){let N=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} delivery checkout failed: ${N}`),w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${N}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let Mn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},oi="";if(m.role==="resolve-conflict"){if(!De.some(_=>Mn[_.name])){let _="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${m.jobId} ${_}`),w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}try{let _=[];for(let N of De){let G=Mn[N.name];if(!G)continue;let H=await Ao(N,G,Le);console.log(`[job] ${m.jobId} ${N.name}: merged ${G} into ${N.ref} \u2014 ${H.length} conflicted file(s)`),H.length>0?_.push(`- **${N.name}**:`,...H.map(fe=>` - \`${fe}\``)):_.push(`- **${N.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}oi=`
550
+ ${i}`}function Pm(){let t=[],e=!1,r=null,n=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},o=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||n(i)},finalize(){e||(n({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,o()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Tr(t={}){vn();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Vr("SANDBOX_LOG","sandbox",Tm("./logs"));if(n.enabled){let x=new jt(n);Jr(x),console.log(`[log] file logging \u2192 ${x.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${me} (protocol ${Ie})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=uc(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=fc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,f=null,p=!1,g=()=>{let x=s.openControlSocket();return u=x,x.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:me,protocolVersion:Ie};x.send(JSON.stringify(m))}),x.on("message",m=>{let R=m.toString("utf-8"),w=null;try{let S=JSON.parse(R);S&&typeof S=="object"&&(w=S)}catch{}if(w&&w.type==="hello"){let S=w;f=Lr(S.protocolVersion);let j=f?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${j}`),f&&(p=!1);return}if(w&&w.type==="pause_job"){let S=typeof w.jobId=="string"?w.jobId:"",j=S?l.get(S):void 0;j?(console.warn(`[ws] pause_job ${S} \u2014 aborting agent`),j.paused=!0,j.abort.abort()):console.log(`[ws] pause_job ${S} \u2014 not a running job, ignoring`),S&&x.send(JSON.stringify({type:"job_paused",jobId:S}));return}if(w&&(w.type==="chat_user_message"||w.type==="chat_finalize")){let S=typeof w.jobId=="string"?w.jobId:"",j=S?l.get(S):void 0;if(j?.chatInbox)if(w.type==="chat_user_message"){let b=typeof w.text=="string"?w.text:"";b.trim()&&j.chatInbox.push({kind:"user",text:b})}else j.chatInbox.finalize();else console.log(`[ws] ${String(w.type)} ${S} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${R}`)}),x.on("close",(m,R)=>{console.log(`[ws] closed code=${m} reason=${R?.toString()||""}`),u===x&&(u=null),!a&&setTimeout(g,2e3)}),x.on("error",m=>console.warn(`[ws] error: ${m.message}`)),x},d=g(),h=async x=>{for(;!a;){if(f===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${me}, protocol ${Ie}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,x);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${x}] ${m.status} \u2014 backoff 5s`),await new Promise(w=>setTimeout(w,5e3));continue}let R=await m.json();await C(s,R)}catch(m){if(c.signal.aborted)break;let R=m instanceof Error?m.message:String(m);console.warn(`[claim:${x}] error: ${R} \u2014 backoff 5s`),await new Promise(w=>setTimeout(w,5e3))}}};async function C(x,m){let R={abort:new AbortController,paused:!1};m.role==="chat"&&(R.chatInbox=Pm()),l.set(m.jobId,R);let w=!1,S=null,j=null,b=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),I=async()=>{try{await x.heartbeat(m.jobId)==="claim_lost"&&(w=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(F){let ke=F instanceof Error?F.message:String(F);console.warn(`[job] ${m.jobId} heartbeat error: ${ke}`)}};I();let B=setInterval(()=>{I()},b),K=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let Re=[],ct=null,E=400,de=25,We=500,Ue=()=>{if(ct&&(clearTimeout(ct),ct=null),Re.length===0)return;let F=Re.splice(0,Re.length),ke=u;if(!ke||ke.readyState!==ke.OPEN)return;let Le={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:F};try{ke.send(JSON.stringify(Le))}catch{}},Ln=F=>{Re.push(F),Re.length>We&&Re.shift(),Re.length>=de?Ue():ct||(ct=setTimeout(Ue,E))},lt=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,ee=new Set,Dn=null;try{if(!o){w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:K,finishedAt:new Date().toISOString()});return}let F=Bc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let ke=$(m,r);S=ke.gitCreds,j=ke.contextGitCreds;let Le=S?.env,ri=ke.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ke.claudeOauthToken}:void 0,De=[],ir=null,Bn=null;try{let _="worktree";De=await Ac(F.dir,m.projectId,m.projectRepos,_,Le);let N=await _c(F.dir,m.projectId,m.contextRepo,_,Le);Bn=N,ir=N?.workspacePath??null}catch(_){let N=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} materialize failed: ${N}`),w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${N}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let ni=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let _=m.contextRepo?.cloneUrl;if(!_||!Le)throw new Error(_?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let N=[];for(let G of m.deliveries){let H=De.find(fe=>fe.name===G.name);if(H){if(m.role==="implement"&&G.baseSha&&G.baseSha!==H.baseSha){let fe=await jc(H,G.deliveryRef,G.deliverySha,G.baseSha,_,Le);console.log(`[job] ${m.jobId} ${H.name}: base moved ${G.baseSha.slice(0,10)} \u2192 ${H.baseSha.slice(0,10)} \u2014 re-applied delivery ${G.deliverySha.slice(0,10)} (${fe.length} conflicted file(s))`),fe.length>0&&N.push(`- **${H.name}**:`,...fe.map(sr=>` - \`${sr}\``));continue}await Ic(H,G.deliveryRef,G.deliverySha,_,Le),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${G.deliverySha.slice(0,10)} for ${m.role}`)}}return N},Gn=[];if(m.role==="build"||m.role==="implement")try{Gn=await ni()}catch(_){let N=_ instanceof Error?_.message:String(_);console.warn(`[job] ${m.jobId} delivery checkout failed: ${N}`),w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${N}`},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}let Mn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},oi="";if(m.role==="resolve-conflict"){if(!De.some(_=>Mn[_.name])){let _="resolve-conflict job carries no task branch to merge for any repo \u2014 nothing to resolve. The task branch could not be identified on the hub (the apply step may have failed before recording it); make sure the task branch exists upstream, then retry the update.";console.warn(`[job] ${m.jobId} ${_}`),w||await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:K,finishedAt:new Date().toISOString()}),F.dispose();return}try{let _=[];for(let N of De){let G=Mn[N.name];if(!G)continue;let H=await Ao(N,G,Le);console.log(`[job] ${m.jobId} ${N.name}: merged ${G} into ${N.ref} \u2014 ${H.length} conflicted file(s)`),H.length>0?_.push(`- **${N.name}**:`,...H.map(fe=>` - \`${fe}\``)):_.push(`- **${N.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}oi=`
550
551
 
551
552
  ## Conflicts to resolve
552
553
 
@@ -560,30 +561,30 @@ The base branch advanced since the previous iteration; its delivery was re-appli
560
561
 
561
562
  `+Gn.join(`
562
563
  `)+`
563
- `:"",pu=v(b(m.prompt,De,ir),ir,m.taskId)+oi+uu,Fn=[...De.map(_=>_.workspacePath),...ir?[ir]:[]];Fn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Fn.join(", ")}`),lt&&(Dn=setInterval(()=>{let N=u;if(!N||N.readyState!==N.OPEN)return;let G;try{G=Sm(Rr(F.dir,"drafts")).filter(H=>H.endsWith(".json")).sort()}catch{return}for(let H of G){if(ee.has(H))continue;if(ee.size>=hi)break;let fe;try{let le=JSON.parse(Oo(Rr(F.dir,"drafts",H),"utf-8")),ut=typeof le.localRef=="string"?le.localRef:"",D=typeof le.title=="string"?le.title:"",ne=typeof le.body=="string"?le.body:"";if(!ut||!D)continue;fe={localRef:ut,title:D,body:ne,...le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(le.links)?{links:le.links}:{}}}catch{continue}ee.add(H);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:lt,child:fe};try{N.send(JSON.stringify(sr))}catch{}}},1500));try{let _={workspaceDir:F.dir,role:m.role,prompt:pu,addDirs:Fn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...ri?{env:ri}:{},signal:R.abort.signal,onActivity:Ln},N=R.chatInbox?await o.run({..._,interactive:{inbox:R.chatInbox.iterable}}):await gc(o,_,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let D of De)try{await Sc(D);let ne=Mn[D.name];m.role==="resolve-conflict"&&ne&&await Ao(D,ne,Le)}catch(ne){let ar=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${ar}`)}try{await ni()}catch(D){let ne=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${ne}`)}},aborted:()=>w||R.paused}),G=[];if(Im.has(m.role)&&De.length>0){let D=m.metadata??{},ne=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,ii=j?.env;if(!ar||!ii)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let du=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Be of De){let cr=await Cc(Be,ne);if(!cr){console.log(`[job] ${m.jobId} ${Be.name}: no changes \u2014 no delivery`);continue}let Hn=`codepipe/deliveries/${du}/${m.jobId}/${Be.name}`;await Rc(Be,cr,Hn,ar,ii),G.push({name:Be.name,deliveryRef:Hn,deliverySha:cr,baseSha:Be.baseSha}),console.log(`[job] ${m.jobId} ${Be.name}: delivered ${cr.slice(0,10)} \u2192 ${Hn}`);let si=await Tc(Be,cr);if(si.trim().length>0){let fu=Rr("display",`${Be.name}.diff`),ai=Rr(F.dir,fu);xm(Rm(ai),{recursive:!0}),Cm(ai,si)}}}if(m.role==="resolve-conflict"&&G.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let H;m.role==="build"&&(H=Nc(F.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let fe=N.artifactPaths.length>0?N.artifactPaths:F.listFiles(),sr=Array.from(new Set(fe)),le;if(Bn)try{let D=await Oc(Bn,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(le=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let ne=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${ne}`)}let ut={jobId:m.jobId,status:"succeeded",artifacts:sr.map(D=>({path:D,contentBase64:Oo(`${F.dir}/${D}`).toString("base64")})),...le?{contextWrites:le}:{},...G.length>0?{deliveries:G}:{},log:jm(N.log),startedAt:K,finishedAt:new Date().toISOString(),usage:N.usage,...N.rateLimit?{rateLimit:N.rateLimit}:{},...H?{build:H}:{}};if(w||R.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${R.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await x.submitResult(ut),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ut.artifacts.length} artifact(s):`);for(let D of ut.artifacts){let ne=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${ne} bytes)`)}ut.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(_){let N=_ instanceof Error?_.message:String(_);if(R.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(w)console.warn(`[job] ${m.jobId} failed after claim lost (${N}) \u2014 skipping result upload`);else{let G=mc(_);console.warn(G?`[job] ${m.jobId} failed: ${N} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${N}`),await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:N},startedAt:K,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(B),Dn&&clearInterval(Dn),Ue(),R.chatInbox?.close(),l.delete(m.jobId),S?.cleanup(),j?.cleanup()}}function $(x,m){if(!x.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${x.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let R;try{R=JSON.parse(on(m,x.credBundle).toString("utf-8"))}catch(k){return console.warn(`[job] ${x.jobId} failed to open credBundle: ${k instanceof Error?k.message:String(k)}`),{gitCreds:null,contextGitCreds:null}}let w=Po(R);w&&console.log(`[job] ${x.jobId} cred bundle opened \u2014 git creds configured`);let S=wc(R,x.contextRepo.cloneUrl),j={gitCreds:w,contextGitCreds:S};return R.claudeOauthToken&&(j.claudeOauthToken=R.claudeOauthToken),j}function y(x,m){return x.split(`
564
+ `:"",pu=v(k(m.prompt,De,ir),ir,m.taskId)+oi+uu,Fn=[...De.map(_=>_.workspacePath),...ir?[ir]:[]];Fn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Fn.join(", ")}`),lt&&(Dn=setInterval(()=>{let N=u;if(!N||N.readyState!==N.OPEN)return;let G;try{G=Sm(Rr(F.dir,"drafts")).filter(H=>H.endsWith(".json")).sort()}catch{return}for(let H of G){if(ee.has(H))continue;if(ee.size>=hi)break;let fe;try{let le=JSON.parse(Oo(Rr(F.dir,"drafts",H),"utf-8")),ut=typeof le.localRef=="string"?le.localRef:"",D=typeof le.title=="string"?le.title:"",ne=typeof le.body=="string"?le.body:"";if(!ut||!D)continue;fe={localRef:ut,title:D,body:ne,...le.isEpic===!0?{isEpic:!0}:{},...Array.isArray(le.links)?{links:le.links}:{}}}catch{continue}ee.add(H);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:lt,child:fe};try{N.send(JSON.stringify(sr))}catch{}}},1500));try{let _={workspaceDir:F.dir,role:m.role,prompt:pu,addDirs:Fn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...ri?{env:ri}:{},signal:R.abort.signal,onActivity:Ln},N=R.chatInbox?await o.run({..._,interactive:{inbox:R.chatInbox.iterable}}):await gc(o,_,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let D of De)try{await Sc(D);let ne=Mn[D.name];m.role==="resolve-conflict"&&ne&&await Ao(D,ne,Le)}catch(ne){let ar=ne instanceof Error?ne.message:String(ne);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${ar}`)}try{await ni()}catch(D){let ne=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${ne}`)}},aborted:()=>w||R.paused}),G=[];if(Im.has(m.role)&&De.length>0){let D=m.metadata??{},ne=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,ii=j?.env;if(!ar||!ii)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let du=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Be of De){let cr=await Cc(Be,ne);if(!cr){console.log(`[job] ${m.jobId} ${Be.name}: no changes \u2014 no delivery`);continue}let Hn=`codepipe/deliveries/${du}/${m.jobId}/${Be.name}`;await Rc(Be,cr,Hn,ar,ii),G.push({name:Be.name,deliveryRef:Hn,deliverySha:cr,baseSha:Be.baseSha}),console.log(`[job] ${m.jobId} ${Be.name}: delivered ${cr.slice(0,10)} \u2192 ${Hn}`);let si=await Tc(Be,cr);if(si.trim().length>0){let fu=Rr("display",`${Be.name}.diff`),ai=Rr(F.dir,fu);xm(Rm(ai),{recursive:!0}),Cm(ai,si)}}}if(m.role==="resolve-conflict"&&G.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let H;m.role==="build"&&(H=Nc(F.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let fe=N.artifactPaths.length>0?N.artifactPaths:F.listFiles(),sr=Array.from(new Set(fe)),le;if(Bn)try{let D=await Oc(Bn,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(le=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let ne=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${ne}`)}let ut={jobId:m.jobId,status:"succeeded",artifacts:sr.map(D=>({path:D,contentBase64:Oo(`${F.dir}/${D}`).toString("base64")})),...le?{contextWrites:le}:{},...G.length>0?{deliveries:G}:{},log:jm(N.log),startedAt:K,finishedAt:new Date().toISOString(),usage:N.usage,...N.rateLimit?{rateLimit:N.rateLimit}:{},...H?{build:H}:{}};if(w||R.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${R.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await x.submitResult(ut),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ut.artifacts.length} artifact(s):`);for(let D of ut.artifacts){let ne=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${ne} bytes)`)}ut.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(_){let N=_ instanceof Error?_.message:String(_);if(R.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(w)console.warn(`[job] ${m.jobId} failed after claim lost (${N}) \u2014 skipping result upload`);else{let G=mc(_);console.warn(G?`[job] ${m.jobId} failed: ${N} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${N}`),await x.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:N},startedAt:K,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(B),Dn&&clearInterval(Dn),Ue(),R.chatInbox?.close(),l.delete(m.jobId),S?.cleanup(),j?.cleanup()}}function $(x,m){if(!x.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${x.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let R;try{R=JSON.parse(on(m,x.credBundle).toString("utf-8"))}catch(b){return console.warn(`[job] ${x.jobId} failed to open credBundle: ${b instanceof Error?b.message:String(b)}`),{gitCreds:null,contextGitCreds:null}}let w=Po(R);w&&console.log(`[job] ${x.jobId} cred bundle opened \u2014 git creds configured`);let S=wc(R,x.contextRepo.cloneUrl),j={gitCreds:w,contextGitCreds:S};return R.claudeOauthToken&&(j.claudeOauthToken=R.claudeOauthToken),j}function y(x,m){return x.split(`
564
565
  `).map(R=>m+R).join(`
565
- `)}function b(x,m,R){let w=m[0]?.workspacePath??"";return x.replace(/\{\{codeDir\}\}/g,w).replace(/\{\{codeRoot\}\}/g,w?w.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,R??"")}function v(x,m,R){let w=x,S=R.includes("::")?"":R.split(":",2)[1]??"",j=k=>{if(!m||!S)return"";try{return Oo(Rr(m,"tasks",S,k),"utf-8").trim()}catch{return""}};if(w.includes("{{solutionMd}}")){let k=j("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";w=w.replace(/\{\{solutionMd\}\}/g,()=>k)}if(w.includes("{{taskDescription}}")){let k=j("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";w=w.replace(/\{\{taskDescription\}\}/g,()=>k)}return w}let O=x=>{if(a)return;a=!0,console.log(`
566
- [${x}] shutting down`),c.abort();let m=[...l.keys()];for(let S of l.values())S.abort.abort();let R=new AbortController,w=setTimeout(()=>R.abort(),3e3);(async()=>(await Promise.all(m.map(async S=>{try{await s.releaseJob(S,`sandbox ${x}`,R.signal),console.log(`[${x}] released job ${S}`)}catch(j){let k=j instanceof Error?j.message:String(j);console.warn(`[${x}] release failed: ${k} (sweeper will reclaim)`)}})),clearTimeout(w),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let P=[h("implementation")];e.planningLane!==!1?P.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(P)}async function Mc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=mn(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ie(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Qm}from"node:child_process";import{existsSync as Jt,mkdirSync as sl,readFileSync as al,readdirSync as Zm,writeFileSync as cl}from"node:fs";import{join as bt,resolve as ll}from"node:path";import{setTimeout as Do}from"node:timers/promises";import{cancel as eg,confirm as zt,intro as ul,isCancel as Mo,log as T,outro as Bo,password as Xt,select as $t,spinner as pl,text as Q}from"@clack/prompts";import{simpleGit as An}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Am(t,e,r):e.host==="gitlab"?Bm(t,e,r):Mm(t,e,r)}async function Fc(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Hc(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Kc(e.gitlabToken,t):o}}return e.bitbucket?(await qt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wc(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Hc(t,e){let r=!1;try{r=(await it(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Kc(t,e){let r=!1;try{r=(await ot(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Wc(t,e){let r=!1;try{r=(await qt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var Em="https://api.github.com";async function it(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Em+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Am(t,e,r){let n=r.githubToken;if(!n)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let o=await _m(n,e,r),i=await Nm(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ot(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Um(n,o.owner,o.name,a.path,i)||await Lm(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function _m(t,e,r){let n=await it(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Hc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Om(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await it(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Om(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Nm(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Um(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Lm(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Dm="https://gitlab.com/api/v4";async function ot(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(Dm+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Bm(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await ot(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Kc(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await ot(n,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await ot(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await ot(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await ot(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await ot(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Gm="https://api.bitbucket.org/2.0";async function qt(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(Gm+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function Mm(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await qt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Wc(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await qt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await qt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await qt(n,"POST",`${o}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Fm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function we(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=Fm[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as Hm}from"node:crypto";import{existsSync as qc,mkdirSync as Km,readFileSync as Yc,readdirSync as Wm,rmSync as Pn,writeFileSync as qm}from"node:fs";import{homedir as Ym}from"node:os";import{dirname as Vm,join as No}from"node:path";var Jm=24*60*60*1e3;function Vc(){return No(Ym(),".codepipe","init-drafts")}function Uo(t){let e=Hm("sha256").update(t).digest("hex").slice(0,16);return No(Vc(),`${e}.json`)}function Jc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Jm)}function zc(t){let e=Uo(t);if(!qc(e))return null;try{let r=JSON.parse(Yc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Jc(r.savedAt)?(Pn(e,{force:!0}),null):r}catch{return null}}function Lo(t){Pn(Uo(t),{force:!0})}function Xc(){let t=Vc();if(qc(t))for(let e of Wm(t)){let r=No(t,e);try{let n=JSON.parse(Yc(r,"utf-8"));Jc(n.savedAt)&&Pn(r,{force:!0})}catch{Pn(r,{force:!0})}}}var Vt=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Lo(this.cwd)}persist(){let e=Uo(this.cwd);Km(Vm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};qm(e,JSON.stringify(r,null,2)+`
567
- `,{mode:384})}};function Qc(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function Zc(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as el}from"node:fs";import{join as tl}from"node:path";import{simpleGit as rl}from"simple-git";var zm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Ir(t,e,r={}){let n=r.log??zm,o=[];for(let i of e){let s=tl(t,i.mountAs),a=bi(i);if(!el(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await rl().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!el(tl(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=rl(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Xm(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function Xm(t,e){return nl(t)===nl(e)}function nl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function ol(t={}){let e=ge();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Ir(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var il=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){eg(t),process.exit(1)}function ke(t){return Mo(t)&&J("aborted"),t}function W(t){return Mo(t)&&J("aborted"),typeof t=="string"?t:""}async function dl(t={}){ul("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Xc();let r=zc(e),n,o=!1;r&&Object.keys(r.answers).length>0?ke(await zt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Lo(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Fo(e),s=await n.ask("target",async()=>ke(await $t({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?T.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||ml(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await Q({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??Te,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qt()),{cliToken:u,accountEmail:f}=await n.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await tg(c,u));let g=a?ng(a.parsed.repoName):"",d=await n.ask("projectId",async()=>W(await Q({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>dt.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>W(await Q({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),C=await n.ask("automationLevel",async()=>ke(await $t({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),$=await n.ask("youtrack",()=>$l()),y=await n.ask("youtrackProjectKey",async()=>W(await Q({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),b=await n.ask("youtrackWrites",async()=>ke(await zt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),v=n.get("tokens")??{},O=()=>n.set("tokens",v),P=await n.ask("repos",()=>ag(v,l,a,{onCred:O,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let x=await cg(await n.ask("contextRepo",()=>wl(d,P,v,l)),d,P,v,l,O,E=>n.set("contextRepo",E)),{spec:m,mode:R}=x;T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let w=await n.ask("assigneeLogin",async()=>W(await Q({message:"your YouTrack login (the assignee value)",...$.login?{initialValue:$.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await n.ask("claudeToken",()=>gg(s==="farm")),j={projectId:d,name:h,automationLevel:C,repos:P,youtrackProjectKey:y};T.step(`${R==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let k;try{k=await Yt(j,m,{...kl(v),youtrackWrites:b,trackerUrl:$.url,mode:R,log:{info:E=>T.message(E),warn:E=>T.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}j.contextRepo=k,T.success(`Context Repo ready: ${k.owner}/${k.name}@${k.branch}`),T.step(`registering project on ${c}\u2026`);let I;try{I=await tt(c,u,j)}catch(E){if(E instanceof A&&E.status===409){T.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{I=await M(c,u,d)}catch(de){throw de instanceof A&&J(`HUB \u2192 ${de.status} ${de.message}`),de}}else if(E instanceof A&&E.status===401)n.delete("cliToken"),J("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)J(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=I.contextRepo??k;T.success(`project ${I.projectId} ready (${I.provisioningStatus})`);let K=await fg(B),Re={url:$.url,token:$.token};if(s==="farm"){let E=p,de={...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re},We=v.github?.token;if(B.host==="github"&&We)try{let ee=Ha(`devpipe-${d}`);await Ka(B,We,ee.publicKey,`devpipe-${d}`),de.contextSsh={privateKey:ee.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ee){T.warn(`could not set up Context Repo SSH deploy key (${ee instanceof Error?ee.message:String(ee)}); the farm will fall back to the token path.`)}let Ue={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:de,contextRepo:B,projectConfig:_e(j,b,$.url,w||void 0)},Ln=He(E.farm.publicKey,JSON.stringify(Ue));T.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let lt;try{lt=await gn(c,u,E.farm.farmId,{projectId:d,sealedBundle:Ln})}catch(ee){throw ee instanceof A&&J(ee.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:ee.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${ee.status} ${ee.message}`),ee}lt.ok||J(`farm rejected provisioning: ${lt.error??"unknown error"}`),await Go(c,u,d,B,We),n.clear(),Bo(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${lt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}bl(v),await gl(e,B.cloneUrl,B.branch),yl(e),a&&await ig(e);{let E=bt(e,Pe);At(E);let de=_e(j,b,$.url,w||void 0),We=dr(E,de);We.length>0&&T.success(`local project config \u2192 .codepipe/{${We.join(", ")}}`),gt(d,de,{info:Ue=>T.message(Ue),warn:Ue=>T.warn(Ue)})}await hl(e,I.repos);let ct={hubUrl:c,cliToken:u,projectId:d,...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re};V(ct),Me({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),T.success(`secrets \u2192 ${Ee(d)}`),await Go(c,u,d,B,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),n.clear(),Bo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Go(t,e,r,n,o){let i=await Zc(n,o),s=Qc(i),a=await $t({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Mo(a)||a!==s.proceedValue))try{let{jobId:c}=await yn(t,e,r,{reindex:s.reindex});T.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){T.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function tg(t,e){let r;try{r=await ua(t,e)}catch(c){throw c instanceof A&&J(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&J("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=ke(await $t({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=fn(i.farmId,i.publicKey)}catch(c){J(c instanceof Error?c.message:String(c))}return ke(await zt({message:`confirm farm ${i.name} cred-channel fingerprint:
566
+ `)}function k(x,m,R){let w=m[0]?.workspacePath??"";return x.replace(/\{\{codeDir\}\}/g,w).replace(/\{\{codeRoot\}\}/g,w?w.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,R??"")}function v(x,m,R){let w=x,S=R.includes("::")?"":R.split(":",2)[1]??"",j=b=>{if(!m||!S)return"";try{return Oo(Rr(m,"tasks",S,b),"utf-8").trim()}catch{return""}};if(w.includes("{{solutionMd}}")){let b=j("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";w=w.replace(/\{\{solutionMd\}\}/g,()=>b)}if(w.includes("{{taskDescription}}")){let b=j("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";w=w.replace(/\{\{taskDescription\}\}/g,()=>b)}return w}let O=x=>{if(a)return;a=!0,console.log(`
567
+ [${x}] shutting down`),c.abort();let m=[...l.keys()];for(let S of l.values())S.abort.abort();let R=new AbortController,w=setTimeout(()=>R.abort(),3e3);(async()=>(await Promise.all(m.map(async S=>{try{await s.releaseJob(S,`sandbox ${x}`,R.signal),console.log(`[${x}] released job ${S}`)}catch(j){let b=j instanceof Error?j.message:String(j);console.warn(`[${x}] release failed: ${b} (sweeper will reclaim)`)}})),clearTimeout(w),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let P=[h("implementation")];e.planningLane!==!1?P.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(P)}async function Mc(t={profile:void 0}){let e=he(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=mn(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await M(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ie(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Qm}from"node:child_process";import{existsSync as Jt,mkdirSync as sl,readFileSync as al,readdirSync as Zm,writeFileSync as cl}from"node:fs";import{join as kt,resolve as ll}from"node:path";import{setTimeout as Do}from"node:timers/promises";import{cancel as eg,confirm as zt,intro as ul,isCancel as Mo,log as T,outro as Bo,password as Xt,select as $t,spinner as pl,text as Q}from"@clack/prompts";import{simpleGit as An}from"simple-git";async function Yt(t,e,r){return e.host==="github"?Am(t,e,r):e.host==="gitlab"?Bm(t,e,r):Mm(t,e,r)}async function Fc(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await it(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Hc(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Kc(e.gitlabToken,t):o}}return e.bitbucket?(await qt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Wc(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Hc(t,e){let r=!1;try{r=(await it(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function Kc(t,e){let r=!1;try{r=(await ot(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function Wc(t,e){let r=!1;try{r=(await qt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var Em="https://api.github.com";async function it(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Em+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Am(t,e,r){let n=r.githubToken;if(!n)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let o=await _m(n,e,r),i=await Nm(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=Ot(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Um(n,o.owner,o.name,a.path,i)||await Lm(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function _m(t,e,r){let n=await it(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Hc(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Om(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await it(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Om(t,e){let{status:r,data:n}=await it(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Nm(t,e,r){let{data:n}=await it(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Um(t,e,r,n,o){let{status:i,data:s}=await it(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Lm(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await it(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var Dm="https://gitlab.com/api/v4";async function ot(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(Dm+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Bm(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await ot(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Kc(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await ot(n,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await ot(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await ot(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await ot(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await ot(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Gm="https://api.bitbucket.org/2.0";async function qt(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(Gm+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function Mm(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await qt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Wc(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await qt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=Ot(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await qt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await qt(n,"POST",`${o}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Fm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function we(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=Fm[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as Hm}from"node:crypto";import{existsSync as qc,mkdirSync as Km,readFileSync as Yc,readdirSync as Wm,rmSync as Pn,writeFileSync as qm}from"node:fs";import{homedir as Ym}from"node:os";import{dirname as Vm,join as No}from"node:path";var Jm=24*60*60*1e3;function Vc(){return No(Ym(),".codepipe","init-drafts")}function Uo(t){let e=Hm("sha256").update(t).digest("hex").slice(0,16);return No(Vc(),`${e}.json`)}function Jc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Jm)}function zc(t){let e=Uo(t);if(!qc(e))return null;try{let r=JSON.parse(Yc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Jc(r.savedAt)?(Pn(e,{force:!0}),null):r}catch{return null}}function Lo(t){Pn(Uo(t),{force:!0})}function Xc(){let t=Vc();if(qc(t))for(let e of Wm(t)){let r=No(t,e);try{let n=JSON.parse(Yc(r,"utf-8"));Jc(n.savedAt)&&Pn(r,{force:!0})}catch{Pn(r,{force:!0})}}}var Vt=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){Lo(this.cwd)}persist(){let e=Uo(this.cwd);Km(Vm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};qm(e,JSON.stringify(r,null,2)+`
568
+ `,{mode:384})}};function Qc(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function Zc(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as el}from"node:fs";import{join as tl}from"node:path";import{simpleGit as rl}from"simple-git";var zm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Ir(t,e,r={}){let n=r.log??zm,o=[];for(let i of e){let s=tl(t,i.mountAs),a=ki(i);if(!el(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await rl().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!el(tl(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=rl(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Xm(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function Xm(t,e){return nl(t)===nl(e)}function nl(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function ol(t={}){let e=ge();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Ir(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var il=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function J(t){eg(t),process.exit(1)}function be(t){return Mo(t)&&J("aborted"),t}function W(t){return Mo(t)&&J("aborted"),typeof t=="string"?t:""}async function dl(t={}){ul("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Xc();let r=zc(e),n,o=!1;r&&Object.keys(r.answers).length>0?be(await zt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new Vt(e,r),o=!0):(Lo(e),n=new Vt(e)):n=new Vt(e);let i=t.force===!0?null:await Fo(e),s=await n.ask("target",async()=>be(await $t({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?T.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||ml(e,t.force===!0));let c=await n.ask("hubUrl",async()=>W(await Q({message:"HUB URL",placeholder:Te,initialValue:L("HUB_URL")??Te,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>Qt()),{cliToken:u,accountEmail:f}=await n.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await tg(c,u));let g=a?ng(a.parsed.repoName):"",d=await n.ask("projectId",async()=>W(await Q({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>dt.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await n.ask("projectName",async()=>W(await Q({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),C=await n.ask("automationLevel",async()=>be(await $t({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),$=await n.ask("youtrack",()=>$l()),y=await n.ask("youtrackProjectKey",async()=>W(await Q({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),k=await n.ask("youtrackWrites",async()=>be(await zt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),v=n.get("tokens")??{},O=()=>n.set("tokens",v),P=await n.ask("repos",()=>ag(v,l,a,{onCred:O,initial:n.get("reposPartial")??[],onProgress:E=>n.set("reposPartial",E)}));n.delete("reposPartial");let x=await cg(await n.ask("contextRepo",()=>wl(d,P,v,l)),d,P,v,l,O,E=>n.set("contextRepo",E)),{spec:m,mode:R}=x;T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let w=await n.ask("assigneeLogin",async()=>W(await Q({message:"your YouTrack login (the assignee value)",...$.login?{initialValue:$.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await n.ask("claudeToken",()=>gg(s==="farm")),j={projectId:d,name:h,automationLevel:C,repos:P,youtrackProjectKey:y};T.step(`${R==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let b;try{b=await Yt(j,m,{...bl(v),youtrackWrites:k,trackerUrl:$.url,mode:R,log:{info:E=>T.message(E),warn:E=>T.warn(E)}})}catch(E){J(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}j.contextRepo=b,T.success(`Context Repo ready: ${b.owner}/${b.name}@${b.branch}`),T.step(`registering project on ${c}\u2026`);let I;try{I=await tt(c,u,j)}catch(E){if(E instanceof A&&E.status===409){T.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{I=await M(c,u,d)}catch(de){throw de instanceof A&&J(`HUB \u2192 ${de.status} ${de.message}`),de}}else if(E instanceof A&&E.status===401)n.delete("cliToken"),J("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)J(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=I.contextRepo??b;T.success(`project ${I.projectId} ready (${I.provisioningStatus})`);let K=await fg(B),Re={url:$.url,token:$.token};if(s==="farm"){let E=p,de={...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re},We=v.github?.token;if(B.host==="github"&&We)try{let ee=Ha(`devpipe-${d}`);await Ka(B,We,ee.publicKey,`devpipe-${d}`),de.contextSsh={privateKey:ee.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ee){T.warn(`could not set up Context Repo SSH deploy key (${ee instanceof Error?ee.message:String(ee)}); the farm will fall back to the token path.`)}let Ue={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:de,contextRepo:B,projectConfig:_e(j,k,$.url,w||void 0)},Ln=He(E.farm.publicKey,JSON.stringify(Ue));T.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let lt;try{lt=await gn(c,u,E.farm.farmId,{projectId:d,sealedBundle:Ln})}catch(ee){throw ee instanceof A&&J(ee.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:ee.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${ee.status} ${ee.message}`),ee}lt.ok||J(`farm rejected provisioning: ${lt.error??"unknown error"}`),await Go(c,u,d,B,We),n.clear(),Bo(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${lt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}kl(v),await gl(e,B.cloneUrl,B.branch),yl(e),a&&await ig(e);{let E=kt(e,Pe);At(E);let de=_e(j,k,$.url,w||void 0),We=dr(E,de);We.length>0&&T.success(`local project config \u2192 .codepipe/{${We.join(", ")}}`),gt(d,de,{info:Ue=>T.message(Ue),warn:Ue=>T.warn(Ue)})}await hl(e,I.repos);let ct={hubUrl:c,cliToken:u,projectId:d,...v,...K?{contextWrite:K}:{},...S?{claude:{oauthToken:S}}:{},youtrack:Re};V(ct),Me({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),T.success(`secrets \u2192 ${Ee(d)}`),await Go(c,u,d,B,v.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),n.clear(),Bo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Go(t,e,r,n,o){let i=await Zc(n,o),s=Qc(i),a=await $t({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Mo(a)||a!==s.proceedValue))try{let{jobId:c}=await yn(t,e,r,{reindex:s.reindex});T.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){T.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function tg(t,e){let r;try{r=await ua(t,e)}catch(c){throw c instanceof A&&J(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&J("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=be(await $t({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=fn(i.farmId,i.publicKey)}catch(c){J(c instanceof Error?c.message:String(c))}return be(await zt({message:`confirm farm ${i.name} cred-channel fingerprint:
568
569
  ${s}
569
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),dn(i.farmId,s),{farm:i,fingerprint:s}}async function fl(t){ul(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ml(e,t.force===!0);let r=W(await Q({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);T.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,o,t.projectId)}catch(f){throw f instanceof A&&J(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await $l(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await En(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,n);bl(c),await gl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),yl(e);{let f=bt(e,Pe);At(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=_e(p,!0,a.url),d=dr(f,g);d.length>0&&T.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),gt(t.projectId,g,{info:h=>T.message(h),warn:h=>T.warn(h)})}await hl(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Me({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${Ee(t.projectId)}`),await Go(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Bo("done.")}function ml(t,e){if(!Jt(t)){sl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=Zm(t).filter(o=>!r.has(o));n.length!==0&&(e||J(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Fo(t){if(!Jt(bt(t,".git")))return null;try{let r=(await An(t).remote(["get-url","origin"])||"").toString().trim(),n=r?we(r):null;return n?{parsed:n,defaultBranch:await rg(t)}:null}catch{return null}}async function rg(t){let e=An(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function ng(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return dt.test(e)?e:""}function og(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function ig(t){let e=bt(t,".gitignore"),r=Jt(e)?al(e,"utf-8"):"";if(og(r))return;if(!ke(await zt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){T.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
570
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||J("farm fingerprint not confirmed \u2014 aborting."),dn(i.farmId,s),{farm:i,fingerprint:s}}async function fl(t){ul(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ml(e,t.force===!0);let r=W(await Q({message:"HUB URL",initialValue:L("HUB_URL")??Te,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await Qt(),{cliToken:o,accountEmail:i}=await Zt(r,n);T.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await M(r,o,t.projectId)}catch(f){throw f instanceof A&&J(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||J(`project ${t.projectId} has no Context Repo on HUB`);let a=await $l(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await En(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,n);kl(c),await gl(e,s.contextRepo.cloneUrl,s.contextRepo.branch),yl(e);{let f=kt(e,Pe);At(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=_e(p,!0,a.url),d=dr(f,g);d.length>0&&T.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),gt(t.projectId,g,{info:h=>T.message(h),warn:h=>T.warn(h)})}await hl(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Me({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${Ee(t.projectId)}`),await Go(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Bo("done.")}function ml(t,e){if(!Jt(t)){sl(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=Zm(t).filter(o=>!r.has(o));n.length!==0&&(e||J(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function Fo(t){if(!Jt(kt(t,".git")))return null;try{let r=(await An(t).remote(["get-url","origin"])||"").toString().trim(),n=r?we(r):null;return n?{parsed:n,defaultBranch:await rg(t)}:null}catch{return null}}async function rg(t){let e=An(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function ng(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return dt.test(e)?e:""}function og(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function ig(t){let e=kt(t,".gitignore"),r=Jt(e)?al(e,"utf-8"):"";if(og(r))return;if(!be(await zt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){T.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
570
571
  `)?"":`
571
572
  `;cl(e,r+o+`
572
573
  # codepipe workspace (added by \`codepipe init\`)
573
574
  .codepipe/
574
- `),T.success(`.codepipe/ added to ${ll(e)}`)}function sg(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Qm(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Qt(){let t="";try{t=(await An().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Q({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Zt(t,e){T.step(`connecting account ${e}`);let r;try{r=await ga(t,e)}catch(s){throw s instanceof br&&J(`${e} is not authorized on this HUB yet.
575
+ `),T.success(`.codepipe/ added to ${ll(e)}`)}function sg(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=Qm(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function Qt(){let t="";try{t=(await An().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Q({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Zt(t,e){T.step(`connecting account ${e}`);let r;try{r=await ga(t,e)}catch(s){throw s instanceof kr&&J(`${e} is not authorized on this HUB yet.
575
576
  Sign up at ${t} (registration form on the login screen),
576
577
  wait for the operator to approve it by email, then re-run
577
578
  \`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(sg(r.authorizeUrl),T.message(`a browser tab was opened to confirm this CLI:
578
579
  ${r.authorizeUrl}
579
580
  `+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
580
581
  otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await ha(t,r.requestId)}catch(a){T.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Do(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&T.message(`connected as ${a} (the account confirmed in the browser).`),T.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&J("the HUB rejected this account"),s.status==="expired"&&J("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,T.message(`email confirmed. waiting for the operator to approve your account\u2026
581
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Do(5e3);continue}await Do(2e3)}J("bootstrap timed out")}async function gl(t,e,r){let n=bt(t,Pe);if(Jt(bt(n,".git"))){T.message(`${n} already cloned \u2014 skipping`);return}Jt(n)&&J(`${n} exists but is not a git repo \u2014 remove it and re-run`),sl(n,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${n}`);try{await An().clone(e,n,["--branch",r]),T.success(`cloned ${e}`)}catch(o){J(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function hl(t,e){if(e.length===0)return;T.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await Ir(t,r,{log:{info:o=>T.message(o),warn:o=>T.warn(o)}});for(let o of n)T.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function yl(t){let e=bt(t,Pe,".gitignore"),r="";if(Jt(e)&&(r=al(e,"utf-8")),il.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
582
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Do(5e3);continue}await Do(2e3)}J("bootstrap timed out")}async function gl(t,e,r){let n=kt(t,Pe);if(Jt(kt(n,".git"))){T.message(`${n} already cloned \u2014 skipping`);return}Jt(n)&&J(`${n} exists but is not a git repo \u2014 remove it and re-run`),sl(n,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${n}`);try{await An().clone(e,n,["--branch",r]),T.success(`cloned ${e}`)}catch(o){J(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function hl(t,e){if(e.length===0)return;T.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await Ir(t,r,{log:{info:o=>T.message(o),warn:o=>T.warn(o)}});for(let o of n)T.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function yl(t){let e=kt(t,Pe,".gitignore"),r="";if(Jt(e)&&(r=al(e,"utf-8")),il.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
582
583
  `)||r.length===0?"":`
583
584
  `,i=il.join(`
584
585
  `)+`
585
586
  `;cl(e,r+o+(r?`
586
- `:"")+i),T.message(`appended runtime entries to ${ll(e)}`)}async function ag(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;T.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await En(s.host,t,s.owner,e),i?.();let c=W(await Q({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=W(await Q({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;ke(await zt({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=W(await Q({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||we(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=we(a);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await En(c.host,t,c.owner,e),i?.();let l=W(await Q({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=W(await Q({message:"default branch (optional)",placeholder:"main"})).trim(),f=W(await Q({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),f&&f!==l&&(p.mountAs=f),o.push(p),n.onProgress?.(o)}return o}async function wl(t,e,r,n){T.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=ke(await $t({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&T.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=W(await Q({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ge(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!we(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await lg(),l=W(await Q({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=W(await Q({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function kl(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??It()}}async function cg(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await En(c.host,n,c.owner,o),i?.();let u=pl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Fc(c,kl(n),{explain:l==="attach"});if(f.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(f.detail,1);let p=ke(await $t({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&J("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await wl(e,r,n,o),s(a)}}async function lg(){return ke(await $t({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function jr(t,e){let r=pl();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function bl(t){yr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),wr(t.gitlab?.token??process.env.GITLAB_TOKEN),kr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function En(t,e,r,n){if(!e[t])if(t==="github"){let o=await ug(r);o?e.github=o:T.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await pg(r,n);o?e.bitbucket=o:T.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let o=await dg();o?e.gitlab=o:T.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function ug(t){for(;;){let e=W(await Xt({message:`GitHub PAT \u2014 blank to skip
587
+ `:"")+i),T.message(`appended runtime entries to ${ll(e)}`)}async function ag(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;T.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await En(s.host,t,s.owner,e),i?.();let c=W(await Q({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=W(await Q({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;be(await zt({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=W(await Q({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||we(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=we(a);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await En(c.host,t,c.owner,e),i?.();let l=W(await Q({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=W(await Q({message:"default branch (optional)",placeholder:"main"})).trim(),f=W(await Q({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),f&&f!==l&&(p.mountAs=f),o.push(p),n.onProgress?.(o)}return o}async function wl(t,e,r,n){T.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=be(await $t({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&T.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=W(await Q({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ge(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!we(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=we(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await lg(),l=W(await Q({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=W(await Q({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function bl(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??It()}}async function cg(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await En(c.host,n,c.owner,o),i?.();let u=pl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Fc(c,bl(n),{explain:l==="attach"});if(f.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(f.detail,1);let p=be(await $t({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&J("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await wl(e,r,n,o),s(a)}}async function lg(){return be(await $t({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function jr(t,e){let r=pl();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function kl(t){yr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),wr(t.gitlab?.token??process.env.GITLAB_TOKEN),br(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function En(t,e,r,n){if(!e[t])if(t==="github"){let o=await ug(r);o?e.github=o:T.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await pg(r,n);o?e.bitbucket=o:T.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let o=await dg();o?e.gitlab=o:T.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function ug(t){for(;;){let e=W(await Xt({message:`GitHub PAT \u2014 blank to skip
587
588
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
588
589
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
589
590
  if org: approve token in org Settings \u2192 Personal access tokens.
@@ -594,31 +595,31 @@ The base branch advanced since the previous iteration; its delivery was re-appli
594
595
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
595
596
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
596
597
  The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Q({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=W(await Xt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){T.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await jr("Bitbucket",()=>Xe(r,n,t)))return{email:r,apiToken:n};T.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function dg(){for(;;){let t=W(await Xt({message:`GitLab PAT \u2014 blank to skip
597
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await jr("GitLab",()=>Qe(t))){let e=await is(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function fg(t){if(ke(await zt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
598
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await jr("GitLab",()=>Qe(t))){let e=await is(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function fg(t){if(be(await zt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
598
599
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
599
600
  credential. A scoped token hardens setups where the SANDBOX runs outside
600
601
  your trusted network.`,initialValue:!1})))for(t.host==="github"?T.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
601
602
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
602
603
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):T.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
603
604
  (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=W(await Xt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await jr("contextWrite",()=>mg(r,t)))return{token:r};T.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function mg(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function gg(t){if(Yn()?.claude?.oauthToken&&!t)return T.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";T.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
604
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Xt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||T.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(T.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function $l(){for(;;){let t=W(await Q({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=W(await Xt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await jr("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await Ns({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as hg}from"node:fs";function Z(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&Z(`config: '${e}' must be a non-empty string`),t.trim()}function Pr(t,e){if(t==null)return;typeof t!="string"&&Z(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function yg(t){(!t||typeof t!="object")&&Z("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Z("config: 'hubUrl' must start with http(s)://");let n=re(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Z("config: 'project' is required");let i=o,s=re(i.id,"project.id");dt.test(s)||Z("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=re(i.name,"project.name"),c=re(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Z("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Z("config: 'project.repos' must be an array");let u=l.map((y,b)=>{(!y||typeof y!="object")&&Z(`config: project.repos[${b}] must be an object`);let v=y,O=re(v.host,`project.repos[${b}].host`);O!=="github"&&O!=="bitbucket"&&O!=="gitlab"&&Z(`config: project.repos[${b}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:re(v.name,`project.repos[${b}].name`),host:O,owner:re(v.owner,`project.repos[${b}].owner`),repoName:re(v.repoName,`project.repos[${b}].repoName`)},x=Pr(v.defaultBranch,`project.repos[${b}].defaultBranch`);x&&(P.defaultBranch=x);let m=Pr(v.mountAs,`project.repos[${b}].mountAs`);return m&&(P.mountAs=m),P}),f=i.contextRepo;(!f||typeof f!="object")&&Z("config: 'project.contextRepo' is required");let p=f,g=Pr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Z("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:re(p.owner,"project.contextRepo.owner"),name:Pr(p.name,"project.contextRepo.name")??Ge(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},C=Pr(i.youtrackProjectKey,"project.youtrackProjectKey");C&&(h.project.youtrackProjectKey=C),i.index!==void 0&&(typeof i.index!="boolean"&&Z("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Z("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&Z("config: 'secrets' must be an object");let y=$,b={};if(y.github){let v=y.github;b.github={token:re(v.token,"secrets.github.token")}}if(y.bitbucket){let v=y.bitbucket;b.bitbucket={email:re(v.email,"secrets.bitbucket.email"),apiToken:re(v.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let v=y.gitlab;b.gitlab={token:re(v.token,"secrets.gitlab.token")}}if(y.youtrack){let v=y.youtrack;b.youtrack={url:re(v.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(v.token,"secrets.youtrack.token")}}if(y.contextWrite){let v=y.contextWrite;b.contextWrite={token:re(v.token,"secrets.contextWrite.token")}}h.secrets=b}return h}async function wg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function kg(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Xe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Qe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function vl(t){let e=!t.configPath||t.configPath==="-"?await wg():hg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Z(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=yg(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await kg(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Yt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??It(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Z(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await tt(o,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(o,i,s.id);else if(p instanceof A)Z(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(V(f),Me({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),gt(s.id,_e(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await yn(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as xl,intro as Sl,isCancel as Cl,log as Ho,outro as bg,password as Rl}from"@clack/prompts";async function $g(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Tl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await $g(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Sl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Rl({message:"Claude OAuth token"});Cl(i)&&(xl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ui({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Yr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){Sl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Rl({message:"Claude OAuth token"});Cl(i)&&(xl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},V(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ho.success("Claude OAuth token saved."),bg("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as vg,confirm as xg,intro as Sg,isCancel as Il,log as se,outro as Cg,select as jl,text as st}from"@clack/prompts";function Pl(t){vg(t),process.exit(1)}function er(t){return Il(t)&&Pl("aborted"),t}function Er(t){return Il(t)&&Pl("aborted"),typeof t=="string"?t:""}async function Rg(t,e){let r=er(await jl({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Er(await st({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Er(await st({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function El(t={profile:void 0}){let e=he(t.profile);Sg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await st({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>dt.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await st({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=er(await jl({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=er(await st({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await xg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Er(await st({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:$=>!$||!$.trim()||we($)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=Er(await st({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),h=Er(await st({message:"default branch (optional)",placeholder:"main"})).trim(),C={name:d,host:g.host,owner:g.owner,repoName:g.repoName};h&&(C.defaultBranch=h),a.push(C)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Rg(r,a),u=U(e.projectId);se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Yt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??It(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await tt(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),gt(r,_e(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),Cg("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as Tg,rmSync as Ig}from"node:fs";import{confirm as jg,intro as Pg,isCancel as Eg,log as at,outro as Ag,spinner as _g}from"@clack/prompts";function Ne(t){at.error(t),process.exit(1)}var Al=t=>t.trim().replace(/\/+$/,"");async function _l(t){Pg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||Ne("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Ne(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Al(r.hubUrl),o=r.projectId,i=Al(t.hub);i.startsWith("http")||Ne("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ne(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=_g();$.start(`reading project ${o} from ${n}\u2026`);try{l=await M(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(y){throw $.stop("could not read the source project",1),y instanceof A&&Ne(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Ne(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(o),f=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(at.message(`move project '${o}'
605
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Xt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||T.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(T.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function $l(){for(;;){let t=W(await Q({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=W(await Xt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await jr("YouTrack",()=>et({baseUrl:t,token:e}))){let r=await Ns({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as hg}from"node:fs";function Z(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&Z(`config: '${e}' must be a non-empty string`),t.trim()}function Pr(t,e){if(t==null)return;typeof t!="string"&&Z(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function yg(t){(!t||typeof t!="object")&&Z("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Z("config: 'hubUrl' must start with http(s)://");let n=re(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Z("config: 'project' is required");let i=o,s=re(i.id,"project.id");dt.test(s)||Z("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=re(i.name,"project.name"),c=re(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Z("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Z("config: 'project.repos' must be an array");let u=l.map((y,k)=>{(!y||typeof y!="object")&&Z(`config: project.repos[${k}] must be an object`);let v=y,O=re(v.host,`project.repos[${k}].host`);O!=="github"&&O!=="bitbucket"&&O!=="gitlab"&&Z(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let P={name:re(v.name,`project.repos[${k}].name`),host:O,owner:re(v.owner,`project.repos[${k}].owner`),repoName:re(v.repoName,`project.repos[${k}].repoName`)},x=Pr(v.defaultBranch,`project.repos[${k}].defaultBranch`);x&&(P.defaultBranch=x);let m=Pr(v.mountAs,`project.repos[${k}].mountAs`);return m&&(P.mountAs=m),P}),f=i.contextRepo;(!f||typeof f!="object")&&Z("config: 'project.contextRepo' is required");let p=f,g=Pr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Z("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:re(p.owner,"project.contextRepo.owner"),name:Pr(p.name,"project.contextRepo.name")??Ge(s)},h={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},C=Pr(i.youtrackProjectKey,"project.youtrackProjectKey");C&&(h.project.youtrackProjectKey=C),i.index!==void 0&&(typeof i.index!="boolean"&&Z("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Z("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let $=e.secrets;if($!==void 0){(typeof $!="object"||$===null)&&Z("config: 'secrets' must be an object");let y=$,k={};if(y.github){let v=y.github;k.github={token:re(v.token,"secrets.github.token")}}if(y.bitbucket){let v=y.bitbucket;k.bitbucket={email:re(v.email,"secrets.bitbucket.email"),apiToken:re(v.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let v=y.gitlab;k.gitlab={token:re(v.token,"secrets.gitlab.token")}}if(y.youtrack){let v=y.youtrack;k.youtrack={url:re(v.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(v.token,"secrets.youtrack.token")}}if(y.contextWrite){let v=y.contextWrite;k.contextWrite={token:re(v.token,"secrets.contextWrite.token")}}h.secrets=k}return h}async function wg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function bg(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await ze(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Xe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await Qe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await et({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function vl(t){let e=!t.configPath||t.configPath==="-"?await wg():hg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Z(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=yg(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await bg(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Yt(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??It(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Z(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await tt(o,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await M(o,i,s.id);else if(p instanceof A)Z(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(V(f),Me({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ee(s.id)}`),gt(s.id,_e(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await yn(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as xl,intro as Sl,isCancel as Cl,log as Ho,outro as kg,password as Rl}from"@clack/prompts";async function $g(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Tl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await $g(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Sl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Rl({message:"Claude OAuth token"});Cl(i)&&(xl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ui({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Yr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=he(t.profile);if(!e){Sl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Rl({message:"Claude OAuth token"});Cl(i)&&(xl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},V(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ho.success("Claude OAuth token saved."),kg("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as vg,confirm as xg,intro as Sg,isCancel as Il,log as se,outro as Cg,select as jl,text as st}from"@clack/prompts";function Pl(t){vg(t),process.exit(1)}function er(t){return Il(t)&&Pl("aborted"),t}function Er(t){return Il(t)&&Pl("aborted"),typeof t=="string"?t:""}async function Rg(t,e){let r=er(await jl({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=Er(await st({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Er(await st({message:"Context Repo name",placeholder:Ge(t),initialValue:Ge(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function El(t={profile:void 0}){let e=he(t.profile);Sg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await st({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>dt.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=er(await st({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=er(await jl({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=er(await st({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await xg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Er(await st({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:$=>!$||!$.trim()||we($)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=we(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=Er(await st({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:$=>$.trim().length>0?void 0:"required"})).trim(),h=Er(await st({message:"default branch (optional)",placeholder:"main"})).trim(),C={name:d,host:g.host,owner:g.owner,repoName:g.repoName};h&&(C.defaultBranch=h),a.push(C)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Rg(r,a),u=U(e.projectId);se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Yt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??It(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await tt(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),gt(r,_e(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),Cg("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as Tg,rmSync as Ig}from"node:fs";import{confirm as jg,intro as Pg,isCancel as Eg,log as at,outro as Ag,spinner as _g}from"@clack/prompts";function Ne(t){at.error(t),process.exit(1)}var Al=t=>t.trim().replace(/\/+$/,"");async function _l(t){Pg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??ge()?.spec.projectId??void 0;e||Ne("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=$e(e);r||Ne(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let n=Al(r.hubUrl),o=r.projectId,i=Al(t.hub);i.startsWith("http")||Ne("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??o,c=s===e;c&&a===o&&i===n&&Ne(`profile '${e}' is already on ${n} \u2014 nothing to move.`);let l;{let $=_g();$.start(`reading project ${o} from ${n}\u2026`);try{l=await M(n,r.cliToken,o),$.stop(`read project ${o} (${l.name})`)}catch(y){throw $.stop("could not read the source project",1),y instanceof A&&Ne(`source HUB ${n} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Ne(`project ${o} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(o),f=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(at.message(`move project '${o}'
605
606
  from : ${n} (profile ${e})
606
607
  to : ${i} (profile ${s}, project ${a}, account ${f})
607
608
  \u2022 the source registration on the old HUB is left intact (non-destructive)
608
609
  \u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
609
- `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let $=await jg({message:"Continue?",initialValue:!0});(Eg($)||!$)&&Ne("aborted")}!c&&a===o&&at.warn(`source and destination share the same project id, so they share one secrets file (${Ee(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Zt(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};at.step(`registering project on ${i}\u2026`);let h;try{h=await tt(i,p,d)}catch($){if($ instanceof A&&$.status===409){at.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await M(i,p,a)}catch(y){throw y instanceof A&&Ne(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if($ instanceof A&&$.status===403)Ne(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if($ instanceof A)Ne(`target HUB \u2192 ${$.status} ${$.message}`);else throw $}at.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),Me({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let C={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete C.sandboxPins,V(C),at.success(`profile '${s}' \u2192 ${Ee(a)}`),c){let $=Ce(s);Tg($)&&(Ig($),at.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Ag(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Ko,rmSync as Og,statSync as Ng}from"node:fs";import{join as _n,relative as Ug,resolve as Lg}from"node:path";import{cancel as Dg,intro as Nl,isCancel as Bg,log as z,outro as Ul,text as vt}from"@clack/prompts";import{simpleGit as Ll}from"simple-git";function ue(t){Dg(t),process.exit(1)}function xt(t){return Bg(t)&&ue("aborted"),typeof t=="string"?t:""}async function Ol(t){try{let e=await Ll(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Gg(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Mg(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Gg(r,e)){z.message(`reusing existing ${e} credentials`);return}if(z.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=xt(await vt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=xt(await vt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=xt(await vt({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}V(r),z.success(`saved ${e} credentials`)}async function Dl(t){let e=he(t.profile);Nl(`codepipe repo add \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{n=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){ue(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await Ol(process.cwd());y?(o=process.cwd(),z.message(`using the current directory (${y})`)):o=xt(await vt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:b=>b.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Ko(o)&&Ng(o).isDirectory()){i=Lg(o);let y=await Ol(i);y||ue(`${i} is not a git repository (no origin remote)`);let b=we(y);b||ue(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=b,s=y,z.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=we(o);y||ue(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=o,z.message(`${a}: ${c}/${l}`)}let u=xt(await vt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&ue(`a repo named "${u}" is already registered`);let f=xt(await vt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=Ug(r.root,i);p=y===""?".":y}let g=xt(await vt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;n.some(y=>(y.mountAs??y.name)===g)&&ue(`mount_as "${g}" is already used by another repo`),await Mg(e,a);let d={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let y=r?_n(r.root,g):ve(e.projectId,u);if(Ko(_n(y,".git")))z.message(`already cloned at ${y}`);else{z.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Ll().clone(s,y),z.success(`cloned into ${y}`)}catch(b){ue(`clone failed: ${b instanceof Error?b.message.trim():String(b)}
610
+ `+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${n}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${n}`)),!t.yes){let $=await jg({message:"Continue?",initialValue:!0});(Eg($)||!$)&&Ne("aborted")}!c&&a===o&&at.warn(`source and destination share the same project id, so they share one secrets file (${Ee(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Zt(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};at.step(`registering project on ${i}\u2026`);let h;try{h=await tt(i,p,d)}catch($){if($ instanceof A&&$.status===409){at.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await M(i,p,a)}catch(y){throw y instanceof A&&Ne(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if($ instanceof A&&$.status===403)Ne(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if($ instanceof A)Ne(`target HUB \u2192 ${$.status} ${$.message}`);else throw $}at.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),Me({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let C={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete C.sandboxPins,V(C),at.success(`profile '${s}' \u2192 ${Ee(a)}`),c){let $=Ce(s);Tg($)&&(Ig($),at.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}Ag(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Ko,rmSync as Og,statSync as Ng}from"node:fs";import{join as _n,relative as Ug,resolve as Lg}from"node:path";import{cancel as Dg,intro as Nl,isCancel as Bg,log as z,outro as Ul,text as vt}from"@clack/prompts";import{simpleGit as Ll}from"simple-git";function ue(t){Dg(t),process.exit(1)}function xt(t){return Bg(t)&&ue("aborted"),typeof t=="string"?t:""}async function Ol(t){try{let e=await Ll(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Gg(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Mg(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Gg(r,e)){z.message(`reusing existing ${e} credentials`);return}if(z.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let n=xt(await vt({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),o=xt(await vt({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:n,apiToken:o}}else{let n=xt(await vt({message:`${e} access token (read access to the repo)`,validate:o=>o.trim()?void 0:"required"})).trim();e==="github"?r.github={token:n}:r.gitlab={token:n}}V(r),z.success(`saved ${e} credentials`)}async function Dl(t){let e=he(t.profile);Nl(`codepipe repo add \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{n=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){ue(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let o=t.target?.trim();if(!o){let y=await Ol(process.cwd());y?(o=process.cwd(),z.message(`using the current directory (${y})`)):o=xt(await vt({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:k=>k.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Ko(o)&&Ng(o).isDirectory()){i=Lg(o);let y=await Ol(i);y||ue(`${i} is not a git repository (no origin remote)`);let k=we(y);k||ue(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=k,s=y,z.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=we(o);y||ue(`"${o}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=o,z.message(`${a}: ${c}/${l}`)}let u=xt(await vt({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();n.some(y=>y.name===u)&&ue(`a repo named "${u}" is already registered`);let f=xt(await vt({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=Ug(r.root,i);p=y===""?".":y}let g=xt(await vt({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;n.some(y=>(y.mountAs??y.name)===g)&&ue(`mount_as "${g}" is already used by another repo`),await Mg(e,a);let d={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let y=r?_n(r.root,g):ve(e.projectId,u);if(Ko(_n(y,".git")))z.message(`already cloned at ${y}`);else{z.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Ll().clone(s,y),z.success(`cloned into ${y}`)}catch(k){ue(`clone failed: ${k instanceof Error?k.message.trim():String(k)}
610
611
  check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await xa(e.hubUrl,e.cliToken,e.projectId,d)}catch(y){y instanceof A&&ue(`HUB \u2192 ${y.status} ${y.message}`),ue(y instanceof Error?y.message:String(y))}let{updated:C,errors:$}=fr(e.projectId,h.repos,r?.contextDir);for(let y of C)z.message(`updated ${y}`);for(let y of $)z.warn(`could not update ${y.path}: ${y.error}`);z.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),Ul("done")}async function Bl(t){let e=he(t.profile);Nl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=ge()??void 0,n;try{let c=(await M(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);n=c?c.mountAs??c.name:void 0}catch{}let o;try{o=await Sa(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&ue(`no repo named "${t.name}" in this project`),ue(`HUB \u2192 ${a.status} ${a.message}`)),ue(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=fr(e.projectId,o.repos,r?.contextDir);for(let a of i)z.message(`updated ${a}`);for(let a of s)z.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(n===".")z.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&n?_n(r.root,n):ve(e.projectId,t.name);if(Ko(_n(a,".git")))try{Og(a,{recursive:!0,force:!0}),z.message(`deleted local clone ${a}`)}catch(c){z.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else z.message(`no local clone found to purge (${a})`)}z.success(`removed "${t.name}" \u2014 ${o.repos.length} repo(s) left`),Ul("done")}async function Gl(t){let e=he(t.profile),r;try{r=(await M(e.hubUrl,e.cliToken,e.projectId)).repos}catch(n){console.error(`could not read project from HUB: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let n of r){let o=n.mountAs??n.name,i=n.defaultBranch?` @${n.defaultBranch}`:"";console.log(` ${n.name} ${n.host}:${n.owner}/${n.repoName}${i} \u2192 ${o}`)}}import{spawn as Fg}from"node:child_process";import{existsSync as Ml}from"node:fs";import{homedir as Hg,hostname as Kg}from"node:os";import{join as On}from"node:path";async function Wg(t,e,r){let n=ie(e);if(!n)return!0;if(n.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${Ce(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let o;try{o=await fa(t.hubUrl.replace(/\/$/,""),n.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(o==="unsupported")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(o==="ok")return console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${n.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${Ce(e)} still holds its token.
611
- Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),Ni(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function qg(t,e,r){let n=ie(e)!==null;if(!await Wg(t,e,r))return;console.log(n?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await hn(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await yt({hub:t.hubUrl,token:o,name:r.name??`${Kg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Yg(t,e){let r=ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ae(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=qr(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Vg(t,e){let r=process.cwd(),n=On(r,Pe);if(Hr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ml(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await M(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Fo(r);if(!ki(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await $n({cfg:t,secrets:s,contextDir:n,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=On(Hg(),".codepipe",e?On("profiles",e,"context-config"):"context-config");if(Xr(c.contextDir,l,a),!Ml(On(c.contextDir,"project.yaml"))){At(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};dr(c.contextDir,_e(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Fl(t){let{cfg:e,profile:r}=Wr(t.profile);await Vg(e,r),await qg(e,r,t),Yg(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,d)=>{let h=C=>$=>{for(let y of $.toString("utf-8").split(`
612
+ Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${n.sandboxId} \u2014 replacing the registration`),Ni(t.projectId,n.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${n.sandboxId}`),!0}async function qg(t,e,r){let n=ie(e)!==null;if(!await Wg(t,e,r))return;console.log(n?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await hn(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await yt({hub:t.hubUrl,token:o,name:r.name??`${Kg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...n?{force:!0}:{},...e?{profile:e}:{}})}function Yg(t,e){let r=ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ae(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=qr(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Vg(t,e){let r=process.cwd(),n=On(r,Pe);if(Hr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ml(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await M(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Fo(r);if(!bi(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await $n({cfg:t,secrets:s,contextDir:n,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=On(Hg(),".codepipe",e?On("profiles",e,"context-config"):"context-config");if(Xr(c.contextDir,l,a),!Ml(On(c.contextDir,"project.yaml"))){At(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};dr(c.contextDir,_e(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Fl(t){let{cfg:e,profile:r}=Wr(t.profile);await Vg(e,r),await qg(e,r,t),Yg(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,d)=>{let h=C=>$=>{for(let y of $.toString("utf-8").split(`
612
613
  `))y.length>0&&C.write(`${d} ${y}
613
614
  `)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=Fg(process.execPath,[n,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(h,g),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
614
615
  [up] ${g} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(g);setTimeout(()=>{for(let{name:d,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let f=c.map(({name:g,child:d})=>new Promise(h=>{d.on("exit",(C,$)=>h({name:g,code:C??($?1:0)}))})),p=await Promise.race(f);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(f),process.exit(p.code)}import{existsSync as eu,mkdirSync as Zg,readFileSync as eh,writeFileSync as th}from"node:fs";import{homedir as rh}from"node:os";import{dirname as nh,join as tu}from"node:path";import*as rr from"node:readline";import{existsSync as Yo,readFileSync as Jg,writeFileSync as zg}from"node:fs";import{join as _r}from"node:path";import{simpleGit as qo}from"simple-git";var Hl=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Xg="apply-queue.json";function Kl(t){return _r(t,Xg)}function tr(t){let e=Kl(t);if(!Yo(e))return{};try{return JSON.parse(Jg(e,"utf-8"))}catch{return{}}}function Wl(t,e){zg(Kl(t),JSON.stringify(e,null,2)+`
615
- `)}async function ql(t,e,r,n,o){let i;try{i=await ka(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find($=>$.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=_r(t.root,g.mountAs);if(!Yo(_r(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await qo(d).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:d})}let a=[];for(let p of s){let g=qo(p.dir),d=await Qg(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await Wo(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${Ar(y)}`}}let C=`origin/${h.baseRef}`,$;try{$=await rn(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await Wo(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${Ar(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:C,deliveryCommit:$,startPoint:C})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Hl,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([...Hl,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Wo(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${Ar(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Wl(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
616
+ `)}async function ql(t,e,r,n,o){let i;try{i=await ba(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find($=>$.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=_r(t.root,g.mountAs);if(!Yo(_r(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await qo(d).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:d})}let a=[];for(let p of s){let g=qo(p.dir),d=await Qg(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await Wo(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${Ar(y)}`}}let C=`origin/${h.baseRef}`,$;try{$=await rn(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await Wo(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${Ar(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:C,deliveryCommit:$,startPoint:C})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...Hl,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([...Hl,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Wo(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${Ar(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Wl(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
616
617
  ${f}
617
618
  or: /abort ${r} --reason "..."`}}function Vo(t,e){let r=tr(t);r[e]&&(delete r[e],Wl(t,r))}async function Wo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${Ar(n)} \u2014 check manually`)}}async function Yl(t,e,r){let o=tr(t.contextDir)[e];if(o){for(let i of o.repos){let s=_r(t.root,i.mountAs);if(!Yo(_r(s,".git")))continue;let a=qo(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${Ar(u)} \u2014 check manually`)}}Vo(t.contextDir,e)}}async function Qg(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Ar(t){return t instanceof Error?t.message.trim():String(t)}var Nn=tu(rh(),".codepipe","history"),Vl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],ru=500,Jl=40;async function nu(){let t=ge();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),pr(e),console.log(`connected to ${e.hubUrl} as project ${t.spec.projectId}`),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let r=tr(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
618
619
  \u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
619
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:oh,history:Sh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ds(s=>St(i,s)),i.daemon=bn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>St(i,s),warn:s=>St(i,s)},onEvent:s=>wh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),zo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await ih(i,a)){Zl(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,zo(i),o.prompt()}),o.on("close",()=>{Zl(i)})}function oh(t){let e=Vl.filter(r=>r.startsWith(t));return[e.length?e:Vl,t]}async function ih(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return sh(),!1;case"/status":return await ah(t),!1;case"/tasks":return await ch(t,n),!1;case"/task":return await lh(t,n),!1;case"/sync":return await uh(t),!1;case"/logs":return kh(t,n),!1;case"/monitor":return bh(t),!1;case"/apply":return await zl(t,n,"apply"),!1;case"/unstash":return await zl(t,n,"unstash"),!1;case"/applied":return await ph(t,n),!1;case"/abort":return await dh(t,n),!1;case"/approve":return await Xl(t,n,"approve"),!1;case"/merge":return await Xl(t,n,"merge"),!1;case"/login":return mh(t,n),!1;case"/secret":return gh(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function sh(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
620
- `))}async function ah(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=eu(tu(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function ch(t,e){let r=$h(e,"--phase");try{let n=await ya(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){Nr(n)}}async function lh(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await wa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){Nr(n)}}async function uh(t){let e=await Ir(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function zl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await ql(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function ph(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=tr(t.ws.contextDir)[r],i=vh(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,f;if(l>0?(u=c.slice(0,l),f=c.slice(l+1)):(f=c,u=o?.repos.length===1?fh(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let p=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:u,url:f,number:Number(p[1])})}try{let c=await ba(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Vo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Nr(c)}}async function Xl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await va(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Nr(o)}}async function dh(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=xh(e,"--reason")||"local apply aborted";await Yl(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await $a(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Nr(o)}}function fh(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function mh(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},V(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function gh(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
621
- `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}hh(t.secrets,n,i),V(t.secrets),pr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}yh(t.secrets,n),V(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function hh(t,e,r){switch(e){case"GH_TOKEN":t.github={token:r};break;case"YOUTRACK_URL":t.youtrack={url:r,token:t.youtrack?.token??""};break;case"YOUTRACK_TOKEN":t.youtrack={url:t.youtrack?.url??"",token:r};break;case"BITBUCKET_EMAIL":t.bitbucket={email:r,apiToken:t.bitbucket?.apiToken??""};break;case"BITBUCKET_API_TOKEN":t.bitbucket={email:t.bitbucket?.email??"",apiToken:r};break;default:console.log(`unknown secret key: ${e}`)}}function yh(t,e){e.startsWith("GH")||e==="github"?delete t.github:e.toUpperCase().startsWith("YOUTRACK")||e==="youtrack"?delete t.youtrack:(e.toUpperCase().startsWith("BITBUCKET")||e==="bitbucket")&&delete t.bitbucket}function wh(t,e){switch(e.kind){case"connected":t.connection="connecting",St(t,"[hub] connected");break;case"registered":t.connection="registered",St(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Or(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",St(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Or(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Or(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?St(t,`[hub] action ${e.actionType} done`):Or(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function St(t,e){t.logBuffer.push(e),t.logBuffer.length>ru&&t.logBuffer.shift(),t.follow&&Or(t,e)}function kh(t,e){let r=e[0];if(r==="follow"||r==="on"){Jo(t,!0);return}if(r==="off"){Jo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(ru,Number(r)||Jl)):Jl,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function bh(t){Jo(t,!t.follow)}function Jo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Or(t,e){rr.cursorTo(process.stdout,0),rr.clearLine(process.stdout,0),process.stdout.write(e+`
620
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=rr.createInterface({input:process.stdin,output:process.stdout,completer:oh,history:Sh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ds(s=>St(i,s)),i.daemon=kn({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>St(i,s),warn:s=>St(i,s)},onEvent:s=>wh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),zo(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await ih(i,a)){Zl(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,zo(i),o.prompt()}),o.on("close",()=>{Zl(i)})}function oh(t){let e=Vl.filter(r=>r.startsWith(t));return[e.length?e:Vl,t]}async function ih(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return sh(),!1;case"/status":return await ah(t),!1;case"/tasks":return await ch(t,n),!1;case"/task":return await lh(t,n),!1;case"/sync":return await uh(t),!1;case"/logs":return bh(t,n),!1;case"/monitor":return kh(t),!1;case"/apply":return await zl(t,n,"apply"),!1;case"/unstash":return await zl(t,n,"unstash"),!1;case"/applied":return await ph(t,n),!1;case"/abort":return await dh(t,n),!1;case"/approve":return await Xl(t,n,"approve"),!1;case"/merge":return await Xl(t,n,"merge"),!1;case"/login":return mh(t,n),!1;case"/secret":return gh(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function sh(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
621
+ `))}async function ah(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=eu(tu(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function ch(t,e){let r=$h(e,"--phase");try{let n=await ya(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){Nr(n)}}async function lh(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await wa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){Nr(n)}}async function uh(t){let e=await Ir(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function zl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await ql(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function ph(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=tr(t.ws.contextDir)[r],i=vh(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,f;if(l>0?(u=c.slice(0,l),f=c.slice(l+1)):(f=c,u=o?.repos.length===1?fh(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let p=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:u,url:f,number:Number(p[1])})}try{let c=await ka(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Vo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Nr(c)}}async function Xl(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await va(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){Nr(o)}}async function dh(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=xh(e,"--reason")||"local apply aborted";await Yl(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await $a(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){Nr(o)}}function fh(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function mh(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},V(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function gh(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
622
+ `)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}hh(t.secrets,n,i),V(t.secrets),pr(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}yh(t.secrets,n),V(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function hh(t,e,r){switch(e){case"GH_TOKEN":t.github={token:r};break;case"YOUTRACK_URL":t.youtrack={url:r,token:t.youtrack?.token??""};break;case"YOUTRACK_TOKEN":t.youtrack={url:t.youtrack?.url??"",token:r};break;case"BITBUCKET_EMAIL":t.bitbucket={email:r,apiToken:t.bitbucket?.apiToken??""};break;case"BITBUCKET_API_TOKEN":t.bitbucket={email:t.bitbucket?.email??"",apiToken:r};break;default:console.log(`unknown secret key: ${e}`)}}function yh(t,e){e.startsWith("GH")||e==="github"?delete t.github:e.toUpperCase().startsWith("YOUTRACK")||e==="youtrack"?delete t.youtrack:(e.toUpperCase().startsWith("BITBUCKET")||e==="bitbucket")&&delete t.bitbucket}function wh(t,e){switch(e.kind){case"connected":t.connection="connecting",St(t,"[hub] connected");break;case"registered":t.connection="registered",St(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Or(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",St(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Or(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Or(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?St(t,`[hub] action ${e.actionType} done`):Or(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function St(t,e){t.logBuffer.push(e),t.logBuffer.length>ru&&t.logBuffer.shift(),t.follow&&Or(t,e)}function bh(t,e){let r=e[0];if(r==="follow"||r==="on"){Jo(t,!0);return}if(r==="off"){Jo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(ru,Number(r)||Jl)):Jl,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function kh(t){Jo(t,!t.follow)}function Jo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Or(t,e){rr.cursorTo(process.stdout,0),rr.clearLine(process.stdout,0),process.stdout.write(e+`
622
623
  `),t.unread+=1,zo(t),t.rl.prompt(!0)}function zo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Ql=!1;function Zl(t){Ql||(Ql=!0,Ch(t.rl),t.daemon.stop(),console.log(`
623
624
  bye.`),setTimeout(()=>process.exit(0),150))}function $h(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function vh(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function xh(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Nr(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Sh(){if(!eu(Nn))return[];try{return eh(Nn,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Ch(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{Zg(nh(Nn),{recursive:!0}),th(Nn,r.slice().reverse().join(`
624
625
  `)+`