@code-partner/codepipe 0.1.128-dev.19.g92ede48 → 0.1.128-dev.20.g1c5fae1
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 +96 -92
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var ce="0.1.128-dev.20.g1c5fae1",me="https://hub.dev.codepipe.dev";var ge=2,Lc=1;function fr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Lc&&t<=ge}var xe=".devpipe-context.yaml",kn=[{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",xe]}];function mr(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
|
-
`);o!==r&&
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function xr(){return
|
|
9
|
-
`,{mode:384})}function dt(t){let e=G(t)?.claude?.oauthToken;return e||ho()?.claude?.oauthToken}function Gt(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 ft(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function
|
|
5
|
+
`}function $n(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 xn(t,e=kn){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 vn(t,e=kn){return e.filter(r=>r.version>t)}function gr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ve=/^[a-z][a-z0-9-]{1,30}$/,Dc="-codepipe-ctx";function ve(t){return`${t}${Dc}`}var Bt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function ut(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 ze="x-bitbucket-api-token-auth";function hr(t){switch(t){case Bt.gitlab:return"oauth2";case Bt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Sn=20;function O(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as tm}from"commander";import{homedir as Pn}from"node:os";import{mkdirSync as Vc,readFileSync as zc,writeFileSync as Jc,existsSync as go}from"node:fs";import{dirname as jn,join as br,resolve as Xc}from"node:path";import{fileURLToPath as Qc}from"node:url";import{existsSync as wr,readFileSync as Rn,readdirSync as Gc,writeFileSync as Mc}from"node:fs";import{dirname as Hc,join as je}from"node:path";import{parse as Fc}from"yaml";import{existsSync as Cn,renameSync as Bc}from"node:fs";function Je(t,e,r=o=>console.error(o)){if(Cn(e)||!Cn(t))return!1;try{return Bc(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 he=".codepipe",mo=".devpipe";function Kc(t=process.cwd()){let e=t;for(;;){if(wr(je(e,he,"project.yaml")))return e;if(wr(je(e,mo,"project.yaml")))return Je(je(e,mo),je(e,he))&&qc(e),e;let r=Hc(e);if(r===e)return null;e=r}}function Wc(t){let e=je(t,he);return wr(e)?e:je(t,mo)}function qc(t){let e=je(t,".gitignore");if(!wr(e))return;let r=Rn(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&&Mc(e,o)}function Xe(t=process.cwd()){let e=Kc(t);if(!e)return null;let r=Wc(e),o=Yc(Rn(je(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function Tn(t,e,r){return Gc(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 yr(t,e=process.cwd()){try{let r=Xe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Yc(t){let e=Fc(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,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:o,repos:i}}function In(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 En=Xc(jn(Qc(import.meta.url)),"..");function An(t){let e=br(En,".env");if(go(e)&&process.loadEnvFile(e),t){let r=br(En,"profiles",t,".env");go(r)&&process.loadEnvFile(r)}}function pt(t){let e=O("CONFIG");return e||(t?br(Pn(),".codepipe","profiles",t,"config.json"):br(Pn(),".codepipe","config.json"))}function Se(t){let e=pt(t);if(!go(e))return null;let r=zc(e,"utf-8");return JSON.parse(r)}function Qe(t,e){let r=pt(e);Vc(jn(r),{recursive:!0}),Jc(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function kr(t){if(t)return{cfg:Ae(t),profile:t};let e;try{e=Xe()?.spec.projectId||void 0}catch{}if(e){let r=Se(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:Ae(void 0),profile:void 0}}function Ae(t){let e=Se(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 ${pt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as _n}from"node:os";import{join as On}from"node:path";function Nn(){Je(On(_n(),".devpipe"),On(_n(),".codepipe"))}import{homedir as Un}from"node:os";import{existsSync as Ln,mkdirSync as Dn,readFileSync as Bn,writeFileSync as Gn}from"node:fs";import{dirname as Mn,join as Hn}from"node:path";function $r(t,e,r){let o=G(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 Ze(t){return Hn(Un(),".codepipe","secrets",`${t}.json`)}function G(t){let e=Ze(t);return Ln(e)?JSON.parse(Bn(e,"utf-8")):null}function z(t){let e=Ze(t.projectId);Dn(Mn(e),{recursive:!0}),Gn(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function xr(){return Hn(Un(),".codepipe","shared.json")}function ho(){let t=xr();return Ln(t)?JSON.parse(Bn(t,"utf-8")):null}function Fn(t){let e=xr();Dn(Mn(e),{recursive:!0}),Gn(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function dt(t){let e=G(t)?.claude?.oauthToken;return e||ho()?.claude?.oauthToken}function Gt(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 ft(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Kn(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=Se(e);r&&!t.force&&(console.error(`already configured at ${pt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Qe({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...G(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};z(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${pt(e)}`)}import{homedir as Bo}from"node:os";import{join as zt}from"node:path";import{appendFileSync as Zc,existsSync as Wn,mkdirSync as el,renameSync as qn,statSync as tl,unlinkSync as rl}from"node:fs";import{Writable as ol}from"node:stream";import{join as nl}from"node:path";var Yn={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},mt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&el(e.dir,{recursive:!0}),this.currentPath=nl(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
10
10
|
`)?e:e+`
|
|
11
|
-
`;
|
|
11
|
+
`;Zc(this.currentPath,r,"utf-8")}asWritable(){return new ol({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||!Wn(this.currentPath)||tl(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Wn(o)&&(r>=this.cfg.maxFiles?rl(o):qn(o,`${this.currentPath}.${r+1}`))}qn(this.currentPath,`${this.currentPath}.1`)}}};function vr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=il(process.env[`${t}_MAX_BYTES`]??String(Yn.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Yn.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function il(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 Sr(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(sl(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 sl(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:al(n)).join(" ");return`${r} ${t} ${o}`}function al(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as qu}from"node:path";import"ws";import{createHash as cl}from"node:crypto";import{existsSync as ll,readFileSync as ul}from"node:fs";import{homedir as pl,hostname as wo}from"node:os";import{join as dl}from"node:path";function Vn(t){return cl("sha256").update(t).digest("hex").slice(0,12)}function fl(){let t=O("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=dl(pl(),".claude","credentials.json");if(!ll(e))return;let r=JSON.parse(ul(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 zn(t){let e=fl(),r=O("ACCOUNT_ID")?.trim(),o=O("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=dt(t);return n?{accountId:`acct-${Vn(n)}`,label:o||wo(),...e?{email:e}:{}}:{accountId:`acct-${Vn(`host:${wo()}`)}`,label:o||wo(),...e?{email:e}:{}}}import{existsSync as ml}from"node:fs";import{join as gl}from"node:path";import{simpleGit as hl}from"simple-git";async function Jn(t,e){if(!ml(gl(t,".git")))return{status:"skipped"};let r=hl(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${wl(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 wl(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as yo,readFileSync as Xn,readdirSync as yl,watch as bl}from"node:fs";import{join as bo}from"node:path";var Cr=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(yo(this.contextDir))try{this.watcher=bl(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=bo(this.contextDir,e);if(!yo(r))return null;try{return Xn(r,"utf-8")}catch{return null}}readPrompts(){let e=bo(this.contextDir,"prompts"),r={};if(!yo(e))return r;let o;try{o=yl(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Xn(bo(e,n),"utf-8")}catch{}}return r}};import{existsSync as El,readFileSync as jl,readdirSync as Al}from"node:fs";import{join as ni}from"node:path";import{simpleGit as _l}from"simple-git";import{existsSync as vl,mkdirSync as Sl,writeFileSync as ei}from"node:fs";import{dirname as Cl,isAbsolute as Rl,join as ri,normalize as So}from"node:path";import{simpleGit as oi}from"simple-git";import{existsSync as _e,mkdirSync as Qn,readFileSync as ko,writeFileSync as gt}from"node:fs";import{homedir as kl}from"node:os";import{join as we}from"node:path";import{simpleGit as $l}from"simple-git";var ht=["project.yaml","regimen.yaml"];function Mt(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=we(t,n);_e(s)||(gt(s,i),r.push(n))}return r}function et(t,e,r){let o=we(kl(),".codepipe","profiles",t,"context-config");return Qn(o,{recursive:!0}),gt(we(o,"project.yaml"),e.projectYaml),gt(we(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Rr(t,e,r){if(_e(e))for(let o of ht){let n=we(e,o),i=we(t,o);if(!(!_e(n)||_e(i)))try{gt(i,ko(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 xl=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function wt(t){let e=we(t,".gitignore"),r=_e(e)?ko(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(ht.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`;return gt(e,r+i
|
|
13
|
+
`;return gt(e,r+i+xl.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;
|
|
17
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
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
|
|
19
|
-
`),a=s.findIndex(
|
|
20
|
-
`).replace(/^\n+/,""),
|
|
21
|
-
`);return{content:
|
|
22
|
-
`)?
|
|
23
|
-
`,supersedes:u}}function
|
|
24
|
-
|
|
25
|
-
- **Status:** superseded by ADR-${r}`):o}function
|
|
15
|
+
`),!0}async function Zn(t,e){try{if(!_e(we(t,".git")))return;let r=$l(t),o=(await r.raw(["ls-files","--",...ht])).split(`
|
|
16
|
+
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;wt(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 vo(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 $o(t){let e=new Map;for(let r of ht){let o=we(t,r);_e(o)&&e.set(r,ko(o))}return e}function xo(t,e){Qn(t,{recursive:!0});for(let[r,o]of e){let n=we(t,r);_e(n)||gt(n,o)}}var ti=3,Tl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function Tr(t,e,r){if(!vl(ri(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Pl(t,i.path);Sl(Cl(s),{recursive:!0}),i.encoding==="base64"?ei(s,Buffer.from(i.content,"base64")):ei(s,i.content)}let o=oi(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...ht]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await vo(t))}async function vo(t){let e=oi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=ti;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 Il(e);if(i.length>0&&i.every(s=>Tl.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 ${ti} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Il(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
17
|
+
`).map(r=>r.trim()).filter(Boolean)}function Pl(t,e){if(Rl(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=So(ri(t,e)),o=So(t+"/");if(r!==So(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Ol=/^(\d{4})-(.+)\.md$/,Nl="0000-template.md";function Ul(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 Ll(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
19
|
+
`),a=s.findIndex(x=>x.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),p=[],f="",u=null,d=a>=0?a+1:0;for(let x=d;x<s.length;x++){let v=(s[x]??"").trim();if(v===""){d=x+1;continue}let A=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!A)break;let T=(A[1]??"").trim().toLowerCase(),U=(A[2]??"").trim(),C=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);C&&(u=parseInt(C[1]??"",10)),T==="tasks"&&(f=U),l.has(T)||p.push(v),d=x+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,w=s.slice(d).join(`
|
|
20
|
+
`).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${g}`,...p,"",w].join(`
|
|
21
|
+
`);return{content:S.endsWith(`
|
|
22
|
+
`)?S:S+`
|
|
23
|
+
`,supersedes:u}}function Dl(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
|
|
24
|
+
|
|
25
|
+
- **Status:** superseded by ADR-${r}`):o}function Bl(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(`
|
|
26
26
|
`)+`
|
|
27
|
-
`}async function
|
|
28
|
-
`+t.slice(t.length-e)}async function _e(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 Pr(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 Oe(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 Fl(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 Fl(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Ne(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 ci(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 Co=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 tt(`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()}`)}},To=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 tt(`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(y=>y.conclusion==="failure")){let y=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!y.ok)continue;let x=await y.text();p.push(`### CI job: ${g.name}
|
|
27
|
+
`}async function ii(t,e,r,o=new Date().toISOString().slice(0,10)){try{await _l(t).pull(void 0,void 0,["--rebase"])}catch{}let n=ni(t,"adr"),i=new Map;if(El(n))for(let u of Al(n)){let d=Ol.exec(u);!d||u===Nl||i.set(u,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:jl(ni(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:S,supersedes:x}=Ll(u.content,g,u.slug,e,o);if(a.set(w,S),i.set(w,{num:g,slug:u.slug,content:S}),c.push(`adr/${w}`),x!==null){let v=[...i.keys()].find(A=>A.startsWith(`${String(x).padStart(4,"0")}-`));if(v&&v!==w){let A=Dl(a.get(v)??i.get(v).content,g);a.set(v,A),i.set(v,{...i.get(v),content:A})}}}if(c.length===0)return{promoted:c,skipped:l};let p=[...i.entries()].map(([u,d])=>({num:d.num,file:u,header:Ul(d.content)}));a.set("INDEX.md",Bl(p));let f=[...a.entries()].map(([u,d])=>({path:`adr/${u}`,content:d}));return await Tr(t,f,`adr(${e}): promote ${r.map(u=>u.slug).join(", ")}`),{promoted:c,skipped:l}}import{existsSync as si,readFileSync as Ml}from"node:fs";import{join as ai}from"node:path";function Hl(t){let e=ai(t,xe);if(!si(e))return 0;try{return $n(Ml(e,"utf-8"))}catch{return 0}}function Fl(t,e,r,o=1){let n=e<o,i=n?xn(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Ir(t,e){return Fl(e,Hl(t),r=>si(ai(t,r)))}import{existsSync as nu,mkdirSync as iu,mkdtempSync as su,rmSync as au,writeFileSync as pi}from"node:fs";import{tmpdir as cu}from"node:os";import{dirname as lu,join as Po}from"node:path";import{simpleGit as Eo}from"simple-git";var tt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function ci(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
28
|
+
`+t.slice(t.length-e)}async function Oe(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 Pr(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 Ne(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 Kl(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 Kl(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Ue(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 ui(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 Co=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 tt(`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()}`)}},Ro=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 tt(`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 f of p.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let 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 f of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${n}/actions/runs/${f.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 S=await w.text();p.push(`### CI job: ${g.name}
|
|
29
29
|
|
|
30
|
-
${
|
|
30
|
+
${ci(S,8e3)}`)}}return p.length===0?void 0:ci(p.join(`
|
|
31
31
|
|
|
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()}`)}},
|
|
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()}`)}},To=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 tt(`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=Wl(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 Wl(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 Io=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(li(e,r,"merge"))}async closePR(e,r,o){throw new Error(li(e,r,"close"))}};function li(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 Ce(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Ro(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Co(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new To(e)}return new Io}function yt(t,e,r,o){return[{path:"README.md",content:tu(t,e)},{path:".gitignore",content:Jl()},{path:"CLAUDE.md",content:Ql(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Xl()},{path:"knowledge/README.md",content:Zl()},{path:"knowledge/build.yaml",content:eu()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:zl()},{path:"adr/README.md",content:ql()},{path:"adr/0000-template.md",content:Yl()},{path:"adr/INDEX.md",content:Vl()},{path:xe,content:mr()}]}function ql(){return`# ADR \u2014 architecture decision records
|
|
33
33
|
|
|
34
34
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
35
35
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -57,7 +57,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
57
57
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
58
58
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
59
59
|
open a PR to this repository.
|
|
60
|
-
`}function
|
|
60
|
+
`}function Yl(){return`# ADR-NNNN: <title>
|
|
61
61
|
|
|
62
62
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
63
63
|
- **Date:** YYYY-MM-DD
|
|
@@ -79,12 +79,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
79
79
|
## Alternatives considered
|
|
80
80
|
|
|
81
81
|
- **<alternative>** \u2014 why it was rejected.
|
|
82
|
-
`}function
|
|
82
|
+
`}function Vl(){return`# ADR index
|
|
83
83
|
|
|
84
84
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
85
85
|
|
|
86
86
|
(no accepted ADRs yet)
|
|
87
|
-
`}function
|
|
87
|
+
`}function zl(){return`# Audit
|
|
88
88
|
|
|
89
89
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
90
90
|
project appends only to its own file \u2014
|
|
@@ -93,14 +93,14 @@ project appends only to its own file \u2014
|
|
|
93
93
|
|
|
94
94
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
95
95
|
shared aggregate here.
|
|
96
|
-
`}function ye(t,e,r,o){return{projectYaml:
|
|
96
|
+
`}function ye(t,e,r,o){return{projectYaml:ru(t,r,o),regimenYaml:ou(t.automationLevel,e)}}function Jl(){return`# codepipe project config is local to each member's workspace
|
|
97
97
|
project.yaml
|
|
98
98
|
regimen.yaml
|
|
99
99
|
|
|
100
100
|
# codepipe runtime
|
|
101
101
|
session.log
|
|
102
102
|
apply-queue.json
|
|
103
|
-
`}function
|
|
103
|
+
`}function Xl(){return`# Index prompt
|
|
104
104
|
|
|
105
105
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
106
106
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -157,7 +157,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
157
157
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
158
158
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
159
159
|
empty or unavailable, say so briefly rather than inventing content.
|
|
160
|
-
`}function
|
|
160
|
+
`}function Ql(t){return`# Project context for the CodePipe agent
|
|
161
161
|
|
|
162
162
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
163
163
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -185,7 +185,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
185
185
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
186
186
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
187
187
|
only after the analysis is approved.
|
|
188
|
-
`}function
|
|
188
|
+
`}function Zl(){return`# Knowledge
|
|
189
189
|
|
|
190
190
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
191
191
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -202,7 +202,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
202
202
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
203
203
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
204
204
|
any merge conflict in it as noise (either side converges on the next run).
|
|
205
|
-
`}function
|
|
205
|
+
`}function eu(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
206
206
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
207
207
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
208
208
|
#
|
|
@@ -218,7 +218,7 @@ any merge conflict in it as noise (either side converges on the next run).
|
|
|
218
218
|
# - name: test
|
|
219
219
|
# run: npm test
|
|
220
220
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
221
|
-
`}function
|
|
221
|
+
`}function tu(t,e){return`# ${e.name}
|
|
222
222
|
|
|
223
223
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
224
224
|
|
|
@@ -244,7 +244,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
244
244
|
pipeline \u2014 don't edit them by hand.
|
|
245
245
|
|
|
246
246
|
Automation level: **${t.automationLevel}**.
|
|
247
|
-
`}function
|
|
247
|
+
`}function ru(t,e,r){let o=e?`
|
|
248
248
|
tracker_url: ${e}`:`
|
|
249
249
|
# tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
|
|
250
250
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -302,7 +302,7 @@ branch:
|
|
|
302
302
|
|
|
303
303
|
repos:
|
|
304
304
|
${s}
|
|
305
|
-
`}function
|
|
305
|
+
`}function ou(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
306
306
|
automation:
|
|
307
307
|
level: ${t}
|
|
308
308
|
|
|
@@ -417,21 +417,21 @@ parallelism:
|
|
|
417
417
|
# # the previous task's branch (auto-merge without reworking the
|
|
418
418
|
# # tail of the chain).
|
|
419
419
|
# mode: parallel
|
|
420
|
-
`}function
|
|
421
|
-
`)}async function
|
|
422
|
-
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function $u(t,e,r){return new Promise((o,n)=>{let i=Le.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 wi(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Ao(t,e,r){return new Promise(o=>{let n=Le.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 xu(t){try{let e=await fetch(t);return e.ok?new wi(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function vi(t,e=443,r=bi){let o=`${t}:${e}`,n=yi.get(o);if(n)return n;let i=vu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return yi.set(o,i),i}async function vu(t,e,r){if(!ki)return!1;let o=8e3;if(await Ao(t,e,o))return!0;let n=await $u(t,e,o),i=Le.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=bu(n);if(!c)break;let l=await xu(c);if(!l)break;if(s.push(l.toString()),Le.setDefaultCACertificates([...i,...s]),await Ao(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 Ao(t,e,o)}function rt(){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){$i();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(xi(s)&&await vi(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Si=t=>new Promise(e=>setTimeout(e,t));function Su(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Cu(){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 Ri(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Cu(),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&&Su(l.status,p)){await Si(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<n){await Si(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function De(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 Ii(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 Ci=new Map;async function Tu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ci.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 Ci.set(o,c.id),c.id}async function Pi(t,e,r){let o=await Tu(t,e,r);await Ri(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 Ei(t,e,r){return await(await Ri(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ti=new Map;async function Ru(t,e){let r=Ti.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 Ti.set(e,i.id),i.id}async function ji(t,e,r,o,n){let i=await Ru(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 Ai(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 _i="attachments(id,name,url,size,mimeType)",Iu="links(direction,linkType(name),issues(idReadable))",Oi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${_i},${Iu}`,Pu=`id,text,created,author(login),${_i}`;function Ni(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 Ui(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 Li(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=${Oi}&$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(Gi)}async function Di(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Oi}`,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 Gi(await o.json())}async function Bi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Pu}&$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=Ni(s.attachments);return c&&(a.attachments=c),a})}function Eu(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 Gi(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=Ni(t.attachments);s&&(i.attachments=s);let a=Eu(t.links);return a&&(i.links=a),i}function pe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Mi(t,e){let r=G(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await De({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:pe(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await _e(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:pe(c)}),n.push({kind:"github",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Oe(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:pe(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Ne(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:pe(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let p of e?.repos??[])if(p.host==="github")try{await Pr(c,p.owner,p.repoName),o.push({name:`repo:${p.name}`,ok:!0})}catch(m){o.push({name:`repo:${p.name}`,ok:!1,detail:pe(m)})}let l=e?.contextRepo;if(l?.host==="github")try{await Pr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(p){o.push({name:"context-repo",ok:!1,detail:pe(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Pr(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:pe(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=dt(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await _o(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function _o(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)}}function Ht(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 Ft(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 Kt(t,e=process.env){if(!t)return!1;let r=`https://${Je}:${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}function Oo(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Hi(t,e=process.env){return Oo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Ht(t,e),e)}function Fi(t,e=process.env){return Oo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Ft(t,e),e)}function Ki(t,e=process.env){return Oo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Je}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Kt(t,e),e)}function Wi(t){let e=G(t);if(!e)return null;if(!e.sealKey){let r=Er();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ue(e.sealKey.publicKey)}}async function qi(t,e,r,o){let n;try{n=JSON.parse(Ar(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=G(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await _e(n.token);return i.github={token:n.token},kt(i,()=>{process.env.GH_TOKEN=n.token,Hi(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Ne(n.token);return i.gitlab={token:n.token},kt(i,()=>{process.env.GITLAB_TOKEN=n.token,Fi(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Oe(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},kt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Ki(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await De({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},kt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await _o(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},kt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},kt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function kt(t,e){V(t),e()}import{existsSync as ju,readFileSync as Au,writeFileSync as _u}from"node:fs";import{join as Ou}from"node:path";import{parseDocument as Nu}from"yaml";var Yi=64;async function Vi(t,e){if(!Number.isInteger(e)||e<1||e>Yi)throw new Error(`maxJobs must be an integer in [1, ${Yi}], got ${e}`);let r=Ou(t,"regimen.yaml");if(!ju(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=Nu(Au(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),_u(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Ji,readFileSync as zi,writeFileSync as Uu}from"node:fs";import{join as No}from"node:path";import{parseDocument as Xi}from"yaml";async function Qi(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=No(t,"project.yaml");if(!Ji(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Xi(zi(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=No(t,"regimen.yaml");if(!Ji(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Xi(zi(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)Uu(No(t,i.path),i.content);return{files:r.map(i=>i.path)}}var Zi=t=>console.log(t);function es(t){Zi=t}function Wt(t,e="info"){Zi(t,e)}import{homedir as Lu}from"node:os";import{existsSync as Du,mkdirSync as Bu}from"node:fs";import{join as Uo}from"node:path";import{simpleGit as ts}from"simple-git";function Yt(t,e,r){let o=r??Uo(Lu(),".codepipe","repos");return Uo(o,t,e)}async function _r(t,e,r={}){let o=Yt(t,e.name,r.baseDir),n=r.cloneUrlOverride??Gu(e);if(!Du(Uo(o,".git"))){Bu(o,{recursive:!0});let a=ts();Wt(`[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}
|
|
423
|
-
${l.trim()}`)}}let i=
|
|
424
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function qt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var
|
|
425
|
-
${v.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),x=m?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(x),await t.push([o,"--delete",n]).catch(()=>{}),{commit:y}}async function is(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await os(t,i,()=>Or(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 ss(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 Gu(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 Nr=new Map;async function Lo(t,e){let o=(Nr.get(t)??Promise.resolve()).catch(()=>{}).then(e);Nr.set(t,o);try{return await o}finally{Nr.get(t)===o&&Nr.delete(t)}}async function as(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;Wt(`[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 Lo(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Yt(i,r.name,t.baseDir),{commit:c}=await ns(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 Lo(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Yt(i,r.name,t.baseDir),{commit:c,pushed:l}=await is(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=Ce(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=Ce(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=Ce(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 Lo(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Yt(i,r.name,t.baseDir),{mergedSha:c}=await ss(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=rt();return i?t.trackerIssueId?(await Pi(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=rt();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 Ei(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=rt();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 ji(i,e.projectKey,e.title,e.body,e.targetStatus);return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=rt();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ai(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 Vi(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 Qi(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 Mu from"ws";function Ur(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Mu(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function bt(t,e,r){return ot(t,e,"/projects",r)}async function cs(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ls(t,e,r,o){return ot(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Lr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function us(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Vt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ps(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 Vt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ds(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function fs(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function ms(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 A(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function gs(t,e,r,o){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function hs(t,e,r,o,n){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function ys(t,e,r,o,n){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ws(t,e,r,o,n){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Dr(t,e,r,o){return ot(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 A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function ot(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 A(n.status,s,a)}return s}var Br=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=Ce(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 tt){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=Ce(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=Hu(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function Hu(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Gr=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=rt();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 Li(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 ks(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 ks(r,u,e.sinceMs,this.log);if(d&&i.push({issueId:u,comments:d}),e.requireAssignee){let g=await Ku(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 Ui(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=Fu(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 Fu(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 Ku(t,e,r){try{return await Di(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function ks(t,e,r,o){try{return await Bi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Do="npm i -g @code-partner/codepipe@latest";function Mr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ae} (protocol ${me})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Xn(n.contextDir,r);let i=bs("CLI_TRACKING_POLL_INTERVAL_SEC"),s=bs("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=Ur(t.hubUrl,t.cliToken),g=null,y=new Br(i,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),x=new Gr(s,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),S=null,v=async()=>{try{let C;try{let k=await te(t.hubUrl,t.cliToken,t.projectId);C={repos:k.repos,contextRepo:k.contextRepo}}catch(k){r.warn(`[readiness] could not fetch project summary for push checks: ${k instanceof Error?k.message:String(k)}`)}let h=await Mi(t.projectId,C);if(d.readyState!==d.OPEN)return;let f={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,creds:h.creds,checkedAt:h.checkedAt};if(d.send(JSON.stringify(f)),h.ready)r.info("[readiness] ready");else{let k=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${k.join(", ")}`)}}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},R=()=>{v(),S=setInterval(()=>void v(),a),typeof S.unref=="function"&&S.unref()},_=()=>{S&&(clearInterval(S),S=null)},U=n?.contextDir?new Cr(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=Yn(t.projectId),h=O("ORIGIN")==="farm"?"farm":"local",f=O("FARM_ID"),k=t.accountEmail??C.email,$;try{let j=Wi(t.projectId);j&&($=j.publicKey,r.info(`[cred-channel] key fingerprint: ${j.fingerprint}`))}catch(j){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${j instanceof Error?j.message:String(j)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ae,protocolVersion:me,accountId:C.accountId,accountLabel:C.label,origin:h,inFlightActionIds:[...p],...k?{accountEmail:k}:{},...h==="farm"&&f?{farmId:f}:{},...$?{sealPublicKey:$}:{}};d.send(JSON.stringify(w))}),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 k=f.type;if(k==="registered"){let w=f;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),o({kind:"registered",projectId:w.projectId??t.projectId}),y.start(),U?.start(),R(),n?.contextDir){let j=n.contextDir;try{let I=Ir(j,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let L;try{L=(await te(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let ne=await ui(j,t.projectId,L,r);d.readyState===d.OPEN&&d.send(JSON.stringify(ne))}catch(L){r.warn(`[ctx] context migration failed (non-fatal): ${L instanceof Error?L.message:String(L)}`)}})()))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),o({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(k==="hello"){let w=f;g=fr(w.protocolVersion);let j=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${j}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ae}, protocol ${me}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Do}`),o({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Do}));return}if(k==="tracking_targets"){y.setTargets(f.targets);return}if(k==="youtrack_sync_request"){x.setRequest(f);return}if(k==="sync_local"){await qu(f,n,d,r);return}if(k==="context_write"){await Yu(f,n,d,r);return}if(k==="adr_promote"){await Vu(f,n,d,r);return}if(k==="cred_update"){let w=f,j=G(t.projectId),I=j?.sealKey?await qi(t.projectId,w.kind,w.sealed,j.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},L={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(L)),I.ok?(r.info(`[cred] ${w.kind} replaced${I.detail?` \u2014 ${I.detail}`:""}`),v()):r.warn(`[cred] ${w.kind} replacement rejected: ${I.detail??"unknown"}`);return}if(k==="sandbox_keys"){let w=G(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let j=dt(t.projectId),I=gi(f,w,j,r);for(let L of I)d.readyState===d.OPEN&&d.send(JSON.stringify(L));return}if(k!=="dispatch_action")return;let $=f;if(g===!1){let w=`refused: HUB protocol incompatible with CLI v${ae} (protocol ${me})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:w})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Do}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:w});return}p.add($.actionId);try{let w=await as({action:$.action,repo:$.repo,trackerIssueId:$.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0}).catch(L=>({status:"failed",error:L instanceof Error?L.message:String(L)}));d.send(JSON.stringify({type:"action_result",actionId:$.actionId,...w}));let j=w.status!=="failed",I=!j&&"error"in w?w.error:void 0;j?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${I??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:j,...I?{error:I}:{}})}finally{p.delete($.actionId)}}),d.on("close",(C,h)=>{let f=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${f?` reason=${f}`:""}`),y.stop(),x.stop(),U?.stop(),_(),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 qu(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=Wu(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await Vn(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 Yu(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 Rr(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 Vu(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 oi(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 bs(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Rs,mkdirSync as Is}from"node:fs";import{dirname as Ps}from"node:path";import{simpleGit as $t}from"simple-git";import{execFileSync as Ju}from"node:child_process";import{mkdtempSync as zu,mkdirSync as Xu,readFileSync as $s,rmSync as Qu,writeFileSync as Zu}from"node:fs";import{tmpdir as ep}from"node:os";import{dirname as tp,join as xs}from"node:path";function vs(t="codepipe-context"){let e=zu(xs(ep(),"codepipe-ssh-")),r=xs(e,"id_ed25519");try{return Ju("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:$s(r,"utf-8"),publicKey:$s(`${r}.pub`,"utf-8").trim()}}finally{Qu(e,{recursive:!0,force:!0})}}async function Ss(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 Cs(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 Ts(t,e){Xu(tp(t),{recursive:!0});let r=e.endsWith(`
|
|
420
|
+
`}function uu(t){return`codepipe/context-migration-v${t}`}function pu(t){let e=vn(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 \`${xe}\` 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 di(t,e,r,o){let n=Eo(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ir(t,e);if(!i.outdated)return i;let s=uu(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 du(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=Ce(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 f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:pu(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.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 du(t,e,r,o,n,i,s){let a=Eo(t),c=su(Po(cu(),"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`},f=new Map(yt(l,p).map(g=>[g.path,g.content])),u=0;for(let g of o.missingPaths){if(g===xe)continue;let w=f.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let S=Po(c,g);nu(S)||(iu(lu(S),{recursive:!0}),pi(S,w),u++)}pi(Po(c,xe),mr(o.currentVersion)),u++;let d=Eo(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(()=>{}),au(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as fu,createDecipheriv as mu,createHash as gu,createPrivateKey as hu,createPublicKey as jo,diffieHellman as fi,generateKeyPairSync as mi,hkdfSync as gi,randomBytes as wu}from"node:crypto";var hi=Buffer.from("devpipe-sealedbox-v1","utf-8");function Er(){let{publicKey:t,privateKey:e}=mi("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Le(t){let e=Buffer.from(t,"base64");return(gu("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function jr(t,e){let r=jo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=mi("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=fi({privateKey:n,publicKey:r}),c=Buffer.from(gi("sha256",a,Buffer.concat([i,s]),hi,32)),l=wu(12),p=fu("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(f),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 Ar(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=hu({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=jo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=jo(o).export({type:"spki",format:"der"}),a=fi({privateKey:o,publicKey:n}),c=Buffer.from(gi("sha256",a,Buffer.concat([i,s]),hi,32)),l=mu("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 yu(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 wi(t,e,r,o){let n=yu(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=$r(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=jr(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{X509Certificate as ki}from"node:crypto";import{readFileSync as bu}from"node:fs";import De from"node:tls";var $i=typeof De.getCACertificates=="function"&&typeof De.setDefaultCACertificates=="function",yi=!1,bi=new Map,xi=t=>console.warn(t);function ku(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function vi(t=xi){if(yi)return;yi=!0;let e=O("EXTRA_CA_FILE");if(!(!e||!$i))try{let r=ku(bu(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}De.setDefaultCACertificates([...De.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 Si(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 $u(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
422
|
+
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function xu(t,e,r){return new Promise((o,n)=>{let i=De.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 ki(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Ao(t,e,r){return new Promise(o=>{let n=De.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 vu(t){try{let e=await fetch(t);return e.ok?new ki(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ci(t,e=443,r=xi){let o=`${t}:${e}`,n=bi.get(o);if(n)return n;let i=Su(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return bi.set(o,i),i}async function Su(t,e,r){if(!$i)return!1;let o=8e3;if(await Ao(t,e,o))return!0;let n=await xu(t,e,o),i=De.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=$u(n);if(!c)break;let l=await vu(c);if(!l)break;if(s.push(l.toString()),De.setDefaultCACertificates([...i,...s]),await Ao(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 Ao(t,e,o)}function rt(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function be(t,e,r){vi();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(Si(s)&&await Ci(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ri=t=>new Promise(e=>setTimeout(e,t));function Cu(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Ru(){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 Pi(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Ru(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await be(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&&Cu(l.status,p)){await Ri(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<n){await Ri(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Be(t){let e;try{e=await be(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 Ei(t){try{let e=await be(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ti=new Map;async function Tu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ti.get(o);if(n)return n;let i=await be(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 Ti.set(o,c.id),c.id}async function ji(t,e,r){let o=await Tu(t,e,r);await Pi(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 Ai(t,e,r){return await(await Pi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ii=new Map;async function Iu(t,e){let r=Ii.get(e);if(r)return r;let o=await be(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 Ii.set(e,i.id),i.id}async function _i(t,e,r,o,n){let i=await Iu(t,e),s=await be(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 Oi(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await be(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 Ni="attachments(id,name,url,size,mimeType)",Pu="links(direction,linkType(name),issues(idReadable))",Ui=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ni},${Pu}`,Eu=`id,text,created,author(login),${Ni}`;function Li(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 Di(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 Bi(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=${Ui}&$top=200`,i=await be(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Hi)}async function Gi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Ui}`,o=await be(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Hi(await o.json())}async function Mi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Eu}&$top=500`,n=await be(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=Li(s.attachments);return c&&(a.attachments=c),a})}function ju(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 Hi(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=Li(t.attachments);s&&(i.attachments=s);let a=ju(t.links);return a&&(i.links=a),i}function de(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Fi(t,e){let r=G(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Be({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:de(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:de(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await Oe(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:de(c)}),n.push({kind:"github",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Ne(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:de(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Ue(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:de(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let p of e?.repos??[])if(p.host==="github")try{await Pr(c,p.owner,p.repoName),o.push({name:`repo:${p.name}`,ok:!0})}catch(f){o.push({name:`repo:${p.name}`,ok:!1,detail:de(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Pr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(p){o.push({name:"context-repo",ok:!1,detail:de(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Pr(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:de(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=dt(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await _o(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function _o(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)}}function Ht(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 Ft(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 Kt(t,e=process.env){if(!t)return!1;let r=`https://${ze}:${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}function Oo(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Ki(t,e=process.env){return Oo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Ht(t,e),e)}function Wi(t,e=process.env){return Oo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Ft(t,e),e)}function qi(t,e=process.env){return Oo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ze}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Kt(t,e),e)}function Yi(t){let e=G(t);if(!e)return null;if(!e.sealKey){let r=Er();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Le(e.sealKey.publicKey)}}async function Vi(t,e,r,o){let n;try{n=JSON.parse(Ar(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=G(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Oe(n.token);return i.github={token:n.token},bt(i,()=>{process.env.GH_TOKEN=n.token,Ki(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Ue(n.token);return i.gitlab={token:n.token},bt(i,()=>{process.env.GITLAB_TOKEN=n.token,Wi(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Ne(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},bt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,qi(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Be({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},bt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await _o(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},bt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},bt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function bt(t,e){z(t),e()}import{existsSync as Au,readFileSync as _u,writeFileSync as Ou}from"node:fs";import{join as Nu}from"node:path";import{parseDocument as Uu}from"yaml";var zi=64;async function Ji(t,e){if(!Number.isInteger(e)||e<1||e>zi)throw new Error(`maxJobs must be an integer in [1, ${zi}], got ${e}`);let r=Nu(t,"regimen.yaml");if(!Au(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=Uu(_u(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Ou(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Xi,readFileSync as Qi,writeFileSync as Lu}from"node:fs";import{join as No}from"node:path";import{parseDocument as Zi}from"yaml";async function es(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=No(t,"project.yaml");if(!Xi(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=Zi(Qi(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=No(t,"regimen.yaml");if(!Xi(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=Zi(Qi(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)Lu(No(t,i.path),i.content);return{files:r.map(i=>i.path)}}var ts=t=>console.log(t);function rs(t){ts=t}function Wt(t,e="info"){ts(t,e)}import{homedir as Du}from"node:os";import{existsSync as Bu,mkdirSync as Gu}from"node:fs";import{join as Uo}from"node:path";import{simpleGit as os}from"simple-git";function Yt(t,e,r){let o=r??Uo(Du(),".codepipe","repos");return Uo(o,t,e)}async function _r(t,e,r={}){let o=Yt(t,e.name,r.baseDir),n=r.cloneUrlOverride??Mu(e);if(!Bu(Uo(o,".git"))){Gu(o,{recursive:!0});let a=os();Wt(`[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}
|
|
423
|
+
${l.trim()}`)}}let i=os(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
|
|
424
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function qt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ns=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Or(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&&Wt(`[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 qt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await qt(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([...ns,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function is(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await qt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await qt(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 ss(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:f}=r,u=await is(t,i,()=>Or(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await qt(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([...ns,"cherry-pick",u])}catch(x){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=x instanceof Error?x.message:String(x);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
425
|
+
${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([o,"--delete",n]).catch(()=>{}),{commit:w}}async function as(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await is(t,i,()=>Or(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 cs(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 Mu(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 Nr=new Map;async function Lo(t,e){let o=(Nr.get(t)??Promise.resolve()).catch(()=>{}).then(e);Nr.set(t,o);try{return await o}finally{Nr.get(t)===o&&Nr.delete(t)}}async function ls(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;Wt(`[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 Lo(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Yt(i,r.name,t.baseDir),{commit:c}=await ss(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return te({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Lo(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Yt(i,r.name,t.baseDir),{commit:c,pushed:l}=await as(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return te({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return F("no repo spec");let i=Ce(r),s=await i.createPullRequest(r,e);return te({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=Ce(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return te({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=Ce(r);return await i.closePR(r,e.prNumber,e.comment),te({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Lo(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Yt(i,r.name,t.baseDir),{mergedSha:c}=await cs(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return te({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return te({stub:!0});case"tracker_status":{let i=rt();return i?t.trackerIssueId?(await ji(i,t.trackerIssueId,e.newStatus),te({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=rt();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 Ai(i,t.trackerIssueId,e.body);return te({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=rt();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 _i(i,e.projectKey,e.title,e.body,e.targetStatus);return te({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=rt();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Oi(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 te({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await Ji(t.contextDir,e.maxJobs);return te({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 es(t.contextDir,e);return te({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),te({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function te(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import Hu from"ws";function Ur(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Hu(r)}var _=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function kt(t,e,r){return ot(t,e,"/projects",r)}async function us(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new _(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function ps(t,e,r,o){return ot(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Lr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new _(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function ds(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new _(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Vt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function fs(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 Vt(e)}if(!r.ok)throw new _(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ms(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new _(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function gs(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new _(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function hs(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 _(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function ws(t,e,r,o){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function ys(t,e,r,o,n){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function bs(t,e,r,o,n){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ks(t,e,r,o,n){return ot(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Dr(t,e,r,o){return ot(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function re(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new _(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function ot(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 _(n.status,s,a)}return s}var Br=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=Ce(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 tt){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=Ce(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=Fu(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function Fu(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Gr=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=rt();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 Bi(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 $s(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 $s(r,u,e.sinceMs,this.log);if(d&&i.push({issueId:u,comments:d}),e.requireAssignee){let g=await Wu(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),f=c.reduce((u,d)=>u+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=[],l=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let u;try{u=await Di(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=Ku(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(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function Ku(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 Wu(t,e,r){try{return await Gi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function $s(t,e,r,o){try{return await Mi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Do="npm i -g @code-partner/codepipe@latest";function Mr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ce} (protocol ${ge})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Zn(n.contextDir,r);let i=xs("CLI_TRACKING_POLL_INTERVAL_SEC"),s=xs("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,f=u();function u(){let d=Ur(t.hubUrl,t.cliToken),g=null,w=new Br(i,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),S=new Gr(s,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),x=null,v=async()=>{try{let C;try{let k=await re(t.hubUrl,t.cliToken,t.projectId);C={repos:k.repos,contextRepo:k.contextRepo}}catch(k){r.warn(`[readiness] could not fetch project summary for push checks: ${k instanceof Error?k.message:String(k)}`)}let h=await Fi(t.projectId,C);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,creds:h.creds,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let k=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${k.join(", ")}`)}}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},A=()=>{v(),x=setInterval(()=>void v(),a),typeof x.unref=="function"&&x.unref()},T=()=>{x&&(clearInterval(x),x=null)},U=n?.contextDir?new Cr(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=zn(t.projectId),h=O("ORIGIN")==="farm"?"farm":"local",m=O("FARM_ID"),k=t.accountEmail??C.email,$;try{let j=Yi(t.projectId);j&&($=j.publicKey,r.info(`[cred-channel] key fingerprint: ${j.fingerprint}`))}catch(j){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${j instanceof Error?j.message:String(j)}`)}let b={type:"register",projectId:t.projectId,platformVersion:ce,protocolVersion:ge,accountId:C.accountId,accountLabel:C.label,origin:h,inFlightActionIds:[...p],...k?{accountEmail:k}:{},...h==="farm"&&m?{farmId:m}:{},...$?{sealPublicKey:$}:{}};d.send(JSON.stringify(b))}),d.on("message",async C=>{let h=C.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 k=m.type;if(k==="registered"){let b=m;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),o({kind:"registered",projectId:b.projectId??t.projectId}),w.start(),U?.start(),A(),n?.contextDir){let j=n.contextDir;try{let I=Ir(j,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.outdated&&(r.warn(`[ctx] context format outdated: v${I.templateVersion} \u2192 v${I.currentVersion}`+(I.missingPaths.length>0?` (missing: ${I.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let B;try{B=(await re(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let q=await di(j,t.projectId,B,r);d.readyState===d.OPEN&&d.send(JSON.stringify(q))}catch(B){r.warn(`[ctx] context migration failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}})()))}catch(I){r.warn(`[ctx] context-format detect failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),o({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,d.close();return}if(k==="hello"){let b=m;g=fr(b.protocolVersion);let j=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${j}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ce}, protocol ${ge}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Do}`),o({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:Do}));return}if(k==="tracking_targets"){w.setTargets(m.targets);return}if(k==="youtrack_sync_request"){S.setRequest(m);return}if(k==="sync_local"){await Yu(m,n,d,r);return}if(k==="context_write"){await Vu(m,n,d,r);return}if(k==="adr_promote"){await zu(m,n,d,r);return}if(k==="cred_update"){let b=m,j=G(t.projectId),I=j?.sealKey?await Vi(t.projectId,b.kind,b.sealed,j.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},B={type:"cred_update_result",updateId:b.updateId,projectId:t.projectId,ok:I.ok,...I.detail?{detail:I.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(B)),I.ok?(r.info(`[cred] ${b.kind} replaced${I.detail?` \u2014 ${I.detail}`:""}`),v()):r.warn(`[cred] ${b.kind} replacement rejected: ${I.detail??"unknown"}`);return}if(k==="sandbox_keys"){let b=G(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let j=dt(t.projectId),I=wi(m,b,j,r);for(let B of I)d.readyState===d.OPEN&&d.send(JSON.stringify(B));return}if(k!=="dispatch_action")return;let $=m;if(g===!1){let b=`refused: HUB protocol incompatible with CLI v${ce} (protocol ${ge})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:b})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${Do}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:b});return}p.add($.actionId);try{let b=await ls({action:$.action,repo:$.repo,trackerIssueId:$.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:$.actionId,...b}));let j=b.status!=="failed",I=!j&&"error"in b?b.error:void 0;j?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${I??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:j,...I?{error:I}:{}})}finally{p.delete($.actionId)}}),d.on("close",(C,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${m?` reason=${m}`:""}`),w.stop(),S.stop(),U?.stop(),T(),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:C}),!c&&setTimeout(()=>{f=u()},2e3)}),d.on("error",C=>r.warn(`[ws] error: ${C.message}`)),d}return{stop(){c=!0,f.close()}}}async function Yu(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=qu(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await Jn(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 Vu(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 Tr(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 zu(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 ii(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 xs(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ps,mkdirSync as Es}from"node:fs";import{dirname as js}from"node:path";import{simpleGit as $t}from"simple-git";import{execFileSync as Ju}from"node:child_process";import{mkdtempSync as Xu,mkdirSync as Qu,readFileSync as vs,rmSync as Zu,writeFileSync as ep}from"node:fs";import{tmpdir as tp}from"node:os";import{dirname as rp,join as Ss}from"node:path";function Cs(t="codepipe-context"){let e=Xu(Ss(tp(),"codepipe-ssh-")),r=Ss(e,"id_ed25519");try{return Ju("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:vs(r,"utf-8"),publicKey:vs(`${r}.pub`,"utf-8").trim()}}finally{Zu(e,{recursive:!0,force:!0})}}async function Rs(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 Ts(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 Is(t,e){Qu(rp(t),{recursive:!0});let r=e.endsWith(`
|
|
426
426
|
`)?e:e+`
|
|
427
|
-
`;return
|
|
428
|
-
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>
|
|
429
|
-
`,{mode:384})}import
|
|
430
|
-
`))!==-1;){let
|
|
431
|
-
`)){let
|
|
427
|
+
`;return ep(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function op(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 np(t,e){return e?.contextWrite?.token?{user:hr(t),secret:e.contextWrite.token}:t===Bt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Bt.bitbucket?e?.bitbucket?.apiToken?{user:ze,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Hr(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await re(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=np(ut(s.cloneUrl),r);if(a){let c=await ip({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 sp({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 ip(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=op(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(Ps(`${r}/.git`)){let l=$t(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=$o(r);await l.reset(["--hard",`origin/${s}`]),xo(r,p),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Es(js(r),{recursive:!0}),await $t().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await As(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 sp(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Is(i,o),a=Ts(e.cloneUrl),c=e.branch;try{if(Ps(`${r}/.git`)){let l=$t(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=$o(r);await l.reset(["--hard",`origin/${c}`]),xo(r,p),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Es(js(r),{recursive:!0}),await $t().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await $t(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await As(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 As(t){let e=$t(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"))}async function _s(t={profile:void 0}){let{cfg:e,profile:r}=kr(t.profile),o=G(e.projectId);o&&Gt(o),Ht(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ft(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Kt(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=zt(Bo(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=vr("CLI_LOG",i,n);if(s.enabled){let u=new mt(s);Sr(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=yr(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=zt(Bo(),".codepipe",r?zt("profiles",r,"context"):"context");if(a=await Hr({cfg:e,secrets:o,contextDir:u,log:{info:d=>console.log(d),warn:d=>console.warn(d)}}),a?.contextDir){let d=zt(Bo(),".codepipe",r?zt("profiles",r,"context-config"):"context-config");Rr(a.contextDir,d,{info:g=>console.log(g),warn:g=>console.warn(g)})}}let l=Mr(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 f(u){p||(p=!0,console.log(`
|
|
428
|
+
[${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as fp}from"node:os";import{spawnSync as ap}from"node:child_process";function cp(){try{return ap("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Os(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:cp(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as xt}from"node:os";import{mkdirSync as lp,readFileSync as Ns,writeFileSync as up,existsSync as Go}from"node:fs";import{dirname as pp,join as Ge}from"node:path";Go(".env")&&process.loadEnvFile(".env");function Me(t){let e=O("SANDBOX_CONFIG");if(e)return e;let r=Ge(xt(),".codepipe","worker");return t?Ge(r,"profiles",t,"config.json"):Ge(r,"config.json")}function Us(){return Ge(xt(),".devpipe-sandbox","config.json")}function Fr(){Je(Ge(xt(),".devpipe"),Ge(xt(),".codepipe")),O("SANDBOX_CONFIG")||Je(Ge(xt(),".devpipe-sandbox"),Ge(xt(),".codepipe-sandbox"))}function oe(t){let e=Me(t);return Go(e)?JSON.parse(Ns(e,"utf-8")):!t&&!O("SANDBOX_CONFIG")&&Go(Us())?JSON.parse(Ns(Us(),"utf-8")):null}function Ls(t,e){let r=Me(e);lp(pp(r),{recursive:!0}),up(r,JSON.stringify(t,null,2)+`
|
|
429
|
+
`,{mode:384})}import dp from"ws";var vt=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 dp(e)}};async function nt(t){Fr();let e=oe(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Me(t.profile)}.`),process.exit(1));let r=t.name??fp(),o=Os({projects:t.projects??[],llm:t.llm??null}),n=new vt(t.hub.replace(/\/$/,"")),i=Er(),s=Le(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Ls({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 ${Me(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 Zp,readFileSync as wa,readdirSync as ed,writeFileSync as td}from"node:fs";import{dirname as rd,join as Zr,resolve as od}from"node:path";import{spawn as mp}from"node:child_process";import{existsSync as gp}from"node:fs";var St=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Kr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},hp=5e3,Jt=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Kr;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=kp(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 S=w?.usage;S&&(a+=1,s.input+=ne(S.input_tokens),s.output+=ne(S.output_tokens),s.cacheRead+=ne(S.cache_read_input_tokens),s.cacheCreate+=ne(S.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,d=g=>{if(u)for(let w of xp(g,e.workspaceDir))try{u(w)}catch{}};return u?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let S=mp(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});S.stdout.setEncoding("utf-8"),S.stderr.setEncoding("utf-8");let x=!1,v=null,A=()=>{x=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),S.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},hp)};e.signal?.addEventListener("abort",A,{once:!0});let T=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",A)},U="";S.stdout.on("data",C=>{o.push(C),U+=C;let h;for(;(h=U.indexOf(`
|
|
430
|
+
`))!==-1;){let m=U.slice(0,h).trim();if(U=U.slice(h+1),m){let k=Ds(m);p(k),k&&d(k)}}}),S.stderr.on("data",C=>{o.push(C),n.push(C);for(let h of C.split(`
|
|
431
|
+
`)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),S.on("error",C=>{T(),w(C)}),S.on("close",C=>{if(T(),x){w(new Kr);return}if(U.trim()){let m=Ds(U.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(C!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,k=typeof i?.subtype=="string"?i.subtype:void 0,$=typeof i?.result=="string"?i.result:void 0;w(new St(wp(C,i,n.join("")),{code:C,apiErrorStatus:m,subtype:k,resultText:$,retryAfterMs:yp(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:$p(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("/")&&gp(o))}};function Ds(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: ${He(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=bp(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=Gs(n.content);console.log(`[claude] tool_result (error)${i?`: ${He(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)} ${He(JSON.stringify(e),200)}`),e}function wp(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(He(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(He(r.trim().split(`
|
|
432
432
|
`).slice(-5).join(`
|
|
433
|
-
`),500)),o.join(" \u2014 ")}function yp(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
|
|
434
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:gr()}}};function
|
|
433
|
+
`),500)),o.join(" \u2014 ")}function yp(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 Gs(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function bp(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=${He(r,80)}`}return""}function He(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ne(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function kp(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ne(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:ne(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 $p(t,e,r,o){let n=gr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=ne(i.input_tokens),n.outputTokens=ne(i.output_tokens),n.cacheReadInputTokens=ne(i.cache_read_input_tokens),n.cacheCreationInputTokens=ne(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=ne(t?.total_cost_usd),n.numTurns=t&&ne(t.num_turns)>0?ne(t.num_turns):r,n.durationMs=ne(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Bs=200;function xp(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:He(c,Bs)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,f=vp(p,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}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?He(Gs(s.content),Bs):"";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 vp(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 Sp,writeFileSync as Xt}from"node:fs";import{dirname as Cp,join as Qt}from"node:path";function Ms(t,e,r){let o=Qt(t,e);Sp(Cp(o),{recursive:!0}),Xt(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=Rp(o,n,i);Xt(Qt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Xt(Qt(e.workspaceDir,"SOLUTION.md"),Tp(o,n,i,a)),s.push("SOLUTION.md"),Xt(Qt(e.workspaceDir,"QUESTIONS.md"),Ip(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Ms(e.workspaceDir,"changes/sample.patch",Pp(o,n,a)),s.push("changes/sample.patch"),Ms(e.workspaceDir,"diff-summary.md",Ep(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Xt(Qt(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:gr()}}};function Rp(t,e,r){return`# ${t} \u2014 Estimate
|
|
435
435
|
|
|
436
436
|
**Title:** ${e}
|
|
437
437
|
|
|
@@ -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 Ip(t){return`# ${t} \u2014 Open questions
|
|
485
485
|
|
|
486
486
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
487
|
-
`}function
|
|
487
|
+
`}function Pp(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 Ep(t,e,r){return`# ${t} \u2014 Diff summary
|
|
499
499
|
|
|
500
500
|
**Title:** ${e}
|
|
501
501
|
${r?`
|
|
@@ -506,78 +506,82 @@ ${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 Hs(t){switch(t){case"mock":return new Zt;case"claude-headless":return new Jt;default:return null}}function Ws(t=process.env){return{maxAttempts:Wr(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Wr(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Wr(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Wr(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var jp=new Set([429,500,502,503,529]),Fs=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,Ap=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,_p=new Set(["error_max_turns"]);function Op(t){if(t instanceof St){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return Ap.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&_p.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:jp.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Fs.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 Fs.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Ks=/(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 qs(t){if(t instanceof St){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Ks.test(o)}let e=t instanceof Error?t.message:String(t);return Ks.test(e)}function Np(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 Ys(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=Op(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=Np(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 Wr(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as Up,rmSync as Lp,writeFileSync as Vs}from"node:fs";import{tmpdir as Dp}from"node:os";import{join as Mo}from"node:path";function qr(t){return`[url "https://${t}/"]
|
|
510
510
|
insteadOf = git@${t}:
|
|
511
511
|
insteadOf = ssh://git@${t}/
|
|
512
|
-
`}var
|
|
512
|
+
`}var Bp=qr("github.com"),Gp=qr("bitbucket.org"),Mp=qr("gitlab.com");function zs(t,e){if(t.length===0)return null;let r=Up(Mo(Dp(),"devpipe-gitcreds-")),o=Mo(r,"credentials"),n=Mo(r,"gitconfig");return Vs(o,t.join(`
|
|
513
513
|
`)+`
|
|
514
|
-
`,{mode:384}),
|
|
514
|
+
`,{mode:384}),Vs(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(l=>l.trim()).filter(l=>l.length>0),c=await ke(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 J(t,e,r){return new Promise((o,n)=>{let i=
|
|
518
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function ke(t,e,r){return new Promise((o,n)=>{let i=
|
|
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-Wo).toString("utf-8")}import{lstatSync as
|
|
516
|
+
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{Lp(r,{recursive:!0,force:!0})}catch{}}}}function Ho(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Bp)),t.bitbucket?.apiToken&&(e.push(`https://${ze}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Gp)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Mp)),zs(e,r)}function Js(t,e){if(t.contextWrite?.token){let r=ut(e)??"github.com",o=hr(r);return zs([`https://${o}:${t.contextWrite.token}@${r}`],[qr(r)])}return Ho(t)}import{spawn as Qs}from"node:child_process";import{existsSync as Yr,mkdirSync as Vr,readFileSync as Hp,rmSync as Fo,symlinkSync as Fp}from"node:fs";import{homedir as Kp}from"node:os";import{dirname as zr,join as it}from"node:path";function Zs(){return it(Kp(),".codepipe-sandbox","repos")}function Xs(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 ea(t,e,r,o,n){if(Yr(it(t,".git"))){let i=async s=>{await J(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await J(t,["reset","--hard",`origin/${s}`],n),await J(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!Xs(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Yr(t)&&Fo(t,{recursive:!0,force:!0}),Vr(zr(t),{recursive:!0});try{return await J(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!Xs(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Yr(t)&&Fo(t,{recursive:!0,force:!0}),Vr(zr(t),{recursive:!0}),await J(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function ta(t){await J(t.workspacePath,["reset","--hard",t.baseSha]),await J(t.workspacePath,["clean","-fdx"])}var Jr="CodePipe Agent",Xr="codepipe@codepartner.ee";async function ra(t,e){let r=t.workspacePath;await J(r,["add","-A"]);let o=(await ke(r,["write-tree"])).trim(),n=(await ke(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Jr,GIT_AUTHOR_EMAIL:Xr,GIT_COMMITTER_NAME:Jr,GIT_COMMITTER_EMAIL:Xr};return(await ke(r,["commit-tree",o,"-m",e],i)).trim()}async function oa(t,e,r,o,n){try{await J(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw ut(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 na(t,e){return ke(t.workspacePath,["diff","--binary",t.baseSha,e])}async function ia(t,e,r,o,n){await J(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await J(t.workspacePath,["checkout","--force",r])}async function Ko(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Jr,GIT_AUTHOR_EMAIL:Xr,GIT_COMMITTER_NAME:Jr,GIT_COMMITTER_EMAIL:Xr};(await ke(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await J(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 J(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await J(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await ke(o,["diff","--name-only","--diff-filter=U"])).split(`
|
|
517
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await ke(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 J(t,e,r){return new Promise((o,n)=>{let i=Qs("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 ke(t,e,r){return new Promise((o,n)=>{let i=Qs("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 sa(t,e){Yr(t)&&Fo(t,{recursive:!0,force:!0}),Vr(zr(t),{recursive:!0}),Fp(e,t,"dir")}async function aa(t,e,r){await J(t,["worktree","prune"]).catch(()=>{}),Vr(zr(r),{recursive:!0}),await J(t,["worktree","add","--detach",r,`origin/${e}`])}async function ca(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=it(Zs(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await ea(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await ke(a,["rev-parse","HEAD"])).trim(),p=it(t,"code",s.name);o==="direct"?(sa(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await aa(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 la(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=it(Zs(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await ea(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=it(t,"context");o==="direct"?(sa(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await aa(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await ke(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function ua(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await J(r,["add","-A",...o]).catch(()=>{});let n;try{n=await ke(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=Hp(it(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Wp}from"node:fs";import{join as qp}from"node:path";var Wo=8*1024,Ct=class extends Error{},er="meta/build-result.json";function pa(t){let e=qp(t,er),r;try{r=Wp(e,"utf-8")}catch{throw new Ct(`BUILD produced no ${er} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new Ct(`${er} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new Ct(`${er} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Ct(`${er}: "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 f=p,u=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(u===null||d===null)return[];let g={name:u,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?Yp(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(f=>f.exitCode!==0);p&&(l.failedStep=p.name)}return l}function Yp(t){let e=Buffer.from(t,"utf-8");return e.length<=Wo?t:`\u2026 [${e.length-Wo} bytes elided] \u2026
|
|
521
|
+
`+e.subarray(e.length-Wo).toString("utf-8")}import{lstatSync as Vp,mkdtempSync as zp,readFileSync as Jp,readdirSync as fa,rmSync as da}from"node:fs";import{tmpdir as Xp}from"node:os";import{join as Qr,relative as Qp}from"node:path";var ma=new Set(["code","context"]);function ga(t){let e=zp(Qr(Xp(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>da(e,{recursive:!0,force:!0}),listFiles:()=>ha(e,e),readFile:r=>Jp(Qr(e,r),"utf-8"),clean:()=>{for(let r of fa(e))ma.has(r)||da(Qr(e,r),{recursive:!0,force:!0})}}}function ha(t,e){let r=[];for(let o of fa(e)){let n=Qr(e,o),i=Vp(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&ma.has(o))continue;r.push(...ha(t,n))}else r.push(Qp(t,n))}return r}var eo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),nd=new Set(["implement","resolve-conflict"]);function id(t){let e=Buffer.from(t,"utf-8");if(e.length<=eo)return t;let r=Math.floor(eo/4),o=eo-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
523
|
\u2026 [${s} bytes elided \u2014 log capped at ${eo} bytes for upload] \u2026
|
|
524
524
|
|
|
525
|
-
${i}`}async function tr(t={}){Fr();let e=
|
|
525
|
+
${i}`}async function tr(t={}){Fr();let e=oe(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=vr("SANDBOX_LOG","sandbox",od("./logs"));if(o.enabled){let h=new mt(o);Sr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${ce} (protocol ${ge})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Hs(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Ws();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new vt(e.hubUrl,e.token),a=!1,c=new AbortController,l=null,p=null,f=!1,u=null,d=null,g=!1,w=()=>{let h=s.openControlSocket();return u=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ce,protocolVersion:ge};h.send(JSON.stringify(m))}),h.on("message",m=>{let k=m.toString("utf-8"),$=null;try{let b=JSON.parse(k);b&&typeof b=="object"&&($=b)}catch{}if($&&$.type==="hello"){let b=$;d=fr(b.protocolVersion);let j=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${j}`),d&&(g=!1);return}if($&&$.type==="pause_job"){let b=typeof $.jobId=="string"?$.jobId:"";b&&b===l?(console.warn(`[ws] pause_job ${b} \u2014 aborting agent`),f=!0,p?.abort()):console.log(`[ws] pause_job ${b} \u2014 not the active job, ignoring`),b&&h.send(JSON.stringify({type:"job_paused",jobId:b}));return}console.log(`[ws] ${k}`)}),h.on("close",(m,k)=>{console.log(`[ws] closed code=${m} reason=${k?.toString()||""}`),u===h&&(u=null),!a&&setTimeout(w,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},S=w(),x=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ce}, protocol ${ge}) \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(k=>setTimeout(k,5e3));continue}let m=await h.json();await v(s,m)}catch(h){if(c.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function v(h,m){l=m.jobId,p=new AbortController,f=!1;let k=!1,$=null,b=null,j=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),I=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let pe=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} heartbeat error: ${pe}`)}};I();let B=setInterval(()=>{I()},j),q=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(T(m.prompt," \u2502 "));let se=[],Te=null,lo=400,R=25,ae=500,fe=()=>{if(Te&&(clearTimeout(Te),Te=null),se.length===0)return;let L=se.splice(0,se.length),pe=u;if(!pe||pe.readyState!==pe.OPEN)return;let Pe={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:L};try{pe.send(JSON.stringify(Pe))}catch{}},qe=L=>{se.push(L),se.length>ae&&se.shift(),se.length>=R?fe():Te||(Te=setTimeout(fe,lo))},pr=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Ie=new Set,Y=null;try{if(!n){k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:q,finishedAt:new Date().toISOString()});return}let L=ga(m.jobId);console.log(`[job] ${m.jobId} workspace=${L.dir}`);let pe=A(m,r);$=pe.gitCreds,b=pe.contextGitCreds;let Pe=$?.env,fn=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,Ee=[],dr=null,uo=null;try{let P="worktree";Ee=await ca(L.dir,m.projectId,m.projectRepos,P,Pe);let E=await la(L.dir,m.projectId,m.contextRepo,P,Pe);uo=E,dr=E?.workspacePath??null}catch(P){let E=P instanceof Error?P.message:String(P);console.warn(`[job] ${m.jobId} materialize failed: ${E}`),k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${E}`},startedAt:q,finishedAt:new Date().toISOString()}),L.dispose();return}let mn=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let P=m.contextRepo?.cloneUrl;if(!P||!Pe)throw new Error(P?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let E of m.deliveries){let H=Ee.find(ie=>ie.name===E.name);H&&(await ia(H,E.deliveryRef,E.deliverySha,P,Pe),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${E.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await mn()}catch(P){let E=P instanceof Error?P.message:String(P);console.warn(`[job] ${m.jobId} delivery checkout failed: ${E}`),k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${E}`},startedAt:q,finishedAt:new Date().toISOString()}),L.dispose();return}let gn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},hn="";if(m.role==="resolve-conflict")try{let P=[];for(let E of Ee){let H=gn[E.name];if(!H)continue;let ie=await Ko(E,H,Pe);console.log(`[job] ${m.jobId} ${E.name}: merged ${H} into ${E.ref} \u2014 ${ie.length} conflicted file(s)`),ie.length>0?P.push(`- **${E.name}**:`,...ie.map(lt=>` - \`${lt}\``)):P.push(`- **${E.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}hn=`
|
|
526
526
|
|
|
527
527
|
## Conflicts to resolve
|
|
528
528
|
|
|
529
529
|
`+(P.length>0?P.join(`
|
|
530
530
|
`):"(no task branches to merge)")+`
|
|
531
|
-
`}catch(P){let E=P instanceof Error?P.message:String(P);console.warn(`[job] ${
|
|
532
|
-
`).map(k=>
|
|
533
|
-
`)}function U(h,
|
|
534
|
-
[${h}] shutting down`),c.abort();let f=new AbortController,k=setTimeout(()=>f.abort(),3e3);(async()=>{let $=l;if($)try{await s.releaseJob($,`sandbox ${h}`,f.signal),console.log(`[${h}] released job ${$}`)}catch(w){let j=w instanceof Error?w.message:String(w);console.warn(`[${h}] release failed: ${j} (sweeper will reclaim)`)}clearTimeout(k),x.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>C("SIGINT")),process.on("SIGTERM",()=>C("SIGTERM")),await S()}async function ha(t={profile:void 0}){let e=je(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ur(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 Pt,mkdirSync as Da,readFileSync as Ba,readdirSync as Nd,writeFileSync as Ga}from"node:fs";import{join as st,resolve as Ma}from"node:path";import{setTimeout as Ud}from"node:timers/promises";import{cancel as Ld,confirm as Et,intro as Ha,isCancel as Qo,log as b,outro as zo,password as jt,select as at,spinner as Fa,text as K}from"@clack/prompts";import{simpleGit as oo}from"simple-git";async function Rt(t,e,r){return e.host==="github"?sd(t,e,r):e.host==="gitlab"?fd(t,e,r):gd(t,e,r)}async function ya(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 Fe(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await wa(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 He(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await ka(e.gitlabToken,t):n}}return e.bitbucket?(await Tt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await ba(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 wa(t,e){let r=!1;try{r=(await Fe(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 ka(t,e){let r=!1;try{r=(await He(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 ba(t,e){let r=!1;try{r=(await Tt(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 id="https://api.github.com";async function Fe(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(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?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function sd(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 ad(o,e,r),i=await ld(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=wt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await ud(o,n.owner,n.name,a.path,i)||await pd(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 ad(t,e,r){let o=await Fe(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 wa(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await cd(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 Fe(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 cd(t,e){let{status:r,data:o}=await Fe(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function ld(t,e,r){let{data:o}=await Fe(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function ud(t,e,r,o,n){let{status:i,data:s}=await Fe(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function pd(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 Fe(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var dd="https://gitlab.com/api/v4";async function He(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(dd+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 fd(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 He(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 ka(o,e)} (attach joins an existing Context Repo and never creates one)`);let m=await He(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 He(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 He(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=wt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let m=1;;m++){let d=(await He(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 He(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 md="https://api.bitbucket.org/2.0";async function Tt(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(md+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 gd(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 Tt(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 ba(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 Tt(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=wt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let m of c)(await Tt(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 Tt(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 hd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Te(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=hd[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 yd}from"node:crypto";import{existsSync as $a,mkdirSync as wd,readFileSync as xa,readdirSync as kd,rmSync as to,writeFileSync as bd}from"node:fs";import{homedir as $d}from"node:os";import{dirname as xd,join as qo}from"node:path";var vd=24*60*60*1e3;function va(){return qo($d(),".codepipe","init-drafts")}function Yo(t){let e=yd("sha256").update(t).digest("hex").slice(0,16);return qo(va(),`${e}.json`)}function Sa(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=vd)}function Ca(t){let e=Yo(t);if(!$a(e))return null;try{let r=JSON.parse(xa(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Sa(r.savedAt)?(to(e,{force:!0}),null):r}catch{return null}}function Vo(t){to(Yo(t),{force:!0})}function Ta(){let t=va();if($a(t))for(let e of kd(t)){let r=qo(t,e);try{let o=JSON.parse(xa(r,"utf-8"));Sa(o.savedAt)&&to(r,{force:!0})}catch{to(r,{force:!0})}}}var It=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(){Vo(this.cwd)}persist(){let e=Yo(this.cwd);wd(xd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};bd(e,JSON.stringify(r,null,2)+`
|
|
535
|
-
`,{mode:384})}};function
|
|
536
|
-
`,{mode:384})}function Ad(t){return Pa()[t]}function Ea(t,e){let r=Pa();r[t]=e,jd(r)}function ja(t,e){let r=Ue(e),o=Ad(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 ${Jo()}.`);return r}import{existsSync as Aa}from"node:fs";import{join as _a}from"node:path";import{simpleGit as Oa}from"simple-git";var _d={info:t=>console.log(t),warn:t=>console.warn(t)};async function rr(t,e,r={}){let o=r.log??_d,n=[];for(let i of e){let s=_a(t,i.mountAs),a=Tn(i);if(!Aa(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 Oa().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(!Aa(_a(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=Oa(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Od(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 Od(t,e){return Na(t)===Na(e)}function Na(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Ua(t={}){let e=Xe();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 rr(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 La=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function M(t){Ld(t),process.exit(1)}function ce(t){return Qo(t)&&M("aborted"),t}function B(t){return Qo(t)&&M("aborted"),typeof t=="string"?t:""}async function Ka(t={}){Ha("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Ta();let r=Ca(e),o,n=!1;r&&Object.keys(r.answers).length>0?ce(await Et({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 It(e,r),n=!0):(Vo(e),o=new It(e)):o=new It(e);let i=t.force===!0?null:await Zo(e),s=await o.ask("target",async()=>ce(await at({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||qa(e,t.force===!0));let c=await o.ask("hubUrl",async()=>B(await K({message:"HUB URL",placeholder:fe,initialValue:O("HUB_URL")??fe,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>Ya()),p=await o.ask("cliToken",()=>no(c,l)),m=null;s==="farm"&&(m=await Dd(c,p));let u=a?Gd(a.parsed.repoName):"",d=await o.ask("projectId",async()=>B(await K({message:"project id (slug)",placeholder:u||"acme",...u?{initialValue:u}:{},validate:T=>Ve.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>B(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),y=await o.ask("automationLevel",async()=>ce(await at({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"}))),x=await o.ask("youtrack",()=>ec()),S=await o.ask("youtrackProjectKey",async()=>B(await K({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ce(await Et({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),R=o.get("tokens")??{},_=()=>o.set("tokens",R),U=await o.ask("repos",()=>Fd(R,l,a,{onCred:_,initial:o.get("reposPartial")??[],onProgress:T=>o.set("reposPartial",T)}));o.delete("reposPartial");let C=await Kd(await o.ask("contextRepo",()=>Xa(d,U,R,l)),d,U,R,l,_,T=>o.set("contextRepo",T)),{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 k=await o.ask("assigneeLogin",async()=>B(await K({message:"your YouTrack login (the assignee value)",...x.login?{initialValue:x.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),$=await o.ask("claudeToken",()=>Xd(s==="farm")),w={projectId:d,name:g,automationLevel:y,repos:U,youtrackProjectKey:S,ownerEmail:l};b.step(`${f==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let j;try{j=await Rt(w,h,{...Qa(R),youtrackWrites:v,trackerUrl:x.url,mode:f,log:{info:T=>b.message(T),warn:T=>b.warn(T)}})}catch(T){M(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}w.contextRepo=j,b.success(`Context Repo ready: ${j.owner}/${j.name}@${j.branch}`),b.step(`registering project on ${c}\u2026`);let I;try{I=await bt(c,p,w)}catch(T){if(T instanceof A&&T.status===409){b.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{I=await te(c,p,d)}catch(se){throw se instanceof A&&M(`HUB \u2192 ${se.status} ${se.message}`),se}}else if(T instanceof A&&T.status===401)o.delete("cliToken"),M("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof A)M(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let L=I.contextRepo??j;b.success(`project ${I.projectId} ready (${I.provisioningStatus})`);let ne=await Jd(L),de={url:x.url,token:x.token};if(s==="farm"){let T=m,se={...R,...ne?{contextWrite:ne}:{},...$?{claude:{oauthToken:$}}:{},youtrack:de},Re=R.github?.token;if(L.host==="github"&&Re)try{let q=vs(`devpipe-${d}`);await Ss(L,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:L,projectConfig:ye(w,v,x.url,k||void 0)},co=jr(T.farm.publicKey,JSON.stringify(be));b.step(`handing project ${d} to farm ${T.farm.name}\u2026`);let qe;try{qe=await ls(c,p,T.farm.farmId,{projectId:d,sealedBundle:co})}catch(q){throw q instanceof A&&M(q.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:q.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${q.status} ${q.message}`),q}qe.ok||M(`farm rejected provisioning: ${qe.error??"unknown error"}`),await Xo(c,p,d,L,Re),o.clear(),zo(`done. project ${d} is now hosted on farm ${T.farm.name} (daemon ${qe.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Za(R),await Va(e,L.cloneUrl,L.branch),za(e),a&&await Hd(e);{let T=st(e,ge);yt(T);let se=ye(w,v,x.url,k||void 0),Re=Mt(T,se);Re.length>0&&b.success(`local project config \u2192 .codepipe/{${Re.join(", ")}}`),et(d,se,{info:be=>b.message(be),warn:be=>b.warn(be)})}await Ja(e,I.repos);let We={hubUrl:c,cliToken:p,projectId:d,...R,...ne?{contextWrite:ne}:{},...$?{claude:{oauthToken:$}}:{},youtrack:de};V(We),Qe({hubUrl:c,cliToken:p,projectId:d,accountEmail:l},d),b.success(`secrets \u2192 ${Ze(d)}`),await Xo(c,p,d,L,R.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),zo("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Xo(t,e,r,o,n){let i=await Ia(o,n),s=Ra(i),a=await at({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Qo(a)||a!==s.proceedValue))try{let{jobId:c}=await Dr(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 Dd(t,e){let r;try{r=await cs(t,e)}catch(c){throw c instanceof A&&M(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&M("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 at({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=ja(i.farmId,i.publicKey)}catch(c){M(c instanceof Error?c.message:String(c))}return ce(await Et({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
531
|
+
`}catch(P){let E=P instanceof Error?P.message:String(P);console.warn(`[job] ${m.jobId} conflict merge failed: ${E}`),k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${E}`},startedAt:q,finishedAt:new Date().toISOString()}),L.dispose();return}let Oc=U(m.prompt,Ee,dr)+hn,po=[...Ee.map(P=>P.workspacePath),...dr?[dr]:[]];po.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${po.join(", ")}`),pr&&(Y=setInterval(()=>{let E=u;if(!E||E.readyState!==E.OPEN)return;let H;try{H=ed(Zr(L.dir,"drafts")).filter(ie=>ie.endsWith(".json")).sort()}catch{return}for(let ie of H){if(Ie.has(ie))continue;if(Ie.size>=Sn)break;let lt;try{let ee=JSON.parse(wa(Zr(L.dir,"drafts",ie),"utf-8")),N=typeof ee.localRef=="string"?ee.localRef:"",V=typeof ee.title=="string"?ee.title:"",Ye=typeof ee.body=="string"?ee.body:"";if(!N||!V)continue;lt={localRef:N,title:V,body:Ye,...ee.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ee.links)?{links:ee.links}:{}}}catch{continue}Ie.add(ie);let Lt={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:pr,child:lt};try{E.send(JSON.stringify(Lt))}catch{}}},1500));try{let P=await Ys(n,{workspaceDir:L.dir,role:m.role,prompt:Oc,addDirs:po,metadata:m.metadata??{},...m.model?{model:m.model}:{},...fn?{env:fn}:{},signal:p.signal,onActivity:qe},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{L.clean();for(let N of Ee)try{await ta(N);let V=gn[N.name];m.role==="resolve-conflict"&&V&&await Ko(N,V,Pe)}catch(V){let Ye=V instanceof Error?V.message:String(V);console.warn(`[job] ${m.jobId} worktree reset failed (${N.name}): ${Ye}`)}try{await mn()}catch(N){let V=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${V}`)}},aborted:()=>k||f}),E=[];if(nd.has(m.role)&&Ee.length>0){let N=m.metadata??{},V=typeof N.commitMessage=="string"?N.commitMessage:`${m.taskId}: changes`,Ye=m.contextRepo?.cloneUrl,wn=b?.env;if(!Ye||!wn)throw new Error("delivery requested but "+(Ye?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Nc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let $e of Ee){let Dt=await ra($e,V);if(!Dt){console.log(`[job] ${m.jobId} ${$e.name}: no changes \u2014 no delivery`);continue}let fo=`codepipe/deliveries/${Nc}/${m.jobId}/${$e.name}`;await oa($e,Dt,fo,Ye,wn),E.push({name:$e.name,deliveryRef:fo,deliverySha:Dt,baseSha:$e.baseSha}),console.log(`[job] ${m.jobId} ${$e.name}: delivered ${Dt.slice(0,10)} \u2192 ${fo}`);let yn=await na($e,Dt);if(yn.trim().length>0){let Uc=Zr("display",`${$e.name}.diff`),bn=Zr(L.dir,Uc);Zp(rd(bn),{recursive:!0}),td(bn,yn)}}}if(m.role==="resolve-conflict"&&E.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let H;m.role==="build"&&(H=pa(L.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let ie=P.artifactPaths.length>0?P.artifactPaths:L.listFiles(),lt=Array.from(new Set(ie)),Lt;if(uo)try{let N=await ua(uo,m.role==="index"?["adr/SOURCES.md"]:[]);N.length>0&&(Lt=N,console.log(`[job] ${m.jobId} captured ${N.length} knowledge file(s) for Context Repo`))}catch(N){let V=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${V}`)}let ee={jobId:m.jobId,status:"succeeded",artifacts:lt.map(N=>({path:N,contentBase64:wa(`${L.dir}/${N}`).toString("base64")})),...Lt?{contextWrites:Lt}:{},...E.length>0?{deliveries:E}:{},log:id(P.log),startedAt:q,finishedAt:new Date().toISOString(),usage:P.usage,...P.rateLimit?{rateLimit:P.rateLimit}:{},...H?{build:H}:{}};if(k||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(ee),console.log(`[job] ${m.jobId} done \u2014 uploaded ${ee.artifacts.length} artifact(s):`);for(let N of ee.artifacts){let V=Buffer.from(N.contentBase64,"base64").length;console.log(` \xB7 ${N.path} (${V} bytes)`)}ee.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(P){let E=P instanceof Error?P.message:String(P);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${m.jobId} failed after claim lost (${E}) \u2014 skipping result upload`);else{let H=qs(P);console.warn(H?`[job] ${m.jobId} failed: ${E} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${E}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:E},startedAt:q,finishedAt:new Date().toISOString(),...H?{authError:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(B),Y&&clearInterval(Y),fe(),l=null,p=null,$?.cleanup(),b?.cleanup()}}function A(h,m){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let k;try{k=JSON.parse(Ar(m,h.credBundle).toString("utf-8"))}catch(I){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${I instanceof Error?I.message:String(I)}`),{gitCreds:null,contextGitCreds:null}}let $=Ho(k);$&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let b=Js(k,h.contextRepo.cloneUrl),j={gitCreds:$,contextGitCreds:b};return k.claudeOauthToken&&(j.claudeOauthToken=k.claudeOauthToken),j}function T(h,m){return h.split(`
|
|
532
|
+
`).map(k=>m+k).join(`
|
|
533
|
+
`)}function U(h,m,k){let $=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,k??"")}let C=h=>{if(a)return;a=!0,console.log(`
|
|
534
|
+
[${h}] shutting down`),c.abort();let m=new AbortController,k=setTimeout(()=>m.abort(),3e3);(async()=>{let $=l;if($)try{await s.releaseJob($,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${$}`)}catch(b){let j=b instanceof Error?b.message:String(b);console.warn(`[${h}] release failed: ${j} (sweeper will reclaim)`)}clearTimeout(k),S.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>C("SIGINT")),process.on("SIGTERM",()=>C("SIGTERM")),await x()}async function ya(t={profile:void 0}){let e=Ae(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Ur(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 f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,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 re(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=oe(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{spawn as Ud}from"node:child_process";import{existsSync as Pt,mkdirSync as Ga,readFileSync as Ma,readdirSync as Ld,writeFileSync as Ha}from"node:fs";import{join as st,resolve as Fa}from"node:path";import{setTimeout as Jo}from"node:timers/promises";import{cancel as Dd,confirm as Et,intro as Ka,isCancel as Zo,log as y,outro as Xo,password as jt,select as at,spinner as Wa,text as K}from"@clack/prompts";import{simpleGit as oo}from"simple-git";async function Tt(t,e,r){return e.host==="github"?ad(t,e,r):e.host==="gitlab"?md(t,e,r):hd(t,e,r)}async function ba(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 Ke(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await ka(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 Fe(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await $a(e.gitlabToken,t):n}}return e.bitbucket?(await Rt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await xa(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 ka(t,e){let r=!1;try{r=(await Ke(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 $a(t,e){let r=!1;try{r=(await Fe(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 xa(t,e){let r=!1;try{r=(await Rt(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 sd="https://api.github.com";async function Ke(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(sd+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 ad(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 cd(o,e,r),i=await ud(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=yt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await pd(o,n.owner,n.name,a.path,i)||await dd(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 cd(t,e,r){let o=await Ke(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 ka(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await ld(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 Ke(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 ld(t,e){let{status:r,data:o}=await Ke(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function ud(t,e,r){let{data:o}=await Ke(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function pd(t,e,r,o,n){let{status:i,data:s}=await Ke(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function dd(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 Ke(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var fd="https://gitlab.com/api/v4";async function Fe(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(fd+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 md(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 Fe(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 $a(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Fe(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(f.data?.username!==e.owner){let g=await Fe(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 Fe(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=yt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let d=(await Fe(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)l.add(g.path);if(d.length<100)break}let p=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Fe(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 gd="https://api.bitbucket.org/2.0";async function Rt(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(gd+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 hd(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 Rt(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 xa(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 Rt(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=yt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Rt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of l)f.set(d.path,d.content);if((await Rt(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 wd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Re(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=wd[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 yd}from"node:crypto";import{existsSync as va,mkdirSync as bd,readFileSync as Sa,readdirSync as kd,rmSync as to,writeFileSync as $d}from"node:fs";import{homedir as xd}from"node:os";import{dirname as vd,join as qo}from"node:path";var Sd=24*60*60*1e3;function Ca(){return qo(xd(),".codepipe","init-drafts")}function Yo(t){let e=yd("sha256").update(t).digest("hex").slice(0,16);return qo(Ca(),`${e}.json`)}function Ra(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Sd)}function Ta(t){let e=Yo(t);if(!va(e))return null;try{let r=JSON.parse(Sa(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Ra(r.savedAt)?(to(e,{force:!0}),null):r}catch{return null}}function Vo(t){to(Yo(t),{force:!0})}function Ia(){let t=Ca();if(va(t))for(let e of kd(t)){let r=qo(t,e);try{let o=JSON.parse(Sa(r,"utf-8"));Ra(o.savedAt)&&to(r,{force:!0})}catch{to(r,{force:!0})}}}var It=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(){Vo(this.cwd)}persist(){let e=Yo(this.cwd);bd(vd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};$d(e,JSON.stringify(r,null,2)+`
|
|
535
|
+
`,{mode:384})}};function Pa(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 Ea(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 Cd}from"node:os";import{existsSync as Rd,mkdirSync as Td,readFileSync as Id,writeFileSync as Pd}from"node:fs";import{dirname as Ed,join as jd}from"node:path";function zo(){return O("FARM_PINS")??jd(Cd(),".codepipe","farm-pins.json")}function ja(){let t=zo();if(!Rd(t))return{};try{return JSON.parse(Id(t,"utf-8"))}catch{return{}}}function Ad(t){let e=zo();Td(Ed(e),{recursive:!0}),Pd(e,JSON.stringify(t,null,2)+`
|
|
536
|
+
`,{mode:384})}function _d(t){return ja()[t]}function Aa(t,e){let r=ja();r[t]=e,Ad(r)}function _a(t,e){let r=Le(e),o=_d(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 ${zo()}.`);return r}import{existsSync as Oa}from"node:fs";import{join as Na}from"node:path";import{simpleGit as Ua}from"simple-git";var Od={info:t=>console.log(t),warn:t=>console.warn(t)};async function rr(t,e,r={}){let o=r.log??Od,n=[];for(let i of e){let s=Na(t,i.mountAs),a=In(i);if(!Oa(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 Ua().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(!Oa(Na(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=Ua(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Nd(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 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 Nd(t,e){return La(t)===La(e)}function La(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Da(t={}){let e=Xe();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 rr(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 Ba=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function M(t){Dd(t),process.exit(1)}function le(t){return Zo(t)&&M("aborted"),t}function D(t){return Zo(t)&&M("aborted"),typeof t=="string"?t:""}async function qa(t={}){Ka("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Ia();let r=Ta(e),o,n=!1;r&&Object.keys(r.answers).length>0?le(await Et({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(y.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new It(e,r),n=!0):(Vo(e),o=new It(e)):o=new It(e);let i=t.force===!0?null:await en(e),s=await o.ask("target",async()=>le(await at({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?y.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||Va(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:me,initialValue:O("HUB_URL")??me,validate:R=>R.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>no()),{cliToken:p,accountEmail:f}=await o.ask("bootstrap",()=>io(c,l)),u=null;s==="farm"&&(u=await Bd(c,p));let d=a?Md(a.parsed.repoName):"",g=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:d||"acme",...d?{initialValue:d}:{},validate:R=>Ve.test(R.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),w=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()),S=await o.ask("automationLevel",async()=>le(await at({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"}))),x=await o.ask("youtrack",()=>tc()),v=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:R=>R.trim().length>0?void 0:"required"})).trim()),A=await o.ask("youtrackWrites",async()=>le(await Et({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},U=()=>o.set("tokens",T),C=await o.ask("repos",()=>Wd(T,l,a,{onCred:U,initial:o.get("reposPartial")??[],onProgress:R=>o.set("reposPartial",R)}));o.delete("reposPartial");let h=await qd(await o.ask("contextRepo",()=>Qa(g,C,T,l)),g,C,T,l,U,R=>o.set("contextRepo",R)),{spec:m,mode:k}=h;y.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let $=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...x.login?{initialValue:x.login}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),b=await o.ask("claudeToken",()=>Zd(s==="farm")),j={projectId:g,name:w,automationLevel:S,repos:C,youtrackProjectKey:v,ownerEmail:f};y.step(`${k==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let I;try{I=await Tt(j,m,{...Za(T),youtrackWrites:A,trackerUrl:x.url,mode:k,log:{info:R=>y.message(R),warn:R=>y.warn(R)}})}catch(R){M(`Context Repo provisioning failed: ${R instanceof Error?R.message:String(R)}`)}j.contextRepo=I,y.success(`Context Repo ready: ${I.owner}/${I.name}@${I.branch}`),y.step(`registering project on ${c}\u2026`);let B;try{B=await kt(c,p,j)}catch(R){if(R instanceof _&&R.status===409){y.warn(`project ${g} already exists on HUB \u2014 reusing it`);try{B=await re(c,p,g)}catch(ae){throw ae instanceof _&&M(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(R instanceof _&&R.status===401)o.delete("cliToken"),M("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(R instanceof _)M(`HUB \u2192 ${R.status} ${R.message}`);else throw R}let q=B.contextRepo??I;y.success(`project ${B.projectId} ready (${B.provisioningStatus})`);let se=await Xd(q),Te={url:x.url,token:x.token};if(s==="farm"){let R=u,ae={...T,...se?{contextWrite:se}:{},...b?{claude:{oauthToken:b}}:{},youtrack:Te},fe=T.github?.token;if(q.host==="github"&&fe)try{let Y=Cs(`devpipe-${g}`);await Rs(q,fe,Y.publicKey,`devpipe-${g}`),ae.contextSsh={privateKey:Y.privateKey},y.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Y){y.warn(`could not set up Context Repo SSH deploy key (${Y instanceof Error?Y.message:String(Y)}); the farm will fall back to the token path.`)}let qe={projectId:g,config:{hubUrl:c,cliToken:p,projectId:g},secrets:ae,contextRepo:q,projectConfig:ye(j,A,x.url,$||void 0)},pr=jr(R.farm.publicKey,JSON.stringify(qe));y.step(`handing project ${g} to farm ${R.farm.name}\u2026`);let Ie;try{Ie=await ps(c,p,R.farm.farmId,{projectId:g,sealedBundle:pr})}catch(Y){throw Y instanceof _&&M(Y.status===409?`farm ${R.farm.name} is offline \u2014 start it and re-run.`:Y.status===504?`farm ${R.farm.name} did not respond in time.`:`HUB \u2192 ${Y.status} ${Y.message}`),Y}Ie.ok||M(`farm rejected provisioning: ${Ie.error??"unknown error"}`),await Qo(c,p,g,q,fe),o.clear(),Xo(`done. project ${g} is now hosted on farm ${R.farm.name} (daemon ${Ie.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}ec(T),await za(e,q.cloneUrl,q.branch),Xa(e),a&&await Fd(e);{let R=st(e,he);wt(R);let ae=ye(j,A,x.url,$||void 0),fe=Mt(R,ae);fe.length>0&&y.success(`local project config \u2192 .codepipe/{${fe.join(", ")}}`),et(g,ae,{info:qe=>y.message(qe),warn:qe=>y.warn(qe)})}await Ja(e,B.repos);let lo={hubUrl:c,cliToken:p,projectId:g,...T,...se?{contextWrite:se}:{},...b?{claude:{oauthToken:b}}:{},youtrack:Te};z(lo),Qe({hubUrl:c,cliToken:p,projectId:g,accountEmail:f},g),y.success(`secrets \u2192 ${Ze(g)}`),await Qo(c,p,g,q,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Xo("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 Ea(o,n),s=Pa(i),a=await at({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Zo(a)||a!==s.proceedValue))try{let{jobId:c}=await Dr(t,e,r,{reindex:s.reindex});y.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){y.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Bd(t,e){let r;try{r=await us(t,e)}catch(c){throw c instanceof _&&M(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&M("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=le(await at({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=_a(i.farmId,i.publicKey)}catch(c){M(c instanceof Error?c.message:String(c))}return le(await Et({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
537
537
|
${s}
|
|
538
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||M("farm fingerprint not confirmed \u2014 aborting."),
|
|
538
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||M("farm fingerprint not confirmed \u2014 aborting."),Aa(i.farmId,s),{farm:i,fingerprint:s}}async function Ya(t){Ka(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Va(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:O("HUB_URL")??me,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await no(),{cliToken:n,accountEmail:i}=await io(r,o);y.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await re(r,n,t.projectId)}catch(f){throw f instanceof _&&M(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||M(`project ${t.projectId} has no Context Repo on HUB`);let a=await tc(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await ro(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(u=>u.host===f)?.owner,o);ec(c),await za(e,s.contextRepo.cloneUrl,s.contextRepo.branch),Xa(e);{let f=st(e,he);wt(f);let u={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},d=ye(u,!0,a.url),g=Mt(f,d);g.length>0&&y.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),et(t.projectId,d,{info:w=>y.message(w),warn:w=>y.warn(w)})}await Ja(e,s.repos);let p={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};z(p),Qe({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),y.success(`secrets \u2192 ${Ze(t.projectId)}`),await Qo(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Xo("done.")}function Va(t,e){if(!Pt(t)){Ga(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Ld(t).filter(n=>!r.has(n));o.length!==0&&(e||M(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function en(t){if(!Pt(st(t,".git")))return null;try{let r=(await oo(t).remote(["get-url","origin"])||"").toString().trim(),o=r?Re(r):null;return o?{parsed:o,defaultBranch:await Gd(t)}:null}catch{return null}}async function Gd(t){let e=oo(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 Md(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ve.test(e)?e:""}function Hd(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Fd(t){let e=st(t,".gitignore"),r=Pt(e)?Ma(e,"utf-8"):"";if(Hd(r))return;if(!le(await Et({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){y.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
|
+
`;Ha(e,r+n+`
|
|
541
541
|
# codepipe workspace (added by \`codepipe init\`)
|
|
542
542
|
.codepipe/
|
|
543
|
-
`),
|
|
543
|
+
`),y.success(`.codepipe/ added to ${Fa(e)}`)}function Kd(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=Ud(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function no(){let t="";try{t=(await oo().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function io(t,e){y.step(`connecting account ${e}`);let r;try{r=await fs(t,e)}catch(s){throw s instanceof Vt&&M(`${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.`),
|
|
546
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&y.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&y.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Kd(r.authorizeUrl),y.message(`a browser tab was opened to confirm this CLI:
|
|
547
|
+
${r.authorizeUrl}
|
|
548
|
+
`+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
|
|
549
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&y.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),y.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let o=!1,n=Date.now(),i=n+15*6e4;for(;Date.now()<i;){let s;try{s=await ms(t,r.requestId)}catch(a){y.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await Jo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&y.message(`connected as ${a} (the account confirmed in the browser).`),y.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&M("the HUB rejected this account"),s.status==="expired"&&M("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,y.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
550
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await Jo(5e3);continue}await Jo(2e3)}M("bootstrap timed out")}async function za(t,e,r){let o=st(t,he);if(Pt(st(o,".git"))){y.message(`${o} already cloned \u2014 skipping`);return}Pt(o)&&M(`${o} exists but is not a git repo \u2014 remove it and re-run`),Ga(o,{recursive:!0}),y.step(`cloning Context Repo \u2192 ${o}`);try{await oo().clone(e,o,["--branch",r]),y.success(`cloned ${e}`)}catch(n){M(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Ja(t,e){if(e.length===0)return;y.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 rr(t,r,{log:{info:n=>y.message(n),warn:n=>y.warn(n)}});for(let n of o)y.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function Xa(t){let e=st(t,he,".gitignore"),r="";if(Pt(e)&&(r=Ma(e,"utf-8")),Ba.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
|
|
547
551
|
`)||r.length===0?"":`
|
|
548
|
-
`,i=
|
|
552
|
+
`,i=Ba.join(`
|
|
549
553
|
`)+`
|
|
550
|
-
`;
|
|
551
|
-
`:"")+i),
|
|
554
|
+
`;Ha(e,r+n+(r?`
|
|
555
|
+
`:"")+i),y.message(`appended runtime entries to ${Fa(e)}`)}async function Wd(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;y.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await ro(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(;le(await Et({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()||Re(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=Re(a);y.message(`${c.host}: ${c.owner}/${c.repoName}`),await ro(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(),f=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),f&&f!==l&&(u.mountAs=f),n.push(u),o.onProgress?.(n)}return n}async function Qa(t,e,r,o){y.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=le(await at({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"&&y.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:ve(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!Re(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=Re(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Yd(),l=D(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"Context Repo name",placeholder:ve(t),initialValue:ve(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:n}}function Za(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??ft()}}async function qd(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await ro(c.host,o,c.owner,n),i?.();let p=Wa();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await ba(c,Za(o),{explain:l==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let u=le(await at({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"&&M("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await Qa(e,r,o,n),s(a)}}async function Yd(){return le(await at({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function or(t,e){let r=Wa();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 ec(t){Ht(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ft(t.gitlab?.token??process.env.GITLAB_TOKEN),Kt(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function ro(t,e,r,o){if(!e[t])if(t==="github"){let n=await Vd(r);n?e.github=n:y.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await zd(r,o);n?e.bitbucket=n:y.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 Jd();n?e.gitlab=n:y.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Vd(t){for(;;){let e=D(await jt({message:`GitHub PAT \u2014 blank to skip
|
|
552
556
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
553
557
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
554
558
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
555
559
|
(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 or("GitHub",()=>
|
|
560
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await or("GitHub",()=>Oe(e,t?{owner:t}:void 0)))return{token:e};y.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function zd(t,e){for(y.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
557
561
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
558
562
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
559
563
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
560
564
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
561
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=
|
|
562
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await or("GitLab",()=>
|
|
565
|
+
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 jt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){y.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await or("Bitbucket",()=>Ne(r,o,t)))return{email:r,apiToken:o};y.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Jd(){for(;;){let t=D(await jt({message:`GitLab PAT \u2014 blank to skip
|
|
566
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await or("GitLab",()=>Ue(t))){let e=await ui(t);return e&&y.warn(e),{token:t}}y.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Xd(t){if(le(await Et({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
563
567
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
564
568
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
565
|
-
your trusted network.`,initialValue:!1})))for(t.host==="github"?
|
|
569
|
+
your trusted network.`,initialValue:!1})))for(t.host==="github"?y.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
566
570
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
567
|
-
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):
|
|
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=
|
|
569
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=B(await jt({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 ec(){for(;;){let t=B(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=B(await jt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await or("YouTrack",()=>De({baseUrl:t,token:e}))){let r=await Ii({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Qd}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 nr(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 Zd(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");Ve.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,R)=>{(!v||typeof v!="object")&&W(`config: project.repos[${R}] must be an object`);let _=v,U=z(_.host,`project.repos[${R}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${R}].host must be 'github', 'bitbucket' or 'gitlab'`);let C={name:z(_.name,`project.repos[${R}].name`),host:U,owner:z(_.owner,`project.repos[${R}].owner`),repoName:z(_.repoName,`project.repos[${R}].repoName`)},h=nr(_.defaultBranch,`project.repos[${R}].defaultBranch`);h&&(C.defaultBranch=h);let f=nr(_.mountAs,`project.repos[${R}].mountAs`);return f&&(C.mountAs=f),C}),m=i.contextRepo;(!m||typeof m!="object")&&W("config: 'project.contextRepo' is required");let u=m,d=nr(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:nr(u.name,"project.contextRepo.name")??ve(s)},y={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},x=nr(i.youtrackProjectKey,"project.youtrackProjectKey");x&&(y.project.youtrackProjectKey=x),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),y.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,R={};if(v.github){let _=v.github;R.github={token:z(_.token,"secrets.github.token")}}if(v.bitbucket){let _=v.bitbucket;R.bitbucket={email:z(_.email,"secrets.bitbucket.email"),apiToken:z(_.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let _=v.gitlab;R.gitlab={token:z(_.token,"secrets.gitlab.token")}}if(v.youtrack){let _=v.youtrack;R.youtrack={url:z(_.url,"secrets.youtrack.url").replace(/\/$/,""),token:z(_.token,"secrets.youtrack.token")}}if(v.contextWrite){let _=v.contextWrite;R.contextWrite={token:z(_.token,"secrets.contextWrite.token")}}y.secrets=R}return y}async function ef(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function tf(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await _e(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 Oe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Ne(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await De({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function tc(t){let e=!t.configPath||t.configPath==="-"?await ef():Qd(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=Zd(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 tf(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??ft(),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 bt(n,i,a)}catch(u){if(u instanceof A&&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 A)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(V(m),Qe({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ze(s.id)}`),et(s.id,ye(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 Dr(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 rc,intro as oc,isCancel as nc,log as en,outro as rf,password as ic}from"@clack/prompts";async function of(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function sc(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await of(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){oc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),en.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ic({message:"Claude OAuth token"});nc(i)&&(rc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Mn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${xr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=je(t.profile);if(!e){oc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),en.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ic({message:"Claude OAuth token"});nc(i)&&(rc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=G(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},V(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(en.success("Claude OAuth token saved."),rf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as nf,confirm as sf,intro as af,isCancel as ac,log as X,outro as cf,select as cc,text as Ke}from"@clack/prompts";function lc(t){nf(t),process.exit(1)}function At(t){return ac(t)&&lc("aborted"),t}function ir(t){return ac(t)&&lc("aborted"),typeof t=="string"?t:""}async function lf(t,e){let r=At(await cc({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=ir(await Ke({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=ir(await Ke({message:"Context Repo name",placeholder:ve(t),initialValue:ve(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function uc(t={profile:void 0}){let e=je(t.profile);af(`codepipe project add \u2192 ${e.hubUrl}`);let r=At(await Ke({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Ve.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=At(await Ke({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),n=At(await cc({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=At(await Ke({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=At(await sf({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=ir(await Ke({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()||Te(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=Te(u);X.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=ir(await Ke({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(),y=ir(await Ke({message:"default branch (optional)",placeholder:"main"})).trim(),x={name:g,host:d.host,owner:d.owner,repoName:d.repoName};y&&(x.defaultBranch=y),a.push(x)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await lf(r,a),p=G(e.projectId);X.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??ft(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>X.message(u),warn:u=>X.warn(u)}})}catch(u){X.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=m,X.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await bt(e.hubUrl,e.cliToken,c);X.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),et(r,ye(c,s,p?.youtrack?.url),{info:d=>X.message(d),warn:d=>X.warn(d)}),u.contextRepo&&(X.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),X.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&X.error(` error: ${u.provisioningError}`),cf("done")}catch(u){u instanceof A?(X.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&X.message(JSON.stringify(u.payload,null,2))):X.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{spawn as uf}from"node:child_process";import{existsSync as pc}from"node:fs";import{homedir as pf,hostname as df}from"node:os";import{join as io}from"node:path";async function ff(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 ${Ge(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 Lr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await nt({hub:t.hubUrl,token:n,name:r.name??`${df()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function mf(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=Ue(r.sealPublicKey);if(!G(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=$r(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 gf(t,e){let r=process.cwd(),o=io(r,ge);if(wr(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(pc(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 Zo(r);if(!Cn(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=G(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Hr({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=io(pf(),".codepipe",e?io("profiles",e,"context-config"):"context-config");if(Tr(c.contextDir,l,a),!pc(io(c.contextDir,"project.yaml"))){yt(c.contextDir);let p={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};Mt(c.contextDir,ye(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 dc(t){let{cfg:e,profile:r}=br(t.profile);await gf(e,r),await ff(e,r,t),mf(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 y=x=>S=>{for(let v of S.toString("utf-8").split(`
|
|
570
|
-
`))v.length>0&&
|
|
571
|
-
`)};d.stdout?.on("data",
|
|
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:
|
|
573
|
-
`)}async function
|
|
574
|
-
${
|
|
575
|
-
or: /abort ${r} --reason "..."`}}function
|
|
571
|
+
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):y.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
572
|
+
(${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 jt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await or("contextWrite",()=>Qd(r,t)))return{token:r};y.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Qd(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 Zd(t){if(ho()?.claude?.oauthToken&&!t)return y.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`)."),"";y.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?`
|
|
573
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=D(await jt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||y.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):(y.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 tc(){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 jt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await or("YouTrack",()=>Be({baseUrl:t,token:e}))){let r=await Ei({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}y.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as ef}from"node:fs";function W(t){throw new Error(t)}function X(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function nr(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 tf(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=X(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=X(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=X(i.id,"project.id");Ve.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=X(i.name,"project.name"),c=X(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,A)=>{(!v||typeof v!="object")&&W(`config: project.repos[${A}] must be an object`);let T=v,U=X(T.host,`project.repos[${A}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${A}].host must be 'github', 'bitbucket' or 'gitlab'`);let C={name:X(T.name,`project.repos[${A}].name`),host:U,owner:X(T.owner,`project.repos[${A}].owner`),repoName:X(T.repoName,`project.repos[${A}].repoName`)},h=nr(T.defaultBranch,`project.repos[${A}].defaultBranch`);h&&(C.defaultBranch=h);let m=nr(T.mountAs,`project.repos[${A}].mountAs`);return m&&(C.mountAs=m),C}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let u=f,d=nr(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:X(u.owner,"project.contextRepo.owner"),name:nr(u.name,"project.contextRepo.name")??ve(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},S=nr(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(w.project.youtrackProjectKey=S),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 x=e.secrets;if(x!==void 0){(typeof x!="object"||x===null)&&W("config: 'secrets' must be an object");let v=x,A={};if(v.github){let T=v.github;A.github={token:X(T.token,"secrets.github.token")}}if(v.bitbucket){let T=v.bitbucket;A.bitbucket={email:X(T.email,"secrets.bitbucket.email"),apiToken:X(T.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let T=v.gitlab;A.gitlab={token:X(T.token,"secrets.gitlab.token")}}if(v.youtrack){let T=v.youtrack;A.youtrack={url:X(T.url,"secrets.youtrack.url").replace(/\/$/,""),token:X(T.token,"secrets.youtrack.token")}}if(v.contextWrite){let T=v.contextWrite;A.contextWrite={token:X(T.token,"secrets.contextWrite.token")}}w.secrets=A}return w}async function rf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function of(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await Oe(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 Ne(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Ue(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Be({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function rc(t){let e=!t.configPath||t.configPath==="-"?await rf():ef(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=tf(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 of(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 Tt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??ft(),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 kt(n,i,a)}catch(u){if(u instanceof _&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await re(n,i,s.id);else if(u instanceof _)W(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(z(f),Qe({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ze(s.id)}`),et(s.id,ye(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 Dr(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 oc,intro as nc,isCancel as ic,log as tn,outro as nf,password as sc}from"@clack/prompts";async function sf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function ac(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await sf(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){nc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),tn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await sc({message:"Claude OAuth token"});ic(i)&&(oc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Fn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${xr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ae(t.profile);if(!e){nc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),tn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await sc({message:"Claude OAuth token"});ic(i)&&(oc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=G(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}.`):(tn.success("Claude OAuth token saved."),nf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as af,confirm as cf,intro as lf,isCancel as cc,log as Q,outro as uf,select as lc,text as We}from"@clack/prompts";function uc(t){af(t),process.exit(1)}function At(t){return cc(t)&&uc("aborted"),t}function ir(t){return cc(t)&&uc("aborted"),typeof t=="string"?t:""}async function pf(t,e){let r=At(await lc({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=ir(await We({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=ir(await We({message:"Context Repo name",placeholder:ve(t),initialValue:ve(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function pc(t={profile:void 0}){let e=Ae(t.profile);lf(`codepipe project add \u2192 ${e.hubUrl}`);let r=At(await We({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Ve.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=At(await We({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),n=At(await lc({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=At(await We({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=At(await cf({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=ir(await We({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:x=>!x||!x.trim()||Re(x)?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=Re(u);Q.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=ir(await We({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:x=>x.trim().length>0?void 0:"required"})).trim(),w=ir(await We({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(S.defaultBranch=w),a.push(S)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await pf(r,a),p=G(e.projectId);Q.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Tt(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??ft(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>Q.message(u),warn:u=>Q.warn(u)}})}catch(u){Q.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,Q.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await kt(e.hubUrl,e.cliToken,c);Q.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),et(r,ye(c,s,p?.youtrack?.url),{info:d=>Q.message(d),warn:d=>Q.warn(d)}),u.contextRepo&&(Q.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),Q.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&Q.error(` error: ${u.provisioningError}`),uf("done")}catch(u){u instanceof _?(Q.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&Q.message(JSON.stringify(u.payload,null,2))):Q.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{spawn as df}from"node:child_process";import{existsSync as dc}from"node:fs";import{homedir as ff,hostname as mf}from"node:os";import{join as so}from"node:path";async function gf(t,e,r){let o=oe(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 ${Me(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 Lr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof _&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof _&&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 _?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 nt({hub:t.hubUrl,token:n,name:r.name??`${mf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function hf(t,e){let r=oe(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=Le(r.sealPublicKey);if(!G(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=$r(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 wf(t,e){let r=process.cwd(),o=so(r,he);if(yr(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(dc(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 re(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 en(r);if(!Tn(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=G(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Hr({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=so(ff(),".codepipe",e?so("profiles",e,"context-config"):"context-config");if(Rr(c.contextDir,l,a),!dc(so(c.contextDir,"project.yaml"))){wt(c.contextDir);let p={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};Mt(c.contextDir,ye(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 fc(t){let{cfg:e,profile:r}=kr(t.profile);await wf(e,r),await gf(e,r,t),hf(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=S=>x=>{for(let v of x.toString("utf-8").split(`
|
|
574
|
+
`))v.length>0&&S.write(`${g} ${v}
|
|
575
|
+
`)};d.stdout?.on("data",w(process.stdout)),d.stderr?.on("data",w(process.stderr))},i=(d,g)=>{let w=df(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(`
|
|
576
|
+
[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 f=c.map(({name:d,child:g})=>new Promise(w=>{g.on("exit",(S,x)=>w({name:d,code:S??(x?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(f),process.exit(u.code)}import{existsSync as Cc,mkdirSync as xf,readFileSync as vf,writeFileSync as Sf}from"node:fs";import{homedir as Cf}from"node:os";import{dirname as Rf,join as Rc}from"node:path";import*as Ot from"node:readline";import{existsSync as nn,readFileSync as yf,writeFileSync as bf}from"node:fs";import{join as ar}from"node:path";import{simpleGit as on}from"simple-git";var mc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],kf="apply-queue.json";function gc(t){return ar(t,kf)}function _t(t){let e=gc(t);if(!nn(e))return{};try{return JSON.parse(yf(e,"utf-8"))}catch{return{}}}function hc(t,e){bf(gc(t),JSON.stringify(e,null,2)+`
|
|
577
|
+
`)}async function wc(t,e,r,o,n){let i;try{i=await ws(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(x=>x.name===u.repoName);if(!d)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let g=ar(t.root,d.mountAs);if(!nn(ar(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await on(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=on(u.dir),g=await $f(d),w=u.claimRepo;try{await d.fetch()}catch(v){return await rn(a,n),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${sr(v)}`}}let S=`origin/${w.baseRef}`,x;try{x=await Or(d,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(v){return await rn(a,n),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${sr(v)}`}}a.push({git:d,dir:u.dir,mountAs:u.spec.mountAs,originalRef:g,branch:w.branchName,baseSha:S,deliveryCommit:x,startPoint:S})}let c=[];for(let u of a)try{if(o==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...mc,"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([...mc,"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 rn(a,n),{ok:!1,message:`apply failed in ${u.mountAs}: ${sr(d)} (rolled back all repos)`}}let l=_t(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},hc(t.contextDir,l);let p=c.map(u=>u.mountAs).join(", "),f=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}
|
|
578
|
+
${f}
|
|
579
|
+
or: /abort ${r} --reason "..."`}}function sn(t,e){let r=_t(t);r[e]&&(delete r[e],hc(t,r))}async function rn(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}: ${sr(o)} \u2014 check manually`)}}async function yc(t,e,r){let n=_t(t.contextDir)[e];if(n){for(let i of n.repos){let s=ar(t.root,i.mountAs);if(!nn(ar(s,".git")))continue;let a=on(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}: ${sr(p)} \u2014 check manually`)}}sn(t.contextDir,e)}}async function $f(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function sr(t){return t instanceof Error?t.message.trim():String(t)}var ao=Rc(Cf(),".codepipe","history"),bc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Tc=500,kc=40;async function Ic(){let t=Xe();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=G(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)),Gt(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=_t(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
|
|
576
580
|
\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=Ot.createInterface({input:process.stdin,output:process.stdout,completer:
|
|
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
|
|
581
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Ot.createInterface({input:process.stdin,output:process.stdout,completer:Tf,history:Yf(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};rs(s=>ct(i,s)),i.daemon=Mr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>ct(i,s),warn:s=>ct(i,s)},onEvent:s=>Mf(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),cn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await If(i,a)){Sc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,cn(i),n.prompt()}),n.on("close",()=>{Sc(i)})}function Tf(t){let e=bc.filter(r=>r.startsWith(t));return[e.length?e:bc,t]}async function If(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Pf(),!1;case"/status":return await Ef(t),!1;case"/tasks":return await jf(t,o),!1;case"/task":return await Af(t,o),!1;case"/sync":return await _f(t),!1;case"/logs":return Hf(t,o),!1;case"/monitor":return Ff(t),!1;case"/apply":return await $c(t,o,"apply"),!1;case"/unstash":return await $c(t,o,"unstash"),!1;case"/applied":return await Of(t,o),!1;case"/abort":return await Nf(t,o),!1;case"/approve":return await xc(t,o,"approve"),!1;case"/merge":return await xc(t,o,"merge"),!1;case"/login":return Lf(t,o),!1;case"/secret":return Df(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Pf(){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(`
|
|
582
|
+
`))}async function Ef(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=Cc(Rc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function jf(t,e){let r=Kf(e,"--phase");try{let o=await gs(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){lr(o)}}async function Af(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await hs(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){lr(o)}}async function _f(t){let e=await rr(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 $c(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await wc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Of(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=_t(t.ws.contextDir)[r],i=Wf(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,f;if(l>0?(p=c.slice(0,l),f=c.slice(l+1)):(f=c,p=n?.repos.length===1?Uf(t,n.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let u=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(u[1])})}try{let c=await ys(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);sn(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){lr(c)}}async function xc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await ks(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){lr(n)}}async function Nf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=qf(e,"--reason")||"local apply aborted";await yc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await bs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){lr(n)}}function Uf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Lf(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 Df(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(`
|
|
583
|
+
`)}`:" (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}Bf(t.secrets,o,i),z(t.secrets),Gt(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}Gf(t.secrets,o),z(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function Bf(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 Gf(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 Mf(t,e){switch(e.kind){case"connected":t.connection="connecting",ct(t,"[hub] connected");break;case"registered":t.connection="registered",ct(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",cr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ct(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",cr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":cr(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?ct(t,`[hub] action ${e.actionType} done`):cr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function ct(t,e){t.logBuffer.push(e),t.logBuffer.length>Tc&&t.logBuffer.shift(),t.follow&&cr(t,e)}function Hf(t,e){let r=e[0];if(r==="follow"||r==="on"){an(t,!0);return}if(r==="off"){an(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(Tc,Number(r)||kc)):kc,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 Ff(t){an(t,!t.follow)}function an(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function cr(t,e){Ot.cursorTo(process.stdout,0),Ot.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
584
|
+
`),t.unread+=1,cn(t),t.rl.prompt(!0)}function cn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var vc=!1;function Sc(t){vc||(vc=!0,Vf(t.rl),t.daemon.stop(),console.log(`
|
|
585
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Kf(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Wf(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 qf(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function lr(t){t instanceof _?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Yf(){if(!Cc(ao))return[];try{return vf(ao,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Vf(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{xf(Rf(ao),{recursive:!0}),Sf(ao,r.slice().reverse().join(`
|
|
582
586
|
`)+`
|
|
583
|
-
`)}catch{}}import{hostname as Yf}from"node:os";import{cancel as Vf,confirm as Ic,intro as Jf,isCancel as jc,log as Nt,multiselect as zf,outro as Pc,password as Xf,select as cn,text as ao}from"@clack/prompts";function pr(t){Vf(t),process.exit(1)}function Ut(t){return jc(t)&&pr("aborted"),t}function ur(t){return jc(t)&&pr("aborted"),typeof t=="string"?t:""}function ln(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Ec(t,e){try{let{secret:r}=await Lr(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&pr("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 Qf(t,e){if(Ut(await cn({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 us(t,e);if(n.length>0)return Ut(await zf({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 ur(await ao({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 un(t){Jf("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`),Ut(await Ic({message:"re-register this worker?",initialValue:!1}))||pr("keeping the existing registration"));let r=Se(t.profile)??Se(),o=ur(await ao({message:"HUB URL",placeholder:fe,initialValue:O("HUB_URL")??r?.hubUrl??fe,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=Ut(await cn({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 Ec(o,a),Nt.success("account-issued registration token minted");else if(i==="login"){let u=ur(await ao({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await no(o,u),s=await Ec(o,a),Nt.success("account-issued registration token minted")}else s=ur(await Xf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||pr("a registration token is required");let c=await Qf(o,a),l=ur(await ao({message:"worker name",initialValue:Yf(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Ut(await cn({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 nt({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"),!Ut(await Ic({message:"start the claim-loop now?",initialValue:!0}))){Pc("registered. start later with `codepipe worker`.");return}Pc("starting the claim-loop\u2026"),await tr(t.profile?{profile:t.profile}:{})}function em(){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 O("PROFILE")}var Q=em();En(Q);_n();var le=new Zf;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 Rc()}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 tc({configPath:t.config,skipVerify:t.skipVerify===!0}):await Ka({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 Hn({...t,profile:Q})}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 Wa({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 js({profile:Q})}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 Ua({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 sc({profile:Q,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 ha({profile:Q})}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 dc({profile:Q,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ac=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Ac.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??O("HUB_URL")??Se(Q)?.hubUrl??fe,r=t.token??O("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ln()){await un({profile:Q});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=O("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??O("WORKER_NAME"),i=t.llm??O("WORKER_LLM");await nt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...Q?{profile:Q}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Ac.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!re(Q)&&ln()){await un({profile:Q});return}await tr(Q?{profile:Q}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var tm=le.command("project").description("Manage CodePipe projects");tm.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await uc({profile:Q})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();
|
|
587
|
+
`)}catch{}}import{hostname as zf}from"node:os";import{cancel as Jf,confirm as Pc,intro as Xf,isCancel as Ac,log as Nt,multiselect as Qf,outro as Ec,password as Zf,select as ln,text as un}from"@clack/prompts";function ur(t){Jf(t),process.exit(1)}function Ut(t){return Ac(t)&&ur("aborted"),t}function co(t){return Ac(t)&&ur("aborted"),typeof t=="string"?t:""}function pn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function jc(t,e){try{let{secret:r}=await Lr(t,e);return r}catch(r){throw r instanceof _&&r.status===404&&ur("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 em(t,e){if(Ut(await ln({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 ds(t,e);if(n.length>0)return Ut(await Qf({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 co(await un({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 dn(t){Xf("codepipe worker \u2014 set up this machine as a runner");let e=oe(t.profile);e&&(Nt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Ut(await Pc({message:"re-register this worker?",initialValue:!1}))||ur("keeping the existing registration"));let r=Se(t.profile)??Se(),o=co(await un({message:"HUB URL",placeholder:me,initialValue:O("HUB_URL")??r?.hubUrl??me,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=Ut(await ln({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 jc(o,a),Nt.success("account-issued registration token minted");else if(i==="login"){let u=await no();a=(await io(o,u)).cliToken,s=await jc(o,a),Nt.success("account-issued registration token minted")}else s=co(await Zf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ur("a registration token is required");let c=await em(o,a),l=co(await un({message:"worker name",initialValue:zf(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Ut(await ln({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 nt({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"),!Ut(await Pc({message:"start the claim-loop now?",initialValue:!0}))){Ec("registered. start later with `codepipe worker`.");return}Ec("starting the claim-loop\u2026"),await tr(t.profile?{profile:t.profile}:{})}function rm(){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 O("PROFILE")}var Z=rm();An(Z);Nn();var ue=new tm;ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ce).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 Ic()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.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 rc({configPath:t.config,skipVerify:t.skipVerify===!0}):await qa({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.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 Kn({...t,profile:Z})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.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 Ya({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await _s({profile:Z})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.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 Da({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.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 ac({profile:Z,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ya({profile:Z})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.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 fc({profile:Z,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var _c=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");_c.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??O("HUB_URL")??Se(Z)?.hubUrl??me,r=t.token??O("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&pn()){await dn({profile:Z});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=O("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??O("WORKER_NAME"),i=t.llm??O("WORKER_LLM");await nt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...Z?{profile:Z}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});_c.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!oe(Z)&&pn()){await dn({profile:Z});return}await tr(Z?{profile:Z}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var om=ue.command("project").description("Manage CodePipe projects");om.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await pc({profile:Z})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();
|