@code-partner/codepipe 0.1.128-dev.14.g0964444 → 0.1.128-dev.15.gc7ae329
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +88 -88
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,34 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var ae="0.1.128-dev.15.gc7ae329",de="https://hub.dev.codepipe.dev";var fe=2,Ic=1;function lr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Ic&&t<=fe}var $e=".devpipe-context.yaml",fn=[{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",$e]}];function ur(t=1){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
|
|
6
|
-
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function
|
|
5
|
+
`}function mn(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 gn(t,e=fn){let r=[];for(let o of e)if(!(o.version<=t))for(let n of o.addedPaths)r.includes(n)||r.push(n);return r}function hn(t,e=fn){return e.filter(r=>r.version>t)}function pr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var He=/^[a-z][a-z0-9-]{1,30}$/,Pc="-codepipe-ctx";function xe(t){return`${t}${Pc}`}var Dt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function ot(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let o=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return o?o[1]??null:null}var nt="x-bitbucket-api-token-auth";function dr(t){switch(t){case Dt.gitlab:return"oauth2";case Dt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var wn=20;function _(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as qf}from"commander";import{homedir as xn}from"node:os";import{mkdirSync as Bc,readFileSync as Gc,writeFileSync as Mc,existsSync as uo}from"node:fs";import{dirname as Sn,join as gr,resolve as Hc}from"node:path";import{fileURLToPath as Fc}from"node:url";import{existsSync as fr,readFileSync as bn,readdirSync as jc,writeFileSync as Ac}from"node:fs";import{dirname as _c,join as Pe}from"node:path";import{parse as Nc}from"yaml";import{existsSync as yn,renameSync as Ec}from"node:fs";function Fe(t,e,r=o=>console.error(o)){if(yn(e)||!yn(t))return!1;try{return Ec(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}var me=".codepipe",lo=".devpipe";function Oc(t=process.cwd()){let e=t;for(;;){if(fr(Pe(e,me,"project.yaml")))return e;if(fr(Pe(e,lo,"project.yaml")))return Fe(Pe(e,lo),Pe(e,me))&&Uc(e),e;let r=_c(e);if(r===e)return null;e=r}}function Lc(t){let e=Pe(t,me);return fr(e)?e:Pe(t,lo)}function Uc(t){let e=Pe(t,".gitignore");if(!fr(e))return;let r=bn(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
|
|
6
|
+
`);o!==r&&Ac(e,o)}function Ke(t=process.cwd()){let e=Oc(t);if(!e)return null;let r=Lc(e),o=Dc(bn(Pe(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function kn(t,e,r){return jc(t).filter(n=>n!==".DS_Store").length===0?!0:e?r.some(n=>n.host===e.host&&n.owner===e.owner&&n.repoName===e.repoName):!1}function mr(t,e=process.cwd()){try{let r=Ke(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Dc(t){let e=Nc(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){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 p=a.host,m=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:m,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:o,repos:i}}function $n(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 vn=Hc(Sn(Fc(import.meta.url)),"..");function Cn(t){let e=gr(vn,".env");if(uo(e)&&process.loadEnvFile(e),t){let r=gr(vn,"profiles",t,".env");uo(r)&&process.loadEnvFile(r)}}function it(t){let e=_("CONFIG");return e||(t?gr(xn(),".codepipe","profiles",t,"config.json"):gr(xn(),".codepipe","config.json"))}function ve(t){let e=it(t);if(!uo(e))return null;let r=Gc(e,"utf-8");return JSON.parse(r)}function We(t,e){let r=it(e);Bc(Sn(r),{recursive:!0}),Mc(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function hr(t){if(t)return{cfg:Ee(t),profile:t};let e;try{e=Ke()?.spec.projectId||void 0}catch{}if(e){let r=ve(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:Ee(void 0),profile:void 0}}function Ee(t){let e=ve(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 ${it(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Rn}from"node:os";import{join as Tn}from"node:path";function In(){Fe(Tn(Rn(),".devpipe"),Tn(Rn(),".codepipe"))}import{homedir as Pn}from"node:os";import{existsSync as En,mkdirSync as jn,readFileSync as An,writeFileSync as _n}from"node:fs";import{dirname as Nn,join as On}from"node:path";function wr(t,e,r){let o=H(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,Z(o),"pinned")}function qe(t){return On(Pn(),".codepipe","secrets",`${t}.json`)}function H(t){let e=qe(t);return En(e)?JSON.parse(An(e,"utf-8")):null}function Z(t){let e=qe(t.projectId);jn(Nn(e),{recursive:!0}),_n(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function yr(){return On(Pn(),".codepipe","shared.json")}function po(){let t=yr();return En(t)?JSON.parse(An(t,"utf-8")):null}function Ln(t){let e=yr();jn(Nn(e),{recursive:!0}),_n(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function st(t){let e=H(t)?.claude?.oauthToken;return e||po()?.claude?.oauthToken}function Bt(t){let e=(r,o)=>{o&&!process.env[r]&&(process.env[r]=o)};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 at(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Un(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=ve(e);r&&!t.force&&(console.error(`already configured at ${it(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");We({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};Z(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${it(e)}`)}import{homedir as No}from"node:os";import{join as Wt}from"node:path";import{appendFileSync as Kc,existsSync as Dn,mkdirSync as Wc,renameSync as Bn,statSync as qc,unlinkSync as Yc}from"node:fs";import{Writable as Vc}from"node:stream";import{join as zc}from"node:path";var Gn={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},ct=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Wc(e.dir,{recursive:!0}),this.currentPath=zc(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
9
10
|
`)?e:e+`
|
|
10
|
-
`;
|
|
11
|
+
`;Kc(this.currentPath,r,"utf-8")}asWritable(){return new Vc({write:(e,r,o)=>{try{let n=typeof e=="string"?e:e.toString("utf-8");for(let i of n.split(/\r?\n/))i&&this.writeLine(i);o()}catch(n){o(n)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!Dn(this.currentPath)||qc(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Dn(o)&&(r>=this.cfg.maxFiles?Yc(o):Bn(o,`${this.currentPath}.${r+1}`))}Bn(this.currentPath,`${this.currentPath}.1`)}}};function br(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Jc(process.env[`${t}_MAX_BYTES`]??String(Gn.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Gn.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Jc(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),o=(e[2]??"").toLowerCase();return o==="g"?r*1024**3:o==="m"?r*1024**2:o==="k"?r*1024:r}function kr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(o,n)=>(...i)=>{o(...i);try{t.writeLine(Xc(n,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Xc(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Qc(n)).join(" ");return`${r} ${t} ${o}`}function Qc(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Du}from"node:path";import"ws";import{createHash as Zc}from"node:crypto";import{existsSync as el,readFileSync as tl}from"node:fs";import{homedir as rl,hostname as fo}from"node:os";import{join as ol}from"node:path";function Mn(t){return Zc("sha256").update(t).digest("hex").slice(0,12)}function nl(){let t=_("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=ol(rl(),".claude","credentials.json");if(!el(e))return;let r=JSON.parse(tl(e,"utf-8")),o=[r.email,r.account?.email,r.user?.email];for(let n of o)if(typeof n=="string"&&n.includes("@"))return n.trim().toLowerCase()}catch{}}function Hn(t){let e=nl(),r=_("ACCOUNT_ID")?.trim(),o=_("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=st(t);return n?{accountId:`acct-${Mn(n)}`,label:o||fo(),...e?{email:e}:{}}:{accountId:`acct-${Mn(`host:${fo()}`)}`,label:o||fo(),...e?{email:e}:{}}}import{existsSync as il}from"node:fs";import{join as sl}from"node:path";import{simpleGit as al}from"simple-git";async function Fn(t,e){if(!il(sl(t,".git")))return{status:"skipped"};let r=al(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${cl(n)}`}}let o=await r.status();if(!o.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(o.current!==e)return{status:"warn",reason:`on '${o.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function cl(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as mo,readFileSync as Kn,readdirSync as ll,watch as ul}from"node:fs";import{join as go}from"node:path";var $r=class{constructor(e,r,o,n,i=6e4){this.contextDir=e;this.projectId=r;this.send=o;this.log=n;this.intervalMs=i}timer=null;watcher=null;debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(mo(this.contextDir))try{this.watcher=ul(this.contextDir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()})}catch{this.watcher=null}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts()}}readFile(e){let r=go(this.contextDir,e);if(!mo(r))return null;try{return Kn(r,"utf-8")}catch{return null}}readPrompts(){let e=go(this.contextDir,"prompts"),r={};if(!mo(e))return r;let o;try{o=ll(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Kn(go(e,n),"utf-8")}catch{}}return r}};import{existsSync as $l,readFileSync as xl,readdirSync as vl}from"node:fs";import{join as Xn}from"node:path";import{simpleGit as Sl}from"simple-git";import{existsSync as ml,mkdirSync as gl,writeFileSync as Yn}from"node:fs";import{dirname as hl,isAbsolute as wl,join as zn,normalize as ko}from"node:path";import{simpleGit as Jn}from"simple-git";import{existsSync as je,mkdirSync as Wn,readFileSync as ho,writeFileSync as lt}from"node:fs";import{homedir as pl}from"node:os";import{join as ge}from"node:path";import{simpleGit as dl}from"simple-git";var ut=["project.yaml","regimen.yaml"];function Gt(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=ge(t,n);je(s)||(lt(s,i),r.push(n))}return r}function Ye(t,e,r){let o=ge(pl(),".codepipe","profiles",t,"context-config");return Wn(o,{recursive:!0}),lt(ge(o,"project.yaml"),e.projectYaml),lt(ge(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function xr(t,e,r){if(je(e))for(let o of ut){let n=ge(e,o),i=ge(t,o);if(!(!je(n)||je(i)))try{lt(i,ho(n)),r.info(`[config] seeded local ${o} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${o}: ${s instanceof Error?s.message:String(s)}`)}}}var fl=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function pt(t){let e=ge(t,".gitignore"),r=je(e)?ho(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(ut.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
11
12
|
`)?"":`
|
|
12
|
-
`;return lt(e,r+i+
|
|
13
|
+
`;return lt(e,r+i+fl.join(`
|
|
13
14
|
`)+`
|
|
14
|
-
`),!0}async function
|
|
15
|
-
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;
|
|
16
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
17
|
-
`),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=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:o,status:n("Status"),date:n("Date")}}function
|
|
18
|
-
`),a=s.findIndex(
|
|
15
|
+
`),!0}async function qn(t,e){try{if(!je(ge(t,".git")))return;let r=dl(t),o=(await r.raw(["ls-files","--",...ut])).split(`
|
|
16
|
+
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;pt(t),await r.raw(["rm","--cached","--quiet","--",...o]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await bo(t),e.info(`[config] migrated ${o.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 wo(t){let e=new Map;for(let r of ut){let o=ge(t,r);je(o)&&e.set(r,ho(o))}return e}function yo(t,e){Wn(t,{recursive:!0});for(let[r,o]of e){let n=ge(t,r);je(n)||lt(n,o)}}var Vn=3,yl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function vr(t,e,r){if(!ml(zn(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=kl(t,i.path);gl(hl(s),{recursive:!0}),i.encoding==="base64"?Yn(s,Buffer.from(i.content,"base64")):Yn(s,i.content)}let o=Jn(t);await o.add(["-A","--",".",...ut.map(i=>`:(exclude)${i}`)]),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await bo(t))}async function bo(t){let e=Jn(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Vn;o++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let n=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${n}`])}catch{let i=await bl(e);if(i.length>0&&i.every(s=>yl.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 ${Vn} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function bl(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
17
|
+
`).map(r=>r.trim()).filter(Boolean)}function kl(t,e){if(wl(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=ko(zn(t,e)),o=ko(t+"/");if(r!==ko(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Cl=/^(\d{4})-(.+)\.md$/,Rl="0000-template.md";function Tl(t){let e=t.split(`
|
|
18
|
+
`),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=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:o,status:n("Status"),date:n("Date")}}function Il(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
19
|
+
`),a=s.findIndex(S=>S.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),p=[],m="",u=null,d=a>=0?a+1:0;for(let S=d;S<s.length;S++){let v=(s[S]??"").trim();if(v===""){d=S+1;continue}let T=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!T)break;let j=(T[1]??"").trim().toLowerCase(),L=(T[2]??"").trim(),C=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);C&&(u=parseInt(C[1]??"",10)),j==="tasks"&&(m=L),l.has(j)||p.push(v),d=S+1}let g=m?m.includes(o)?m:`${m}, ${o}`:o,w=s.slice(d).join(`
|
|
19
20
|
`).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${g}`,...p,"",w].join(`
|
|
20
21
|
`);return{content:k.endsWith(`
|
|
21
22
|
`)?k:k+`
|
|
22
|
-
`,supersedes:
|
|
23
|
+
`,supersedes:u}}function Pl(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
|
|
23
24
|
|
|
24
|
-
- **Status:** superseded by ADR-${r}`):o}function
|
|
25
|
+
- **Status:** superseded by ADR-${r}`):o}function El(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((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
|
|
25
26
|
`)+`
|
|
26
|
-
`}async function
|
|
27
|
-
`+t.slice(t.length-e)}async function pt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=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(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.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 bo(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{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(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function dt(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{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(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await $l(n);throw n.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):n.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):n.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${n.status} ${n.statusText}${i}`)}async function $l(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ft(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}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 zn(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 o=(await e.json()).scopes??[];return o.length>0&&!o.includes("api")?`GitLab token scopes [${o.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var go=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 o=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(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.links?.html?.href??"",number:n.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(n.status===404)throw new Ye(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.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,o,n){let i=o==="squash"?"squash":o==="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:n})});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,o){if(o&&o.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:o}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let n=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(!n.ok)throw new Error(`bitbucket decline PR #${r}: ${n.status} ${await n.text()}`)}},ho=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=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(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.html_url,number:n.number}}async findOpenPrByBranch(e,r){let o=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(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(n.status===404)throw new Ye(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.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 o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,u=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])u=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(u=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return u?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let u=(await c.json()).workflow_runs??[],p=[];for(let f of u.filter(l=>l.conclusion&&i.includes(l.conclusion))){let l=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!l.ok)continue;let d=(await l.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let k=await w.text();p.push(`### CI job: ${g.name}
|
|
27
|
+
`}async function Qn(t,e,r,o=new Date().toISOString().slice(0,10)){try{await Sl(t).pull(void 0,void 0,["--rebase"])}catch{}let n=Xn(t,"adr"),i=new Map;if($l(n))for(let u of vl(n)){let d=Cl.exec(u);!d||u===Rl||i.set(u,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:xl(Xn(n,u),"utf-8")})}let s=Math.max(0,...[...i.values()].map(u=>u.num))+1,a=new Map,c=[],l=[];for(let u of r){if([...i.entries()].find(([,v])=>v.slug===u.slug&&v.content.includes(e))){l.push(u.slug);continue}let g=s++,w=`${String(g).padStart(4,"0")}-${u.slug}.md`,{content:k,supersedes:S}=Il(u.content,g,u.slug,e,o);if(a.set(w,k),i.set(w,{num:g,slug:u.slug,content:k}),c.push(`adr/${w}`),S!==null){let v=[...i.keys()].find(T=>T.startsWith(`${String(S).padStart(4,"0")}-`));if(v&&v!==w){let T=Pl(a.get(v)??i.get(v).content,g);a.set(v,T),i.set(v,{...i.get(v),content:T})}}}if(c.length===0)return{promoted:c,skipped:l};let p=[...i.entries()].map(([u,d])=>({num:d.num,file:u,header:Tl(d.content)}));a.set("INDEX.md",El(p));let m=[...a.entries()].map(([u,d])=>({path:`adr/${u}`,content:d}));return await vr(t,m,`adr(${e}): promote ${r.map(u=>u.slug).join(", ")}`),{promoted:c,skipped:l}}import{existsSync as Zn,readFileSync as Al}from"node:fs";import{join as ei}from"node:path";function _l(t){let e=ei(t,$e);if(!Zn(e))return 0;try{return mn(Al(e,"utf-8"))}catch{return 0}}function Nl(t,e,r,o=1){let n=e<o,i=n?gn(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Sr(t,e){return Nl(e,_l(t),r=>Zn(ei(t,r)))}import{existsSync as zl,mkdirSync as Jl,mkdtempSync as Xl,rmSync as Ql,writeFileSync as ni}from"node:fs";import{tmpdir as Zl}from"node:os";import{dirname as eu,join as Ro}from"node:path";import{simpleGit as To}from"simple-git";var Ve=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function ti(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
28
|
+
`+t.slice(t.length-e)}async function dt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=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(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.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 Co(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{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(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function ft(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{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(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await Ol(n);throw n.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):n.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):n.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${n.status} ${n.statusText}${i}`)}async function Ol(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function mt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}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 oi(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 o=(await e.json()).scopes??[];return o.length>0&&!o.includes("api")?`GitLab token scopes [${o.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var $o=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 o=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(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.links?.html?.href??"",number:n.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(n.status===404)throw new Ve(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.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,o,n){let i=o==="squash"?"squash":o==="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:n})});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,o){if(o&&o.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:o}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let n=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(!n.ok)throw new Error(`bitbucket decline PR #${r}: ${n.status} ${await n.text()}`)}},xo=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=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(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.html_url,number:n.number}}async findOpenPrByBranch(e,r){let o=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(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(n.status===404)throw new Ve(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.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 o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let p=await i.json();for(let m of p.check_runs??[])l=!0,m.status!=="completed"?a=!0:m.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(m.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],p=[];for(let m of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${n}/actions/runs/${m.id}/jobs?per_page=50`,{headers:o});if(!u.ok)continue;let d=(await u.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let k=await w.text();p.push(`### CI job: ${g.name}
|
|
28
29
|
|
|
29
|
-
${
|
|
30
|
+
${ti(k,8e3)}`)}}return p.length===0?void 0:ti(p.join(`
|
|
30
31
|
|
|
31
|
-
`),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let
|
|
32
|
+
`),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},vo=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!o.ok)throw new Error(`gitlab mr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.web_url??"",number:n.iid}}async findOpenPrByBranch(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let o=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,n=await fetch(o,{method:"GET",headers:this.headers()});if(n.status===404)throw new Ve(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(n.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=Ll(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function Ll(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}var So=class{name="mock";async createPullRequest(e,r){let o=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${o}`,number:o}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){throw new Error(ri(e,r,"merge"))}async closePR(e,r,o){throw new Error(ri(e,r,"close"))}};function ri(t,e,r){let o=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${o}`}function Se(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new xo(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new $o(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new vo(e)}return new So}function gt(t,e,r,o){return[{path:"README.md",content:ql(t,e)},{path:".gitignore",content:Ml()},{path:"CLAUDE.md",content:Fl(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Hl()},{path:"knowledge/README.md",content:Kl()},{path:"knowledge/build.yaml",content:Wl()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Gl()},{path:"adr/README.md",content:Ul()},{path:"adr/0000-template.md",content:Dl()},{path:"adr/INDEX.md",content:Bl()},{path:$e,content:ur()}]}function Ul(){return`# ADR \u2014 architecture decision records
|
|
32
33
|
|
|
33
34
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
34
35
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -56,7 +57,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
56
57
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
57
58
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
58
59
|
open a PR to this repository.
|
|
59
|
-
`}function
|
|
60
|
+
`}function Dl(){return`# ADR-NNNN: <title>
|
|
60
61
|
|
|
61
62
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
62
63
|
- **Date:** YYYY-MM-DD
|
|
@@ -78,12 +79,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
78
79
|
## Alternatives considered
|
|
79
80
|
|
|
80
81
|
- **<alternative>** \u2014 why it was rejected.
|
|
81
|
-
`}function
|
|
82
|
+
`}function Bl(){return`# ADR index
|
|
82
83
|
|
|
83
84
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
84
85
|
|
|
85
86
|
(no accepted ADRs yet)
|
|
86
|
-
`}function
|
|
87
|
+
`}function Gl(){return`# Audit
|
|
87
88
|
|
|
88
89
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
89
90
|
project appends only to its own file \u2014
|
|
@@ -92,14 +93,14 @@ project appends only to its own file \u2014
|
|
|
92
93
|
|
|
93
94
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
94
95
|
shared aggregate here.
|
|
95
|
-
`}function
|
|
96
|
+
`}function he(t,e,r,o){return{projectYaml:Yl(t,r,o),regimenYaml:Vl(t.automationLevel,e)}}function Ml(){return`# codepipe project config is local to each member's workspace
|
|
96
97
|
project.yaml
|
|
97
98
|
regimen.yaml
|
|
98
99
|
|
|
99
100
|
# codepipe runtime
|
|
100
101
|
session.log
|
|
101
102
|
apply-queue.json
|
|
102
|
-
`}function
|
|
103
|
+
`}function Hl(){return`# Index prompt
|
|
103
104
|
|
|
104
105
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
105
106
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -156,7 +157,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
156
157
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
157
158
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
158
159
|
empty or unavailable, say so briefly rather than inventing content.
|
|
159
|
-
`}function
|
|
160
|
+
`}function Fl(t){return`# Project context for the CodePipe agent
|
|
160
161
|
|
|
161
162
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
162
163
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -184,7 +185,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
184
185
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
185
186
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
186
187
|
only after the analysis is approved.
|
|
187
|
-
`}function
|
|
188
|
+
`}function Kl(){return`# Knowledge
|
|
188
189
|
|
|
189
190
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
190
191
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -201,7 +202,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
201
202
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
202
203
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
203
204
|
any merge conflict in it as noise (either side converges on the next run).
|
|
204
|
-
`}function
|
|
205
|
+
`}function Wl(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
205
206
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
206
207
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
207
208
|
#
|
|
@@ -217,7 +218,7 @@ any merge conflict in it as noise (either side converges on the next run).
|
|
|
217
218
|
# - name: test
|
|
218
219
|
# run: npm test
|
|
219
220
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
220
|
-
`}function
|
|
221
|
+
`}function ql(t,e){return`# ${e.name}
|
|
221
222
|
|
|
222
223
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
223
224
|
|
|
@@ -243,7 +244,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
243
244
|
pipeline \u2014 don't edit them by hand.
|
|
244
245
|
|
|
245
246
|
Automation level: **${t.automationLevel}**.
|
|
246
|
-
`}function
|
|
247
|
+
`}function Yl(t,e,r){let o=e?`
|
|
247
248
|
tracker_url: ${e}`:`
|
|
248
249
|
# tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
|
|
249
250
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -301,7 +302,7 @@ branch:
|
|
|
301
302
|
|
|
302
303
|
repos:
|
|
303
304
|
${s}
|
|
304
|
-
`}function
|
|
305
|
+
`}function Vl(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
305
306
|
automation:
|
|
306
307
|
level: ${t}
|
|
307
308
|
|
|
@@ -416,22 +417,21 @@ parallelism:
|
|
|
416
417
|
# # the previous task's branch (auto-merge without reworking the
|
|
417
418
|
# # tail of the chain).
|
|
418
419
|
# mode: parallel
|
|
419
|
-
`}function
|
|
420
|
-
`)}async function
|
|
421
|
-
${
|
|
422
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
423
|
-
${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),k=
|
|
424
|
-
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function lu(t,e,r){return new Promise((o,n)=>{let i=Ee.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 $i(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Co(t,e,r){return new Promise(o=>{let n=Ee.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function uu(t){try{let e=await fetch(t);return e.ok?new $i(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ri(t,e=443,r=vi){let o=`${t}:${e}`,n=ki.get(o);if(n)return n;let i=pu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ki.set(o,i),i}async function pu(t,e,r){if(!xi)return!1;let o=8e3;if(await Co(t,e,o))return!0;let n=await lu(t,e,o),i=Ee.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=cu(n);if(!c)break;let u=await uu(c);if(!u)break;if(s.push(u.toString()),Ee.setDefaultCACertificates([...i,...s]),await Co(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(u.subject===u.issuer)break;n=u}return Co(t,e,o)}function Ve(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function he(t,e,r){Si();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let n=t.baseUrl+e,i={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(n,i)}catch(s){if(Ci(s)&&await Ri(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ti=t=>new Promise(e=>setTimeout(e,t));function du(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fu(){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 Ei(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=fu(),a=null;for(let c=1;c<=n;c++){let u=null;try{u=await he(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(u){if(u.ok)return u;let p=await u.text();if(c<n&&du(u.status,p)){await Ti(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${u.status} ${p}`)}if(c<n){await Ti(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function ht(t){let e;try{e=await he(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}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 ji(t){try{let e=await he(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ii=new Map;async function mu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ii.get(o);if(n)return n;let i=await he(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let a=(await i.json()).customFields.find(u=>u.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(u=>u.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ii.set(o,c.id),c.id}async function Ai(t,e,r){let o=await mu(t,e,r);await Ei(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function _i(t,e,r){return await(await Ei(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Pi=new Map;async function gu(t,e){let r=Pi.get(e);if(r)return r;let o=await he(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Pi.set(e,i.id),i.id}async function Oi(t,e,r,o,n){let i=await gu(t,e),s=await he(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function Ni(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await he(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Ui="attachments(id,name,url,size,mimeType)",hu="links(direction,linkType(name),issues(idReadable))",Li=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ui},${hu}`,wu=`id,text,created,author(login),${Ui}`;function Di(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 Bi(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Gi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),n=`/api/issues?query=${encodeURIComponent(o)}&fields=${Li}&$top=200`,i=await he(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Fi)}async function Mi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Li}`,o=await he(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Fi(await o.json())}async function Hi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${wu}&$top=500`,n=await he(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.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=Di(s.attachments);return c&&(a.attachments=c),a})}function yu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Fi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),n=e.find(c=>c.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),n?.value?.name&&(i.issueType=n.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=Di(t.attachments);s&&(i.attachments=s);let a=yu(t.links);return a&&(i.links=a),i}var vr=new Map;async function Ro(t,e){let o=(vr.get(t)??Promise.resolve()).catch(()=>{}).then(e);vr.set(t,o);try{return await o}finally{vr.get(t)===o&&vr.delete(t)}}async function Ki(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",n="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Dt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ro(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Gt(i,r.name,t.baseDir),{commit:c}=await hi(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 ee({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 F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ro(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Gt(i,r.name,t.baseDir),{commit:c,pushed:u}=await wi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:u})})}case"create_pr":{if(!r)return F("no repo spec");let i=xe(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=xe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=xe(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ro(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Gt(i,r.name,t.baseDir),{mergedSha:c}=await yi(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return ee({stub:!0});case"tracker_status":{let i=Ve();return i?t.trackerIssueId?(await Ai(i,t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Ve();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await _i(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ve();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Oi(i,e.projectKey,e.title,e.body,e.targetStatus);return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ve();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ni(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await si(t.contextDir,e.maxJobs);return ee({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await ui(t.contextDir,e);return ee({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import bu from"ws";function Sr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new bu(r)}var j=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function wt(t,e,r){return ze(t,e,"/projects",r)}async function Wi(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new j(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function qi(t,e,r,o){return ze(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Cr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new j(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Yi(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new j(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Mt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Vi(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 o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new Mt(e)}if(!r.ok)throw new j(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function zi(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new j(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ji(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new j(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function Xi(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new j(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function Qi(t,e,r,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Zi(t,e,r,o,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function es(t,e,r,o,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ts(t,e,r,o,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Rr(t,e,r,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function ae(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new j(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function ze(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new j(n.status,s,a)}return s}function yt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function rs(t,e){let r=H(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await ht({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(i){o.push({name:"youtrack",ok:!1,detail:yt(i)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await pt(r.github.token),o.push({name:"github",ok:!0})}catch(i){o.push({name:"github",ok:!1,detail:yt(i)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await dt(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(i){o.push({name:"bitbucket",ok:!1,detail:yt(i)})}else if(r?.gitlab?.token)try{await ft(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(i){o.push({name:"gitlab",ok:!1,detail:yt(i)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let i=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await bo(i,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:yt(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await bo(i,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:yt(a)})}}let n=st(t);if(!n)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let i=await ku(n);o.push(i==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(i=>i.ok),checks:o,checkedAt:Date.now()}}async function ku(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=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 o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var Tr=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}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 o=[];for(let s of r.prs){let a=xe(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Ye){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 n=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===n)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=xe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let u=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);u&&(a.ciFailureLog=u)}catch(u){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${u instanceof Error?u.message:String(u)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=$u(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function $u(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Ir=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;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 tick(){if(this.running||!this.request)return;let e=Ve();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 o=Date.now(),n;try{let l=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Gi(r,{projectKey:e.projectKey,columns:l,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(l){this.log.warn(`[yt-sync] listIssues failed: ${l instanceof Error?l.message:String(l)}`);return}let i=[],s=new Set;for(let l of n){s.add(l.id);let d=await os(r,l.id,e.sinceMs,this.log);d&&i.push({issueId:l.id,comments:d})}let a=[];for(let l of e.offBoardIssueIds){if(s.has(l))continue;let d=await os(r,l,e.sinceMs,this.log);if(d&&i.push({issueId:l,comments:d}),e.requireAssignee){let g=await vu(r,l,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),u={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(u);let p=i.reduce((l,d)=>l+d.comments.length,0),f=c.reduce((l,d)=>l+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${p} attachments=${f} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let n=[];for(let i of e){let s=[...i.attachments??[]],a=r.find(p=>p.issueId===i.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],u=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let l;try{l=await Bi(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${i.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=xu(p.name);u.has(d)&&(d=`${p.id}-${d}`),u.add(d),c.push({name:d,contentBase64:l.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function xu(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 vu(t,e,r){try{return await Mi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function os(t,e,r,o){try{return await Hi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var To="npm i -g @code-partner/codepipe@latest";function Pr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${se} (protocol ${fe})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Dn(n.contextDir,r);let i=ns("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ns("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,u=!1,p=new Set,f=l();function l(){let d=Sr(t.hubUrl,t.cliToken),g=null,w=new Tr(i,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),k=new Ir(s,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),C=null,v=async()=>{try{let S;try{let y=await ae(t.hubUrl,t.cliToken,t.projectId);S={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await rs(t.projectId,S);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},T=()=>{v(),C=setInterval(()=>void v(),a),typeof C.unref=="function"&&C.unref()},E=()=>{C&&(clearInterval(C),C=null)},U=n?.contextDir?new hr(n.contextDir,t.projectId,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let S=_n(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",m=_("FARM_ID"),y=t.accountEmail??S.email,x={type:"register",projectId:t.projectId,platformVersion:se,protocolVersion:fe,accountId:S.accountId,accountLabel:S.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&m?{farmId:m}:{}};d.send(JSON.stringify(x))}),d.on("message",async S=>{let h=S.toString("utf-8");if(h==="pong"||h==="ping")return;let m;try{m=JSON.parse(h)}catch{return}if(!m||typeof m!="object")return;let y=m.type;if(y==="registered"){let $=m;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),w.start(),U?.start(),T(),n?.contextDir){let N=n.contextDir;try{let A=br(N,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(A)),A.outdated&&(r.warn(`[ctx] context format outdated: v${A.templateVersion} \u2192 v${A.currentVersion}`+(A.missingPaths.length>0?` (missing: ${A.missingPaths.join(", ")})`:"")),u||(u=!0,(async()=>{try{let B;try{B=(await ae(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let oe=await Xn(N,t.projectId,B,r);d.readyState===d.OPEN&&d.send(JSON.stringify(oe))}catch(B){r.warn(`[ctx] context migration failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}})()))}catch(A){r.warn(`[ctx] context-format detect failed (non-fatal): ${A instanceof Error?A.message:String(A)}`)}}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let $=m;g=ar($.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${N}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${se}, protocol ${fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${To}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:To}));return}if(y==="tracking_targets"){w.setTargets(m.targets);return}if(y==="youtrack_sync_request"){k.setRequest(m);return}if(y==="sync_local"){await Cu(m,n,d,r);return}if(y==="context_write"){await Ru(m,n,d,r);return}if(y==="adr_promote"){await Tu(m,n,d,r);return}if(y==="sandbox_keys"){let $=H(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let N=st(t.projectId),A=ni(m,$,N,r);for(let B of A)d.readyState===d.OPEN&&d.send(JSON.stringify(B));return}if(y!=="dispatch_action")return;let x=m;if(g===!1){let $=`refused: HUB protocol incompatible with CLI v${se} (protocol ${fe})`;d.send(JSON.stringify({type:"action_result",actionId:x.actionId,status:"failed",error:$})),r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${To}`),o({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:!1,error:$});return}p.add(x.actionId);try{let $=await Ki({action:x.action,repo:x.repo,trackerIssueId:x.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0}).catch(B=>({status:"failed",error:B instanceof Error?B.message:String(B)}));d.send(JSON.stringify({type:"action_result",actionId:x.actionId,...$}));let N=$.status!=="failed",A=!N&&"error"in $?$.error:void 0;N?r.info(`[exec] ${x.actionId} (${x.action.type}) \u2192 done`):r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 FAILED: ${A??"?"}`),o({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:N,...A?{error:A}:{}})}finally{p.delete(x.actionId)}}),d.on("close",(S,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${m?` reason=${m}`:""}`),w.stop(),k.stop(),U?.stop(),E(),m==="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.`),o({kind:"replaced"});return}o({kind:"disconnected",code:S}),!c&&setTimeout(()=>{f=l()},2e3)}),d.on("error",S=>r.warn(`[ws] error: ${S.message}`)),d}return{stop(){c=!0,f.close()}}}async function Cu(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(u=>u.name===n.repoName),s=Su(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await On(s,a).catch(u=>({status:"warn",reason:u instanceof Error?u.message:String(u)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Ru(t,e,r,o){let n=(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){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await yr(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Tu(t,e,r,o){let n=(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){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Kn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function ns(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as ps,mkdirSync as ds}from"node:fs";import{dirname as fs}from"node:path";import{simpleGit as Je}from"simple-git";import{execFileSync as Iu}from"node:child_process";import{mkdtempSync as Pu,mkdirSync as Eu,readFileSync as is,rmSync as ju,writeFileSync as Au}from"node:fs";import{tmpdir as _u}from"node:os";import{dirname as Ou,join as ss}from"node:path";function as(t="codepipe-context"){let e=Pu(ss(_u(),"codepipe-ssh-")),r=ss(e,"id_ed25519");try{return Iu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:is(r,"utf-8"),publicKey:is(`${r}.pub`,"utf-8").trim()}}finally{ju(e,{recursive:!0,force:!0})}}async function cs(t,e,r,o="codepipe-context"){let n=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:o,key:r,read_only:!1})});if(n.ok)return;let i=await n.text();if(!(n.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${n.status} ${i}`)}function ls(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 us(t,e){Eu(Ou(t),{recursive:!0});let r=e.endsWith(`
|
|
420
|
+
`}function tu(t){return`codepipe/context-migration-v${t}`}function ru(t){let e=hn(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${$e}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
|
|
421
|
+
`)}async function ii(t,e,r,o){let n=To(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Sr(t,e);if(!i.outdated)return i;let s=tu(i.currentVersion),a=r?.branch??(await n.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await n.fetch().catch(()=>{}),(await n.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await ou(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return o.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=Se(c),p=await l.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let m=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:ru(i)});return o.info(`[ctx] migration PR opened: ${m.url}`),{...i,migrationPrUrl:m.url}}catch(l){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function ou(t,e,r,o,n,i,s){let a=To(t),c=Xl(Ro(Zl(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},m=new Map(gt(l,p).map(g=>[g.path,g.content])),u=0;for(let g of o.missingPaths){if(g===$e)continue;let w=m.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=Ro(c,g);zl(k)||(Jl(eu(k),{recursive:!0}),ni(k,w),u++)}ni(Ro(c,$e),ur(o.currentVersion)),u++;let d=To(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Ql(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as nu,createDecipheriv as iu,createHash as su,createPrivateKey as au,createPublicKey as Io,diffieHellman as si,generateKeyPairSync as ai,hkdfSync as ci,randomBytes as cu}from"node:crypto";var li=Buffer.from("devpipe-sealedbox-v1","utf-8");function ui(){let{publicKey:t,privateKey:e}=ai("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ht(t){let e=Buffer.from(t,"base64");return(su("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Cr(t,e){let r=Io({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=ai("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=si({privateKey:n,publicKey:r}),c=Buffer.from(ci("sha256",a,Buffer.concat([i,s]),li,32)),l=cu(12),p=nu("aes-256-gcm",c,l),m=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(m),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:d.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function pi(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 o=au({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=Io({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=Io(o).export({type:"spki",format:"der"}),a=si({privateKey:o,publicKey:n}),c=Buffer.from(ci("sha256",a,Buffer.concat([i,s]),li,32)),l=iu("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 lu(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 o=e??t.claude?.oauthToken;return o&&(r.claudeOauthToken=o),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function di(t,e,r,o){let n=lu(e,r);t.sandboxes.length>0&&!n.claudeOauthToken&&o.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&&!n.contextWrite&&(n.github||n.gitlab||n.bitbucket)&&o.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(n),s=[];for(let a of t.sandboxes){let c=wr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.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"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Cr(a.publicKey,i)}catch(p){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{existsSync as uu,readFileSync as pu,writeFileSync as du}from"node:fs";import{join as fu}from"node:path";import{parseDocument as mu}from"yaml";var fi=64;async function mi(t,e){if(!Number.isInteger(e)||e<1||e>fi)throw new Error(`maxJobs must be an integer in [1, ${fi}], got ${e}`);let r=fu(t,"regimen.yaml");if(!uu(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=mu(pu(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),du(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as gi,readFileSync as hi,writeFileSync as gu}from"node:fs";import{join as Po}from"node:path";import{parseDocument as wi}from"yaml";async function yi(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=Po(t,"project.yaml");if(!gi(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=wi(hi(i,"utf-8"));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),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=Po(t,"regimen.yaml");if(!gi(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=wi(hi(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)gu(Po(t,i.path),i.content);return{files:r.map(i=>i.path)}}var bi=t=>console.log(t);function ki(t){bi=t}function Mt(t,e="info"){bi(t,e)}import{homedir as hu}from"node:os";import{existsSync as wu,mkdirSync as yu}from"node:fs";import{join as Eo}from"node:path";import{simpleGit as $i}from"simple-git";function Ft(t,e,r){let o=r??Eo(hu(),".codepipe","repos");return Eo(o,t,e)}async function Rr(t,e,r={}){let o=Ft(t,e.name,r.baseDir),n=r.cloneUrlOverride??bu(e);if(!wu(Eo(o,".git"))){yu(o,{recursive:!0});let a=$i();Mt(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
|
|
422
|
+
${l.trim()}`)}}let i=$i(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
|
|
423
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Ht(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var xi=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Tr(t,e){let{contextRepoCloneUrl:r,deliveryRef:o,deliverySha:n,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${o}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();n&&a!==n&&Mt(`[git] delivery ${o} resolved ${a.slice(0,10)} (expected ${n.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Ht(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Ht(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([...xi,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function vi(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await Ht(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await Ht(t,n)){let s=(await t.revparse([n])).trim();return await t.raw(["update-ref",o,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",o,i]).catch(()=>{}),i}async function Si(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:m}=r,u=await vi(t,i,()=>Tr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));m&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await Ht(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...xi,"cherry-pick",u])}catch(S){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=S instanceof Error?S.message:String(S);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
424
|
+
${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),k=m?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(k),await t.push([o,"--delete",n]).catch(()=>{}),{commit:w}}async function Ci(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await vi(t,i,()=>Tr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:l}}async function Ri(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function bu(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{X509Certificate as Pi}from"node:crypto";import{readFileSync as ku}from"node:fs";import Ae from"node:tls";var Ei=typeof Ae.getCACertificates=="function"&&typeof Ae.setDefaultCACertificates=="function",Ti=!1,Ii=new Map,ji=t=>console.warn(t);function $u(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Ai(t=ji){if(Ti)return;Ti=!0;let e=_("EXTRA_CA_FILE");if(!(!e||!Ei))try{let r=$u(ku(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ae.setDefaultCACertificates([...Ae.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 _i(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 xu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
425
|
+
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function vu(t,e,r){return new Promise((o,n)=>{let i=Ae.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 Pi(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function jo(t,e,r){return new Promise(o=>{let n=Ae.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function Su(t){try{let e=await fetch(t);return e.ok?new Pi(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ni(t,e=443,r=ji){let o=`${t}:${e}`,n=Ii.get(o);if(n)return n;let i=Cu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ii.set(o,i),i}async function Cu(t,e,r){if(!Ei)return!1;let o=8e3;if(await jo(t,e,o))return!0;let n=await vu(t,e,o),i=Ae.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=xu(n);if(!c)break;let l=await Su(c);if(!l)break;if(s.push(l.toString()),Ae.setDefaultCACertificates([...i,...s]),await jo(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;n=l}return jo(t,e,o)}function ze(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function we(t,e,r){Ai();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let n=t.baseUrl+e,i={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(n,i)}catch(s){if(_i(s)&&await Ni(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Oi=t=>new Promise(e=>setTimeout(e,t));function Ru(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Tu(){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 Di(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Tu(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await we(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(l){if(l.ok)return l;let p=await l.text();if(c<n&&Ru(l.status,p)){await Oi(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<n){await Oi(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function wt(t){let e;try{e=await we(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}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 Bi(t){try{let e=await we(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Li=new Map;async function Iu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Li.get(o);if(n)return n;let i=await we(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let a=(await i.json()).customFields.find(l=>l.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(l=>l.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Li.set(o,c.id),c.id}async function Gi(t,e,r){let o=await Iu(t,e,r);await Di(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Mi(t,e,r){return await(await Di(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ui=new Map;async function Pu(t,e){let r=Ui.get(e);if(r)return r;let o=await we(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Ui.set(e,i.id),i.id}async function Hi(t,e,r,o,n){let i=await Pu(t,e),s=await we(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function Fi(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await we(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Ki="attachments(id,name,url,size,mimeType)",Eu="links(direction,linkType(name),issues(idReadable))",Wi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ki},${Eu}`,ju=`id,text,created,author(login),${Ki}`;function qi(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 Yi(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Vi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),n=`/api/issues?query=${encodeURIComponent(o)}&fields=${Wi}&$top=200`,i=await we(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Xi)}async function zi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Wi}`,o=await we(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Xi(await o.json())}async function Ji(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${ju}&$top=500`,n=await we(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.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=qi(s.attachments);return c&&(a.attachments=c),a})}function Au(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Xi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),n=e.find(c=>c.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),n?.value?.name&&(i.issueType=n.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=qi(t.attachments);s&&(i.attachments=s);let a=Au(t.links);return a&&(i.links=a),i}var Ir=new Map;async function Ao(t,e){let o=(Ir.get(t)??Promise.resolve()).catch(()=>{}).then(e);Ir.set(t,o);try{return await o}finally{Ir.get(t)===o&&Ir.delete(t)}}async function Qi(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",n="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Mt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ao(`${i}/${r.name}`,async()=>{let s=await Rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ft(i,r.name,t.baseDir),{commit:c}=await Si(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 ee({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 F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ao(`${i}/${r.name}`,async()=>{let s=await Rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ft(i,r.name,t.baseDir),{commit:c,pushed:l}=await Ci(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return F("no repo spec");let i=Se(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=Se(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=Se(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ao(`${i}/${r.name}`,async()=>{let s=await Rr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ft(i,r.name,t.baseDir),{mergedSha:c}=await Ri(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return ee({stub:!0});case"tracker_status":{let i=ze();return i?t.trackerIssueId?(await Gi(i,t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=ze();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await Mi(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=ze();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Hi(i,e.projectKey,e.title,e.body,e.targetStatus);return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=ze();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Fi(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await mi(t.contextDir,e.maxJobs);return ee({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await yi(t.contextDir,e);return ee({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import _u from"ws";function Pr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new _u(r)}var E=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function yt(t,e,r){return Je(t,e,"/projects",r)}async function Zi(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new E(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function es(t,e,r,o){return Je(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Er(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new E(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function ts(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new E(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Kt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function rs(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 o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new Kt(e)}if(!r.ok)throw new E(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function os(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new E(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function ns(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new E(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function is(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new E(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function ss(t,e,r,o){return Je(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function as(t,e,r,o,n){return Je(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function cs(t,e,r,o,n){return Je(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ls(t,e,r,o,n){return Je(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function jr(t,e,r,o){return Je(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function te(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new E(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Je(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new E(n.status,s,a)}return s}function bt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function us(t,e){let r=H(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await wt({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(i){o.push({name:"youtrack",ok:!1,detail:bt(i)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await dt(r.github.token),o.push({name:"github",ok:!0})}catch(i){o.push({name:"github",ok:!1,detail:bt(i)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await ft(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(i){o.push({name:"bitbucket",ok:!1,detail:bt(i)})}else if(r?.gitlab?.token)try{await mt(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(i){o.push({name:"gitlab",ok:!1,detail:bt(i)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let i=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await Co(i,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:bt(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await Co(i,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:bt(a)})}}let n=st(t);if(!n)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let i=await Nu(n);o.push(i==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(i=>i.ok),checks:o,checkedAt:Date.now()}}async function Nu(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=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 o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var Ar=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}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 o=[];for(let s of r.prs){let a=Se(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Ve){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 n=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===n)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=Se(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:o}),this.lastSig.set(e,n);let i=Ou(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function Ou(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var _r=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;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 tick(){if(this.running||!this.request)return;let e=ze();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 o=Date.now(),n;try{let u=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Vi(r,{projectKey:e.projectKey,columns:u,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(u){this.log.warn(`[yt-sync] listIssues failed: ${u instanceof Error?u.message:String(u)}`);return}let i=[],s=new Set;for(let u of n){s.add(u.id);let d=await ps(r,u.id,e.sinceMs,this.log);d&&i.push({issueId:u.id,comments:d})}let a=[];for(let u of e.offBoardIssueIds){if(s.has(u))continue;let d=await ps(r,u,e.sinceMs,this.log);if(d&&i.push({issueId:u,comments:d}),e.requireAssignee){let g=await Uu(r,u,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),l={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(l);let p=i.reduce((u,d)=>u+d.comments.length,0),m=c.reduce((u,d)=>u+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${p} attachments=${m} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let n=[];for(let i of e){let s=[...i.attachments??[]],a=r.find(p=>p.issueId===i.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],l=new Set;for(let p of s){let m=`${i.id}:${p.id}`;if(this.shippedAttachments.has(m))continue;let u;try{u=await Yi(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${i.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=Lu(p.name);l.has(d)&&(d=`${p.id}-${d}`),l.add(d),c.push({name:d,contentBase64:u.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(m)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function Lu(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 Uu(t,e,r){try{return await zi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function ps(t,e,r,o){try{return await Ji(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var _o="npm i -g @code-partner/codepipe@latest";function Nr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ae} (protocol ${fe})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&qn(n.contextDir,r);let i=ds("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ds("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,p=new Set,m=u();function u(){let d=Pr(t.hubUrl,t.cliToken),g=null,w=new Ar(i,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),k=new _r(s,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),S=null,v=async()=>{try{let C;try{let y=await te(t.hubUrl,t.cliToken,t.projectId);C={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await us(t.projectId,C);if(d.readyState!==d.OPEN)return;let f={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(f)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},T=()=>{v(),S=setInterval(()=>void v(),a),typeof S.unref=="function"&&S.unref()},j=()=>{S&&(clearInterval(S),S=null)},L=n?.contextDir?new $r(n.contextDir,t.projectId,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let C=Hn(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",f=_("FARM_ID"),y=t.accountEmail??C.email,x={type:"register",projectId:t.projectId,platformVersion:ae,protocolVersion:fe,accountId:C.accountId,accountLabel:C.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&f?{farmId:f}:{}};d.send(JSON.stringify(x))}),d.on("message",async C=>{let h=C.toString("utf-8");if(h==="pong"||h==="ping")return;let f;try{f=JSON.parse(h)}catch{return}if(!f||typeof f!="object")return;let y=f.type;if(y==="registered"){let $=f;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),w.start(),L?.start(),T(),n?.contextDir){let O=n.contextDir;try{let A=Sr(O,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(A)),A.outdated&&(r.warn(`[ctx] context format outdated: v${A.templateVersion} \u2192 v${A.currentVersion}`+(A.missingPaths.length>0?` (missing: ${A.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let B;try{B=(await te(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let ne=await ii(O,t.projectId,B,r);d.readyState===d.OPEN&&d.send(JSON.stringify(ne))}catch(B){r.warn(`[ctx] context migration failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}})()))}catch(A){r.warn(`[ctx] context-format detect failed (non-fatal): ${A instanceof Error?A.message:String(A)}`)}}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let $=f;g=lr($.protocolVersion);let O=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${O}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ae}, protocol ${fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${_o}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:_o}));return}if(y==="tracking_targets"){w.setTargets(f.targets);return}if(y==="youtrack_sync_request"){k.setRequest(f);return}if(y==="sync_local"){await Bu(f,n,d,r);return}if(y==="context_write"){await Gu(f,n,d,r);return}if(y==="adr_promote"){await Mu(f,n,d,r);return}if(y==="sandbox_keys"){let $=H(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let O=st(t.projectId),A=di(f,$,O,r);for(let B of A)d.readyState===d.OPEN&&d.send(JSON.stringify(B));return}if(y!=="dispatch_action")return;let x=f;if(g===!1){let $=`refused: HUB protocol incompatible with CLI v${ae} (protocol ${fe})`;d.send(JSON.stringify({type:"action_result",actionId:x.actionId,status:"failed",error:$})),r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${_o}`),o({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:!1,error:$});return}p.add(x.actionId);try{let $=await Qi({action:x.action,repo:x.repo,trackerIssueId:x.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:L?()=>L.reportNow():void 0}).catch(B=>({status:"failed",error:B instanceof Error?B.message:String(B)}));d.send(JSON.stringify({type:"action_result",actionId:x.actionId,...$}));let O=$.status!=="failed",A=!O&&"error"in $?$.error:void 0;O?r.info(`[exec] ${x.actionId} (${x.action.type}) \u2192 done`):r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 FAILED: ${A??"?"}`),o({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:O,...A?{error:A}:{}})}finally{p.delete(x.actionId)}}),d.on("close",(C,h)=>{let f=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${f?` reason=${f}`:""}`),w.stop(),k.stop(),L?.stop(),j(),f==="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.`),o({kind:"replaced"});return}o({kind:"disconnected",code:C}),!c&&setTimeout(()=>{m=u()},2e3)}),d.on("error",C=>r.warn(`[ws] error: ${C.message}`)),d}return{stop(){c=!0,m.close()}}}async function Bu(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=Du(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await Fn(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Gu(t,e,r,o){let n=(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){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await vr(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Mu(t,e,r,o){let n=(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){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Qn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function ds(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as bs,mkdirSync as ks}from"node:fs";import{dirname as $s}from"node:path";import{simpleGit as kt}from"simple-git";import{execFileSync as Hu}from"node:child_process";import{mkdtempSync as Fu,mkdirSync as Ku,readFileSync as fs,rmSync as Wu,writeFileSync as qu}from"node:fs";import{tmpdir as Yu}from"node:os";import{dirname as Vu,join as ms}from"node:path";function gs(t="codepipe-context"){let e=Fu(ms(Yu(),"codepipe-ssh-")),r=ms(e,"id_ed25519");try{return Hu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:fs(r,"utf-8"),publicKey:fs(`${r}.pub`,"utf-8").trim()}}finally{Wu(e,{recursive:!0,force:!0})}}async function hs(t,e,r,o="codepipe-context"){let n=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:o,key:r,read_only:!1})});if(n.ok)return;let i=await n.text();if(!(n.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${n.status} ${i}`)}function ws(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 ys(t,e){Ku(Vu(t),{recursive:!0});let r=e.endsWith(`
|
|
425
426
|
`)?e:e+`
|
|
426
|
-
`;return
|
|
427
|
-
`)
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
`))
|
|
431
|
-
`)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),k.on("error",S=>{E(),w(S)}),k.on("close",S=>{if(E(),C){w(new Nr);return}if(U.trim()){let m=vs(U.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(S!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,y=typeof i?.subtype=="string"?i.subtype:void 0,x=typeof i?.result=="string"?i.result:void 0;w(new $t(rp(S,i,n.join("")),{code:S,apiErrorStatus:m,subtype:y,resultText:x,retryAfterMs:op(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:sp(i,s,a,c),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&ep(o))}};function vs(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 o=e.subtype??"";return console.log(`[claude] system ${o}`),e}if(r==="assistant"){let o=e.message;for(let n of o?.content??[]){let i=n.type;if(i==="text"){let s=String(n.text??"").trim();s&&console.log(`[claude] text: ${Ne(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=np(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=Cs(n.content);console.log(`[claude] tool_result (error)${i?`: ${Ne(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let o=e.subtype??"",n=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${o} turns=${n} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${Ne(JSON.stringify(e),200)}`),e}function rp(t,e,r){let o=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let n=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;n?o.push(Ne(n,500)):typeof s=="string"&&s!=="success"&&o.push(s),typeof i=="number"&&o.push(`(api_status=${i})`)}return o.length===1&&r.trim()&&o.push(Ne(r.trim().split(`
|
|
427
|
+
`;return qu(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function zu(t,e,r="x-access-token"){let o=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,n=t.match(/^git@([^:]+):(.+)$/);if(n)return`https://${o}@${n[1]}/${n[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${o}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${o}@${s[1]}`:t}function Ju(t,e){return e?.contextWrite?.token?{user:dr(t),secret:e.contextWrite.token}:t===Dt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Dt.bitbucket?e?.bitbucket?.apiToken?{user:nt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Or(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await te(e.hubUrl,e.cliToken,e.projectId)}catch(c){return n.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return n.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Ju(ot(s.cloneUrl),r);if(a){let c=await Xu({ctx:s,contextDir:o,cred:a,log:n});if(c)return c;n.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Qu({ctx:s,contextDir:o,privateKey:r.contextSsh.privateKey,log:n});if(c)return c;n.warn("[ctx] SSH deploy-key clone failed")}return n.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 Xu(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=zu(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=l=>l.split(o.secret).join("***").split(a).join("***");try{if(bs(`${r}/.git`)){let l=kt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=wo(r);await l.reset(["--hard",`origin/${s}`]),yo(r,p),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ks($s(r),{recursive:!0}),await kt().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await xs(r)}catch(l){return n.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Qu(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=ys(i,o),a=ws(e.cloneUrl),c=e.branch;try{if(bs(`${r}/.git`)){let l=kt(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 p=wo(r);await l.reset(["--hard",`origin/${c}`]),yo(r,p),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ks($s(r),{recursive:!0}),await kt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await kt(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await xs(r),{root:r,contextDir:r,repos:[]}}catch(l){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function xs(t){let e=kt(t);await e.raw(["config","user.email"]).then(o=>o.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}function Lr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@github.com:"),n(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Ur(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@gitlab.com:"),n(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Dr(t,e=process.env){if(!t)return!1;let r=`https://${nt}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}async function vs(t={profile:void 0}){let{cfg:e,profile:r}=hr(t.profile),o=H(e.projectId);o&&Bt(o),Lr(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ur(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Dr(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=Wt(No(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=br("CLI_LOG",i,n);if(s.enabled){let u=new ct(s);kr(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=mr(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 u=Wt(No(),".codepipe",r?Wt("profiles",r,"context"):"context");if(a=await Or({cfg:e,secrets:o,contextDir:u,log:{info:d=>console.log(d),warn:d=>console.warn(d)}}),a?.contextDir){let d=Wt(No(),".codepipe",r?Wt("profiles",r,"context-config"):"context-config");xr(a.contextDir,d,{info:g=>console.log(g),warn:g=>console.warn(g)})}}let l=Nr(e,{...a?{workspace:a}:{},onEvent:u=>{u.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))}}),p=!1;function m(u){p||(p=!0,console.log(`
|
|
428
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),await new Promise(()=>{})}import{hostname as ip}from"node:os";import{spawnSync as Zu}from"node:child_process";function ep(){try{return Zu("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Ss(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:ep(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as $t}from"node:os";import{mkdirSync as tp,readFileSync as Cs,writeFileSync as rp,existsSync as Oo}from"node:fs";import{dirname as op,join as _e}from"node:path";Oo(".env")&&process.loadEnvFile(".env");function Ne(t){let e=_("SANDBOX_CONFIG");if(e)return e;let r=_e($t(),".codepipe","worker");return t?_e(r,"profiles",t,"config.json"):_e(r,"config.json")}function Rs(){return _e($t(),".devpipe-sandbox","config.json")}function Br(){Fe(_e($t(),".devpipe"),_e($t(),".codepipe")),_("SANDBOX_CONFIG")||Fe(_e($t(),".devpipe-sandbox"),_e($t(),".codepipe-sandbox"))}function re(t){let e=Ne(t);return Oo(e)?JSON.parse(Cs(e,"utf-8")):!t&&!_("SANDBOX_CONFIG")&&Oo(Rs())?JSON.parse(Cs(Rs(),"utf-8")):null}function Ts(t,e){let r=Ne(e);tp(op(r),{recursive:!0}),rp(r,JSON.stringify(t,null,2)+`
|
|
429
|
+
`,{mode:384})}import np from"ws";var xt=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){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}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 o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){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,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);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 np(e)}};async function Xe(t){Br();let e=re(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Ne(t.profile)}.`),process.exit(1));let r=t.name??ip(),o=Ss({projects:t.projects??[],llm:t.llm??null}),n=new xt(t.hub.replace(/\/$/,"")),i=ui(),s=ht(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Ts({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 ${Ne(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 Wp,readFileSync as aa,readdirSync as qp,writeFileSync as Yp}from"node:fs";import{dirname as Vp,join as zr,resolve as zp}from"node:path";import{spawn as sp}from"node:child_process";import{existsSync as ap}from"node:fs";var vt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Gr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},cp=5e3,qt=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Gr;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 g of e.addDirs??[])r.push("--add-dir",g);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let w=dp(g.rate_limit_info);w&&(!l||w.utilization>l.utilization)&&(l=w);return}if(g.type==="assistant"){let w=g.message;typeof w?.model=="string"&&(c=w.model);let k=w?.usage;k&&(a+=1,s.input+=oe(k.input_tokens),s.output+=oe(k.output_tokens),s.cacheRead+=oe(k.cache_read_input_tokens),s.cacheCreate+=oe(k.cache_creation_input_tokens))}}},m=e.role,u=e.onActivity,d=g=>{if(u)for(let w of mp(g,e.workspaceDir))try{u(w)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${m} job started`}),console.log(`[claude] spawn ${this.binary} role=${m}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let k=sp(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let S=!1,v=null,T=()=>{S=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${m}`),k.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},cp)};e.signal?.addEventListener("abort",T,{once:!0});let j=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",T)},L="";k.stdout.on("data",C=>{o.push(C),L+=C;let h;for(;(h=L.indexOf(`
|
|
430
|
+
`))!==-1;){let f=L.slice(0,h).trim();if(L=L.slice(h+1),f){let y=Is(f);p(y),y&&d(y)}}}),k.stderr.on("data",C=>{o.push(C),n.push(C);for(let h of C.split(`
|
|
431
|
+
`)){let f=h.trim();f&&console.warn(`[claude:stderr] ${f}`)}}),k.on("error",C=>{j(),w(C)}),k.on("close",C=>{if(j(),S){w(new Gr);return}if(L.trim()){let f=Is(L.trim());p(f),f&&d(f)}let h=i?.is_error===!0;if(C!==0||h){let f=typeof i?.api_error_status=="number"?i.api_error_status:void 0,y=typeof i?.subtype=="string"?i.subtype:void 0,x=typeof i?.result=="string"?i.result:void 0;w(new vt(lp(C,i,n.join("")),{code:C,apiErrorStatus:f,subtype:y,resultText:x,retryAfterMs:up(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:fp(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&ap(o))}};function Is(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 o=e.subtype??"";return console.log(`[claude] system ${o}`),e}if(r==="assistant"){let o=e.message;for(let n of o?.content??[]){let i=n.type;if(i==="text"){let s=String(n.text??"").trim();s&&console.log(`[claude] text: ${Oe(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=pp(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=Es(n.content);console.log(`[claude] tool_result (error)${i?`: ${Oe(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let o=e.subtype??"",n=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${o} turns=${n} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${Oe(JSON.stringify(e),200)}`),e}function lp(t,e,r){let o=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let n=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;n?o.push(Oe(n,500)):typeof s=="string"&&s!=="success"&&o.push(s),typeof i=="number"&&o.push(`(api_status=${i})`)}return o.length===1&&r.trim()&&o.push(Oe(r.trim().split(`
|
|
432
432
|
`).slice(-5).join(`
|
|
433
|
-
`),500)),o.join(" \u2014 ")}function
|
|
434
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
433
|
+
`),500)),o.join(" \u2014 ")}function up(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",o=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),n=o?Number(o[1]??o[2]):NaN;return Number.isFinite(n)&&n>0?n*1e3:void 0}function Es(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function pp(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Oe(r,80)}`}return""}function Oe(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function dp(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=oe(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:oe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:o,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(n.surpassedThreshold=e.surpassedThreshold),n}function fp(t,e,r,o){let n=pr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=oe(i.input_tokens),n.outputTokens=oe(i.output_tokens),n.cacheReadInputTokens=oe(i.cache_read_input_tokens),n.cacheCreationInputTokens=oe(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=oe(t?.total_cost_usd),n.numTurns=t&&oe(t.num_turns)>0?oe(t.num_turns):r,n.durationMs=oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Ps=200;function mp(t,e){let r=Date.now(),o=t.type;if(o==="system"){let n=String(t.subtype??"").trim();return n?[{ts:r,kind:"system",text:n}]:[]}if(o==="assistant"){let n=t.message,i=[];for(let s of n?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:Oe(c,Ps)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,m=gp(p,e);i.push({ts:r,kind:"tool",tool:c,...m?{file:m}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Oe(Es(s.content),Ps):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(o==="result"){let n=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...n?{text:n}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function gp(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}import{mkdirSync as hp,writeFileSync as Yt}from"node:fs";import{dirname as wp,join as Vt}from"node:path";function js(t,e,r){let o=Vt(t,e);hp(wp(o),{recursive:!0}),Yt(o,r)}var zt=class{name(){return"mock"}async run(e){let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=yp(o,n,i);Yt(Vt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Yt(Vt(e.workspaceDir,"SOLUTION.md"),bp(o,n,i,a)),s.push("SOLUTION.md"),Yt(Vt(e.workspaceDir,"QUESTIONS.md"),kp(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;js(e.workspaceDir,"changes/sample.patch",$p(o,n,a)),s.push("changes/sample.patch"),js(e.workspaceDir,"diff-summary.md",xp(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Yt(Vt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
|
|
434
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:pr()}}};function yp(t,e,r){return`# ${t} \u2014 Estimate
|
|
435
435
|
|
|
436
436
|
**Title:** ${e}
|
|
437
437
|
|
|
@@ -452,7 +452,7 @@ production-grade estimates.)
|
|
|
452
452
|
${r.split(`
|
|
453
453
|
`).slice(0,8).join(`
|
|
454
454
|
`).trim()||"(empty)"}
|
|
455
|
-
`}function
|
|
455
|
+
`}function bp(t,e,r,o){let n=o?`
|
|
456
456
|
## Reviewer rework instruction
|
|
457
457
|
|
|
458
458
|
> ${o.split(`
|
|
@@ -481,10 +481,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
481
481
|
${r.split(`
|
|
482
482
|
`).slice(0,8).join(`
|
|
483
483
|
`).trim()||"(empty)"}
|
|
484
|
-
`}function
|
|
484
|
+
`}function kp(t){return`# ${t} \u2014 Open questions
|
|
485
485
|
|
|
486
486
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
487
|
-
`}function
|
|
487
|
+
`}function $p(t,e,r){let o=r?` (rework: ${r.split(`
|
|
488
488
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
489
489
|
index 0000000..1111111 100644
|
|
490
490
|
--- a/CHANGELOG.md
|
|
@@ -495,7 +495,7 @@ index 0000000..1111111 100644
|
|
|
495
495
|
+- mock-runner placeholder change for slice 5 testing.
|
|
496
496
|
+
|
|
497
497
|
# Changelog
|
|
498
|
-
`}function
|
|
498
|
+
`}function xp(t,e,r){return`# ${t} \u2014 Diff summary
|
|
499
499
|
|
|
500
500
|
**Title:** ${e}
|
|
501
501
|
${r?`
|
|
@@ -506,78 +506,78 @@ ${r?`
|
|
|
506
506
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
507
507
|
|
|
508
508
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
509
|
-
`}function
|
|
509
|
+
`}function As(t){switch(t){case"mock":return new zt;case"claude-headless":return new qt;default:return null}}function Os(t=process.env){return{maxAttempts:Mr(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Mr(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Mr(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Mr(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var vp=new Set([429,500,502,503,529]),_s=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,Sp=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Cp=new Set(["error_max_turns"]);function Rp(t){if(t instanceof vt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return Sp.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&Cp.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:vp.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:_s.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:o??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return _s.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Ns=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i;function Ls(t){if(t instanceof vt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Ns.test(o)}let e=t instanceof Error?t.message:String(t);return Ns.test(e)}function Tp(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let o=e.baseDelayMs*2**(t-1),n=Math.min(o,e.maxDelayMs);return Math.round(n/2+Math.random()*(n/2))}async function Us(t,e,r){let o=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),n=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=Rp(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=Tp(s,r.policy,c.retryAfterMs);if(Date.now()+p>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await o(p)}}function Mr(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as Ip,rmSync as Pp,writeFileSync as Ds}from"node:fs";import{tmpdir as Ep}from"node:os";import{join as Lo}from"node:path";function Hr(t){return`[url "https://${t}/"]
|
|
510
510
|
insteadOf = git@${t}:
|
|
511
511
|
insteadOf = ssh://git@${t}/
|
|
512
|
-
`}var
|
|
512
|
+
`}var jp=Hr("github.com"),Ap=Hr("bitbucket.org"),_p=Hr("gitlab.com");function Bs(t,e){if(t.length===0)return null;let r=Ip(Lo(Ep(),"devpipe-gitcreds-")),o=Lo(r,"credentials"),n=Lo(r,"gitconfig");return Ds(o,t.join(`
|
|
513
513
|
`)+`
|
|
514
|
-
`,{mode:384}),
|
|
514
|
+
`,{mode:384}),Ds(n,`[credential]
|
|
515
515
|
helper = store --file=${o}
|
|
516
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{
|
|
517
|
-
`).map(
|
|
518
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
519
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
520
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
521
|
-
`+e.subarray(e.length-
|
|
516
|
+
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{Pp(r,{recursive:!0,force:!0})}catch{}}}}function Uo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(jp)),t.bitbucket?.apiToken&&(e.push(`https://${nt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Ap)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(_p)),Bs(e,r)}function Gs(t,e){if(t.contextWrite?.token){let r=ot(e)??"github.com",o=dr(r);return Bs([`https://${o}:${t.contextWrite.token}@${r}`],[Hr(r)])}return Uo(t)}import{spawn as Hs}from"node:child_process";import{existsSync as Fr,mkdirSync as Kr,readFileSync as Np,rmSync as Do,symlinkSync as Op}from"node:fs";import{homedir as Lp}from"node:os";import{dirname as Wr,join as Qe}from"node:path";function Fs(){return Qe(Lp(),".codepipe-sandbox","repos")}function Ms(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 Ks(t,e,r,o,n){if(Fr(Qe(t,".git"))){let i=async s=>{await V(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await V(t,["reset","--hard",`origin/${s}`],n),await V(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!Ms(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Fr(t)&&Do(t,{recursive:!0,force:!0}),Kr(Wr(t),{recursive:!0});try{return await V(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!Ms(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Fr(t)&&Do(t,{recursive:!0,force:!0}),Kr(Wr(t),{recursive:!0}),await V(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function Ws(t){await V(t.workspacePath,["reset","--hard",t.baseSha]),await V(t.workspacePath,["clean","-fdx"])}var qr="CodePipe Agent",Yr="codepipe@codepartner.ee";async function qs(t,e){let r=t.workspacePath;await V(r,["add","-A"]);let o=(await ye(r,["write-tree"])).trim(),n=(await ye(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:qr,GIT_AUTHOR_EMAIL:Yr,GIT_COMMITTER_NAME:qr,GIT_COMMITTER_EMAIL:Yr};return(await ye(r,["commit-tree",o,"-m",e],i)).trim()}async function Ys(t,e,r,o,n){try{await V(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw ot(o)==="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 Vs(t,e){return ye(t.workspacePath,["diff","--binary",t.baseSha,e])}async function zs(t,e,r,o,n){await V(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await V(t.workspacePath,["checkout","--force",r])}async function Bo(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:qr,GIT_AUTHOR_EMAIL:Yr,GIT_COMMITTER_NAME:qr,GIT_COMMITTER_EMAIL:Yr};(await ye(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await V(o,["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 V(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await V(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await ye(o,["diff","--name-only","--diff-filter=U"])).split(`
|
|
517
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await ye(o,["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 V(t,e,r){return new Promise((o,n)=>{let i=Hs("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",n),i.on("close",a=>{if(a===0)return o();n(new Error(`git ${e[0]} failed (exit ${a}):
|
|
518
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function ye(t,e,r){return new Promise((o,n)=>{let i=Hs("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",n),i.on("close",c=>{if(c===0)return o(s.join(""));n(new Error(`git ${e[0]} failed (exit ${c}):
|
|
519
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Js(t,e){Fr(t)&&Do(t,{recursive:!0,force:!0}),Kr(Wr(t),{recursive:!0}),Op(e,t,"dir")}async function Xs(t,e,r){await V(t,["worktree","prune"]).catch(()=>{}),Kr(Wr(r),{recursive:!0}),await V(t,["worktree","add","--detach",r,`origin/${e}`])}async function Qs(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=Qe(Fs(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Ks(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(m){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(m instanceof Error?m.message:String(m)))}let l=(await ye(a,["rev-parse","HEAD"])).trim(),p=Qe(t,"code",s.name);o==="direct"?(Js(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Xs(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:l})}return i}async function Zs(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=Qe(Fs(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Ks(i,r.cloneUrl,r.ref,void 0,n)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=Qe(t,"context");o==="direct"?(Js(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await Xs(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await ye(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function ea(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await V(r,["add","-A",...o]).catch(()=>{});let n;try{n=await ye(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
|
|
520
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Np(Qe(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Up}from"node:fs";import{join as Dp}from"node:path";var Go=8*1024,St=class extends Error{},Jt="meta/build-result.json";function ta(t){let e=Dp(t,Jt),r;try{r=Up(e,"utf-8")}catch{throw new St(`BUILD produced no ${Jt} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new St(`${Jt} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new St(`${Jt} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new St(`${Jt}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let m=p,u=typeof m.name=="string"?m.name:null,d=typeof m.exitCode=="number"?m.exitCode:null;if(u===null||d===null)return[];let g={name:u,exitCode:d};return typeof m.durationMs=="number"&&(g.durationMs=m.durationMs),[g]}),c=typeof n.logTail=="string"?Bp(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let p=a.find(m=>m.exitCode!==0);p&&(l.failedStep=p.name)}return l}function Bp(t){let e=Buffer.from(t,"utf-8");return e.length<=Go?t:`\u2026 [${e.length-Go} bytes elided] \u2026
|
|
521
|
+
`+e.subarray(e.length-Go).toString("utf-8")}import{lstatSync as Gp,mkdtempSync as Mp,readFileSync as Hp,readdirSync as oa,rmSync as ra}from"node:fs";import{tmpdir as Fp}from"node:os";import{join as Vr,relative as Kp}from"node:path";var na=new Set(["code","context"]);function ia(t){let e=Mp(Vr(Fp(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>ra(e,{recursive:!0,force:!0}),listFiles:()=>sa(e,e),readFile:r=>Hp(Vr(e,r),"utf-8"),clean:()=>{for(let r of oa(e))na.has(r)||ra(Vr(e,r),{recursive:!0,force:!0})}}}function sa(t,e){let r=[];for(let o of oa(e)){let n=Vr(e,o),i=Gp(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&na.has(o))continue;r.push(...sa(t,n))}else r.push(Kp(t,n))}return r}var Jr=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Jp=new Set(["implement","resolve-conflict"]);function Xp(t){let e=Buffer.from(t,"utf-8");if(e.length<=Jr)return t;let r=Math.floor(Jr/4),o=Jr-r,n=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-o).toString("utf-8"),s=e.length-r-o;return`${n}
|
|
522
522
|
|
|
523
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
523
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${Jr} bytes for upload] \u2026
|
|
524
524
|
|
|
525
|
-
${i}`}async function
|
|
525
|
+
${i}`}async function Xt(t={}){Br();let e=re(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=br("SANDBOX_LOG","sandbox",zp("./logs"));if(o.enabled){let h=new ct(o);kr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${ae} (protocol ${fe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=As(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Os();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new xt(e.hubUrl,e.token),a=!1,c=new AbortController,l=null,p=null,m=!1,u=null,d=null,g=!1,w=()=>{let h=s.openControlSocket();return u=h,h.on("open",()=>{console.log("[ws] connected");let f={type:"sandbox_hello",platformVersion:ae,protocolVersion:fe};h.send(JSON.stringify(f))}),h.on("message",f=>{let y=f.toString("utf-8"),x=null;try{let $=JSON.parse(y);$&&typeof $=="object"&&(x=$)}catch{}if(x&&x.type==="hello"){let $=x;d=lr($.protocolVersion);let O=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${O}`),d&&(g=!1);return}if(x&&x.type==="pause_job"){let $=typeof x.jobId=="string"?x.jobId:"";$&&$===l?(console.warn(`[ws] pause_job ${$} \u2014 aborting agent`),m=!0,p?.abort()):console.log(`[ws] pause_job ${$} \u2014 not the active job, ignoring`),$&&h.send(JSON.stringify({type:"job_paused",jobId:$}));return}console.log(`[ws] ${y}`)}),h.on("close",(f,y)=>{console.log(`[ws] closed code=${f} reason=${y?.toString()||""}`),u===h&&(u=null),!a&&setTimeout(w,2e3)}),h.on("error",f=>console.warn(`[ws] error: ${f.message}`)),h},k=w(),S=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ae}, protocol ${fe}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await s.claim(c.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 sandbox token rejected. exiting."),a=!0;break}if(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3));continue}let f=await h.json();await v(s,f)}catch(h){if(c.signal.aborted)break;let f=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${f} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3))}}};async function v(h,f){l=f.jobId,p=new AbortController,m=!1;let y=!1,x=null,$=null,O=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),A=async()=>{try{await h.heartbeat(f.jobId)==="claim_lost"&&(y=!0,console.warn(`[job] ${f.jobId} claim lost \u2014 HUB sweeper took it`))}catch(U){let ue=U instanceof Error?U.message:String(U);console.warn(`[job] ${f.jobId} heartbeat error: ${ue}`)}};A();let B=setInterval(()=>{A()},O),ne=new Date().toISOString();console.log(`[job] ${f.jobId} claimed \u2014 role=${f.role} task=${f.taskId} phase=${f.phase}`),console.log(`[job] ${f.jobId} prompt (${f.prompt.length} chars):`),console.log(j(f.prompt," \u2502 "));let pe=[],Be=null,R=400,se=25,Re=500,be=()=>{if(Be&&(clearTimeout(Be),Be=null),pe.length===0)return;let U=pe.splice(0,pe.length),ue=u;if(!ue||ue.readyState!==ue.OPEN)return;let Te={type:"agent_activity",jobId:f.jobId,taskId:f.taskId,projectId:f.projectId,role:f.role,phase:f.phase,events:U};try{ue.send(JSON.stringify(Te))}catch{}},no=U=>{pe.push(U),pe.length>Re&&pe.shift(),pe.length>=se?be():Be||(Be=setTimeout(be,R))},Ge=f.role==="analysis"&&f.taskId.startsWith("draft::")?f.taskId.slice(7):null,q=new Set,io=null;try{if(!n){y||await h.submitResult({jobId:f.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ne,finishedAt:new Date().toISOString()});return}let U=ia(f.jobId);console.log(`[job] ${f.jobId} workspace=${U.dir}`);let ue=T(f,r);x=ue.gitCreds,$=ue.contextGitCreds;let Te=x?.env,sn=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,Ie=[],cr=null,so=null;try{let I="worktree";Ie=await Qs(U.dir,f.projectId,f.projectRepos,I,Te);let P=await Zs(U.dir,f.projectId,f.contextRepo,I,Te);so=P,cr=P?.workspacePath??null}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${f.jobId} materialize failed: ${P}`),y||await h.submitResult({jobId:f.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${P}`},startedAt:ne,finishedAt:new Date().toISOString()}),U.dispose();return}let an=async()=>{if(!f.deliveries||f.deliveries.length===0)return;let I=f.contextRepo?.cloneUrl;if(!I||!Te)throw new Error(I?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let P of f.deliveries){let M=Ie.find(ie=>ie.name===P.name);M&&(await zs(M,P.deliveryRef,P.deliverySha,I,Te),console.log(`[job] ${f.jobId} ${M.name}: checked out delivery ${P.deliverySha.slice(0,10)} for ${f.role}`))}};if(f.role==="build"||f.role==="implement")try{await an()}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${f.jobId} delivery checkout failed: ${P}`),y||await h.submitResult({jobId:f.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${P}`},startedAt:ne,finishedAt:new Date().toISOString()}),U.dispose();return}let cn=f.role==="resolve-conflict"?f.metadata?.taskBranchByRepo??{}:{},ln="";if(f.role==="resolve-conflict")try{let I=[];for(let P of Ie){let M=cn[P.name];if(!M)continue;let ie=await Bo(P,M,Te);console.log(`[job] ${f.jobId} ${P.name}: merged ${M} into ${P.ref} \u2014 ${ie.length} conflicted file(s)`),ie.length>0?I.push(`- **${P.name}**:`,...ie.map(rt=>` - \`${rt}\``)):I.push(`- **${P.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}ln=`
|
|
526
526
|
|
|
527
527
|
## Conflicts to resolve
|
|
528
528
|
|
|
529
529
|
`+(I.length>0?I.join(`
|
|
530
530
|
`):"(no task branches to merge)")+`
|
|
531
|
-
`}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${
|
|
532
|
-
`).map(y=>
|
|
533
|
-
`)}function
|
|
534
|
-
[${h}] shutting down`),c.abort();let m=new AbortController,y=setTimeout(()=>m.abort(),3e3);(async()=>{let x=u;if(x)try{await s.releaseJob(x,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${x}`)}catch($){let N=$ instanceof Error?$.message:String($);console.warn(`[${h}] release failed: ${N} (sweeper will reclaim)`)}clearTimeout(y),k.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>S("SIGINT")),process.on("SIGTERM",()=>S("SIGTERM")),await C()}async function oa(t={profile:void 0}){let e=me(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Sr(e.hubUrl,e.cliToken),o=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 u={type:"register",projectId:e.projectId};r.send(JSON.stringify(u))}),r.on("message",u=>{let p=u.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",u=>s.push(`error:${u.message}`)),r.on("close",(u,p)=>{s.push(`close:${u}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await ae(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 n=te(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as Rt,mkdirSync as Ca,readFileSync as Ra,readdirSync as $d,writeFileSync as Ta}from"node:fs";import{join as Ze,resolve as Ia}from"node:path";import{setTimeout as xd}from"node:timers/promises";import{cancel as vd,confirm as Tt,intro as Pa,isCancel as Ho,log as b,outro as Go,password as It,select as et,spinner as Ea,text as K}from"@clack/prompts";import{simpleGit as Vr}from"simple-git";async function St(t,e,r){return e.host==="github"?qp(t,e,r):e.host==="gitlab"?Zp(t,e,r):td(t,e,r)}async function na(t,e,r={}){let o=r.explain??!0,n=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Le(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await ia(e.githubToken,t):n}:{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 Ue(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await sa(e.gitlabToken,t):n}}return e.bitbucket?(await vt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await aa(e.bitbucket,t):n}:{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 ia(t,e){let r=!1;try{r=(await Le(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 sa(t,e){let r=!1;try{r=(await Ue(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 aa(t,e){let r=!1;try{r=(await vt(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 Wp="https://api.github.com";async function Le(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(Wp+r,n),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 qp(t,e,r){let o=r.githubToken;if(!o)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 n=await Yp(o,e,r),i=await zp(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=mt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Jp(o,n.owner,n.name,a.path,i)||await Xp(o,n.owner,n.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:n.owner,name:n.name,cloneUrl:n.sshUrl,branch:i}}async function Yp(t,e,r){let o=await Le(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await ia(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Vp(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await Le(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 Vp(t,e){let{status:r,data:o}=await Le(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function zp(t,e,r){let{data:o}=await Le(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Jp(t,e,r,o,n){let{status:i,data:s}=await Le(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Xp(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Le(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Qp="https://gitlab.com/api/v4";async function Ue(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(Qp+r,n),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 Zp(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ue(o,"GET",`/projects/${n}`);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 sa(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ue(o,"GET","/user"),l={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 g=await Ue(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.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`);l.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await Ue(o,"POST","/projects",l);if(!d.data)throw new Error("GitLab create project: empty response");i=d.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=mt(t,e,r.youtrackWrites,r.trackerUrl),u=new Set;for(let f=1;;f++){let d=(await Ue(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)u.add(g.path);if(d.length<100)break}let p=c.filter(f=>!u.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Ue(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):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 ed="https://api.bitbucket.org/2.0";async function vt(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(ed+r,n),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 td(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await vt(o,"GET",n);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 aa(o,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 vt(o,"POST",n,{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=mt(t,e,r.youtrackWrites,r.trackerUrl),u=[];for(let f of c)(await vt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&u.push(f);if(u.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of u)f.set(d.path,d.content);if((await vt(o,"POST",`${n}/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 p=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ve(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=rd[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as od}from"node:crypto";import{existsSync as ca,mkdirSync as nd,readFileSync as la,readdirSync as id,rmSync as qr,writeFileSync as sd}from"node:fs";import{homedir as ad}from"node:os";import{dirname as cd,join as Uo}from"node:path";var ld=24*60*60*1e3;function ua(){return Uo(ad(),".codepipe","init-drafts")}function Lo(t){let e=od("sha256").update(t).digest("hex").slice(0,16);return Uo(ua(),`${e}.json`)}function pa(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=ld)}function da(t){let e=Lo(t);if(!ca(e))return null;try{let r=JSON.parse(la(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:pa(r.savedAt)?(qr(e,{force:!0}),null):r}catch{return null}}function Do(t){qr(Lo(t),{force:!0})}function fa(){let t=ua();if(ca(t))for(let e of id(t)){let r=Uo(t,e);try{let o=JSON.parse(la(r,"utf-8"));pa(o.savedAt)&&qr(r,{force:!0})}catch{qr(r,{force:!0})}}}var Ct=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 o=await r();return this.set(e,o),o}clear(){Do(this.cwd)}persist(){let e=Lo(this.cwd);nd(cd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sd(e,JSON.stringify(r,null,2)+`
|
|
535
|
-
`,{mode:384})}};function
|
|
536
|
-
`,{mode:384})}function yd(t){return ha()[t]}function wa(t,e){let r=ha();r[t]=e,wd(r)}function ya(t,e){let r=gt(e),o=yd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Bo()}.`);return r}import{existsSync as ba}from"node:fs";import{join as ka}from"node:path";import{simpleGit as $a}from"simple-git";var bd={info:t=>console.log(t),warn:t=>console.warn(t)};async function Jt(t,e,r={}){let o=r.log??bd,n=[];for(let i of e){let s=ka(t,i.mountAs),a=ws(i);if(!ba(s)){if(r.dryRun){o.info(`would clone ${a} \u2192 ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{o.info(`cloning ${a} \u2192 ${i.mountAs}/`),await $a().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!ba(ka(s,".git"))){o.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=$a(s),u="";try{u=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{u=""}if(!kd(u,a)){o.warn(`${i.mountAs}/ origin (${u||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:u});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function kd(t,e){return xa(t)===xa(e)}function xa(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function va(t={}){let e=Ht();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 Jt(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var Sa=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function G(t){vd(t),process.exit(1)}function ce(t){return Ho(t)&&G("aborted"),t}function D(t){return Ho(t)&&G("aborted"),typeof t=="string"?t:""}async function ja(t={}){Pa("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();fa();let r=da(e),o,n=!1;r&&Object.keys(r.answers).length>0?ce(await Tt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(b.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new Ct(e,r),n=!0):(Do(e),o=new Ct(e)):o=new Ct(e);let i=t.force===!0?null:await Cd(e),s=await o.ask("target",async()=>ce(await et({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?b.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)`):n&&o.get("contextRepo")!==void 0||_a(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:de,initialValue:_("HUB_URL")??de,validate:R=>R.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),u=await o.ask("email",()=>Oa()),p=await o.ask("cliToken",()=>zr(c,u)),f=null;s==="farm"&&(f=await Sd(c,p));let l=a?Td(a.parsed.repoName):"",d=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:l||"acme",...l?{initialValue:l}:{},validate:R=>He.test(R.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),w=await o.ask("automationLevel",async()=>ce(await et({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"}))),k=await o.ask("youtrack",()=>Ma()),C=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:R=>R.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ce(await Tt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},E=()=>o.set("tokens",T),U=await o.ask("repos",()=>Ed(T,u,a,{onCred:E,initial:o.get("reposPartial")??[],onProgress:R=>o.set("reposPartial",R)}));o.delete("reposPartial");let S=await jd(await o.ask("contextRepo",()=>Da(d,U,T,u)),d,U,T,u,E,R=>o.set("contextRepo",R)),{spec:h,mode:m}=S;b.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let y=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),x=await o.ask("claudeToken",()=>Dd(s==="farm")),$={projectId:d,name:g,automationLevel:w,repos:U,youtrackProjectKey:C,ownerEmail:u};b.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let N;try{N=await St($,h,{...Ba(T),youtrackWrites:v,trackerUrl:k.url,mode:m,log:{info:R=>b.message(R),warn:R=>b.warn(R)}})}catch(R){G(`Context Repo provisioning failed: ${R instanceof Error?R.message:String(R)}`)}$.contextRepo=N,b.success(`Context Repo ready: ${N.owner}/${N.name}@${N.branch}`),b.step(`registering project on ${c}\u2026`);let A;try{A=await wt(c,p,$)}catch(R){if(R instanceof j&&R.status===409){b.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{A=await ae(c,p,d)}catch(ie){throw ie instanceof j&&G(`HUB \u2192 ${ie.status} ${ie.message}`),ie}}else if(R instanceof j&&R.status===401)o.delete("cliToken"),G("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(R instanceof j)G(`HUB \u2192 ${R.status} ${R.message}`);else throw R}let B=A.contextRepo??N;b.success(`project ${A.projectId} ready (${A.provisioningStatus})`);let oe=await Ud(B),pe={url:k.url,token:k.token};if(s==="farm"){let R=f,ie={...T,...oe?{contextWrite:oe}:{},...x?{claude:{oauthToken:x}}:{},youtrack:pe},Se=T.github?.token;if(B.host==="github"&&Se)try{let q=as(`devpipe-${d}`);await cs(B,Se,q.publicKey,`devpipe-${d}`),ie.contextSsh={privateKey:q.privateKey},b.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(q){b.warn(`could not set up Context Repo SSH deploy key (${q instanceof Error?q.message:String(q)}); the farm will fall back to the token path.`)}let ye={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:ie,contextRepo:B,projectConfig:Pe($,v,k.url,y||void 0)},Qr=kr(R.farm.publicKey,JSON.stringify(ye));b.step(`handing project ${d} to farm ${R.farm.name}\u2026`);let Ge;try{Ge=await qi(c,p,R.farm.farmId,{projectId:d,sealedBundle:Qr})}catch(q){throw q instanceof j&&G(q.status===409?`farm ${R.farm.name} is offline \u2014 start it and re-run.`:q.status===504?`farm ${R.farm.name} did not respond in time.`:`HUB \u2192 ${q.status} ${q.message}`),q}Ge.ok||G(`farm rejected provisioning: ${Ge.error??"unknown error"}`),await Mo(c,p,d,B,Se),o.clear(),Go(`done. project ${d} is now hosted on farm ${R.farm.name} (daemon ${Ge.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Ga(T),await Na(e,B.cloneUrl,B.branch),La(e),a&&await Pd(e);{let R=Ze(e,Ae);wr(R);let ie=Pe($,v,k.url,y||void 0),Se=lo(R,ie);Se.length>0&&b.success(`local project config \u2192 .codepipe/{${Se.join(", ")}}`),qe(d,ie,{info:ye=>b.message(ye),warn:ye=>b.warn(ye)})}await Ua(e,A.repos);let Be={hubUrl:c,cliToken:p,projectId:d,...T,...oe?{contextWrite:oe}:{},...x?{claude:{oauthToken:x}}:{},youtrack:pe};Z(Be),Fe({hubUrl:c,cliToken:p,projectId:d,accountEmail:u},d),b.success(`secrets \u2192 ${We(d)}`),await Mo(c,p,d,B,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Go(`done. next: \`codepipe\` (interactive) or \`codepipe --profile ${d} daemon\`.`)}async function Mo(t,e,r,o,n){let i=await ga(o,n),s=ma(i),a=await et({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Ho(a)||a!==s.proceedValue))try{let{jobId:c}=await Rr(t,e,r,{reindex:s.reindex});b.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){b.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Sd(t,e){let r;try{r=await Wi(t,e)}catch(c){throw c instanceof j&&G(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&G("no farms registered on this HUB. Register one first: on the farm host run `codepipe-farm register --hub <url> --token <HUB_FARM_REG_TOKEN>` and `codepipe-farm start`.");let n=ce(await et({message:"target farm",options:o.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=o.find(c=>c.farmId===n),s;try{s=ya(i.farmId,i.publicKey)}catch(c){G(c instanceof Error?c.message:String(c))}return ce(await Tt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
531
|
+
`}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${f.jobId} conflict merge failed: ${P}`),y||await h.submitResult({jobId:f.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${P}`},startedAt:ne,finishedAt:new Date().toISOString()}),U.dispose();return}let Cc=L(f.prompt,Ie,cr)+ln,ao=[...Ie.map(I=>I.workspacePath),...cr?[cr]:[]];ao.length>0&&console.log(`[job] ${f.jobId} --add-dir: ${ao.join(", ")}`),Ge&&(io=setInterval(()=>{let P=u;if(!P||P.readyState!==P.OPEN)return;let M;try{M=qp(zr(U.dir,"drafts")).filter(ie=>ie.endsWith(".json")).sort()}catch{return}for(let ie of M){if(q.has(ie))continue;if(q.size>=wn)break;let rt;try{let Q=JSON.parse(aa(zr(U.dir,"drafts",ie),"utf-8")),N=typeof Q.localRef=="string"?Q.localRef:"",Y=typeof Q.title=="string"?Q.title:"",Me=typeof Q.body=="string"?Q.body:"";if(!N||!Y)continue;rt={localRef:N,title:Y,body:Me,...Q.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Q.links)?{links:Q.links}:{}}}catch{continue}q.add(ie);let Lt={type:"child_draft",jobId:f.jobId,projectId:f.projectId,draftId:Ge,child:rt};try{P.send(JSON.stringify(Lt))}catch{}}},1500));try{let I=await Us(n,{workspaceDir:U.dir,role:f.role,prompt:Cc,addDirs:ao,metadata:f.metadata??{},...f.model?{model:f.model}:{},...sn?{env:sn}:{},signal:p.signal,onActivity:no},{jobId:f.jobId,policy:i,onBeforeRetry:async()=>{U.clean();for(let N of Ie)try{await Ws(N);let Y=cn[N.name];f.role==="resolve-conflict"&&Y&&await Bo(N,Y,Te)}catch(Y){let Me=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${f.jobId} worktree reset failed (${N.name}): ${Me}`)}try{await an()}catch(N){let Y=N instanceof Error?N.message:String(N);console.warn(`[job] ${f.jobId} delivery re-checkout failed: ${Y}`)}},aborted:()=>y||m}),P=[];if(Jp.has(f.role)&&Ie.length>0){let N=f.metadata??{},Y=typeof N.commitMessage=="string"?N.commitMessage:`${f.taskId}: changes`,Me=f.contextRepo?.cloneUrl,un=$?.env;if(!Me||!un)throw new Error("delivery requested but "+(Me?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Rc=f.taskId.includes(":")?f.taskId.slice(f.taskId.indexOf(":")+1):f.taskId;for(let ke of Ie){let Ut=await qs(ke,Y);if(!Ut){console.log(`[job] ${f.jobId} ${ke.name}: no changes \u2014 no delivery`);continue}let co=`codepipe/deliveries/${Rc}/${f.jobId}/${ke.name}`;await Ys(ke,Ut,co,Me,un),P.push({name:ke.name,deliveryRef:co,deliverySha:Ut,baseSha:ke.baseSha}),console.log(`[job] ${f.jobId} ${ke.name}: delivered ${Ut.slice(0,10)} \u2192 ${co}`);let pn=await Vs(ke,Ut);if(pn.trim().length>0){let Tc=zr("display",`${ke.name}.diff`),dn=zr(U.dir,Tc);Wp(Vp(dn),{recursive:!0}),Yp(dn,pn)}}}if(f.role==="resolve-conflict"&&P.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 M;f.role==="build"&&(M=ta(U.dir),console.log(`[job] ${f.jobId} build verdict: ok=${M.ok}`+(M.failedStep?` failedStep=${M.failedStep}`:"")));let ie=I.artifactPaths.length>0?I.artifactPaths:U.listFiles(),rt=Array.from(new Set(ie)),Lt;if(so)try{let N=await ea(so,f.role==="index"?["adr/SOURCES.md"]:[]);N.length>0&&(Lt=N,console.log(`[job] ${f.jobId} captured ${N.length} knowledge file(s) for Context Repo`))}catch(N){let Y=N instanceof Error?N.message:String(N);console.warn(`[job] ${f.jobId} knowledge capture failed (non-fatal): ${Y}`)}let Q={jobId:f.jobId,status:"succeeded",artifacts:rt.map(N=>({path:N,contentBase64:aa(`${U.dir}/${N}`).toString("base64")})),...Lt?{contextWrites:Lt}:{},...P.length>0?{deliveries:P}:{},log:Xp(I.log),startedAt:ne,finishedAt:new Date().toISOString(),usage:I.usage,...I.rateLimit?{rateLimit:I.rateLimit}:{},...M?{build:M}:{}};if(y||m)console.warn(`[job] ${f.jobId} skipping result upload \u2014 ${m?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(Q),console.log(`[job] ${f.jobId} done \u2014 uploaded ${Q.artifacts.length} artifact(s):`);for(let N of Q.artifacts){let Y=Buffer.from(N.contentBase64,"base64").length;console.log(` \xB7 ${N.path} (${Y} bytes)`)}Q.artifacts.length===0&&console.warn(`[job] ${f.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(I){let P=I instanceof Error?I.message:String(I);if(m)console.log(`[job] ${f.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(y)console.warn(`[job] ${f.jobId} failed after claim lost (${P}) \u2014 skipping result upload`);else{let M=Ls(I);console.warn(M?`[job] ${f.jobId} failed: ${P} (Claude auth \u2014 token invalid/expired)`:`[job] ${f.jobId} failed: ${P}`),await h.submitResult({jobId:f.jobId,status:"failed",artifacts:[],error:{message:P},startedAt:ne,finishedAt:new Date().toISOString(),...M?{authError:!0}:{}})}}finally{U.dispose()}}finally{clearInterval(B),io&&clearInterval(io),be(),l=null,p=null,x?.cleanup(),$?.cleanup()}}function T(h,f){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!f)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let y;try{y=JSON.parse(pi(f,h.credBundle).toString("utf-8"))}catch(A){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${A instanceof Error?A.message:String(A)}`),{gitCreds:null,contextGitCreds:null}}let x=Uo(y);x&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let $=Gs(y,h.contextRepo.cloneUrl),O={gitCreds:x,contextGitCreds:$};return y.claudeOauthToken&&(O.claudeOauthToken=y.claudeOauthToken),O}function j(h,f){return h.split(`
|
|
532
|
+
`).map(y=>f+y).join(`
|
|
533
|
+
`)}function L(h,f,y){let x=f[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,x).replace(/\{\{codeRoot\}\}/g,x?x.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,y??"")}let C=h=>{if(a)return;a=!0,console.log(`
|
|
534
|
+
[${h}] shutting down`),c.abort();let f=new AbortController,y=setTimeout(()=>f.abort(),3e3);(async()=>{let x=l;if(x)try{await s.releaseJob(x,`sandbox ${h}`,f.signal),console.log(`[${h}] released job ${x}`)}catch($){let O=$ instanceof Error?$.message:String($);console.warn(`[${h}] release failed: ${O} (sweeper will reclaim)`)}clearTimeout(y),k.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>C("SIGINT")),process.on("SIGTERM",()=>C("SIGTERM")),await S()}async function ca(t={profile:void 0}){let e=Ee(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Pr(e.hubUrl,e.cliToken),o=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 p=l.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let m=JSON.parse(p);m.type==="registered"?(a=!!m.ok,clearTimeout(c),r.send("ping")):m.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await te(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 n=re(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as It,mkdirSync as Ea,readFileSync as ja,readdirSync as Id,writeFileSync as Aa}from"node:fs";import{join as Ze,resolve as _a}from"node:path";import{setTimeout as Pd}from"node:timers/promises";import{cancel as Ed,confirm as Pt,intro as Na,isCancel as Yo,log as b,outro as Wo,password as Et,select as et,spinner as Oa,text as K}from"@clack/prompts";import{simpleGit as Zr}from"simple-git";async function Rt(t,e,r){return e.host==="github"?Zp(t,e,r):e.host==="gitlab"?sd(t,e,r):cd(t,e,r)}async function la(t,e,r={}){let o=r.explain??!0,n=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Ue(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await ua(e.githubToken,t):n}:{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 Le(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await pa(e.gitlabToken,t):n}}return e.bitbucket?(await Ct(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await da(e.bitbucket,t):n}:{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 ua(t,e){let r=!1;try{r=(await Ue(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 pa(t,e){let r=!1;try{r=(await Le(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 da(t,e){let r=!1;try{r=(await Ct(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 Qp="https://api.github.com";async function Ue(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(Qp+r,n),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 Zp(t,e,r){let o=r.githubToken;if(!o)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 n=await ed(o,e,r),i=await rd(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=gt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await od(o,n.owner,n.name,a.path,i)||await nd(o,n.owner,n.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:n.owner,name:n.name,cloneUrl:n.sshUrl,branch:i}}async function ed(t,e,r){let o=await Ue(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await ua(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await td(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await Ue(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 td(t,e){let{status:r,data:o}=await Ue(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function rd(t,e,r){let{data:o}=await Ue(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function od(t,e,r,o,n){let{status:i,data:s}=await Ue(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function nd(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Ue(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var id="https://gitlab.com/api/v4";async function Le(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(id+r,n),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 sd(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Le(o,"GET",`/projects/${n}`);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 pa(o,e)} (attach joins an existing Context Repo and never creates one)`);let m=await Le(o,"GET","/user"),u={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(m.data?.username!==e.owner){let g=await Le(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.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`);u.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await Le(o,"POST","/projects",u);if(!d.data)throw new Error("GitLab create project: empty response");i=d.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=gt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let m=1;;m++){let d=(await Le(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${m}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)l.add(g.path);if(d.length<100)break}let p=c.filter(m=>!l.has(m.path)).map(m=>({action:"create",file_path:m.path,content:m.content}));return p.length>0?await Le(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):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 ad="https://api.bitbucket.org/2.0";async function Ct(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(ad+r,n),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 cd(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await Ct(o,"GET",n);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 da(o,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let m=await Ct(o,"POST",n,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(m.status===404||!m.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=m.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=gt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let m of c)(await Ct(o,"GET",`${n}/src/${encodeURIComponent(a)}/${m.path}?format=meta`)).status===404&&l.push(m);if(l.length>0){let m=new URLSearchParams;m.set("message","chore(codepipe): scaffold context repo files"),m.set("branch",a);for(let d of l)m.set(d.path,d.content);if((await Ct(o,"POST",`${n}/src`,{form:m})).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 p=i.links?.clone?.find(m=>m.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var ld={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Ce(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=ld[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as ud}from"node:crypto";import{existsSync as fa,mkdirSync as pd,readFileSync as ma,readdirSync as dd,rmSync as Xr,writeFileSync as fd}from"node:fs";import{homedir as md}from"node:os";import{dirname as gd,join as Mo}from"node:path";var hd=24*60*60*1e3;function ga(){return Mo(md(),".codepipe","init-drafts")}function Ho(t){let e=ud("sha256").update(t).digest("hex").slice(0,16);return Mo(ga(),`${e}.json`)}function ha(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=hd)}function wa(t){let e=Ho(t);if(!fa(e))return null;try{let r=JSON.parse(ma(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:ha(r.savedAt)?(Xr(e,{force:!0}),null):r}catch{return null}}function Fo(t){Xr(Ho(t),{force:!0})}function ya(){let t=ga();if(fa(t))for(let e of dd(t)){let r=Mo(t,e);try{let o=JSON.parse(ma(r,"utf-8"));ha(o.savedAt)&&Xr(r,{force:!0})}catch{Xr(r,{force:!0})}}}var Tt=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 o=await r();return this.set(e,o),o}clear(){Fo(this.cwd)}persist(){let e=Ho(this.cwd);pd(gd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};fd(e,JSON.stringify(r,null,2)+`
|
|
535
|
+
`,{mode:384})}};function ba(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 ka(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{homedir as wd}from"node:os";import{existsSync as yd,mkdirSync as bd,readFileSync as kd,writeFileSync as $d}from"node:fs";import{dirname as xd,join as vd}from"node:path";function Ko(){return _("FARM_PINS")??vd(wd(),".codepipe","farm-pins.json")}function $a(){let t=Ko();if(!yd(t))return{};try{return JSON.parse(kd(t,"utf-8"))}catch{return{}}}function Sd(t){let e=Ko();bd(xd(e),{recursive:!0}),$d(e,JSON.stringify(t,null,2)+`
|
|
536
|
+
`,{mode:384})}function Cd(t){return $a()[t]}function xa(t,e){let r=$a();r[t]=e,Sd(r)}function va(t,e){let r=ht(e),o=Cd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Ko()}.`);return r}import{existsSync as Sa}from"node:fs";import{join as Ca}from"node:path";import{simpleGit as Ra}from"simple-git";var Rd={info:t=>console.log(t),warn:t=>console.warn(t)};async function Qt(t,e,r={}){let o=r.log??Rd,n=[];for(let i of e){let s=Ca(t,i.mountAs),a=$n(i);if(!Sa(s)){if(r.dryRun){o.info(`would clone ${a} \u2192 ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{o.info(`cloning ${a} \u2192 ${i.mountAs}/`),await Ra().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let m=p instanceof Error?p.message:String(p);o.warn(`clone failed for ${i.mountAs}: ${m}`),n.push({mountAs:i.mountAs,status:"error",detail:m})}continue}if(!Sa(Ca(s,".git"))){o.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=Ra(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Td(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(p){let m=p instanceof Error?p.message:String(p);o.warn(`fetch failed for ${i.mountAs}: ${m}`),n.push({mountAs:i.mountAs,status:"error",detail:m})}}return n}function Td(t,e){return Ta(t)===Ta(e)}function Ta(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Ia(t={}){let e=Ke();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 Qt(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var Pa=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function G(t){Ed(t),process.exit(1)}function ce(t){return Yo(t)&&G("aborted"),t}function D(t){return Yo(t)&&G("aborted"),typeof t=="string"?t:""}async function La(t={}){Na("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();ya();let r=wa(e),o,n=!1;r&&Object.keys(r.answers).length>0?ce(await Pt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(b.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new Tt(e,r),n=!0):(Fo(e),o=new Tt(e)):o=new Tt(e);let i=t.force===!0?null:await Vo(e),s=await o.ask("target",async()=>ce(await et({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?b.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)`):n&&o.get("contextRepo")!==void 0||Da(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:de,initialValue:_("HUB_URL")??de,validate:R=>R.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>Ba()),p=await o.ask("cliToken",()=>eo(c,l)),m=null;s==="farm"&&(m=await jd(c,p));let u=a?_d(a.parsed.repoName):"",d=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:u||"acme",...u?{initialValue:u}:{},validate:R=>He.test(R.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),w=await o.ask("automationLevel",async()=>ce(await et({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"}))),k=await o.ask("youtrack",()=>qa()),S=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:R=>R.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ce(await Pt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},j=()=>o.set("tokens",T),L=await o.ask("repos",()=>Ld(T,l,a,{onCred:j,initial:o.get("reposPartial")??[],onProgress:R=>o.set("reposPartial",R)}));o.delete("reposPartial");let C=await Ud(await o.ask("contextRepo",()=>Fa(d,L,T,l)),d,L,T,l,j,R=>o.set("contextRepo",R)),{spec:h,mode:f}=C;b.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let y=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),x=await o.ask("claudeToken",()=>Kd(s==="farm")),$={projectId:d,name:g,automationLevel:w,repos:L,youtrackProjectKey:S,ownerEmail:l};b.step(`${f==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let O;try{O=await Rt($,h,{...Ka(T),youtrackWrites:v,trackerUrl:k.url,mode:f,log:{info:R=>b.message(R),warn:R=>b.warn(R)}})}catch(R){G(`Context Repo provisioning failed: ${R instanceof Error?R.message:String(R)}`)}$.contextRepo=O,b.success(`Context Repo ready: ${O.owner}/${O.name}@${O.branch}`),b.step(`registering project on ${c}\u2026`);let A;try{A=await yt(c,p,$)}catch(R){if(R instanceof E&&R.status===409){b.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{A=await te(c,p,d)}catch(se){throw se instanceof E&&G(`HUB \u2192 ${se.status} ${se.message}`),se}}else if(R instanceof E&&R.status===401)o.delete("cliToken"),G("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(R instanceof E)G(`HUB \u2192 ${R.status} ${R.message}`);else throw R}let B=A.contextRepo??O;b.success(`project ${A.projectId} ready (${A.provisioningStatus})`);let ne=await Hd(B),pe={url:k.url,token:k.token};if(s==="farm"){let R=m,se={...T,...ne?{contextWrite:ne}:{},...x?{claude:{oauthToken:x}}:{},youtrack:pe},Re=T.github?.token;if(B.host==="github"&&Re)try{let q=gs(`devpipe-${d}`);await hs(B,Re,q.publicKey,`devpipe-${d}`),se.contextSsh={privateKey:q.privateKey},b.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(q){b.warn(`could not set up Context Repo SSH deploy key (${q instanceof Error?q.message:String(q)}); the farm will fall back to the token path.`)}let be={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:se,contextRepo:B,projectConfig:he($,v,k.url,y||void 0)},no=Cr(R.farm.publicKey,JSON.stringify(be));b.step(`handing project ${d} to farm ${R.farm.name}\u2026`);let Ge;try{Ge=await es(c,p,R.farm.farmId,{projectId:d,sealedBundle:no})}catch(q){throw q instanceof E&&G(q.status===409?`farm ${R.farm.name} is offline \u2014 start it and re-run.`:q.status===504?`farm ${R.farm.name} did not respond in time.`:`HUB \u2192 ${q.status} ${q.message}`),q}Ge.ok||G(`farm rejected provisioning: ${Ge.error??"unknown error"}`),await qo(c,p,d,B,Re),o.clear(),Wo(`done. project ${d} is now hosted on farm ${R.farm.name} (daemon ${Ge.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Wa(T),await Ga(e,B.cloneUrl,B.branch),Ha(e),a&&await Od(e);{let R=Ze(e,me);pt(R);let se=he($,v,k.url,y||void 0),Re=Gt(R,se);Re.length>0&&b.success(`local project config \u2192 .codepipe/{${Re.join(", ")}}`),Ye(d,se,{info:be=>b.message(be),warn:be=>b.warn(be)})}await Ma(e,A.repos);let Be={hubUrl:c,cliToken:p,projectId:d,...T,...ne?{contextWrite:ne}:{},...x?{claude:{oauthToken:x}}:{},youtrack:pe};Z(Be),We({hubUrl:c,cliToken:p,projectId:d,accountEmail:l},d),b.success(`secrets \u2192 ${qe(d)}`),await qo(c,p,d,B,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Wo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function qo(t,e,r,o,n){let i=await ka(o,n),s=ba(i),a=await et({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Yo(a)||a!==s.proceedValue))try{let{jobId:c}=await jr(t,e,r,{reindex:s.reindex});b.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){b.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function jd(t,e){let r;try{r=await Zi(t,e)}catch(c){throw c instanceof E&&G(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&G("no farms registered on this HUB. Register one first: on the farm host run `codepipe-farm register --hub <url> --token <HUB_FARM_REG_TOKEN>` and `codepipe-farm start`.");let n=ce(await et({message:"target farm",options:o.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=o.find(c=>c.farmId===n),s;try{s=va(i.farmId,i.publicKey)}catch(c){G(c instanceof Error?c.message:String(c))}return ce(await Pt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
537
537
|
${s}
|
|
538
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||G("farm fingerprint not confirmed \u2014 aborting."),
|
|
538
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||G("farm fingerprint not confirmed \u2014 aborting."),xa(i.farmId,s),{farm:i,fingerprint:s}}async function Ua(t){Na(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Da(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:_("HUB_URL")??de,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await Ba(),n=await eo(r,o);b.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await te(r,n,t.projectId)}catch(p){throw p instanceof E&&G(`HUB \u2192 ${p.status} ${p.message}`),p}i.contextRepo||G(`project ${t.projectId} has no Context Repo on HUB`);let s=await qa(),a={},c=new Set(i.repos.map(p=>p.host));c.add(i.contextRepo.host);for(let p of c)await Qr(p,a,p===i.contextRepo.host?i.contextRepo.owner:i.repos.find(m=>m.host===p)?.owner,o);Wa(a),await Ga(e,i.contextRepo.cloneUrl,i.contextRepo.branch),Ha(e);{let p=Ze(e,me);pt(p);let m={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{}},u=he(m,!0,s.url),d=Gt(p,u);d.length>0&&b.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),Ye(t.projectId,u,{info:g=>b.message(g),warn:g=>b.warn(g)})}await Ma(e,i.repos);let l={hubUrl:r,cliToken:n,projectId:t.projectId,...a,youtrack:{url:s.url,token:s.token}};Z(l),We({hubUrl:r,cliToken:n,projectId:t.projectId},t.projectId),b.success(`secrets \u2192 ${qe(t.projectId)}`),await qo(r,n,t.projectId,i.contextRepo,a.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Wo("done.")}function Da(t,e){if(!It(t)){Ea(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Id(t).filter(n=>!r.has(n));o.length!==0&&(e||G(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Vo(t){if(!It(Ze(t,".git")))return null;try{let r=(await Zr(t).remote(["get-url","origin"])||"").toString().trim(),o=r?Ce(r):null;return o?{parsed:o,defaultBranch:await Ad(t)}:null}catch{return null}}async function Ad(t){let e=Zr(t);try{let o=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(o)return o}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function _d(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return He.test(e)?e:""}function Nd(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Od(t){let e=Ze(t,".gitignore"),r=It(e)?ja(e,"utf-8"):"";if(Nd(r))return;if(!ce(await Pt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){b.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
|
|
539
539
|
`)?"":`
|
|
540
|
-
`;
|
|
540
|
+
`;Aa(e,r+n+`
|
|
541
541
|
# codepipe workspace (added by \`codepipe init\`)
|
|
542
542
|
.codepipe/
|
|
543
|
-
`),b.success(`.codepipe/ added to ${
|
|
543
|
+
`),b.success(`.codepipe/ added to ${_a(e)}`)}async function Ba(){let t="";try{t=(await Zr().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Email (admin email of this HUB)",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function eo(t,e){b.step(`sending magic link to ${e}`);let r;try{r=await rs(t,e)}catch(n){throw n instanceof Kt&&G(`${e} is not authorized on this HUB yet.
|
|
544
544
|
Sign up at ${t} (registration form on the login screen),
|
|
545
545
|
wait for the operator to approve it by email, then re-run
|
|
546
|
-
\`codepipe init\` with the same email.`),n}b.message(`click the link in your inbox to confirm. polling\u2026 (request ${r.requestId})`);let o=Date.now();for(;Date.now()-o<15*6e4;){let n=await
|
|
546
|
+
\`codepipe init\` with the same email.`),n}b.message(`click the link in your inbox to confirm. polling\u2026 (request ${r.requestId})`);let o=Date.now();for(;Date.now()-o<15*6e4;){let n=await os(t,r.requestId);if(n.status==="confirmed"&&n.cliToken)return b.success("confirmed"),n.cliToken;n.status==="rejected"&&G("HUB rejected this email \u2014 not the admin"),n.status==="expired"&&G("link expired \u2014 re-run init"),await Pd(2e3)}G("bootstrap timed out after 15 minutes")}async function Ga(t,e,r){let o=Ze(t,me);if(It(Ze(o,".git"))){b.message(`${o} already cloned \u2014 skipping`);return}It(o)&&G(`${o} exists but is not a git repo \u2014 remove it and re-run`),Ea(o,{recursive:!0}),b.step(`cloning Context Repo \u2192 ${o}`);try{await Zr().clone(e,o,["--branch",r]),b.success(`cloned ${e}`)}catch(n){G(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Ma(t,e){if(e.length===0)return;b.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await Qt(t,r,{log:{info:n=>b.message(n),warn:n=>b.warn(n)}});for(let n of o)b.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function Ha(t){let e=Ze(t,me,".gitignore"),r="";if(It(e)&&(r=ja(e,"utf-8")),Pa.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
|
|
547
547
|
`)||r.length===0?"":`
|
|
548
|
-
`,i=
|
|
548
|
+
`,i=Pa.join(`
|
|
549
549
|
`)+`
|
|
550
|
-
`;
|
|
551
|
-
`:"")+i),b.message(`appended runtime entries to ${
|
|
550
|
+
`;Aa(e,r+n+(r?`
|
|
551
|
+
`:"")+i),b.message(`appended runtime entries to ${_a(e)}`)}async function Ld(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;b.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Qr(s.host,t,s.owner,e),i?.();let c=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),l=D(await K({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),o.onProgress?.(n)}for(;ce(await Pt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=D(await K({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:d=>!d||!d.trim()||Ce(d)?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=Ce(a);b.message(`${c.host}: ${c.owner}/${c.repoName}`),await Qr(c.host,t,c.owner,e),i?.();let l=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"default branch (optional)",placeholder:"main"})).trim(),m=D(await K({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),m&&m!==l&&(u.mountAs=m),n.push(u),o.onProgress?.(n)}return n}async function Fa(t,e,r,o){b.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 n=ce(await et({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"}));n==="attach"&&b.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=D(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:xe(t),validate:p=>{let m=(p??"").trim();if(!m)return"required";if(!Ce(m)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(m))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=Ce(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Dd(),l=D(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:m=>m.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"Context Repo name",placeholder:xe(t),initialValue:xe(t),validate:m=>m.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:n}}function Ka(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??at()}}async function Ud(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Qr(c.host,o,c.owner,n),i?.();let p=Oa();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let m=await la(c,Ka(o),{explain:l==="attach"});if(m.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(m.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${m.detail}) \u2014 continuing`,1),a;if(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(m.detail,1);let u=ce(await et({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(u==="abort"&&G("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Fa(e,r,o,n),s(a)}}async function Dd(){return ce(await et({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Zt(t,e){let r=Oa();r.start(`verifying ${t}\u2026`);try{let o=await e();return r.stop(`${t} OK \u2014 ${o}`),!0}catch(o){return r.stop(`${t} failed \u2014 ${o instanceof Error?o.message:String(o)}`,1),!1}}function Wa(t){Lr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ur(t.gitlab?.token??process.env.GITLAB_TOKEN),Dr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Qr(t,e,r,o){if(!e[t])if(t==="github"){let n=await Bd(r);n?e.github=n:b.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Gd(r,o);n?e.bitbucket=n:b.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 n=await Md();n?e.gitlab=n:b.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Bd(t){for(;;){let e=D(await Et({message:`GitHub PAT \u2014 blank to skip
|
|
552
552
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
553
553
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
554
554
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
555
555
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
556
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
556
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Zt("GitHub",()=>dt(e,t?{owner:t}:void 0)))return{token:e};b.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Gd(t,e){for(b.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
557
557
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
558
558
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
559
559
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
560
560
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
561
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=D(await K({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:n=>!n||!n.trim()||n.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let o=D(await
|
|
562
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
561
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let r=D(await K({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:n=>!n||!n.trim()||n.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let o=D(await Et({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){b.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Zt("Bitbucket",()=>ft(r,o,t)))return{email:r,apiToken:o};b.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Md(){for(;;){let t=D(await Et({message:`GitLab PAT \u2014 blank to skip
|
|
562
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Zt("GitLab",()=>mt(t))){let e=await oi(t);return e&&b.warn(e),{token:t}}b.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Hd(t){if(ce(await Pt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
563
563
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
564
564
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
565
565
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?b.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
566
566
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
567
567
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):b.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
568
|
-
(${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=D(await
|
|
569
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=D(await It({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||b.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):(b.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 Ma(){for(;;){let t=D(await K({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=D(await It({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Xt("YouTrack",()=>ht({baseUrl:t,token:e}))){let r=await ji({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Bd}from"node:fs";function W(t){throw new Error(t)}function z(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function Qt(t,e){if(t==null)return;typeof t!="string"&&W(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Gd(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=z(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=z(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=z(i.id,"project.id");He.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=z(i.name,"project.name"),c=z(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let u=i.repos;Array.isArray(u)||W("config: 'project.repos' must be an array");let p=u.map((v,T)=>{(!v||typeof v!="object")&&W(`config: project.repos[${T}] must be an object`);let E=v,U=z(E.host,`project.repos[${T}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${T}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:z(E.name,`project.repos[${T}].name`),host:U,owner:z(E.owner,`project.repos[${T}].owner`),repoName:z(E.repoName,`project.repos[${T}].repoName`)},h=Qt(E.defaultBranch,`project.repos[${T}].defaultBranch`);h&&(S.defaultBranch=h);let m=Qt(E.mountAs,`project.repos[${T}].mountAs`);return m&&(S.mountAs=m),S}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let l=f,d=Qt(l.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&W("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:z(l.owner,"project.contextRepo.owner"),name:Qt(l.name,"project.contextRepo.name")??$e(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},k=Qt(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(w.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let C=e.secrets;if(C!==void 0){(typeof C!="object"||C===null)&&W("config: 'secrets' must be an object");let v=C,T={};if(v.github){let E=v.github;T.github={token:z(E.token,"secrets.github.token")}}if(v.bitbucket){let E=v.bitbucket;T.bitbucket={email:z(E.email,"secrets.bitbucket.email"),apiToken:z(E.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let E=v.gitlab;T.gitlab={token:z(E.token,"secrets.gitlab.token")}}if(v.youtrack){let E=v.youtrack;T.youtrack={url:z(E.url,"secrets.youtrack.url").replace(/\/$/,""),token:z(E.token,"secrets.youtrack.token")}}if(v.contextWrite){let E=v.contextWrite;T.contextWrite={token:z(E.token,"secrets.contextWrite.token")}}w.secrets=T}return w}async function Md(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Hd(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await pt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(n=>n.host==="bitbucket")?.owner,o=await dt(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await ft(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await ht({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ha(t){let e=!t.configPath||t.configPath==="-"?await Md():Bd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(l){W(`config: invalid JSON \u2014 ${l instanceof Error?l.message:String(l)}`)}let o=Gd(r),{hubUrl:n,cliToken:i,project:s}=o;console.log(`codepipe init --headless \u2192 ${n} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Hd(o));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=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,u;try{u=await St(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??at(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:l=>console.log(` ${l}`),warn:l=>console.warn(` ${l}`)}})}catch(l){W(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`)}a.contextRepo=u,console.log(`Context Repo ready: ${u.owner}/${u.name}@${u.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await wt(n,i,a)}catch(l){if(l instanceof j&&l.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await ae(n,i,s.id);else if(l instanceof j)W(`HUB \u2192 ${l.status} ${l.message}`);else throw l}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(Z(f),Fe({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${We(s.id)}`),qe(s.id,Pe(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:l=>console.log(l),warn:l=>console.warn(l)}),s.index)try{let{jobId:l}=await Rr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${l}); runs once a SANDBOX claims it.`)}catch(l){console.warn(`could not enqueue index job: ${l instanceof Error?l.message:String(l)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Fa,intro as Ka,isCancel as Wa,log as Fo,outro as Fd,password as qa}from"@clack/prompts";async function Kd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ya(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Kd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Ka("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Fo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await qa({message:"Claude OAuth token"});Wa(i)&&(Fa("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Tn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${fr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=me(t.profile);if(!e){Ka(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Fo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await qa({message:"Claude OAuth token"});Wa(i)&&(Fa("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},Z(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Fo.success("Claude OAuth token saved."),Fd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Wd,confirm as qd,intro as Yd,isCancel as Va,log as J,outro as Vd,select as za,text as De}from"@clack/prompts";function Ja(t){Wd(t),process.exit(1)}function Pt(t){return Va(t)&&Ja("aborted"),t}function Zt(t){return Va(t)&&Ja("aborted"),typeof t=="string"?t:""}async function zd(t,e){let r=Pt(await za({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=Zt(await De({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Zt(await De({message:"Context Repo name",placeholder:$e(t),initialValue:$e(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function Xa(t={profile:void 0}){let e=me(t.profile);Yd(`codepipe project add \u2192 ${e.hubUrl}`);let r=Pt(await De({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:l=>He.test(l.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Pt(await De({message:"project name (human-readable)",placeholder:"CodePartner",validate:l=>l.trim().length>0?void 0:"required"})).trim(),n=Pt(await za({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=Pt(await De({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Pt(await qd({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let l=Zt(await De({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:C=>!C||!C.trim()||ve(C)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!l)break;let d=ve(l);J.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=Zt(await De({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:C=>C.trim().length>0?void 0:"required"})).trim(),w=Zt(await De({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(k.defaultBranch=w),a.push(k)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let u=await zd(r,a),p=H(e.projectId);J.info(`provisioning Context Repo ${u.owner}/${u.name} (${u.host})\u2026`);let f;try{f=await St(c,u,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??at(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:l=>J.message(l),warn:l=>J.warn(l)}})}catch(l){J.error(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}c.contextRepo=f,J.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let l=await wt(e.hubUrl,e.cliToken,c);J.success(`project "${l.projectId}" \u2014 ${l.provisioningStatus}`),qe(r,Pe(c,s,p?.youtrack?.url),{info:d=>J.message(d),warn:d=>J.warn(d)}),l.contextRepo&&(J.message(` context repo: ${l.contextRepo.owner}/${l.contextRepo.name} (${l.contextRepo.cloneUrl})`),J.message(` branch: ${l.contextRepo.branch}`)),l.provisioningError&&J.error(` error: ${l.provisioningError}`),Vd("done")}catch(l){l instanceof j?(J.error(`HUB \u2192 ${l.status} ${l.message}`),l.payload&&typeof l.payload=="object"&&J.message(JSON.stringify(l.payload,null,2))):J.error(l instanceof Error?l.message:String(l)),process.exit(1)}}import{spawn as Jd}from"node:child_process";import{hostname as Xd}from"node:os";async function Qd(t,e){let r=te(e.profile);if(r){if(r.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${r.sandboxId} (${r.name})`);return}throw new Error(`worker config ${Oe(e.profile)} points at a different HUB (${r.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await Cr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(n){throw n instanceof j&&n.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):n instanceof j&&n.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"):n}await Xe({hub:t.hubUrl,token:o,name:e.name??`${Xd()}-up`,llm:e.llm??"claude-headless",projects:e.projects??[],...e.profile?{profile:e.profile}:{}})}function Zd(t,e){let r=te(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=gt(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=dr(t,r.sandboxId,o);if(n==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${n==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function Qa(t){let e=me(t.profile);await Qd(e,t),Zd(e.projectId,t.profile);let r=process.argv[1];if(!r)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(l,d)=>{let g=w=>k=>{for(let C of k.toString("utf-8").split(`
|
|
570
|
-
`))
|
|
571
|
-
`)};
|
|
572
|
-
[up] ${
|
|
573
|
-
`)}async function
|
|
574
|
-
${
|
|
575
|
-
or: /abort ${r} --reason "..."`}}function
|
|
568
|
+
(${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=D(await Et({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Zt("contextWrite",()=>Fd(r,t)))return{token:r};b.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Fd(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=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(o.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(o.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(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let n=await o.json();if(n.permissions&&n.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return n.full_name??`${e.owner}/${e.name}`}async function Kd(t){if(po()?.claude?.oauthToken&&!t)return b.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`)."),"";b.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?`
|
|
569
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=D(await Et({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||b.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):(b.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 qa(){for(;;){let t=D(await K({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=D(await Et({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Zt("YouTrack",()=>wt({baseUrl:t,token:e}))){let r=await Bi({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Wd}from"node:fs";function W(t){throw new Error(t)}function z(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function er(t,e){if(t==null)return;typeof t!="string"&&W(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function qd(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=z(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=z(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=z(i.id,"project.id");He.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=z(i.name,"project.name"),c=z(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||W("config: 'project.repos' must be an array");let p=l.map((v,T)=>{(!v||typeof v!="object")&&W(`config: project.repos[${T}] must be an object`);let j=v,L=z(j.host,`project.repos[${T}].host`);L!=="github"&&L!=="bitbucket"&&L!=="gitlab"&&W(`config: project.repos[${T}].host must be 'github', 'bitbucket' or 'gitlab'`);let C={name:z(j.name,`project.repos[${T}].name`),host:L,owner:z(j.owner,`project.repos[${T}].owner`),repoName:z(j.repoName,`project.repos[${T}].repoName`)},h=er(j.defaultBranch,`project.repos[${T}].defaultBranch`);h&&(C.defaultBranch=h);let f=er(j.mountAs,`project.repos[${T}].mountAs`);return f&&(C.mountAs=f),C}),m=i.contextRepo;(!m||typeof m!="object")&&W("config: 'project.contextRepo' is required");let u=m,d=er(u.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&W("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:z(u.owner,"project.contextRepo.owner"),name:er(u.name,"project.contextRepo.name")??xe(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},k=er(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(w.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let S=e.secrets;if(S!==void 0){(typeof S!="object"||S===null)&&W("config: 'secrets' must be an object");let v=S,T={};if(v.github){let j=v.github;T.github={token:z(j.token,"secrets.github.token")}}if(v.bitbucket){let j=v.bitbucket;T.bitbucket={email:z(j.email,"secrets.bitbucket.email"),apiToken:z(j.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let j=v.gitlab;T.gitlab={token:z(j.token,"secrets.gitlab.token")}}if(v.youtrack){let j=v.youtrack;T.youtrack={url:z(j.url,"secrets.youtrack.url").replace(/\/$/,""),token:z(j.token,"secrets.youtrack.token")}}if(v.contextWrite){let j=v.contextWrite;T.contextWrite={token:z(j.token,"secrets.contextWrite.token")}}w.secrets=T}return w}async function Yd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Vd(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await dt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(n=>n.host==="bitbucket")?.owner,o=await ft(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await mt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await wt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ya(t){let e=!t.configPath||t.configPath==="-"?await Yd():Wd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){W(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let o=qd(r),{hubUrl:n,cliToken:i,project:s}=o;console.log(`codepipe init --headless \u2192 ${n} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Vd(o));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=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Rt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??at(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){W(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await yt(n,i,a)}catch(u){if(u instanceof E&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await te(n,i,s.id);else if(u instanceof E)W(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let m={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(Z(m),We({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${qe(s.id)}`),Ye(s.id,he(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await jr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Va,intro as za,isCancel as Ja,log as zo,outro as zd,password as Xa}from"@clack/prompts";async function Jd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Qa(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Jd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){za("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),zo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Xa({message:"Claude OAuth token"});Ja(i)&&(Va("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ln({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=Ee(t.profile);if(!e){za(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),zo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Xa({message:"Claude OAuth token"});Ja(i)&&(Va("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},Z(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(zo.success("Claude OAuth token saved."),zd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Xd,confirm as Qd,intro as Zd,isCancel as Za,log as J,outro as ef,select as ec,text as De}from"@clack/prompts";function tc(t){Xd(t),process.exit(1)}function jt(t){return Za(t)&&tc("aborted"),t}function tr(t){return Za(t)&&tc("aborted"),typeof t=="string"?t:""}async function tf(t,e){let r=jt(await ec({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=tr(await De({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=tr(await De({message:"Context Repo name",placeholder:xe(t),initialValue:xe(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function rc(t={profile:void 0}){let e=Ee(t.profile);Zd(`codepipe project add \u2192 ${e.hubUrl}`);let r=jt(await De({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>He.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=jt(await De({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),n=jt(await ec({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=jt(await De({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=jt(await Qd({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=tr(await De({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:S=>!S||!S.trim()||Ce(S)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let d=Ce(u);J.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=tr(await De({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:S=>S.trim().length>0?void 0:"required"})).trim(),w=tr(await De({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(k.defaultBranch=w),a.push(k)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await tf(r,a),p=H(e.projectId);J.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let m;try{m=await Rt(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??at(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>J.message(u),warn:u=>J.warn(u)}})}catch(u){J.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=m,J.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await yt(e.hubUrl,e.cliToken,c);J.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),Ye(r,he(c,s,p?.youtrack?.url),{info:d=>J.message(d),warn:d=>J.warn(d)}),u.contextRepo&&(J.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),J.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&J.error(` error: ${u.provisioningError}`),ef("done")}catch(u){u instanceof E?(J.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&J.message(JSON.stringify(u.payload,null,2))):J.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{spawn as rf}from"node:child_process";import{existsSync as oc}from"node:fs";import{homedir as of,hostname as nf}from"node:os";import{join as to}from"node:path";async function sf(t,e,r){let o=re(e);if(o){if(o.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`);return}throw new Error(`worker config ${Ne(e)} points at a different HUB (${o.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let n;try{({secret:n}=await Er(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof E&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof E&&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 E?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 Xe({hub:t.hubUrl,token:n,name:r.name??`${nf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function af(t,e){let r=re(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=ht(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=wr(t,r.sandboxId,o);if(n==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${n==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function cf(t,e){let r=process.cwd(),o=to(r,me);if(mr(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(oc(o)){console.warn(`[up] ${o} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let n;try{n=await te(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Vo(r);if(!kn(r,i?.parsed??null,n.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=H(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Or({cfg:t,secrets:s,contextDir:o,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=to(of(),".codepipe",e?to("profiles",e,"context-config"):"context-config");if(xr(c.contextDir,l,a),!oc(to(c.contextDir,"project.yaml"))){pt(c.contextDir);let p={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};Gt(c.contextDir,he(p,!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 ${o}`)}async function nc(t){let{cfg:e,profile:r}=hr(t.profile);await cf(e,r),await sf(e,r,t),af(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(d,g)=>{let w=k=>S=>{for(let v of S.toString("utf-8").split(`
|
|
570
|
+
`))v.length>0&&k.write(`${g} ${v}
|
|
571
|
+
`)};d.stdout?.on("data",w(process.stdout)),d.stderr?.on("data",w(process.stderr))},i=(d,g)=>{let w=rf(process.execPath,[o,...g],{stdio:["ignore","pipe","pipe"],env:process.env});return n(w,d),w};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,p=d=>{if(!l){l=!0,console.log(`
|
|
572
|
+
[up] ${d} \u2014 stopping both roles`);for(let{child:g}of c)g.exitCode===null&&g.kill(d);setTimeout(()=>{for(let{name:g,child:w}of c)w.exitCode===null&&(console.warn(`[up] ${g} did not stop \u2014 SIGKILL`),w.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let m=c.map(({name:d,child:g})=>new Promise(w=>{g.on("exit",(k,S)=>w({name:d,code:k??(S?1:0)}))})),u=await Promise.race(m);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(m),process.exit(u.code)}import{existsSync as hc,mkdirSync as ff,readFileSync as mf,writeFileSync as gf}from"node:fs";import{homedir as hf}from"node:os";import{dirname as wf,join as wc}from"node:path";import*as _t from"node:readline";import{existsSync as Qo,readFileSync as lf,writeFileSync as uf}from"node:fs";import{join as or}from"node:path";import{simpleGit as Xo}from"simple-git";var ic=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],pf="apply-queue.json";function sc(t){return or(t,pf)}function At(t){let e=sc(t);if(!Qo(e))return{};try{return JSON.parse(lf(e,"utf-8"))}catch{return{}}}function ac(t,e){uf(sc(t),JSON.stringify(e,null,2)+`
|
|
573
|
+
`)}async function cc(t,e,r,o,n){let i;try{i=await ss(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let d=t.spec.repos.find(S=>S.name===u.repoName);if(!d)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let g=or(t.root,d.mountAs);if(!Qo(or(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Xo(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:d,dir:g})}let a=[];for(let u of s){let d=Xo(u.dir),g=await df(d),w=u.claimRepo;try{await d.fetch()}catch(v){return await Jo(a,n),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${rr(v)}`}}let k=`origin/${w.baseRef}`,S;try{S=await Tr(d,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(v){return await Jo(a,n),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${rr(v)}`}}a.push({git:d,dir:u.dir,mountAs:u.spec.mountAs,originalRef:g,branch:w.branchName,baseSha:k,deliveryCommit:S,startPoint:k})}let c=[];for(let u of a)try{if(o==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...ic,"cherry-pick",u.deliveryCommit]);let d=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:d})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...ic,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(d){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Jo(a,n),{ok:!1,message:`apply failed in ${u.mountAs}: ${rr(d)} (rolled back all repos)`}}let l=At(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},ac(t.contextDir,l);let p=c.map(u=>u.mountAs).join(", "),m=o==="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:`${o==="apply"?"applied":"unstashed"} ${r} in ${p}
|
|
574
|
+
${m}
|
|
575
|
+
or: /abort ${r} --reason "..."`}}function Zo(t,e){let r=At(t);r[e]&&(delete r[e],ac(t,r))}async function Jo(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(o){e.warn(`rollback failed in ${r.mountAs}: ${rr(o)} \u2014 check manually`)}}async function lc(t,e,r){let n=At(t.contextDir)[e];if(n){for(let i of n.repos){let s=or(t.root,i.mountAs);if(!Qo(or(s,".git")))continue;let a=Xo(s),c=t.spec.repos.find(p=>p.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(p){r.warn(`rollback failed in ${i.mountAs}: ${rr(p)} \u2014 check manually`)}}Zo(t.contextDir,e)}}async function df(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function rr(t){return t instanceof Error?t.message.trim():String(t)}var ro=wc(hf(),".codepipe","history"),uc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],yc=500,pc=40;async function bc(){let t=Ke();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=H(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)),Bt(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=At(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
|
|
576
576
|
\u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
577
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=
|
|
578
|
-
`))}async function
|
|
579
|
-
`)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}
|
|
580
|
-
`),t.unread+=1,
|
|
581
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
577
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=_t.createInterface({input:process.stdin,output:process.stdout,completer:yf,history:Df(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ki(s=>tt(i,s)),i.daemon=Nr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>tt(i,s),warn:s=>tt(i,s)},onEvent:s=>Af(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),tn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await bf(i,a)){gc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,tn(i),n.prompt()}),n.on("close",()=>{gc(i)})}function yf(t){let e=uc.filter(r=>r.startsWith(t));return[e.length?e:uc,t]}async function bf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return kf(),!1;case"/status":return await $f(t),!1;case"/tasks":return await xf(t,o),!1;case"/task":return await vf(t,o),!1;case"/sync":return await Sf(t),!1;case"/logs":return _f(t,o),!1;case"/monitor":return Nf(t),!1;case"/apply":return await dc(t,o,"apply"),!1;case"/unstash":return await dc(t,o,"unstash"),!1;case"/applied":return await Cf(t,o),!1;case"/abort":return await Rf(t,o),!1;case"/approve":return await fc(t,o,"approve"),!1;case"/merge":return await fc(t,o,"merge"),!1;case"/login":return If(t,o),!1;case"/secret":return Pf(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function kf(){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(`
|
|
578
|
+
`))}async function $f(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 o=hc(wc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function xf(t,e){let r=Of(e,"--phase");try{let o=await ns(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),n=r?o.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):o;if(n.length===0){console.log(" (no tasks)");return}for(let i of n)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(o){ir(o)}}async function vf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await is(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${o.task.phase} \u2014 ${o.task.title}`),o.artifacts.length>0){console.log(" artifacts:");for(let n of o.artifacts)console.log(` ${n.path}`)}}catch(o){ir(o)}}async function Sf(t){let e=await Qt(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 dc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await cc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Cf(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=At(t.ws.contextDir)[r],i=Lf(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("="),p,m;if(l>0?(p=c.slice(0,l),m=c.slice(l+1)):(m=c,p=n?.repos.length===1?Tf(t,n.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${m}`);return}let u=m.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${m}`);return}a.push({repoName:p,url:m,number:Number(u[1])})}try{let c=await as(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Zo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){ir(c)}}async function fc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await ls(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){ir(n)}}async function Rf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=Uf(e,"--reason")||"local apply aborted";await lc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await cs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){ir(n)}}function Tf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function If(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},Z(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 Pf(t,e){let[r,o,...n]=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(`
|
|
579
|
+
`)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}Ef(t.secrets,o,i),Z(t.secrets),Bt(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}jf(t.secrets,o),Z(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function Ef(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 jf(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 Af(t,e){switch(e.kind){case"connected":t.connection="connecting",tt(t,"[hub] connected");break;case"registered":t.connection="registered",tt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",nr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",tt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",nr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":nr(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?tt(t,`[hub] action ${e.actionType} done`):nr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function tt(t,e){t.logBuffer.push(e),t.logBuffer.length>yc&&t.logBuffer.shift(),t.follow&&nr(t,e)}function _f(t,e){let r=e[0];if(r==="follow"||r==="on"){en(t,!0);return}if(r==="off"){en(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(yc,Number(r)||pc)):pc,n=t.logBuffer.slice(-o);if(n.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of n)console.log(` ${i}`);console.log(` \u2014 ${n.length} line(s); /monitor for live stream`)}function Nf(t){en(t,!t.follow)}function en(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function nr(t,e){_t.cursorTo(process.stdout,0),_t.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
580
|
+
`),t.unread+=1,tn(t),t.rl.prompt(!0)}function tn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var mc=!1;function gc(t){mc||(mc=!0,Bf(t.rl),t.daemon.stop(),console.log(`
|
|
581
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Of(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Lf(t,e){let r=[];for(let o=0;o<t.length;o++)t[o]===e&&t[o+1]&&r.push(t[o+1]);return r}function Uf(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function ir(t){t instanceof E?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Df(){if(!hc(ro))return[];try{return mf(ro,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Bf(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{ff(wf(ro),{recursive:!0}),gf(ro,r.slice().reverse().join(`
|
|
582
582
|
`)+`
|
|
583
|
-
`)}catch{}}import{hostname as Af}from"node:os";import{cancel as _f,confirm as mc,intro as Of,isCancel as wc,log as At,multiselect as Nf,outro as gc,password as Uf,select as Jo,text as Xr}from"@clack/prompts";function ir(t){_f(t),process.exit(1)}function _t(t){return wc(t)&&ir("aborted"),t}function nr(t){return wc(t)&&ir("aborted"),typeof t=="string"?t:""}function Xo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function hc(t,e){try{let{secret:r}=await Cr(t,e);return r}catch(r){throw r instanceof j&&r.status===404&&ir("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Lf(t,e){if(_t(await Jo({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let n=await Yi(t,e);if(n.length>0)return _t(await Nf({message:"pick the projects (space to toggle, enter to confirm)",options:n.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));At.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){At.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return nr(await Xr({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:n=>n.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Qo(t){Of("codepipe worker \u2014 set up this machine as a runner");let e=te(t.profile);e&&(At.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),_t(await mc({message:"re-register this worker?",initialValue:!1}))||ir("keeping the existing registration"));let r=Te(t.profile)??Te(),o=nr(await Xr({message:"HUB URL",placeholder:de,initialValue:_("HUB_URL")??r?.hubUrl??de,validate:l=>l.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=_t(await Jo({message:"how to authorize the registration?",options:[...n?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:n?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await hc(o,a),At.success("account-issued registration token minted");else if(i==="login"){let l=nr(await Xr({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await zr(o,l),s=await hc(o,a),At.success("account-issued registration token minted")}else s=nr(await Uf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ir("a registration token is required");let c=await Lf(o,a),u=nr(await Xr({message:"worker name",initialValue:Af(),validate:l=>l.trim().length>0?void 0:"required"})).trim(),p=_t(await Jo({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Xe({hub:o,token:s,name:u,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),At.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!_t(await mc({message:"start the claim-loop now?",initialValue:!0}))){gc("registered. start later with `codepipe worker`.");return}gc("starting the claim-loop\u2026"),await zt(t.profile?{profile:t.profile}:{})}function Bf(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var X=Bf();gn(X);bn();var le=new Df;le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(se).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await fc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Ha({configPath:t.config,skipVerify:t.skipVerify===!0}):await ja({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await In({...t,profile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Aa({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});le.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ys({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await va({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Ya({profile:X,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await oa({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await Qa({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var yc=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");yc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??Te(X)?.hubUrl??de,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Xo()){await Qo({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??_("WORKER_NAME"),i=t.llm??_("WORKER_LLM");await Xe({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...X?{profile:X}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!te(X)&&Xo()){await Qo({profile:X});return}await zt(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Gf=le.command("project").description("Manage CodePipe projects");Gf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Xa({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();
|
|
583
|
+
`)}catch{}}import{hostname as Gf}from"node:os";import{cancel as Mf,confirm as kc,intro as Hf,isCancel as vc,log as Nt,multiselect as Ff,outro as $c,password as Kf,select as rn,text as oo}from"@clack/prompts";function ar(t){Mf(t),process.exit(1)}function Ot(t){return vc(t)&&ar("aborted"),t}function sr(t){return vc(t)&&ar("aborted"),typeof t=="string"?t:""}function on(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function xc(t,e){try{let{secret:r}=await Er(t,e);return r}catch(r){throw r instanceof E&&r.status===404&&ar("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Wf(t,e){if(Ot(await rn({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let n=await ts(t,e);if(n.length>0)return Ot(await Ff({message:"pick the projects (space to toggle, enter to confirm)",options:n.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Nt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){Nt.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return sr(await oo({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:n=>n.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function nn(t){Hf("codepipe worker \u2014 set up this machine as a runner");let e=re(t.profile);e&&(Nt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Ot(await kc({message:"re-register this worker?",initialValue:!1}))||ar("keeping the existing registration"));let r=ve(t.profile)??ve(),o=sr(await oo({message:"HUB URL",placeholder:de,initialValue:_("HUB_URL")??r?.hubUrl??de,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=Ot(await rn({message:"how to authorize the registration?",options:[...n?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:n?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await xc(o,a),Nt.success("account-issued registration token minted");else if(i==="login"){let u=sr(await oo({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await eo(o,u),s=await xc(o,a),Nt.success("account-issued registration token minted")}else s=sr(await Kf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ar("a registration token is required");let c=await Wf(o,a),l=sr(await oo({message:"worker name",initialValue:Gf(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Ot(await rn({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await Xe({hub:o,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Nt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Ot(await kc({message:"start the claim-loop now?",initialValue:!0}))){$c("registered. start later with `codepipe worker`.");return}$c("starting the claim-loop\u2026"),await Xt(t.profile?{profile:t.profile}:{})}function Yf(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var X=Yf();Cn(X);In();var le=new qf;le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ae).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await bc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Ya({configPath:t.config,skipVerify:t.skipVerify===!0}):await La({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Un({...t,profile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Ua({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});le.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await vs({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Ia({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Qa({profile:X,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ca({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await nc({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Sc=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Sc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??ve(X)?.hubUrl??de,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&on()){await nn({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??_("WORKER_NAME"),i=t.llm??_("WORKER_LLM");await Xe({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...X?{profile:X}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Sc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!re(X)&&on()){await nn({profile:X});return}await Xt(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Vf=le.command("project").description("Manage CodePipe projects");Vf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await rc({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();
|