@code-partner/codepipe 0.1.134 → 0.1.135-dev.44.g3e57365
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 +117 -108
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var ce="0.1.135-dev.44.g3e57365",me="https://hub.dev.codepipe.dev";var ge=3,Zc=3;function yr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Zc&&t<=ge}var Se=".devpipe-context.yaml",Io=[{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",Se]}];function wr(t=1){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function
|
|
6
|
-
`);
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function
|
|
9
|
-
`,{mode:384})}function mt(t){let e=
|
|
5
|
+
`}function Po(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 jo(t,e=Io){let r=[];for(let n of e)if(!(n.version<=t))for(let o of n.addedPaths)r.includes(o)||r.push(o);return r}function Eo(t,e=Io){return e.filter(r=>r.version>t)}function kr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Xe=/^[a-z][a-z0-9-]{1,30}$/,el="-codepipe-ctx";function Ce(t){return`${t}${el}`}var tl=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function br(t){for(let e of tl){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var Kt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function dt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let n=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return n?n[1]??null:null}var Qe="x-bitbucket-api-token-auth";function $r(t){switch(t){case Kt.gitlab:return"oauth2";case Kt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Ao=20;function U(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Tm}from"commander";import{homedir as Lo}from"node:os";import{mkdirSync as pl,readFileSync as dl,writeFileSync as fl,existsSync as $n}from"node:fs";import{dirname as Bo,join as Sr,resolve as ml}from"node:path";import{fileURLToPath as gl}from"node:url";import{existsSync as xr,readFileSync as Oo,readdirSync as nl,writeFileSync as ol}from"node:fs";import{dirname as il,join as Ae}from"node:path";import{parse as sl}from"yaml";import{existsSync as _o,renameSync as rl}from"node:fs";function Ze(t,e,r=n=>console.error(n)){if(_o(e)||!_o(t))return!1;try{return rl(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(n){return r(`failed to migrate ${t} \u2192 ${e}: ${n instanceof Error?n.message:String(n)} \u2014 continuing with the legacy path untouched`),!1}}var he=".codepipe",bn=".devpipe";function al(t=process.cwd()){let e=t;for(;;){if(xr(Ae(e,he,"project.yaml")))return e;if(xr(Ae(e,bn,"project.yaml")))return Ze(Ae(e,bn),Ae(e,he))&&ll(e),e;let r=il(e);if(r===e)return null;e=r}}function cl(t){let e=Ae(t,he);return xr(e)?e:Ae(t,bn)}function ll(t){let e=Ae(t,".gitignore");if(!xr(e))return;let r=Oo(e,"utf-8"),n=r.split(/\r?\n/).map(o=>{let i=o.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?o.replace(".devpipe",".codepipe"):o}).join(`
|
|
6
|
+
`);n!==r&&ol(e,n)}function et(t=process.cwd()){let e=al(t);if(!e)return null;let r=cl(e),n=ul(Oo(Ae(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:n}}function No(t,e,r){return nl(t).filter(o=>o!==".DS_Store").length===0?!0:e?r.some(o=>o.host===e.host&&o.owner===e.owner&&o.repoName===e.repoName):!1}function vr(t,e=process.cwd()){try{let r=et(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function ul(t){let e=sl(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),n=String(e.name??r),o=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of o){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,f=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:n,repos:i}}function Uo(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 Do=ml(Bo(gl(import.meta.url)),"..");function Mo(t){let e=Sr(Do,".env");if($n(e)&&process.loadEnvFile(e),t){let r=Sr(Do,"profiles",t,".env");$n(r)&&process.loadEnvFile(r)}}function ft(t){let e=U("CONFIG");return e||(t?Sr(Lo(),".codepipe","profiles",t,"config.json"):Sr(Lo(),".codepipe","config.json"))}function Te(t){let e=ft(t);if(!$n(e))return null;let r=dl(e,"utf-8");return JSON.parse(r)}function tt(t,e){let r=ft(e);pl(Bo(r),{recursive:!0}),fl(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function Cr(t){if(t)return{cfg:_e(t),profile:t};let e;try{e=et()?.spec.projectId||void 0}catch{}if(e){let r=Te(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:_e(void 0),profile:void 0}}function _e(t){let e=Te(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 ${ft(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Go}from"node:os";import{join as Fo}from"node:path";function Ho(){Ze(Fo(Go(),".devpipe"),Fo(Go(),".codepipe"))}import{homedir as Ko}from"node:os";import{existsSync as Wo,mkdirSync as Yo,readFileSync as qo,writeFileSync as Vo}from"node:fs";import{dirname as Jo,join as zo}from"node:path";function Tr(t,e,r){let n=B(t);if(!n)return"mismatch";let o=n.sandboxPins??{},i=o[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(o[e]=r,n.sandboxPins=o,J(n),"pinned")}function rt(t){return zo(Ko(),".codepipe","secrets",`${t}.json`)}function B(t){let e=rt(t);return Wo(e)?JSON.parse(qo(e,"utf-8")):null}function J(t){let e=rt(t.projectId);Yo(Jo(e),{recursive:!0}),Vo(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function Rr(){return zo(Ko(),".codepipe","shared.json")}function xn(){let t=Rr();return Wo(t)?JSON.parse(qo(t,"utf-8")):null}function Xo(t){let e=Rr();Yo(Jo(e),{recursive:!0}),Vo(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function mt(t){let e=B(t)?.claude?.oauthToken;return e||xn()?.claude?.oauthToken}function Wt(t){let e=(r,n)=>{n&&!process.env[r]&&(process.env[r]=n)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function gt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Qo(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=Te(e);r&&!t.force&&(console.error(`already configured at ${ft(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let n=t.hub.replace(/\/$/,"");tt({hubUrl:n,cliToken:t.token,projectId:t.project},e);let i={...B(t.project)??{},hubUrl:n,cliToken:t.token,projectId:t.project};J(i),console.log(`configured \u2192 hub=${n}, project=${t.project}, config=${ft(e)}`)}import{homedir as qn}from"node:os";import{join as er}from"node:path";import{appendFileSync as hl,existsSync as Zo,mkdirSync as yl,renameSync as ei,statSync as wl,unlinkSync as kl}from"node:fs";import{Writable as bl}from"node:stream";import{join as $l}from"node:path";var ti={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},ht=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&yl(e.dir,{recursive:!0}),this.currentPath=$l(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
|
+
`;hl(this.currentPath,r,"utf-8")}asWritable(){return new bl({write:(e,r,n)=>{try{let o=typeof e=="string"?e:e.toString("utf-8");for(let i of o.split(/\r?\n/))i&&this.writeLine(i);n()}catch(o){n(o)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!Zo(this.currentPath)||wl(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let n=`${this.currentPath}.${r}`;Zo(n)&&(r>=this.cfg.maxFiles?kl(n):ei(n,`${this.currentPath}.${r+1}`))}ei(this.currentPath,`${this.currentPath}.1`)}}};function Ir(t,e,r){let n=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",o=process.env[`${t}_DIR`]??r,i=xl(process.env[`${t}_MAX_BYTES`]??String(ti.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ti.maxFiles;return{enabled:n,dir:o,basename:e,maxBytes:i,maxFiles:a}}function xl(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),n=(e[2]??"").toLowerCase();return n==="g"?r*1024**3:n==="m"?r*1024**2:n==="k"?r*1024:r}function Pr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(n,o)=>(...i)=>{n(...i);try{t.writeLine(vl(o,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 vl(t,e){let r=new Date().toISOString(),n=e.map(o=>typeof o=="string"?o:Sl(o)).join(" ");return`${r} ${t} ${n}`}function Sl(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Tp}from"node:path";import"ws";import{createHash as Cl}from"node:crypto";import{existsSync as Tl,readFileSync as Rl}from"node:fs";import{homedir as Il,hostname as vn}from"node:os";import{join as Pl}from"node:path";function ri(t){return Cl("sha256").update(t).digest("hex").slice(0,12)}function jl(){let t=U("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Pl(Il(),".claude","credentials.json");if(!Tl(e))return;let r=JSON.parse(Rl(e,"utf-8")),n=[r.email,r.account?.email,r.user?.email];for(let o of n)if(typeof o=="string"&&o.includes("@"))return o.trim().toLowerCase()}catch{}}function ni(t){let e=jl(),r=U("ACCOUNT_ID")?.trim(),n=U("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:n||r,...e?{email:e}:{}};let o=mt(t);return o?{accountId:`acct-${ri(o)}`,label:n||vn(),...e?{email:e}:{}}:{accountId:`acct-${ri(`host:${vn()}`)}`,label:n||vn(),...e?{email:e}:{}}}import{existsSync as El}from"node:fs";import{join as Al}from"node:path";import{simpleGit as _l}from"simple-git";async function oi(t,e){if(!El(Al(t,".git")))return{status:"skipped"};let r=_l(t);try{await r.fetch()}catch(o){return{status:"warn",reason:`git fetch failed: ${Ol(o)}`}}let n=await r.status();if(!n.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(n.current!==e)return{status:"warn",reason:`on '${n.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 Ol(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Sn,readFileSync as ii,readdirSync as Nl,watch as Ul}from"node:fs";import{join as Cn}from"node:path";var jr=class{constructor(e,r,n,o,i=6e4){this.contextDir=e;this.projectId=r;this.send=n;this.log=o;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(Sn(this.contextDir))try{this.watcher=Ul(this.contextDir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()})}catch{this.watcher=null}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts()}}readFile(e){let r=Cn(this.contextDir,e);if(!Sn(r))return null;try{return ii(r,"utf-8")}catch{return null}}readPrompts(){let e=Cn(this.contextDir,"prompts"),r={};if(!Sn(e))return r;let n;try{n=Nl(e)}catch{return r}for(let o of n){if(!o.endsWith(".md"))continue;let i=o.slice(0,-3);try{r[i]=ii(Cn(e,o),"utf-8")}catch{}}return r}};import{existsSync as di,readFileSync as fi,readdirSync as Yl}from"node:fs";import{join as mi}from"node:path";import{simpleGit as ql}from"simple-git";import{existsSync as Ml,mkdirSync as Gl,writeFileSync as ci}from"node:fs";import{dirname as Fl,isAbsolute as Hl,join as ui,normalize as jn}from"node:path";import{simpleGit as pi}from"simple-git";import{existsSync as Oe,mkdirSync as si,readFileSync as Tn,writeFileSync as yt}from"node:fs";import{homedir as Ll}from"node:os";import{join as ye}from"node:path";import{simpleGit as Dl}from"simple-git";var wt=["project.yaml","regimen.yaml"];function Yt(t,e){let r=[],n=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[o,i]of n){let s=ye(t,o);Oe(s)||(yt(s,i),r.push(o))}return r}function nt(t,e,r){let n=ye(Ll(),".codepipe","profiles",t,"context-config");return si(n,{recursive:!0}),yt(ye(n,"project.yaml"),e.projectYaml),yt(ye(n,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${n}`),n}function Er(t,e,r){if(Oe(e))for(let n of wt){let o=ye(e,n),i=ye(t,n);if(!(!Oe(o)||Oe(i)))try{yt(i,Tn(o)),r.info(`[config] seeded local ${n} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${n}: ${s instanceof Error?s.message:String(s)}`)}}}var Bl=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function kt(t){let e=ye(t,".gitignore"),r=Oe(e)?Tn(e,"utf-8"):"",n=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(wt.filter(s=>!n.has(s)&&!n.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`;return yt(e,r+i+
|
|
13
|
+
`;return yt(e,r+i+Bl.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(
|
|
17
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
18
|
-
`),r=e.find(i=>i.startsWith("# ")),
|
|
19
|
-
`),a=s.findIndex(
|
|
20
|
-
`).replace(/^\n+/,""),
|
|
21
|
-
`);return{content:
|
|
22
|
-
`)?
|
|
23
|
-
`,supersedes:
|
|
24
|
-
|
|
25
|
-
- **Status:** superseded by ADR-${r}`):
|
|
15
|
+
`),!0}async function ai(t,e){try{if(!Oe(ye(t,".git")))return;let r=Dl(t),n=(await r.raw(["ls-files","--",...wt])).split(`
|
|
16
|
+
`).map(o=>o.trim()).filter(Boolean);if(n.length===0)return;kt(t),await r.raw(["rm","--cached","--quiet","--",...n]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await Pn(t),e.info(`[config] migrated ${n.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function Rn(t){let e=new Map;for(let r of wt){let n=ye(t,r);Oe(n)&&e.set(r,Tn(n))}return e}function In(t,e){si(t,{recursive:!0});for(let[r,n]of e){let o=ye(t,r);Oe(o)||yt(o,n)}}var li=3,Kl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function bt(t,e,r){if(!Ml(ui(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Ne(t,i.path);Gl(Fl(s),{recursive:!0}),i.encoding==="base64"?ci(s,Buffer.from(i.content,"base64")):ci(s,i.content)}let n=pi(t);await n.add(["-A","--","."]),await n.raw(["reset","-q","--",...wt]).catch(()=>{}),(await n.raw(["diff","--cached","--name-only"])).trim()&&(await n.commit(r),await Pn(t))}async function Pn(t){let e=pi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let n=0;n<=li;n++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let o=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${o}`])}catch{let i=await Wl(e);if(i.length>0&&i.every(s=>Kl.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 ${li} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Wl(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
17
|
+
`).map(r=>r.trim()).filter(Boolean)}function Ne(t,e){if(Hl(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=jn(ui(t,e)),n=jn(t+"/");if(r!==jn(t)&&!r.startsWith(n))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Vl=/^(\d{4})-(.+)\.md$/,Jl="0000-template.md";function zl(t){let e=t.split(`
|
|
18
|
+
`),r=e.find(i=>i.startsWith("# ")),n=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",o=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:n,status:o("Status"),date:o("Date")}}function Xl(t,e,r,n,o){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
19
|
+
`),a=s.findIndex(C=>C.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],f="",p=null,g=a>=0?a+1:0;for(let C=g;C<s.length;C++){let T=(s[C]??"").trim();if(T===""){g=C+1;continue}let k=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(T);if(!k)break;let b=(k[1]??"").trim().toLowerCase(),_=(k[2]??"").trim(),O=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(T);O&&(p=parseInt(O[1]??"",10)),b==="tasks"&&(f=_),l.has(b)||u.push(T),g=C+1}let d=f?f.includes(n)?f:`${f}, ${n}`:n,y=s.slice(g).join(`
|
|
20
|
+
`).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${o}`,`- **Tasks:** ${d}`,...u,"",y].join(`
|
|
21
|
+
`);return{content:S.endsWith(`
|
|
22
|
+
`)?S:S+`
|
|
23
|
+
`,supersedes:p}}function Ql(t,e){let r=String(e).padStart(4,"0"),n=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return n===t?t.replace(/^(# .*)$/m,`$1
|
|
24
|
+
|
|
25
|
+
- **Status:** superseded by ADR-${r}`):n}function Zl(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((n,o)=>n.num-o.num)){let n=String(r.num).padStart(4,"0"),o=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${n} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${o}`)}return e.join(`
|
|
26
26
|
`)+`
|
|
27
|
-
`}async function
|
|
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 Ar(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 eu(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 eu(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 yi(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 jo=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 rt(`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()}`)}},Eo=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 rt(`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(y=>y.conclusion==="failure")){let y=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!y.ok)continue;let v=await y.text();p.push(`### CI job: ${g.name}
|
|
27
|
+
`}async function gi(t,e,r,n=new Date().toISOString().slice(0,10)){try{await ql(t).pull(void 0,void 0,["--rebase"])}catch{}let o=[],i=[];for(let d of r){let y=Ne(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!di(y)){i.push(d);continue}o.push({slug:d,content:fi(y,"utf-8")})}let s=mi(t,"adr"),a=new Map;if(di(s))for(let d of Yl(s)){let y=Vl.exec(d);!y||d===Jl||a.set(d,{num:parseInt(y[1]??"",10),slug:y[2]??"",content:fi(mi(s,d),"utf-8")})}let c=Math.max(0,...[...a.values()].map(d=>d.num))+1,l=new Map,u=[],f=[];for(let d of o){if([...a.entries()].find(([,b])=>b.slug===d.slug&&b.content.includes(e))){f.push(d.slug);continue}let S=c++,C=`${String(S).padStart(4,"0")}-${d.slug}.md`,{content:T,supersedes:k}=Xl(d.content,S,d.slug,e,n);if(l.set(C,T),a.set(C,{num:S,slug:d.slug,content:T}),u.push(`adr/${C}`),k!==null){let b=[...a.keys()].find(_=>_.startsWith(`${String(k).padStart(4,"0")}-`));if(b&&b!==C){let _=Ql(l.get(b)??a.get(b).content,S);l.set(b,_),a.set(b,{...a.get(b),content:_})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,y])=>({num:y.num,file:d,header:zl(y.content)}));l.set("INDEX.md",Zl(p));let g=[...l.entries()].map(([d,y])=>({path:`adr/${d}`,content:y}));return await bt(t,g,`adr(${e}): promote ${o.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as hi,readFileSync as tu}from"node:fs";import{join as yi}from"node:path";function ru(t){let e=yi(t,Se);if(!hi(e))return 0;try{return Po(tu(e,"utf-8"))}catch{return 0}}function nu(t,e,r,n=1){let o=e<n,i=o?jo(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:n,outdated:o,missingPaths:i}}function Ar(t,e){return nu(e,ru(t),r=>hi(yi(t,r)))}import{existsSync as wu,mkdirSync as ku,mkdtempSync as bu,rmSync as $u,writeFileSync as $i}from"node:fs";import{tmpdir as xu}from"node:os";import{dirname as vu,join as Nn}from"node:path";import{simpleGit as Un}from"simple-git";var ot=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function wi(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
28
|
+
`+t.slice(t.length-e)}async function Ue(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let i=(await n.json()).login??"ok",s=n.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function _r(t,e,r){let n=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,o;try{o=await fetch(n,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(o.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!o.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${o.status} ${o.statusText}`);if((await o.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Le(t,e,r){let n=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",o;try{o=await fetch(n,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(o.ok)return t;if(o.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await ou(o);throw o.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):o.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):o.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${o.status} ${o.statusText}${i}`)}async function ou(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function De(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(n){throw new Error(`cannot reach gitlab.com (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function bi(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let n=(await e.json()).scopes??[];return n.length>0&&!n.includes("api")?`GitLab token scopes [${n.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var En=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!n.ok)throw new Error(`bitbucket pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.links?.html?.href??"",number:o.id}}async findOpenPrByBranch(e,r){let n=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${n}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let s=(await o.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let n=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(o.status===404)throw new ot(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){let i=n==="squash"?"squash":n==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:o})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,n){if(n&&n.length>0){let i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:n}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!o.ok)throw new Error(`bitbucket decline PR #${r}: ${o.status} ${await o.text()}`)}},An=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!n.ok)throw new Error(`github pr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.html_url,number:o.number}}async findOpenPrByBranch(e,r){let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let n=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,o=await fetch(n,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(o.status===404)throw new ot(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(o.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${o}/check-runs?per_page=100`,{headers:n}),fetch(`${o}/status`,{headers:n})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let f of u.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let n={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},o=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${o}/pulls/${r}`,{headers:n});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${o}/actions/runs?head_sha=${a}&per_page=20`,{headers:n});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let f of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${o}/actions/runs/${f.id}/jobs?per_page=50`,{headers:n});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(y=>y.conclusion==="failure")){let y=await fetch(`${o}/actions/jobs/${d.id}/logs`,{headers:n});if(!y.ok)continue;let S=await y.text();u.push(`### CI job: ${d.name}
|
|
29
29
|
|
|
30
|
-
${
|
|
30
|
+
${wi(S,8e3)}`)}}return u.length===0?void 0:wi(u.join(`
|
|
31
31
|
|
|
32
|
-
`),16e3)}catch{return}}async mergePR(e,r,o
|
|
32
|
+
`),16e3)}catch{return}}async mergePR(e,r,n,o){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:n})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(o){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,n){if(n&&n.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:n})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`github close PR #${r}: ${o.status} ${await o.text()}`)}},_n=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 n=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(!n.ok)throw new Error(`gitlab mr create: ${n.status} ${await n.text()}`);let o=await n.json();return{url:o.web_url??"",number:o.iid}}async findOpenPrByBranch(e,r){let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!n.ok)return null;let i=(await n.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let n=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,o=await fetch(n,{method:"GET",headers:this.headers()});if(o.status===404)throw new ot(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(o.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${o.status} ${await o.text()}`);let i=await o.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=iu(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,n,o){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:n==="squash",should_remove_source_branch:o})});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,n){if(n&&n.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:n})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let o=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(!o.ok)throw new Error(`gitlab close MR !${r}: ${o.status} ${await o.text()}`)}};function iu(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 On=class{name="mock";async createPullRequest(e,r){let n=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${n}`,number:n}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,n,o){throw new Error(ki(e,r,"merge"))}async closePR(e,r,n){throw new Error(ki(e,r,"close"))}};function ki(t,e,r){let n=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 ${n}`}function Re(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new An(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new En(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new _n(e)}return new On}function $t(t,e,r,n){return[{path:"README.md",content:gu(t,e)},{path:".gitignore",content:uu()},{path:"CLAUDE.md",content:du(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:pu()},{path:"knowledge/README.md",content:fu()},{path:"knowledge/build.yaml",content:mu()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:lu()},{path:"adr/README.md",content:su()},{path:"adr/0000-template.md",content:au()},{path:"adr/INDEX.md",content:cu()},{path:Se,content:wr()}]}function su(){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 au(){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 cu(){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 lu(){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
|
|
96
|
+
`}function we(t,e,r,n){return{projectYaml:hu(t,r,n),regimenYaml:yu(t.automationLevel,e)}}function uu(){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 pu(){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 du(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 fu(){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 mu(){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 gu(t,e){return`# ${e.name}
|
|
222
222
|
|
|
223
223
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
224
224
|
|
|
@@ -244,11 +244,11 @@ 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 hu(t,e,r){let n=e?`
|
|
248
248
|
tracker_url: ${e}`:`
|
|
249
|
-
# tracker_url: https://your.youtrack.cloud`,
|
|
249
|
+
# tracker_url: https://your.youtrack.cloud`,o=r?`require_assignee: true
|
|
250
250
|
assignee: ${r}`:`require_assignee: false
|
|
251
|
-
# assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${
|
|
251
|
+
# assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${n}
|
|
252
252
|
poll_interval_sec: 60
|
|
253
253
|
# Values of the custom YT \`Stage\` field. CodePipe only pulls tasks with
|
|
254
254
|
# one of these stages into the pipeline.
|
|
@@ -259,11 +259,16 @@ Automation level: **${t.automationLevel}**.
|
|
|
259
259
|
# promoted with the Develop button or moved into source_columns manually.
|
|
260
260
|
# Optional: remove the key to disable the TODO section.
|
|
261
261
|
backlog_column: Backlog
|
|
262
|
+
# Optional: YT stages meaning the task is completed. A task in one of these
|
|
263
|
+
# stages is synced to DONE and leaves the board (must not overlap the stages
|
|
264
|
+
# above). Its open PR is left untouched. Remove the key to disable.
|
|
265
|
+
# done_columns:
|
|
266
|
+
# - Done
|
|
262
267
|
# Sync gate on assignee. require_assignee=false (or the key missing) \u2014
|
|
263
268
|
# behavior unchanged. When true, CodePipe only pulls tasks of the given
|
|
264
269
|
# assignee (YT login) into the pipeline; without assignee \u2014 any task with a
|
|
265
270
|
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
266
|
-
${
|
|
271
|
+
${o}`:` # project_key: \u2026
|
|
267
272
|
# tracker_url: https://your.youtrack.cloud
|
|
268
273
|
poll_interval_sec: 60`,s=t.repos.length===0?` [] # add repos here
|
|
269
274
|
`:t.repos.map(a=>` - name: ${a.name}
|
|
@@ -302,7 +307,7 @@ branch:
|
|
|
302
307
|
|
|
303
308
|
repos:
|
|
304
309
|
${s}
|
|
305
|
-
`}function
|
|
310
|
+
`}function yu(t,e){let r=t==="full",n=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
306
311
|
automation:
|
|
307
312
|
level: ${t}
|
|
308
313
|
|
|
@@ -312,11 +317,11 @@ youtrack:
|
|
|
312
317
|
# These flags are set from a dedicated 'codepipe init' question and do
|
|
313
318
|
# NOT depend on automation.level \u2014 the two are orthogonal axes (writes vs gates).
|
|
314
319
|
writes:
|
|
315
|
-
enabled: ${
|
|
316
|
-
status_changes: ${
|
|
317
|
-
pr_comment: ${
|
|
320
|
+
enabled: ${n}
|
|
321
|
+
status_changes: ${n}
|
|
322
|
+
pr_comment: ${n}
|
|
318
323
|
# Mirror dashboard comments back into YouTrack. Off without enabled.
|
|
319
|
-
dashboard_mirror: ${
|
|
324
|
+
dashboard_mirror: ${n}
|
|
320
325
|
# YT column (Stage) for new drafts published from PLAN.
|
|
321
326
|
# Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
|
|
322
327
|
draft_target_status: Backlog
|
|
@@ -417,22 +422,26 @@ parallelism:
|
|
|
417
422
|
# # the previous task's branch (auto-merge without reworking the
|
|
418
423
|
# # tail of the chain).
|
|
419
424
|
# 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 Au(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 Ri(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Lo(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 _u(t){try{let e=await fetch(t);return e.ok?new Ri(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ai(t,e=443,r=Pi){let o=`${t}:${e}`,n=Ti.get(o);if(n)return n;let i=Ou(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ti.set(o,i),i}async function Ou(t,e,r){if(!Ii)return!1;let o=8e3;if(await Lo(t,e,o))return!0;let n=await Au(t,e,o),i=Le.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=Eu(n);if(!c)break;let l=await _u(c);if(!l)break;if(s.push(l.toString()),Le.setDefaultCACertificates([...i,...s]),await Lo(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 Lo(t,e,o)}function ot(){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){ji();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(Ei(s)&&await Ai(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var _i=t=>new Promise(e=>setTimeout(e,t));function Nu(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Uu(){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 Ui(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Uu(),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&&Nu(l.status,p)){await _i(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<n){await _i(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 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 Li(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 Oi=new Map;async function Lu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Oi.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 Oi.set(o,c.id),c.id}async function Bi(t,e,r){let o=await Lu(t,e,r);await Ui(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 Di(t,e,r){return await(await Ui(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ni=new Map;async function Bu(t,e){let r=Ni.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 Ni.set(e,i.id),i.id}async function Mi(t,e,r,o,n){let i=await Bu(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 Gi(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 Fi="attachments(id,name,url,size,mimeType)",Du="links(direction,linkType(name),issues(idReadable))",Hi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Fi},${Du}`,Mu=`id,text,created,author(login),${Fi}`;function Ki(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 Wi(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 qi(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=${Hi}&$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(zi)}async function Yi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Hi}`,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 zi(await o.json())}async function Vi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Mu}&$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=Ki(s.attachments);return c&&(a.attachments=c),a})}function Gu(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 zi(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=Ki(t.attachments);s&&(i.attachments=s);let a=Gu(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 Ji(t,e){let r=L(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: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 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: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 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: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 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: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 Ar(c,p.owner,p.repoName),o.push({name:`repo:${p.name}`,ok:!0})}catch(f){o.push({name:`repo:${p.name}`,ok:!1,detail:pe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ar(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 Ar(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=mt(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 Bo(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 Bo(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 Wt(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 qt(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 Yt(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 Do(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 Xi(t,e=process.env){return Do(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Wt(t,e),e)}function Qi(t,e=process.env){return Do(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>qt(t,e),e)}function Zi(t,e=process.env){return Do(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Je}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Yt(t,e),e)}function es(t){let e=L(t);if(!e)return null;if(!e.sealKey){let r=_r();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ye(e.sealKey.publicKey)}}async function ts(t,e,r,o){let n;try{n=JSON.parse(Or(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=L(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},xt(i,()=>{process.env.GH_TOKEN=n.token,Xi(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},xt(i,()=>{process.env.GITLAB_TOKEN=n.token,Qi(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},xt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Zi(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},xt(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 Bo(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},xt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},xt(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 xt(t,e){V(t),e()}import{existsSync as Fu,readFileSync as Hu,writeFileSync as Ku}from"node:fs";import{join as Wu}from"node:path";import{parseDocument as qu}from"yaml";var rs=64;async function os(t,e){if(!Number.isInteger(e)||e<1||e>rs)throw new Error(`maxJobs must be an integer in [1, ${rs}], got ${e}`);let r=Wu(t,"regimen.yaml");if(!Fu(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=qu(Hu(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Ku(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Yu,readFileSync as Vu,writeFileSync as zu}from"node:fs";import{join as Ju}from"node:path";import{isMap as ns,parseDocument as Xu}from"yaml";async function is(t,e){let r=e.repoName?.trim(),o=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!o||!jn(o))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let n=Ju(t,"project.yaml");if(!Yu(n))throw new Error(`project.yaml not found in context repo (${t})`);let i=Xu(Vu(n,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>ns(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!ns(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",o),zu(n,i.toString()),{repoName:r,defaultBranch:o}}import{existsSync as ss,readFileSync as as,writeFileSync as Qu}from"node:fs";import{join as Mo}from"node:path";import{parseDocument as cs}from"yaml";async function ls(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=Mo(t,"project.yaml");if(!ss(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=cs(as(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=Mo(t,"regimen.yaml");if(!ss(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=cs(as(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)Qu(Mo(t,i.path),i.content);return{files:r.map(i=>i.path)}}var us=t=>console.log(t);function ps(t){us=t}function Vt(t,e="info"){us(t,e)}import{homedir as Zu}from"node:os";import{existsSync as ep,mkdirSync as tp}from"node:fs";import{join as Go}from"node:path";import{simpleGit as ds}from"simple-git";function Jt(t,e,r){let o=r??Go(Zu(),".codepipe","repos");return Go(o,t,e)}async function Nr(t,e,r={}){let o=Jt(t,e.name,r.baseDir),n=r.cloneUrlOverride??rp(e);if(!ep(Go(o,".git"))){tp(o,{recursive:!0});let a=ds();Vt(`[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
|
|
425
|
-
${
|
|
426
|
-
`,{mode:384})}function pp(t){return bs()[t]}function Br(t,e){let r=bs();r[t]=e,up(r)}function Dr(t,e){let r=ye(e),o=pp(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 ${Ho()}.`);return r}import dp from"ws";function Mr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new dp(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function vt(t,e,r){return De(t,e,"/projects",r)}async function ks(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 Gr(t,e,r,o){return De(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Fr(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 $s(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 Xt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function xs(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 Xt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function vs(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 Ss(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 Cs(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 Ts(t,e,r,o){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Rs(t,e,r,o,n){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function Is(t,e,r,o,n){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function Ps(t,e,r,o,n){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Hr(t,e,r,o){return De(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function Ko(t,e,r,o){await De(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function Z(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 De(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}async function _s(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ye(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Dr(e.farmId,e.farmPublicKey);let s=L(t.projectId);if(!s)return n("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Z(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=As(r,"project.yaml"),d=As(r,"regimen.yaml");js(u)&&js(d)?c={projectYaml:Es(u,"utf-8"),regimenYaml:Es(d,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},p=$t(e.farmPublicKey,JSON.stringify(l));Br(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await Gr(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var Kr=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=Te(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 rt){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=Te(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=fp(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function fp(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Wr=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=ot();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 qi(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 Os(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 Os(r,u,e.sinceMs,this.log);if(d&&i.push({issueId:u,comments:d}),e.requireAssignee){let g=await gp(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 Wi(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=mp(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 mp(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 gp(t,e,r){try{return await Yi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Os(t,e,r,o){try{return await Vi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Wo="npm i -g @code-partner/codepipe@latest";function qr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ae} (protocol ${fe})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&si(n.contextDir,r);let i=Ns("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ns("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,p=new Set,f=u();function u(){let d=Mr(t.hubUrl,t.cliToken),g=null,y=new Kr(i,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),v=new Wr(s,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),x=null,S=async()=>{try{let C;try{let h=await Z(t.hubUrl,t.cliToken,t.projectId);C={repos:h.repos,contextRepo:h.contextRepo}}catch(h){r.warn(`[readiness] could not fetch project summary for push checks: ${h instanceof Error?h.message:String(h)}`)}let _=await Ji(t.projectId,C);if(d.readyState!==d.OPEN)return;let R={type:"cli_readiness",projectId:t.projectId,ready:_.ready,checks:_.checks,creds:_.creds,checkedAt:_.checkedAt};if(d.send(JSON.stringify(R)),_.ready)r.info("[readiness] ready");else{let h=_.checks.filter(m=>!m.ok).map(m=>`${m.name}(${m.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${h.join(", ")}`)}}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},E=()=>{S(),x=setInterval(()=>void S(),a),typeof x.unref=="function"&&x.unref()},I=()=>{x&&(clearInterval(x),x=null)},B=n?.contextDir?new Ir(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=ri(t.projectId),_=N("ORIGIN")==="farm"?"farm":"local",R=N("FARM_ID"),h=t.accountEmail??C.email,m;try{let k=es(t.projectId);k&&(m=k.publicKey,r.info(`[cred-channel] key fingerprint: ${k.fingerprint}`))}catch(k){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${k instanceof Error?k.message:String(k)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ae,protocolVersion:fe,accountId:C.accountId,accountLabel:C.label,origin:_,inFlightActionIds:[...p],...h?{accountEmail:h}:{},..._==="farm"&&R?{farmId:R}:{},...m?{sealPublicKey:m}:{}};d.send(JSON.stringify(w))}),d.on("message",async C=>{let _=C.toString("utf-8");if(_==="pong"||_==="ping")return;let R;try{R=JSON.parse(_)}catch{return}if(!R||typeof R!="object")return;let h=R.type;if(h==="registered"){let w=R;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),o({kind:"registered",projectId:w.projectId??t.projectId}),y.start(),B?.start(),E(),n?.contextDir){let k=n.contextDir;try{let $=Er(k,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let O;try{O=(await Z(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let q=await bi(k,t.projectId,O,r);d.readyState===d.OPEN&&d.send(JSON.stringify(q))}catch(O){r.warn(`[ctx] context migration failed (non-fatal): ${O instanceof Error?O.message:String(O)}`)}})()))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),o({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(h==="hello"){let w=R;g=hr(w.protocolVersion);let k=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${k}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ae}, protocol ${fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Wo}`),o({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Wo}));return}if(h==="tracking_targets"){y.setTargets(R.targets);return}if(h==="youtrack_sync_request"){v.setRequest(R);return}if(h==="sync_local"){await yp(R,n,d,r);return}if(h==="context_write"){await wp(R,n,d,r);return}if(h==="adr_promote"){await bp(R,n,d,r);return}if(h==="cred_update"){let w=R,k=L(t.projectId),$=k?.sealKey?await ts(t.projectId,w.kind,w.sealed,k.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},O={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(O)),$.ok?(r.info(`[cred] ${w.kind} replaced${$.detail?` \u2014 ${$.detail}`:""}`),S()):r.warn(`[cred] ${w.kind} replacement rejected: ${$.detail??"unknown"}`);return}if(h==="move_to_farm"){let w=R;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let k=await _s(t,w,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(k)),k.ok?r.info(`[farm-move] done \u2014 farm daemon ${k.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${k.error??"unknown error"}`);return}if(h==="sandbox_keys"){let w=L(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let k=mt(t.projectId),$=Si(R,w,k,r);for(let O of $)d.readyState===d.OPEN&&d.send(JSON.stringify(O));return}if(h!=="dispatch_action")return;let m=R;if(g===!1){let w=`refused: HUB protocol incompatible with CLI v${ae} (protocol ${fe})`;d.send(JSON.stringify({type:"action_result",actionId:m.actionId,status:"failed",error:w})),r.warn(`[exec] ${m.actionId} (${m.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Wo}`),o({kind:"action",actionId:m.actionId,actionType:m.action.type,ok:!1,error:w});return}p.add(m.actionId);try{let w=await ws({action:m.action,repo:m.repo,trackerIssueId:m.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:B?()=>B.reportNow():void 0}).catch(O=>({status:"failed",error:O instanceof Error?O.message:String(O)}));d.send(JSON.stringify({type:"action_result",actionId:m.actionId,...w}));let k=w.status!=="failed",$=!k&&"error"in w?w.error:void 0;k?r.info(`[exec] ${m.actionId} (${m.action.type}) \u2192 done`):r.warn(`[exec] ${m.actionId} (${m.action.type}) \u2192 FAILED: ${$??"?"}`),o({kind:"action",actionId:m.actionId,actionType:m.action.type,ok:k,...$?{error:$}:{}})}finally{p.delete(m.actionId)}}),d.on("close",(C,_)=>{let R=_?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${R?` reason=${R}`:""}`),y.stop(),v.stop(),B?.stop(),I(),R==="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 yp(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=hp(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await oi(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 wp(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 jr(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 bp(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 di(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function Ns(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Fs,mkdirSync as Hs}from"node:fs";import{dirname as Ks}from"node:path";import{simpleGit as St}from"simple-git";import{execFileSync as kp}from"node:child_process";import{mkdtempSync as $p,mkdirSync as xp,readFileSync as Us,rmSync as vp,writeFileSync as Sp}from"node:fs";import{tmpdir as Cp}from"node:os";import{dirname as Tp,join as Ls}from"node:path";function Bs(t="codepipe-context"){let e=$p(Ls(Cp(),"codepipe-ssh-")),r=Ls(e,"id_ed25519");try{return kp("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Us(r,"utf-8"),publicKey:Us(`${r}.pub`,"utf-8").trim()}}finally{vp(e,{recursive:!0,force:!0})}}async function Ds(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 Ms(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 Gs(t,e){xp(Tp(t),{recursive:!0});let r=e.endsWith(`
|
|
425
|
+
`}function Su(t){return`codepipe/context-migration-v${t}`}function Cu(t){let e=Eo(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 \`${Se}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let n of e){r.push(`- **v${n.version}** \u2014 ${n.summary}`);for(let o of n.addedPaths)r.push(` - \`${o}\``)}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(`
|
|
426
|
+
`)}async function xi(t,e,r,n){let o=Un(t);await o.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Ar(t,e);if(!i.outdated)return i;let s=Su(i.currentVersion),a=r?.branch??(await o.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await o.fetch().catch(()=>{}),(await o.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Tu(t,e,r,i,s,a,n):n.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return n.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Re(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return n.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Cu(i)});return n.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return n.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function Tu(t,e,r,n,o,i,s){let a=Un(t),c=bu(Nn(xu(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",o,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map($t(l,u).map(d=>[d.path,d.content])),p=0;for(let d of n.missingPaths){if(d===Se)continue;let y=f.get(d);if(y==null){s.warn(`[ctx] migration: no template for ${d} \u2014 skipped`);continue}let S=Nn(c,d);wu(S)||(ku(vu(S),{recursive:!0}),$i(S,y),p++)}$i(Nn(c,Se),wr(n.currentVersion)),p++;let g=Un(c);await g.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await g.commit(`chore(context): migrate format v${n.templateVersion} -> v${n.currentVersion}`),await g.push(["-u","origin",o]),s.info(`[ctx] migration branch ${o} pushed (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),$u(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",o]).catch(()=>{})}}import{createCipheriv as Ru,createDecipheriv as Iu,createHash as Pu,createPrivateKey as ju,createPublicKey as Ln,diffieHellman as vi,generateKeyPairSync as Si,hkdfSync as Ci,randomBytes as Eu}from"node:crypto";var Ti=Buffer.from("devpipe-sealedbox-v1","utf-8");function Or(){let{publicKey:t,privateKey:e}=Si("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ke(t){let e=Buffer.from(t,"base64");return(Pu("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function xt(t,e){let r=Ln({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:n,privateKey:o}=Si("x25519"),i=n.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=vi({privateKey:o,publicKey:r}),c=Buffer.from(Ci("sha256",a,Buffer.concat([i,s]),Ti,32)),l=Eu(12),u=Ru("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(f),u.final()]),g=u.getAuthTag(),d={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(d),"utf-8").toString("base64")}function Nr(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let n=ju({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),o=Ln({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=o.export({type:"spki",format:"der"}),s=Ln(n).export({type:"spki",format:"der"}),a=vi({privateKey:n,publicKey:o}),c=Buffer.from(Ci("sha256",a,Buffer.concat([i,s]),Ti,32)),l=Iu("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}function Au(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let n=e??t.claude?.oauthToken;return n&&(r.claudeOauthToken=n),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function Ri(t,e,r,n){let o=Au(e,r);t.sandboxes.length>0&&!o.claudeOauthToken&&n.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!o.contextWrite&&(o.github||o.gitlab||o.bitbucket)&&n.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(o),s=[];for(let a of t.sandboxes){let c=Tr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){n.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&n.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=xt(a.publicKey,i)}catch(u){n.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as ji}from"node:crypto";import{readFileSync as _u}from"node:fs";import Be from"node:tls";var Ei=typeof Be.getCACertificates=="function"&&typeof Be.setDefaultCACertificates=="function",Ii=!1,Pi=new Map,Ai=t=>console.warn(t);function Ou(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function _i(t=Ai){if(Ii)return;Ii=!0;let e=U("EXTRA_CA_FILE");if(!(!e||!Ei))try{let r=Ou(_u(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Be.setDefaultCACertificates([...Be.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 Oi(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 Nu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
427
|
+
`)){let n=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(n?.[1])return n[1].trim()}return null}function Uu(t,e,r){return new Promise((n,o)=>{let i=Be.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 ji(s.raw):null;i.end(),n(c)});i.on("error",o),i.setTimeout(r,()=>{i.destroy(),o(new Error("tls connect timeout"))})})}function Dn(t,e,r){return new Promise(n=>{let o=Be.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{o.end(),n(!0)});o.on("error",()=>n(!1)),o.setTimeout(r,()=>{o.destroy(),n(!1)})})}async function Lu(t){try{let e=await fetch(t);return e.ok?new ji(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ni(t,e=443,r=Ai){let n=`${t}:${e}`,o=Pi.get(n);if(o)return o;let i=Du(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Pi.set(n,i),i}async function Du(t,e,r){if(!Ei)return!1;let n=8e3;if(await Dn(t,e,n))return!0;let o=await Uu(t,e,n),i=Be.getCACertificates(),s=[];for(let a=0;a<4&&o&&o.subject!==o.issuer;a++){let c=Nu(o);if(!c)break;let l=await Lu(c);if(!l)break;if(s.push(l.toString()),Be.setDefaultCACertificates([...i,...s]),await Dn(t,e,n))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;o=l}return Dn(t,e,n)}function it(){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){_i();let n={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(n["Content-Type"]="application/json");let o=t.baseUrl+e,i={...r,headers:{...n,...r?.headers??{}}};try{return await fetch(o,i)}catch(s){if(Oi(s)&&await Ni(new URL(t.baseUrl).host))return await fetch(o,i);throw s}}var Ui=t=>new Promise(e=>setTimeout(e,t));function Bu(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Mu(){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 Bi(t,e,r,n){let{attempts:o,baseMs:i,capMs:s}=Mu(),a=null;for(let c=1;c<=o;c++){let l=null;try{l=await be(t,r,n)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<o&&Bu(l.status,u)){await Ui(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<o){await Ui(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Me(t){let e;try{e=await be(t,"/api/users/me?fields=login,fullName")}catch(n){throw new Error(`cannot reach ${t.baseUrl} (${n instanceof Error?n.message:String(n)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Mi(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 Li=new Map;async function Gu(t,e,r){let n=`${e.split("-")[0]}:${r}`,o=Li.get(n);if(o)return o;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 Li.set(n,c.id),c.id}async function Gi(t,e,r){let n=await Gu(t,e,r);await Bi(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:n,$type:"StateBundleElement"}}]})})}async function Fi(t,e,r){return await(await Bi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Di=new Map;async function Fu(t,e){let r=Di.get(e);if(r)return r;let n=await be(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!n.ok)throw new Error(`yt resolveProjectId: ${n.status} ${await n.text()}`);let i=(await n.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Di.set(e,i.id),i.id}async function Hi(t,e,r,n,o){let i=await Fu(t,e),s=await be(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:n,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:o,$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 Ki(t,e,r,n){let o=r==="subtask_of"?`subtask of ${n}`:`depends on ${n}`,i=await be(t,"/api/commands",{method:"POST",body:JSON.stringify({query:o,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${o} on ${e}): ${i.status} ${await i.text()}`)}var Wi="attachments(id,name,url,size,mimeType)",Hu="links(direction,linkType(name),issues(idReadable))",Yi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Wi},${Hu}`,Ku=`id,text,created,author(login),${Wi}`;function qi(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Vi(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,n=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!n.ok)throw new Error(`yt downloadAttachment ${e}: ${n.status}`);return Buffer.from(await n.arrayBuffer())}async function Ji(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 n=r.join(" "),o=`/api/issues?query=${encodeURIComponent(n)}&fields=${Yi}&$top=200`,i=await be(t,o);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Qi)}async function zi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Yi}`,n=await be(t,r);if(n.status===404)return null;if(!n.ok)throw new Error(`yt getIssue ${e}: ${n.status} ${await n.text()}`);return Qi(await n.json())}async function Xi(t,e,r){let n=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Ku}&$top=500`,o=await be(t,n);if(!o.ok)throw new Error(`yt listComments ${e}: ${o.status} ${await o.text()}`);return(await o.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=qi(s.attachments);return c&&(a.attachments=c),a})}function Wu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let n=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(n)for(let o of r.issues??[])o.idReadable&&e.push({type:n,targetKey:o.idReadable})}return e.length>0?e:void 0}function Qi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),n=e.find(c=>c.name==="Assignee"),o=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),n?.value?.login&&(i.assignee=n.value.login),o?.value?.name&&(i.issueType=o.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=qi(t.attachments);s&&(i.attachments=s);let a=Wu(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 Zi(t,e){let r=B(t),n=[],o=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Me({baseUrl:r.youtrack.url,token:r.youtrack.token});n.push({name:"youtrack",ok:!0}),o.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"youtrack",ok:!1,detail:de(c)}),o.push({kind:"youtrack",present:!0,ok:!1,detail:de(c),checkedAt:i()})}else n.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),o.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await Ue(r.github.token);n.push({name:"github",ok:!0}),o.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"github",ok:!1,detail:de(c)}),o.push({kind:"github",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else o.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Le(r.bitbucket.email,r.bitbucket.apiToken);n.push({name:"bitbucket",ok:!0}),o.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"bitbucket",ok:!1,detail:de(c)}),o.push({kind:"bitbucket",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else o.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await De(r.gitlab.token);n.push({name:"gitlab",ok:!0}),o.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){n.push({name:"gitlab",ok:!1,detail:de(c)}),o.push({kind:"gitlab",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else o.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||n.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await _r(c,u.owner,u.repoName),n.push({name:`repo:${u.name}`,ok:!0})}catch(f){n.push({name:`repo:${u.name}`,ok:!1,detail:de(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await _r(c,l.owner,l.name),n.push({name:"context-repo",ok:!0})}catch(u){n.push({name:"context-repo",ok:!1,detail:de(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await _r(r.contextWrite.token,c.owner,c.name),o.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){o.push({kind:"contextWrite",present:!0,ok:!1,detail:de(l),checkedAt:i()})}else o.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else o.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=mt(t);if(!a)n.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),o.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Bn(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";n.push({name:"claude",ok:!1,detail:l}),o.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else n.push({name:"claude",ok:!0}),o.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:n.every(c=>c.ok),checks:n,creds:o,checkedAt:Date.now()}}async function Bn(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let n=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return n.status===200?"valid":n.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function qt(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@github.com:"),o(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Vt(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@gitlab.com:"),o(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Jt(t,e=process.env){if(!t)return!1;let r=`https://${Qe}:${encodeURIComponent(t)}@bitbucket.org/`,n=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,o=(i,s)=>{e[`GIT_CONFIG_KEY_${n+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${n+i}`]=s};return o(0,"git@bitbucket.org:"),o(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(n+2),!0}function Mn(t,e,r,n){let o=Number.parseInt(n.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<o;s++){let a=n[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(n[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function es(t,e=process.env){return Mn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>qt(t,e),e)}function ts(t,e=process.env){return Mn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Vt(t,e),e)}function rs(t,e=process.env){return Mn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Qe}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Jt(t,e),e)}function ns(t){let e=B(t);if(!e)return null;if(!e.sealKey){let r=Or();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},J(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ke(e.sealKey.publicKey)}}async function os(t,e,r,n){let o;try{o=JSON.parse(Nr(n,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=B(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Ue(o.token);return i.github={token:o.token},vt(i,()=>{process.env.GH_TOKEN=o.token,es(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await De(o.token);return i.gitlab={token:o.token},vt(i,()=>{process.env.GITLAB_TOKEN=o.token,ts(o.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!o.email||!o.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Le(o.email,o.apiToken);return i.bitbucket={email:o.email,apiToken:o.apiToken},vt(i,()=>{process.env.BITBUCKET_EMAIL=o.email,process.env.BITBUCKET_API_TOKEN=o.apiToken,rs(o.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=o.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Me({baseUrl:s,token:o.token});return i.youtrack={url:s,token:o.token},vt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=o.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!o.token)return{ok:!1,detail:"payload has no token"};let s=await Bn(o.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:o.token},vt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return o.token?(i.contextWrite={token:o.token},vt(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 vt(t,e){J(t),e()}import{existsSync as Yu,readFileSync as qu,statSync as is}from"node:fs";var ss=2*1024*1024;function Vu(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function as(t,e){let r=Ne(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!Yu(r)||!is(r).isFile())throw new Error(`file not found: ${e}`);let{size:n}=is(r);if(n>ss)throw new Error(`file too large: ${e} is ${n} bytes (limit ${ss})`);let o=qu(r);return Vu(o)?{content:o.toString("utf-8"),encoding:"utf8",sizeBytes:o.length}:{content:o.toString("base64"),encoding:"base64",sizeBytes:o.length}}import{existsSync as Ju,readFileSync as zu,writeFileSync as Xu}from"node:fs";import{join as Qu}from"node:path";import{parseDocument as Zu}from"yaml";var cs=64;async function ls(t,e){if(!Number.isInteger(e)||e<1||e>cs)throw new Error(`maxJobs must be an integer in [1, ${cs}], got ${e}`);let r=Qu(t,"regimen.yaml");if(!Ju(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let n=Zu(zu(r,"utf-8"));return n.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(n.setIn(["parallelism","max_jobs"],e),Xu(r,n.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as us,readFileSync as ps,writeFileSync as ep}from"node:fs";import{join as Gn}from"node:path";import{parseDocument as ds}from"yaml";async function fs(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=Gn(t,"project.yaml");if(!us(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ds(ps(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=Gn(t,"regimen.yaml");if(!us(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ds(ps(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)ep(Gn(t,i.path),i.content);return{files:r.map(i=>i.path)}}var ms=t=>console.log(t);function gs(t){ms=t}function zt(t,e="info"){ms(t,e)}import{homedir as tp}from"node:os";import{existsSync as rp,mkdirSync as np}from"node:fs";import{join as Fn}from"node:path";import{simpleGit as hs}from"simple-git";function Qt(t,e,r){let n=r??Fn(tp(),".codepipe","repos");return Fn(n,t,e)}async function Ur(t,e,r={}){let n=Qt(t,e.name,r.baseDir),o=r.cloneUrlOverride??op(e);if(!rp(Fn(n,".git"))){np(n,{recursive:!0});let a=hs();zt(`[git] clone ${o} \u2192 ${n}`);try{await a.clone(o,n)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${o}
|
|
428
|
+
${l.trim()}`)}}let i=hs(n);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${n}
|
|
429
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Xt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ys=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Lr(t,e){let{contextRepoCloneUrl:r,deliveryRef:n,deliverySha:o,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${n}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();o&&a!==o&&zt(`[git] delivery ${n} resolved ${a.slice(0,10)} (expected ${o.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Xt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Xt(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([...ys,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ws(t,e,r){let n=`refs/codepipe/deliveries/${e}`;if(await Xt(t,n))return(await t.revparse([n])).trim();let o=`refs/devpipe/deliveries/${e}`;if(await Xt(t,o)){let s=(await t.revparse([o])).trim();return await t.raw(["update-ref",n,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",n,i]).catch(()=>{}),i}async function ks(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await ws(t,i,()=>Lr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await Xt(t,g)||(g=`origin/${u??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,p]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...ys,"cherry-pick",p])}catch(C){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let T=C instanceof Error?C.message:String(C);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
430
|
+
${T.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([n,"--delete",o]).catch(()=>{}),{commit:y}}async function bs(t,e,r){let{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await ws(t,i,()=>Lr(t,{contextRepoCloneUrl:n,deliveryRef:o,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function $s(t,e,r){let{branchName:n,baseBranch:o,mergeMethod:i,deleteBranch:s}=r,a=`origin/${n}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${n}'`)):i==="rebase"?(await t.checkout(["-B",n,a]),await t.rebase([o]),await t.checkout(o),await t.merge(["--ff-only",n])):await t.merge(["--no-ff",a,"-m",`Merge branch '${n}'`]),await t.push(["origin",o]),s&&await t.push(["origin","--delete",n]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function op(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 Dr=new Map;async function Hn(t,e){let n=(Dr.get(t)??Promise.resolve()).catch(()=>{}).then(e);Dr.set(t,n);try{return await n}finally{Dr.get(t)===n&&Dr.delete(t)}}async function xs(t){let{action:e,repo:r}=t,n="repoName"in e?e.repoName:"-",o="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;zt(`[exec] ${e.type} task=${o} repo=${n}`);try{switch(e.type){case"apply_delivery":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Hn(`${i}/${r.name}`,async()=>{let s=await Ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Qt(i,r.name,t.baseDir),{commit:c}=await ks(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 Z({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 K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Hn(`${i}/${r.name}`,async()=>{let s=await Ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Qt(i,r.name,t.baseDir),{commit:c,pushed:l}=await bs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return K("no repo spec");let i=Re(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return K("no repo spec");let i=Re(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Z({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return K("no repo spec");let i=Re(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return K("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Hn(`${i}/${r.name}`,async()=>{let s=await Ur(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Qt(i,r.name,t.baseDir),{mergedSha:c}=await $s(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return Z({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return Z({stub:!0});case"tracker_status":{let i=it();return i?t.trackerIssueId?(await Gi(i,t.trackerIssueId,e.newStatus),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):K("no tracker_issue_id provided"):K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=it();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return K("no tracker_issue_id provided");let s=await Fi(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=it();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return K("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Hi(i,e.projectKey,e.title,e.body,e.targetStatus);return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=it();if(!i)return K("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ki(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return K(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_parallelism":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await ls(t.contextDir,e.maxJobs);return Z({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=await fs(t.contextDir,e);return Z({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):K("no context repo clone on this CLI");case"read_context_file":{if(!t.contextDir)return K("no context repo clone on this CLI");let i=as(t.contextDir,e.path);return Z({path:e.path,...i})}}}catch(i){return K(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function K(t){return{status:"failed",error:t}}import{existsSync as Os,readFileSync as Ns}from"node:fs";import{join as Us}from"node:path";import{homedir as ip}from"node:os";import{existsSync as sp,mkdirSync as ap,readFileSync as cp,writeFileSync as lp}from"node:fs";import{dirname as up,join as pp}from"node:path";function Kn(){return U("FARM_PINS")??pp(ip(),".codepipe","farm-pins.json")}function vs(){let t=Kn();if(!sp(t))return{};try{return JSON.parse(cp(t,"utf-8"))}catch{return{}}}function dp(t){let e=Kn();ap(up(e),{recursive:!0}),lp(e,JSON.stringify(t,null,2)+`
|
|
431
|
+
`,{mode:384})}function fp(t){return vs()[t]}function Br(t,e){let r=vs();r[t]=e,dp(r)}function Mr(t,e){let r=ke(e),n=fp(t);if(n&&n!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${n}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Kn()}.`);return r}import mp from"ws";function Gr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new mp(r)}var N=class extends Error{constructor(r,n,o){super(o);this.status=r;this.payload=n;this.name="HubHttpError"}};async function St(t,e,r){return Ge(t,e,"/projects",r)}async function Ss(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Fr(t,e,r,n){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,n)}async function Hr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Cs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new N(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Zt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Ts(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let n;try{n=(await r.json()).error}catch{}if(n==="registration_required")throw new Zt(e)}if(!r.ok)throw new N(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Rs(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new N(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Is(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET cli-tasks HTTP ${n.status}`);return await n.json()}async function Ps(t,e,r,n){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new N(o.status,null,`GET cli-task HTTP ${o.status}`);return await o.json()}async function js(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/apply-claim`,{})}async function Es(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/applied`,{prs:o})}async function As(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/abort`,{reason:o})}async function _s(t,e,r,n,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(n)}/command`,{command:o})}async function Kr(t,e,r,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,n)}async function Wn(t,e,r,n){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,n)}async function Q(t,e,r){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new N(n.status,null,`GET /projects/${r}/cli-summary HTTP ${n.status}`);return await n.json()}async function Ge(t,e,r,n){let o=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${o.status}`;throw new N(o.status,s,a)}return s}async function Ls(t,e,r,n){let o=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return o(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ke(e.farmPublicKey);if(i!==e.fingerprint)return o("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Mr(e.farmId,e.farmPublicKey);let s=B(t.projectId);if(!s)return o("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Us(r,"project.yaml"),g=Us(r,"regimen.yaml");Os(p)&&Os(g)?c={projectYaml:Ns(p,"utf-8"),regimenYaml:Ns(g,"utf-8")}:n.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=xt(e.farmPublicKey,JSON.stringify(l));Br(e.farmId,i),n.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await Fr(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:o(f.error??"farm provisioning failed")}catch(i){return o(i instanceof Error?i.message:String(i))}}var Wr=class{constructor(e,r,n){this.intervalMs=e;this.send=r;this.log=n}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let n=[];for(let s of r.prs){let a=Re(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);n.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof ot){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let o=n.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===o)return;for(let s=0;s<n.length;s++){let a=n[s];if(a.ci!=="failed")continue;let c=Re(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:n}),this.lastSig.set(e,o);let i=gp(n);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${n.length} PR(s))`)}};function gp(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}import{existsSync as Ds,readFileSync as hp,readdirSync as yp}from"node:fs";function wp(t,e,r){let n=[];for(let o of r){let i=o.issue.key,s=xp(t,i,o.attachments);n.push({path:`tasks/${i}/task.md`,content:kp(o.issue,e,s)}),n.push({path:`tasks/${i}/comments.jsonl`,content:$p(bp(t,i,o.comments))});for(let a of o.attachments)n.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return n}async function Bs(t,e,r){if(r.length===0)return;let n=wp(t,e,r),o=r.map(i=>i.issue.key);await bt(t,n,`sync(${o.join(", ")}): task data`)}function kp(t,e,r){let n=new Date(t.updatedAt).toISOString(),o=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${n}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){o.push("## Attachments","");for(let i of r)o.push(`- [${i}](attachments/${encodeURI(i)})`);o.push("")}return o.join(`
|
|
432
|
+
`)}function bp(t,e,r){let n=new Map,o=Ne(t,`tasks/${e}/comments.jsonl`);if(Ds(o))for(let i of hp(o,"utf-8").split(`
|
|
433
|
+
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&n.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=br(i.body);a&&(s.parsedCommand=a),n.set(i.id,s)}return[...n.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function $p(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
434
|
+
`)+(t.length>0?`
|
|
435
|
+
`:"")}function xp(t,e,r){let n=[],o=Ne(t,`tasks/${e}/attachments`);if(Ds(o))for(let i of yp(o))n.push(i);for(let i of r)n.includes(i.name)||n.push(i.name);return n}var Yr=class t{constructor(e,r,n,o={contextDir:null}){this.intervalMs=e;this.send=r;this.log=n;this.options=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=it();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let n=Date.now(),o;try{let k=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];o=await Ji(r,{projectKey:e.projectKey,columns:k,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(k){this.log.warn(`[yt-sync] listIssues failed: ${k instanceof Error?k.message:String(k)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let k of o){if(s.add(k.id),a.has(k.status))continue;let b=await Gs(r,k.id,e.sinceMs,this.log);b&&i.set(k.id,b)}let c=[];for(let k of e.offBoardIssueIds){if(s.has(k))continue;let b=await Gs(r,k,e.sinceMs,this.log);if(b&&b.length>0&&i.set(k,b),e.requireAssignee||b&&b.length>0){let _=await Cp(r,k,this.log);if(_)c.push(_);else if(b&&b.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=o.filter(k=>!a.has(k.status)),{attachmentsByIssue:u,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(k=>({issue:k,comments:i.get(k.id)??[],attachments:u.get(k.id)??[]}));try{await Bs(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let k of f)this.shippedAttachments.add(k)}catch(k){let b=k instanceof Error?k.message:String(k);this.abandonTick(`context task sync failed: ${b}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],y=[];for(let[k,b]of i){let _=b.filter(R=>!g(R.id));if(_.length===0)continue;d.push({issueId:k,comments:_.map(vp)});let O=_.flatMap(R=>{let h=br(R.body);return h?[{commentId:R.id,author:R.author,name:h.name,args:h.args,createdAt:R.createdAt}]:[]});O.length>0&&y.push({issueId:k,commands:O})}let S={type:"youtrack_observation",projectId:e.projectId,issues:o.map(Ms),commentsBatch:d,...y.length>0?{commandsBatch:y}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ms)}:{},observedAtMs:n};this.send(S);let C=d.reduce((k,b)=>k+b.comments.length,0),T=y.reduce((k,b)=>k+b.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${o.length} comments=${C} commands=${T} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,n){let o=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Vi(n,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=Sp(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&o.set(s.id,c)}return{attachmentsByIssue:o,attachmentKeys:i}}};function Ms(t){let{description:e,...r}=t;return r}function vp(t){let{body:e,...r}=t;return r}function Sp(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 Cp(t,e,r){try{return await zi(t,e)}catch(n){return r.warn(`[yt-sync] getIssue ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}async function Gs(t,e,r,n){try{return await Xi(t,e,r)}catch(o){return n.warn(`[yt-sync] listComments ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}var Yn="npm i -g @code-partner/codepipe@latest";function qr(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 n=d=>e.onEvent?.(d),o=e.workspace;o?.contextDir&&ai(o.contextDir,r);let i=Fs("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Fs("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,u=new Set,f=new Set,p=g();function g(){let d=Gr(t.hubUrl,t.cliToken),y=null,S=new Wr(i,R=>{d.readyState===d.OPEN&&d.send(JSON.stringify(R))},r),C=new Yr(s,R=>{d.readyState===d.OPEN&&d.send(JSON.stringify(R))},r,{contextDir:o?.contextDir??null,isSelfComment:R=>f.has(R)}),T=null,k=async()=>{try{let R;try{let v=await Q(t.hubUrl,t.cliToken,t.projectId);R={repos:v.repos,contextRepo:v.contextRepo}}catch(v){r.warn(`[readiness] could not fetch project summary for push checks: ${v instanceof Error?v.message:String(v)}`)}let h=await Zi(t.projectId,R);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 v=h.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${v.join(", ")}`)}}catch(R){r.warn(`[readiness] check failed: ${R instanceof Error?R.message:String(R)}`)}},b=()=>{k(),T=setInterval(()=>void k(),a),typeof T.unref=="function"&&T.unref()},_=()=>{T&&(clearInterval(T),T=null)},O=o?.contextDir?new jr(o.contextDir,t.projectId,R=>{d.readyState===d.OPEN&&d.send(JSON.stringify(R))},r):null;return d.on("open",()=>{r.info("[ws] connected"),n({kind:"connected"});let R=ni(t.projectId),h=U("ORIGIN")==="farm"?"farm":"local",m=U("FARM_ID"),v=t.accountEmail??R.email,x;try{let I=ns(t.projectId);I&&(x=I.publicKey,r.info(`[cred-channel] key fingerprint: ${I.fingerprint}`))}catch(I){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${I instanceof Error?I.message:String(I)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ce,protocolVersion:ge,accountId:R.accountId,accountLabel:R.label,origin:h,inFlightActionIds:[...u],...v?{accountEmail:v}:{},...h==="farm"&&m?{farmId:m}:{},...x?{sealPublicKey:x}:{}};d.send(JSON.stringify(w))}),d.on("message",async R=>{let h=R.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 v=m.type;if(v==="registered"){let w=m;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),n({kind:"registered",projectId:w.projectId??t.projectId}),S.start(),O?.start(),b(),o?.contextDir){let I=o.contextDir;try{let P=Ar(I,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let D;try{D=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let ie=await xi(I,t.projectId,D,r);d.readyState===d.OPEN&&d.send(JSON.stringify(ie))}catch(D){r.warn(`[ctx] context migration failed (non-fatal): ${D instanceof Error?D.message:String(D)}`)}})()))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),n({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(v==="hello"){let w=m;y=yr(w.protocolVersion);let I=y?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${I}`),y||(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: ${Yn}`),n({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Yn}));return}if(v==="tracking_targets"){S.setTargets(m.targets);return}if(v==="youtrack_sync_request"){C.setRequest(m);return}if(v==="sync_local"){await Rp(m,o,d,r);return}if(v==="context_write"){await Ip(m,o,d,r);return}if(v==="adr_promote"){await Pp(m,o,d,r);return}if(v==="cred_update"){let w=m,I=B(t.projectId),P=I?.sealKey?await os(t.projectId,w.kind,w.sealed,I.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},D={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:P.ok,...P.detail?{detail:P.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(D)),P.ok?(r.info(`[cred] ${w.kind} replaced${P.detail?` \u2014 ${P.detail}`:""}`),k()):r.warn(`[cred] ${w.kind} replacement rejected: ${P.detail??"unknown"}`);return}if(v==="move_to_farm"){let w=m;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let I=await Ls(t,w,o?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(I)),I.ok?r.info(`[farm-move] done \u2014 farm daemon ${I.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${I.error??"unknown error"}`);return}if(v==="sandbox_keys"){let w=B(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let I=mt(t.projectId),P=Ri(m,w,I,r);for(let D of P)d.readyState===d.OPEN&&d.send(JSON.stringify(D));return}if(v!=="dispatch_action")return;let x=m;if(y===!1){let w=`refused: HUB protocol incompatible with CLI v${ce} (protocol ${ge})`;d.send(JSON.stringify({type:"action_result",actionId:x.actionId,status:"failed",error:w})),r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Yn}`),n({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:!1,error:w});return}u.add(x.actionId);try{let w=await xs({action:x.action,repo:x.repo,trackerIssueId:x.trackerIssueId,contextDir:o?.contextDir,requestConfigReport:O?()=>O.reportNow():void 0}).catch(D=>({status:"failed",error:D instanceof Error?D.message:String(D)}));x.action.type==="tracker_comment"&&w.status==="done"&&"result"in w&&typeof w.result?.commentId=="string"&&f.add(w.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:x.actionId,...w}));let I=w.status!=="failed",P=!I&&"error"in w?w.error:void 0;I?r.info(`[exec] ${x.actionId} (${x.action.type}) \u2192 done`):r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 FAILED: ${P??"?"}`),n({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:I,...P?{error:P}:{}})}finally{u.delete(x.actionId)}}),d.on("close",(R,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${R}${m?` reason=${m}`:""}`),S.stop(),C.stop(),O?.stop(),_(),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.`),n({kind:"replaced"});return}n({kind:"disconnected",code:R}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",R=>r.warn(`[ws] error: ${R.message}`)),d}return{stop(){c=!0,p.close()}}}async function Rp(t,e,r,n){if(!e){n.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let o of t.repos){let i=e.repos.find(l=>l.name===o.repoName),s=Tp(e.root,i?.mountAs??o.repoName),a=i?.defaultBranch??o.defaultBranch,c=await oi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?n.info(`[sync] ${o.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?n.info(`[sync] ${o.repoName}: not cloned in workspace \u2014 skipped`):(n.warn(`[sync] ${o.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:o.repoName,reason:c.reason??"sync skipped"})))}}async function Ip(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{await bt(e.contextDir,t.files,t.message),n.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[ctx] context_write ${t.id} failed: ${s}`),o("failed",s)}}async function Pp(t,e,r,n){let o=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){n.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),o("failed","no context repo clone on this CLI");return}try{let i=await gi(e.contextDir,t.taskKey,t.slugs);if(n.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;n.warn(`[adr] adr_promote ${t.id}: ${s}`),o("failed",s);return}o("done")}catch(i){let s=i instanceof Error?i.message:String(i);n.warn(`[adr] adr_promote ${t.id} failed: ${s}`),o("failed",s)}}function Fs(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Js,mkdirSync as zs}from"node:fs";import{dirname as Xs}from"node:path";import{simpleGit as Ct}from"simple-git";import{execFileSync as jp}from"node:child_process";import{mkdtempSync as Ep,mkdirSync as Ap,readFileSync as Hs,rmSync as _p,writeFileSync as Op}from"node:fs";import{tmpdir as Np}from"node:os";import{dirname as Up,join as Ks}from"node:path";function Ws(t="codepipe-context"){let e=Ep(Ks(Np(),"codepipe-ssh-")),r=Ks(e,"id_ed25519");try{return jp("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Hs(r,"utf-8"),publicKey:Hs(`${r}.pub`,"utf-8").trim()}}finally{_p(e,{recursive:!0,force:!0})}}async function Ys(t,e,r,n="codepipe-context"){let o=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:n,key:r,read_only:!1})});if(o.ok)return;let i=await o.text();if(!(o.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${o.status} ${i}`)}function qs(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 Vs(t,e){Ap(Up(t),{recursive:!0});let r=e.endsWith(`
|
|
427
436
|
`)?e:e+`
|
|
428
|
-
`;return
|
|
429
|
-
[${
|
|
430
|
-
`,{mode:384})}import
|
|
431
|
-
`))!==-1;){let
|
|
432
|
-
`)){let R
|
|
437
|
+
`;return Op(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Lp(t,e,r="x-access-token"){let n=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,o=t.match(/^git@([^:]+):(.+)$/);if(o)return`https://${n}@${o[1]}/${o[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${n}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${n}@${s[1]}`:t}function Dp(t,e){return e?.contextWrite?.token?{user:$r(t),secret:e.contextWrite.token}:t===Kt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Kt.bitbucket?e?.bitbucket?.apiToken?{user:Qe,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Vr(t){let{cfg:e,secrets:r,contextDir:n,log:o}=t,i;try{i=await Q(e.hubUrl,e.cliToken,e.projectId)}catch(c){return o.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return o.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Dp(dt(s.cloneUrl),r);if(a){let c=await Bp({ctx:s,contextDir:n,cred:a,log:o});if(c)return c;o.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Mp({ctx:s,contextDir:n,privateKey:r.contextSsh.privateKey,log:o});if(c)return c;o.warn("[ctx] SSH deploy-key clone failed")}return o.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function Bp(t){let{ctx:e,contextDir:r,cred:n,log:o}=t,i=Lp(e.cloneUrl,n.secret,n.user),s=e.branch,a=encodeURIComponent(n.secret),c=l=>l.split(n.secret).join("***").split(a).join("***");try{if(Js(`${r}/.git`)){let l=Ct(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Rn(r);await l.reset(["--hard",`origin/${s}`]),In(r,u),o.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else zs(Xs(r),{recursive:!0}),await Ct().clone(i,r,["--branch",s]),o.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Qs(r)}catch(l){return o.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Mp(t){let{ctx:e,contextDir:r,privateKey:n,log:o}=t,i=`${r}.deploy-key`,s=Vs(i,n),a=qs(e.cloneUrl),c=e.branch;try{if(Js(`${r}/.git`)){let l=Ct(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Rn(r);await l.reset(["--hard",`origin/${c}`]),In(r,u),o.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else zs(Xs(r),{recursive:!0}),await Ct().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ct(r).addConfig("core.sshCommand",s,!1,"local"),o.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Qs(r),{root:r,contextDir:r,repos:[]}}catch(l){return o.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function Qs(t){let e=Ct(t);await e.raw(["config","user.email"]).then(n=>n.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Zs(t={profile:void 0}){let{cfg:e,profile:r}=Cr(t.profile),n=B(e.projectId);n&&Wt(n),qt(n?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Vt(n?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Jt(n?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=er(qn(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Ir("CLI_LOG",i,o);if(s.enabled){let p=new ht(s);Pr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=vr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let p=er(qn(),".codepipe",r?er("profiles",r,"context"):"context");if(await Wn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Vr({cfg:e,secrets:n,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await Wn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=er(qn(),".codepipe",r?er("profiles",r,"context-config"):"context-config");Er(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=qr(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function f(p){u||(u=!0,console.log(`
|
|
438
|
+
[${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as qp}from"node:os";import{spawnSync as Gp}from"node:child_process";function Fp(){try{return Gp("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ea(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Fp(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Tt}from"node:os";import{mkdirSync as Hp,readFileSync as ta,writeFileSync as Kp,existsSync as Vn}from"node:fs";import{dirname as Wp,join as Fe}from"node:path";Vn(".env")&&process.loadEnvFile(".env");function He(t){let e=U("SANDBOX_CONFIG");if(e)return e;let r=Fe(Tt(),".codepipe","worker");return t?Fe(r,"profiles",t,"config.json"):Fe(r,"config.json")}function ra(){return Fe(Tt(),".devpipe-sandbox","config.json")}function Jr(){Ze(Fe(Tt(),".devpipe"),Fe(Tt(),".codepipe")),U("SANDBOX_CONFIG")||Ze(Fe(Tt(),".devpipe-sandbox"),Fe(Tt(),".codepipe-sandbox"))}function ne(t){let e=He(t);return Vn(e)?JSON.parse(ta(e,"utf-8")):!t&&!U("SANDBOX_CONFIG")&&Vn(ra())?JSON.parse(ta(ra(),"utf-8")):null}function na(t,e){let r=He(e);Hp(Wp(r),{recursive:!0}),Kp(r,JSON.stringify(t,null,2)+`
|
|
439
|
+
`,{mode:384})}import Yp from"ws";var Rt=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 n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(n.signal=r);let o=await fetch(`${this.hubUrl}/jobs/heartbeat`,n);if(o.status===410)return"claim_lost";if(!o.ok)throw new Error(`heartbeat failed: ${o.status} ${await o.text()}`);return"ok"}async releaseJob(e,r,n){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};n&&(o.signal=n);let i=await fetch(`${this.hubUrl}/jobs/release`,o);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Yp(e)}};async function st(t){Jr();let e=ne(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${He(t.profile)}.`),process.exit(1));let r=t.name??qp(),n=ea({projects:t.projects??[],llm:t.llm??null}),o=new Rt(t.hub.replace(/\/$/,"")),i=Or(),s=ke(i.publicKey),{sandboxId:a,token:c}=await o.register({name:r,registrationToken:t.token,capabilities:n,publicKey:i.publicKey});na({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 ${He(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 _d,readFileSync as eo,readdirSync as Od,writeFileSync as Nd}from"node:fs";import{dirname as Ud,join as sr,resolve as Ld}from"node:path";import{spawn as Vp}from"node:child_process";import{existsSync as Jp}from"node:fs";var It=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},zr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},zp=5e3,tr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new zr;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let n=[],o=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let y=ed(d.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(d.type==="assistant"){let y=d.message;typeof y?.model=="string"&&(c=y.model);let S=y?.usage;S&&(a+=1,s.input+=oe(S.input_tokens),s.output+=oe(S.output_tokens),s.cacheRead+=oe(S.cache_read_input_tokens),s.cacheCreate+=oe(S.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let y of rd(d,e.workspaceDir))try{p(y)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((d,y)=>{let S=Vp(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 C=!1,T=null,k=()=>{C=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),S.kill("SIGTERM"),T=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},zp)};e.signal?.addEventListener("abort",k,{once:!0});let b=()=>{T&&clearTimeout(T),e.signal?.removeEventListener("abort",k)},_="";S.stdout.on("data",O=>{n.push(O),_+=O;let R;for(;(R=_.indexOf(`
|
|
440
|
+
`))!==-1;){let h=_.slice(0,R).trim();if(_=_.slice(R+1),h){let m=oa(h);u(m),m&&g(m)}}}),S.stderr.on("data",O=>{n.push(O),o.push(O);for(let R of O.split(`
|
|
441
|
+
`)){let h=R.trim();h&&console.warn(`[claude:stderr] ${h}`)}}),S.on("error",O=>{b(),y(O)}),S.on("close",O=>{if(b(),C){y(new zr);return}if(_.trim()){let h=oa(_.trim());u(h),h&&g(h)}let R=i?.is_error===!0;if(O!==0||R){let h=typeof i?.api_error_status=="number"?i.api_error_status:void 0,m=typeof i?.subtype=="string"?i.subtype:void 0,v=typeof i?.result=="string"?i.result:void 0;y(new It(Xp(O,i,o.join("")),{code:O,apiErrorStatus:h,subtype:m,resultText:v,retryAfterMs:Qp(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:n.join(""),usage:td(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(n=>n.includes("/")&&Jp(n))}};function oa(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let n=e.subtype??"";return console.log(`[claude] system ${n}`),e}if(r==="assistant"){let n=e.message;for(let o of n?.content??[]){let i=o.type;if(i==="text"){let s=String(o.text??"").trim();s&&console.log(`[claude] text: ${Ke(s,200)}`)}else if(i==="tool_use"){let s=String(o.name??""),a=o.input,c=Zp(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let n=e.message;for(let o of n?.content??[])if(o.type==="tool_result")if(o.is_error===!0){let i=sa(o.content);console.log(`[claude] tool_result (error)${i?`: ${Ke(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let n=e.subtype??"",o=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${n} turns=${o} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${Ke(JSON.stringify(e),200)}`),e}function Xp(t,e,r){let n=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let o=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;o?n.push(Ke(o,500)):typeof s=="string"&&s!=="success"&&n.push(s),typeof i=="number"&&n.push(`(api_status=${i})`)}return n.length===1&&r.trim()&&n.push(Ke(r.trim().split(`
|
|
433
442
|
`).slice(-5).join(`
|
|
434
|
-
`),500)),
|
|
435
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
443
|
+
`),500)),n.join(" \u2014 ")}function Qp(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:"",n=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),o=n?Number(n[1]??n[2]):NaN;return Number.isFinite(o)&&o>0?o*1e3:void 0}function sa(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Zp(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=${Ke(r,80)}`}return""}function Ke(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function oe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ed(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=oe(e.utilization),n=r>1?r/100:r,o={status:typeof e.status=="string"?e.status:"",resetsAt:oe(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:n,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(o.surpassedThreshold=e.surpassedThreshold),o}function td(t,e,r,n){let o=kr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(o.inputTokens=oe(i.input_tokens),o.outputTokens=oe(i.output_tokens),o.cacheReadInputTokens=oe(i.cache_read_input_tokens),o.cacheCreationInputTokens=oe(i.cache_creation_input_tokens)):(o.inputTokens=e.input,o.outputTokens=e.output,o.cacheReadInputTokens=e.cacheRead,o.cacheCreationInputTokens=e.cacheCreate),o.totalCostUsd=oe(t?.total_cost_usd),o.numTurns=t&&oe(t.num_turns)>0?oe(t.num_turns):r,o.durationMs=oe(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return o.model=s||n,o}var ia=200;function rd(t,e){let r=Date.now(),n=t.type;if(n==="system"){let o=String(t.subtype??"").trim();return o?[{ts:r,kind:"system",text:o}]:[]}if(n==="assistant"){let o=t.message,i=[];for(let s of o?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:Ke(c,ia)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=nd(u,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(n==="user"){let o=t.message,i=[];for(let s of o?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Ke(sa(s.content),ia):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(n==="result"){let o=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",...o?{text:o}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function nd(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 od,writeFileSync as rr}from"node:fs";import{dirname as id,join as nr}from"node:path";function aa(t,e,r){let n=nr(t,e);od(id(n),{recursive:!0}),rr(n,r)}var or=class{name(){return"mock"}async run(e){let r=e.metadata??{},n=r.trackerIssueKey??"TASK",o=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=sd(n,o,i);rr(nr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;rr(nr(e.workspaceDir,"SOLUTION.md"),ad(n,o,i,a)),s.push("SOLUTION.md"),rr(nr(e.workspaceDir,"QUESTIONS.md"),cd(n)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;aa(e.workspaceDir,"changes/sample.patch",ld(n,o,a)),s.push("changes/sample.patch"),aa(e.workspaceDir,"diff-summary.md",ud(n,o,a)),s.push("diff-summary.md")}else e.role==="rework"&&(rr(nr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${n})
|
|
444
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:kr()}}};function sd(t,e,r){return`# ${t} \u2014 Estimate
|
|
436
445
|
|
|
437
446
|
**Title:** ${e}
|
|
438
447
|
|
|
@@ -453,10 +462,10 @@ production-grade estimates.)
|
|
|
453
462
|
${r.split(`
|
|
454
463
|
`).slice(0,8).join(`
|
|
455
464
|
`).trim()||"(empty)"}
|
|
456
|
-
`}function
|
|
465
|
+
`}function ad(t,e,r,n){let o=n?`
|
|
457
466
|
## Reviewer rework instruction
|
|
458
467
|
|
|
459
|
-
> ${
|
|
468
|
+
> ${n.split(`
|
|
460
469
|
`).join(`
|
|
461
470
|
> `)}
|
|
462
471
|
|
|
@@ -464,7 +473,7 @@ This pass addresses the points above.
|
|
|
464
473
|
`:"";return`# ${t} \u2014 Solution
|
|
465
474
|
|
|
466
475
|
**Title:** ${e}
|
|
467
|
-
${
|
|
476
|
+
${o}
|
|
468
477
|
## Plan
|
|
469
478
|
1. Locate the relevant module(s) in the project repo.
|
|
470
479
|
2. Apply the minimum diff that satisfies the DoD in the YouTrack task.
|
|
@@ -482,21 +491,21 @@ TBD (mock runner does not yet inspect project code).
|
|
|
482
491
|
${r.split(`
|
|
483
492
|
`).slice(0,8).join(`
|
|
484
493
|
`).trim()||"(empty)"}
|
|
485
|
-
`}function
|
|
494
|
+
`}function cd(t){return`# ${t} \u2014 Open questions
|
|
486
495
|
|
|
487
496
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
488
|
-
`}function
|
|
497
|
+
`}function ld(t,e,r){let n=r?` (rework: ${r.split(`
|
|
489
498
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
490
499
|
index 0000000..1111111 100644
|
|
491
500
|
--- a/CHANGELOG.md
|
|
492
501
|
+++ b/CHANGELOG.md
|
|
493
502
|
@@ -1,3 +1,6 @@
|
|
494
|
-
+## ${t} \u2014 ${e}${
|
|
503
|
+
+## ${t} \u2014 ${e}${n}
|
|
495
504
|
+
|
|
496
505
|
+- mock-runner placeholder change for slice 5 testing.
|
|
497
506
|
+
|
|
498
507
|
# Changelog
|
|
499
|
-
`}function
|
|
508
|
+
`}function ud(t,e,r){return`# ${t} \u2014 Diff summary
|
|
500
509
|
|
|
501
510
|
**Title:** ${e}
|
|
502
511
|
${r?`
|
|
@@ -507,81 +516,81 @@ ${r?`
|
|
|
507
516
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
508
517
|
|
|
509
518
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
510
|
-
`}function
|
|
519
|
+
`}function ca(t){switch(t){case"mock":return new or;case"claude-headless":return new tr;default:return null}}function pa(t=process.env){return{maxAttempts:Xr(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Xr(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Xr(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Xr(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var pd=new Set([429,500,502,503,529]),la=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,dd=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,fd=new Set(["error_max_turns"]);function md(t){if(t instanceof It){let{apiErrorStatus:r,subtype:n,resultText:o,retryAfterMs:i}=t.details,s=o??"";return dd.test(s)?{retryable:!1,reason:"out_of_credits"}:n&&fd.has(n)?{retryable:!1,reason:n}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:pd.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:la.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:n??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return la.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var ua=/(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 da(t){if(t instanceof It){let{apiErrorStatus:r,resultText:n}=t.details;return r===401||r===403?!0:!!n&&ua.test(n)}let e=t instanceof Error?t.message:String(t);return ua.test(e)}function gd(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let n=e.baseDelayMs*2**(t-1),o=Math.min(n,e.maxDelayMs);return Math.round(o/2+Math.random()*(o/2))}async function fa(t,e,r){let n=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),o=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=md(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 u=gd(s,r.policy,c.retryAfterMs);if(Date.now()+u>o)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 ${u}ms`),await r.onBeforeRetry(),await n(u)}}function Xr(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as hd,rmSync as yd,writeFileSync as ma}from"node:fs";import{tmpdir as wd}from"node:os";import{join as Jn}from"node:path";function Qr(t){return`[url "https://${t}/"]
|
|
511
520
|
insteadOf = git@${t}:
|
|
512
521
|
insteadOf = ssh://git@${t}/
|
|
513
|
-
`}var
|
|
522
|
+
`}var kd=Qr("github.com"),bd=Qr("bitbucket.org"),$d=Qr("gitlab.com");function ga(t,e){if(t.length===0)return null;let r=hd(Jn(wd(),"devpipe-gitcreds-")),n=Jn(r,"credentials"),o=Jn(r,"gitconfig");return ma(n,t.join(`
|
|
514
523
|
`)+`
|
|
515
|
-
`,{mode:384}),
|
|
516
|
-
helper = store --file=${
|
|
517
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:
|
|
518
|
-
`).map(l=>l.trim()).filter(l=>l.length>0),c=await
|
|
519
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
520
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
521
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=
|
|
522
|
-
`+e.subarray(e.length-
|
|
524
|
+
`,{mode:384}),ma(o,`[credential]
|
|
525
|
+
helper = store --file=${n}
|
|
526
|
+
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:o,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{yd(r,{recursive:!0,force:!0})}catch{}}}}function zn(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(kd)),t.bitbucket?.apiToken&&(e.push(`https://${Qe}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(bd)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push($d)),ga(e,r)}function ha(t,e){if(t.contextWrite?.token){let r=dt(e)??"github.com",n=$r(r);return ga([`https://${n}:${t.contextWrite.token}@${r}`],[Qr(r)])}return zn(t)}import{spawn as wa}from"node:child_process";import{existsSync as Zr,mkdirSync as en,readFileSync as xd,rmSync as Xn,symlinkSync as vd}from"node:fs";import{homedir as Sd}from"node:os";import{dirname as tn,join as at}from"node:path";function ka(){return at(Sd(),".codepipe-sandbox","repos")}function ya(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 ba(t,e,r,n,o){if(Zr(at(t,".git"))){let i=async s=>{await z(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],o),await z(t,["reset","--hard",`origin/${s}`],o),await z(t,["clean","-fdx"],o)};try{return await i(r),r}catch(s){if(!n||n===r||!ya(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${n}`),await i(n),n}}Zr(t)&&Xn(t,{recursive:!0,force:!0}),en(tn(t),{recursive:!0});try{return await z(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],o),r}catch(i){if(!n||n===r||!ya(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${n}`),Zr(t)&&Xn(t,{recursive:!0,force:!0}),en(tn(t),{recursive:!0}),await z(void 0,["clone","--depth=1","--single-branch","--branch",n,e,t],o),n}}async function $a(t){await z(t.workspacePath,["reset","--hard",t.baseSha]),await z(t.workspacePath,["clean","-fdx"])}var rn="CodePipe Agent",nn="codepipe@codepartner.ee";async function xa(t,e){let r=t.workspacePath;await z(r,["add","-A"]);let n=(await $e(r,["write-tree"])).trim(),o=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(n===o)return null;let i={...process.env,GIT_AUTHOR_NAME:rn,GIT_AUTHOR_EMAIL:nn,GIT_COMMITTER_NAME:rn,GIT_COMMITTER_EMAIL:nn};return(await $e(r,["commit-tree",n,"-m",e],i)).trim()}async function va(t,e,r,n,o){try{await z(t.workspacePath,["push","--force",n,`${e}:refs/heads/${r}`],o)}catch(i){let s=i instanceof Error?i.message:String(i);throw dt(n)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Sa(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ca(t,e,r,n,o){await z(t.workspacePath,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],o),await z(t.workspacePath,["checkout","--force",r])}async function Qn(t,e,r){let n=t.workspacePath,o={...r??process.env,GIT_AUTHOR_NAME:rn,GIT_AUTHOR_EMAIL:nn,GIT_COMMITTER_NAME:rn,GIT_COMMITTER_EMAIL:nn};(await $e(n,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(n,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await z(n,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await z(n,["merge","--no-commit","--no-ff",`origin/${e}`],o)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(n,["diff","--name-only","--diff-filter=U"])).split(`
|
|
527
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(n,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function z(t,e,r){return new Promise((n,o)=>{let i=wa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",o),i.on("close",a=>{if(a===0)return n();o(new Error(`git ${e[0]} failed (exit ${a}):
|
|
528
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function $e(t,e,r){return new Promise((n,o)=>{let i=wa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",o),i.on("close",c=>{if(c===0)return n(s.join(""));o(new Error(`git ${e[0]} failed (exit ${c}):
|
|
529
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Ta(t,e){Zr(t)&&Xn(t,{recursive:!0,force:!0}),en(tn(t),{recursive:!0}),vd(e,t,"dir")}async function Ra(t,e,r){await z(t,["worktree","prune"]).catch(()=>{}),en(tn(r),{recursive:!0}),await z(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ia(t,e,r,n="worktree",o){if(r.length===0)return[];let i=[];for(let s of r){let a=at(ka(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await ba(a,s.cloneUrl,s.ref,s.defaultBranch,o)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await $e(a,["rev-parse","HEAD"])).trim(),u=at(t,"code",s.name);n==="direct"?(Ta(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await Ra(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i}async function Pa(t,e,r,n="worktree",o){if(!r||!r.cloneUrl)return null;let i=at(ka(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await ba(i,r.cloneUrl,r.ref,void 0,o)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=at(t,"context");n==="direct"?(Ta(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await Ra(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await $e(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function ja(t,e=[]){let r=t.workspacePath,n=["knowledge",...e];await z(r,["add","-A",...n]).catch(()=>{});let o;try{o=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...n])}catch{return[]}let i=o.split(`
|
|
530
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=xd(at(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Cd}from"node:fs";import{join as Td}from"node:path";var Zn=8*1024,Pt=class extends Error{},ir="meta/build-result.json";function Ea(t){let e=Td(t,ir),r;try{r=Cd(e,"utf-8")}catch{throw new Pt(`BUILD produced no ${ir} verdict \u2014 inconclusive run`)}let n;try{n=JSON.parse(r)}catch(u){throw new Pt(`${ir} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!n||typeof n!="object")throw new Pt(`${ir} must be a JSON object`);let o=n;if(typeof o.ok!="boolean")throw new Pt(`${ir}: "ok" must be a boolean`);let i=o.ok,a=(Array.isArray(o.steps)?o.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let f=u,p=typeof f.name=="string"?f.name:null,g=typeof f.exitCode=="number"?f.exitCode:null;if(p===null||g===null)return[];let d={name:p,exitCode:g};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof o.logTail=="string"?Rd(o.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof o.failedStep=="string"&&o.failedStep)l.failedStep=o.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function Rd(t){let e=Buffer.from(t,"utf-8");return e.length<=Zn?t:`\u2026 [${e.length-Zn} bytes elided] \u2026
|
|
531
|
+
`+e.subarray(e.length-Zn).toString("utf-8")}import{lstatSync as Id,mkdtempSync as Pd,readFileSync as jd,readdirSync as _a,rmSync as Aa}from"node:fs";import{tmpdir as Ed}from"node:os";import{join as on,relative as Ad}from"node:path";var Oa=new Set(["code","context"]);function Na(t){let e=Pd(on(Ed(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Aa(e,{recursive:!0,force:!0}),listFiles:()=>Ua(e,e),readFile:r=>jd(on(e,r),"utf-8"),clean:()=>{for(let r of _a(e))Oa.has(r)||Aa(on(e,r),{recursive:!0,force:!0})}}}function Ua(t,e){let r=[];for(let n of _a(e)){let o=on(e,n),i=Id(o);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Oa.has(n))continue;r.push(...Ua(t,o))}else r.push(Ad(t,o))}return r}var sn=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Dd=new Set(["implement","resolve-conflict"]);function Bd(t){let e=Buffer.from(t,"utf-8");if(e.length<=sn)return t;let r=Math.floor(sn/4),n=sn-r,o=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-n).toString("utf-8"),s=e.length-r-n;return`${o}
|
|
523
532
|
|
|
524
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
533
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${sn} bytes for upload] \u2026
|
|
525
534
|
|
|
526
|
-
${i}`}async function
|
|
535
|
+
${i}`}async function ar(t={}){Jr();let e=ne(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,n=Ir("SANDBOX_LOG","sandbox",Ld("./logs"));if(n.enabled){let h=new ht(n);Pr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${n.maxBytes}B, keep ${n.maxFiles})`)}console.log(`codepipe-sandbox v${ce} (protocol ${ge})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let o=ca(e.llm);console.log(`llm backend: ${o?o.name():"(none \u2014 will not claim agent jobs)"}`);let i=pa();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Rt(e.hubUrl,e.token),a=!1,c=new AbortController,l=null,u=null,f=!1,p=null,g=null,d=!1,y=()=>{let h=s.openControlSocket();return p=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 v=m.toString("utf-8"),x=null;try{let w=JSON.parse(v);w&&typeof w=="object"&&(x=w)}catch{}if(x&&x.type==="hello"){let w=x;g=yr(w.protocolVersion);let I=g?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${I}`),g&&(d=!1);return}if(x&&x.type==="pause_job"){let w=typeof x.jobId=="string"?x.jobId:"";w&&w===l?(console.warn(`[ws] pause_job ${w} \u2014 aborting agent`),f=!0,u?.abort()):console.log(`[ws] pause_job ${w} \u2014 not the active job, ignoring`),w&&h.send(JSON.stringify({type:"job_paused",jobId:w}));return}console.log(`[ws] ${v}`)}),h.on("close",(m,v)=>{console.log(`[ws] closed code=${m} reason=${v?.toString()||""}`),p===h&&(p=null),!a&&setTimeout(y,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},S=y(),C=async()=>{for(;!a;){if(g===!1){d||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ce}, protocol ${ge}) \u2014 not claiming jobs until versions align.`),d=!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(v=>setTimeout(v,5e3));continue}let m=await h.json();await T(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(v=>setTimeout(v,5e3))}}};async function T(h,m){l=m.jobId,u=new AbortController,f=!1;let v=!1,x=null,w=null,I=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(v=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(M){let pe=M instanceof Error?M.message:String(M);console.warn(`[job] ${m.jobId} heartbeat error: ${pe}`)}};P();let D=setInterval(()=>{P()},I),ie=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(b(m.prompt," \u2502 "));let fe=[],Ve=null,j=400,ae=25,Pe=500,xe=()=>{if(Ve&&(clearTimeout(Ve),Ve=null),fe.length===0)return;let M=fe.splice(0,fe.length),pe=p;if(!pe||pe.readyState!==pe.OPEN)return;let je={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:M};try{pe.send(JSON.stringify(je))}catch{}},gn=M=>{fe.push(M),fe.length>Pe&&fe.shift(),fe.length>=ae?xe():Ve||(Ve=setTimeout(xe,j))},Je=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,q=new Set,hn=null;try{if(!o){v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ie,finishedAt:new Date().toISOString()});return}let M=Na(m.jobId);console.log(`[job] ${m.jobId} workspace=${M.dir}`);let pe=k(m,r);x=pe.gitCreds,w=pe.contextGitCreds;let je=x?.env,$o=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,Ee=[],Gt=null,yn=null;try{let E="worktree";Ee=await Ia(M.dir,m.projectId,m.projectRepos,E,je);let A=await Pa(M.dir,m.projectId,m.contextRepo,E,je);yn=A,Gt=A?.workspacePath??null}catch(E){let A=E instanceof Error?E.message:String(E);console.warn(`[job] ${m.jobId} materialize failed: ${A}`),v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let xo=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let E=m.contextRepo?.cloneUrl;if(!E||!je)throw new Error(E?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let A of m.deliveries){let H=Ee.find(se=>se.name===A.name);H&&(await Ca(H,A.deliveryRef,A.deliverySha,E,je),console.log(`[job] ${m.jobId} ${H.name}: checked out delivery ${A.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await xo()}catch(E){let A=E instanceof Error?E.message:String(E);console.warn(`[job] ${m.jobId} delivery checkout failed: ${A}`),v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let vo=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},So="";if(m.role==="resolve-conflict")try{let E=[];for(let A of Ee){let H=vo[A.name];if(!H)continue;let se=await Qn(A,H,je);console.log(`[job] ${m.jobId} ${A.name}: merged ${H} into ${A.ref} \u2014 ${se.length} conflicted file(s)`),se.length>0?E.push(`- **${A.name}**:`,...se.map(pt=>` - \`${pt}\``)):E.push(`- **${A.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}So=`
|
|
527
536
|
|
|
528
537
|
## Conflicts to resolve
|
|
529
538
|
|
|
530
|
-
`+(
|
|
539
|
+
`+(E.length>0?E.join(`
|
|
531
540
|
`):"(no task branches to merge)")+`
|
|
532
|
-
`}catch(
|
|
533
|
-
`).map(
|
|
534
|
-
`)}function _(h,m,
|
|
535
|
-
[${h}] shutting down`),p.abort();let m=new AbortController,w=setTimeout(()=>m.abort(),3e3);(async()=>{let k=f;if(k)try{await c.releaseJob(k,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${k}`)}catch($){let O=$ instanceof Error?$.message:String($);console.warn(`[${h}] release failed: ${O} (sweeper will reclaim)`)}clearTimeout(w),S.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>R("SIGINT")),process.on("SIGTERM",()=>R("SIGTERM")),await E()}async function Ea(t={profile:void 0}){let e=Ae(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Mr(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 Z(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=ne(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 Xd}from"node:child_process";import{existsSync as Et,mkdirSync as Ja,readFileSync as Xa,readdirSync as Qd,writeFileSync as Qa}from"node:fs";import{join as st,resolve as Za}from"node:path";import{setTimeout as rn}from"node:timers/promises";import{cancel as Zd,confirm as At,intro as ec,isCancel as sn,log as b,outro as on,password as _t,select as at,spinner as tc,text as K}from"@clack/prompts";import{simpleGit as ao}from"simple-git";async function Pt(t,e,r){return e.host==="github"?Ed(t,e,r):e.host==="gitlab"?Bd(t,e,r):Md(t,e,r)}async function Aa(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 We(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await _a(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 Ke(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Oa(e.gitlabToken,t):n}}return e.bitbucket?(await It(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Na(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 _a(t,e){let r=!1;try{r=(await We(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 Oa(t,e){let r=!1;try{r=(await Ke(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 Na(t,e){let r=!1;try{r=(await It(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 jd="https://api.github.com";async function We(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(jd+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 Ed(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 Od(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=kt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Nd(o,n.owner,n.name,a.path,i)||await Ud(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 We(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 _a(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await _d(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 We(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 _d(t,e){let{status:r,data:o}=await We(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function Od(t,e,r){let{data:o}=await We(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Nd(t,e,r,o,n){let{status:i,data:s}=await We(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Ud(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 We(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Ld="https://gitlab.com/api/v4";async function Ke(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(Ld+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 Bd(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 Ke(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 Oa(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ke(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 Ke(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 Ke(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=kt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let d=(await Ke(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 Ke(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 Dd="https://api.bitbucket.org/2.0";async function It(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(Dd+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 Md(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 It(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 Na(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 It(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=kt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await It(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 It(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 Gd={"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=Gd[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 Fd}from"node:crypto";import{existsSync as Ua,mkdirSync as Hd,readFileSync as La,readdirSync as Kd,rmSync as io,writeFileSync as Wd}from"node:fs";import{homedir as qd}from"node:os";import{dirname as Yd,join as Zo}from"node:path";var Vd=24*60*60*1e3;function Ba(){return Zo(qd(),".codepipe","init-drafts")}function en(t){let e=Fd("sha256").update(t).digest("hex").slice(0,16);return Zo(Ba(),`${e}.json`)}function Da(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Vd)}function Ma(t){let e=en(t);if(!Ua(e))return null;try{let r=JSON.parse(La(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Da(r.savedAt)?(io(e,{force:!0}),null):r}catch{return null}}function tn(t){io(en(t),{force:!0})}function Ga(){let t=Ba();if(Ua(t))for(let e of Kd(t)){let r=Zo(t,e);try{let o=JSON.parse(La(r,"utf-8"));Da(o.savedAt)&&io(r,{force:!0})}catch{io(r,{force:!0})}}}var jt=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(){tn(this.cwd)}persist(){let e=en(this.cwd);Hd(Yd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Wd(e,JSON.stringify(r,null,2)+`
|
|
536
|
-
`,{mode:384})}};function Fa(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 Ha(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as Ka}from"node:fs";import{join as Wa}from"node:path";import{simpleGit as qa}from"simple-git";var zd={info:t=>console.log(t),warn:t=>console.warn(t)};async function sr(t,e,r={}){let o=r.log??zd,n=[];for(let i of e){let s=Wa(t,i.mountAs),a=Nn(i);if(!Ka(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 qa().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(!Ka(Wa(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=qa(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Jd(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 Jd(t,e){return Ya(t)===Ya(e)}function Ya(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Va(t={}){let e=Qe();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 sr(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 za=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function G(t){Zd(t),process.exit(1)}function ce(t){return sn(t)&&G("aborted"),t}function M(t){return sn(t)&&G("aborted"),typeof t=="string"?t:""}async function rc(t={}){ec("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Ga();let r=Ma(e),o,n=!1;r&&Object.keys(r.answers).length>0?ce(await At({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 jt(e,r),n=!0):(tn(e),o=new jt(e)):o=new jt(e);let i=t.force===!0?null:await an(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||nc(e,t.force===!0));let c=await o.ask("hubUrl",async()=>M(await K({message:"HUB URL",placeholder:de,initialValue:N("HUB_URL")??de,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>co()),{cliToken:p,accountEmail:f}=await o.ask("bootstrap",()=>lo(c,l)),u=null;s==="farm"&&(u=await ef(c,p));let d=a?rf(a.parsed.repoName):"",g=await o.ask("projectId",async()=>M(await K({message:"project id (slug)",placeholder:d||"acme",...d?{initialValue:d}:{},validate:T=>ze.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await o.ask("projectName",async()=>M(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()),v=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",()=>pc()),S=await o.ask("youtrackProjectKey",async()=>M(await K({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),E=await o.ask("youtrackWrites",async()=>ce(await At({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),I=o.get("tokens")??{},B=()=>o.set("tokens",I),C=await o.ask("repos",()=>af(I,l,a,{onCred:B,initial:o.get("reposPartial")??[],onProgress:T=>o.set("reposPartial",T)}));o.delete("reposPartial");let _=await cf(await o.ask("contextRepo",()=>cc(g,C,I,l)),g,C,I,l,B,T=>o.set("contextRepo",T)),{spec:R,mode:h}=_;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 m=await o.ask("assigneeLogin",async()=>M(await K({message:"your YouTrack login (the assignee value)",...x.login?{initialValue:x.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),w=await o.ask("claudeToken",()=>gf(s==="farm")),k={projectId:g,name:y,automationLevel:v,repos:C,youtrackProjectKey:S,ownerEmail:f};b.step(`${h==="attach"?"attaching to":"provisioning"} Context Repo ${R.owner}/${R.name} (${R.host})\u2026`);let $;try{$=await Pt(k,R,{...lc(I),youtrackWrites:E,trackerUrl:x.url,mode:h,log:{info:T=>b.message(T),warn:T=>b.warn(T)}})}catch(T){G(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}k.contextRepo=$,b.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),b.step(`registering project on ${c}\u2026`);let O;try{O=await vt(c,p,k)}catch(T){if(T instanceof A&&T.status===409){b.warn(`project ${g} already exists on HUB \u2014 reusing it`);try{O=await Z(c,p,g)}catch(se){throw se instanceof A&&G(`HUB \u2192 ${se.status} ${se.message}`),se}}else if(T instanceof A&&T.status===401)o.delete("cliToken"),G("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof A)G(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let q=O.contextRepo??$;b.success(`project ${O.projectId} ready (${O.provisioningStatus})`);let lt=await ff(q),ke={url:x.url,token:x.token};if(s==="farm"){let T=u,se={...I,...lt?{contextWrite:lt}:{},...w?{claude:{oauthToken:w}}:{},youtrack:ke},Ie=I.github?.token;if(q.host==="github"&&Ie)try{let X=Bs(`devpipe-${g}`);await Ds(q,Ie,X.publicKey,`devpipe-${g}`),se.contextSsh={privateKey:X.privateKey},b.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(X){b.warn(`could not set up Context Repo SSH deploy key (${X instanceof Error?X.message:String(X)}); the farm will fall back to the token path.`)}let Ye={projectId:g,config:{hubUrl:c,cliToken:p,projectId:g},secrets:se,contextRepo:q,projectConfig:he(k,E,x.url,m||void 0)},Dt=$t(T.farm.publicKey,JSON.stringify(Ye));b.step(`handing project ${g} to farm ${T.farm.name}\u2026`);let ut;try{ut=await Gr(c,p,T.farm.farmId,{projectId:g,sealedBundle:Dt})}catch(X){throw X instanceof A&&G(X.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:X.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${X.status} ${X.message}`),X}ut.ok||G(`farm rejected provisioning: ${ut.error??"unknown error"}`),await nn(c,p,g,q,Ie),o.clear(),on(`done. project ${g} is now hosted on farm ${T.farm.name} (daemon ${ut.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}uc(I),await ic(e,q.cloneUrl,q.branch),ac(e),a&&await nf(e);{let T=st(e,me);bt(T);let se=he(k,E,x.url,m||void 0),Ie=Kt(T,se);Ie.length>0&&b.success(`local project config \u2192 .codepipe/{${Ie.join(", ")}}`),tt(g,se,{info:Ye=>b.message(Ye),warn:Ye=>b.warn(Ye)})}await sc(e,O.repos);let $e={hubUrl:c,cliToken:p,projectId:g,...I,...lt?{contextWrite:lt}:{},...w?{claude:{oauthToken:w}}:{},youtrack:ke};V($e),Ze({hubUrl:c,cliToken:p,projectId:g,accountEmail:f},g),b.success(`secrets \u2192 ${et(g)}`),await nn(c,p,g,q,I.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),on("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function nn(t,e,r,o,n){let i=await Ha(o,n),s=Fa(i),a=await at({message:s.message,options:s.options,initialValue:s.initialValue});if(!(sn(a)||a!==s.proceedValue))try{let{jobId:c}=await Hr(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 ef(t,e){let r;try{r=await ks(t,e)}catch(c){throw c instanceof A&&G(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&G("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let 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=Dr(i.farmId,i.publicKey)}catch(c){G(c instanceof Error?c.message:String(c))}return ce(await At({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
541
|
+
`}catch(E){let A=E instanceof Error?E.message:String(E);console.warn(`[job] ${m.jobId} conflict merge failed: ${A}`),v||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${A}`},startedAt:ie,finishedAt:new Date().toISOString()}),M.dispose();return}let zc=O(_(m.prompt,Ee,Gt),Gt,m.taskId)+So,wn=[...Ee.map(E=>E.workspacePath),...Gt?[Gt]:[]];wn.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${wn.join(", ")}`),Je&&(hn=setInterval(()=>{let A=p;if(!A||A.readyState!==A.OPEN)return;let H;try{H=Od(sr(M.dir,"drafts")).filter(se=>se.endsWith(".json")).sort()}catch{return}for(let se of H){if(q.has(se))continue;if(q.size>=Ao)break;let pt;try{let re=JSON.parse(eo(sr(M.dir,"drafts",se),"utf-8")),L=typeof re.localRef=="string"?re.localRef:"",V=typeof re.title=="string"?re.title:"",ze=typeof re.body=="string"?re.body:"";if(!L||!V)continue;pt={localRef:L,title:V,body:ze,...re.isEpic===!0?{isEpic:!0}:{},...Array.isArray(re.links)?{links:re.links}:{}}}catch{continue}q.add(se);let Ft={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:Je,child:pt};try{A.send(JSON.stringify(Ft))}catch{}}},1500));try{let E=await fa(o,{workspaceDir:M.dir,role:m.role,prompt:zc,addDirs:wn,metadata:m.metadata??{},...m.model?{model:m.model}:{},...$o?{env:$o}:{},signal:u.signal,onActivity:gn},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{M.clean();for(let L of Ee)try{await $a(L);let V=vo[L.name];m.role==="resolve-conflict"&&V&&await Qn(L,V,je)}catch(V){let ze=V instanceof Error?V.message:String(V);console.warn(`[job] ${m.jobId} worktree reset failed (${L.name}): ${ze}`)}try{await xo()}catch(L){let V=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${V}`)}},aborted:()=>v||f}),A=[];if(Dd.has(m.role)&&Ee.length>0){let L=m.metadata??{},V=typeof L.commitMessage=="string"?L.commitMessage:`${m.taskId}: changes`,ze=m.contextRepo?.cloneUrl,Co=w?.env;if(!ze||!Co)throw new Error("delivery requested but "+(ze?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Xc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let ve of Ee){let Ht=await xa(ve,V);if(!Ht){console.log(`[job] ${m.jobId} ${ve.name}: no changes \u2014 no delivery`);continue}let kn=`codepipe/deliveries/${Xc}/${m.jobId}/${ve.name}`;await va(ve,Ht,kn,ze,Co),A.push({name:ve.name,deliveryRef:kn,deliverySha:Ht,baseSha:ve.baseSha}),console.log(`[job] ${m.jobId} ${ve.name}: delivered ${Ht.slice(0,10)} \u2192 ${kn}`);let To=await Sa(ve,Ht);if(To.trim().length>0){let Qc=sr("display",`${ve.name}.diff`),Ro=sr(M.dir,Qc);_d(Ud(Ro),{recursive:!0}),Nd(Ro,To)}}}if(m.role==="resolve-conflict"&&A.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=Ea(M.dir),console.log(`[job] ${m.jobId} build verdict: ok=${H.ok}`+(H.failedStep?` failedStep=${H.failedStep}`:"")));let se=E.artifactPaths.length>0?E.artifactPaths:M.listFiles(),pt=Array.from(new Set(se)),Ft;if(yn)try{let L=await ja(yn,m.role==="index"?["adr/SOURCES.md"]:[]);L.length>0&&(Ft=L,console.log(`[job] ${m.jobId} captured ${L.length} knowledge file(s) for Context Repo`))}catch(L){let V=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${V}`)}let re={jobId:m.jobId,status:"succeeded",artifacts:pt.map(L=>({path:L,contentBase64:eo(`${M.dir}/${L}`).toString("base64")})),...Ft?{contextWrites:Ft}:{},...A.length>0?{deliveries:A}:{},log:Bd(E.log),startedAt:ie,finishedAt:new Date().toISOString(),usage:E.usage,...E.rateLimit?{rateLimit:E.rateLimit}:{},...H?{build:H}:{}};if(v||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(re),console.log(`[job] ${m.jobId} done \u2014 uploaded ${re.artifacts.length} artifact(s):`);for(let L of re.artifacts){let V=Buffer.from(L.contentBase64,"base64").length;console.log(` \xB7 ${L.path} (${V} bytes)`)}re.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(E){let A=E instanceof Error?E.message:String(E);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(v)console.warn(`[job] ${m.jobId} failed after claim lost (${A}) \u2014 skipping result upload`);else{let H=da(E);console.warn(H?`[job] ${m.jobId} failed: ${A} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${A}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:A},startedAt:ie,finishedAt:new Date().toISOString(),...H?{authError:!0}:{}})}}finally{M.dispose()}}finally{clearInterval(D),hn&&clearInterval(hn),xe(),l=null,u=null,x?.cleanup(),w?.cleanup()}}function k(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 v;try{v=JSON.parse(Nr(m,h.credBundle).toString("utf-8"))}catch(P){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${P instanceof Error?P.message:String(P)}`),{gitCreds:null,contextGitCreds:null}}let x=zn(v);x&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let w=ha(v,h.contextRepo.cloneUrl),I={gitCreds:x,contextGitCreds:w};return v.claudeOauthToken&&(I.claudeOauthToken=v.claudeOauthToken),I}function b(h,m){return h.split(`
|
|
542
|
+
`).map(v=>m+v).join(`
|
|
543
|
+
`)}function _(h,m,v){let x=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,x).replace(/\{\{codeRoot\}\}/g,x?x.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,v??"")}function O(h,m,v){let x=h,w=v.includes("::")?"":v.split(":",2)[1]??"",I=P=>{if(!m||!w)return"";try{return eo(sr(m,"tasks",w,P),"utf-8").trim()}catch{return""}};if(x.includes("{{solutionMd}}")){let P=I("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";x=x.replace(/\{\{solutionMd\}\}/g,()=>P)}if(x.includes("{{taskDescription}}")){let P=I("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";x=x.replace(/\{\{taskDescription\}\}/g,()=>P)}return x}let R=h=>{if(a)return;a=!0,console.log(`
|
|
544
|
+
[${h}] shutting down`),c.abort();let m=new AbortController,v=setTimeout(()=>m.abort(),3e3);(async()=>{let x=l;if(x)try{await s.releaseJob(x,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${x}`)}catch(w){let I=w instanceof Error?w.message:String(w);console.warn(`[${h}] release failed: ${I} (sweeper will reclaim)`)}clearTimeout(v),S.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>R("SIGINT")),process.on("SIGTERM",()=>R("SIGTERM")),await C()}async function La(t={profile:void 0}){let e=_e(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Gr(e.hubUrl,e.cliToken),n=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of n.events)console.log(` ${i}`);n.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await Q(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let o=ne(t.profile);o?o.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${o.sandboxId} (${o.name}), llm=${o.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${o.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as cf}from"node:child_process";import{existsSync as _t,mkdirSync as rc,readFileSync as nc,readdirSync as lf,writeFileSync as oc}from"node:fs";import{join as ct,resolve as ic}from"node:path";import{setTimeout as oo}from"node:timers/promises";import{cancel as uf,confirm as Ot,intro as sc,isCancel as ao,log as $,outro as io,password as Nt,select as lt,spinner as ac,text as W}from"@clack/prompts";import{simpleGit as ln}from"simple-git";async function Et(t,e,r){return e.host==="github"?Gd(t,e,r):e.host==="gitlab"?Vd(t,e,r):zd(t,e,r)}async function Da(t,e,r={}){let n=r.explain??!0,o=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Ye(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ba(e.githubToken,t):o}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await We(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ma(e.gitlabToken,t):o}}return e.bitbucket?(await jt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:n?await Ga(e.bitbucket,t):o}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function Ba(t,e){let r=!1;try{r=(await Ye(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 Ma(t,e){let r=!1;try{r=(await We(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 Ga(t,e){let r=!1;try{r=(await jt(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 Md="https://api.github.com";async function Ye(t,e,r,n){let o={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};n!==void 0&&(o.body=JSON.stringify(n),o.headers["Content-Type"]="application/json");let i=await fetch(Md+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Gd(t,e,r){let n=r.githubToken;if(!n)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let o=await Fd(n,e,r),i=await Kd(n,o.owner,o.name);r.log.info(`scaffolding Context Repo files \u2192 ${o.owner}/${o.name}@${i}`);let s=$t(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Wd(n,o.owner,o.name,a.path,i)||await Yd(n,o.owner,o.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:o.owner,name:o.name,cloneUrl:o.sshUrl,branch:i}}async function Fd(t,e,r){let n=await Ye(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(n.status===200&&n.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:n.data.owner.login,name:n.data.name,sshUrl:n.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await Ba(t,e)} (attach joins an existing Context Repo and never creates one)`);let o=await Hd(t,e.owner),i=o?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${o?"org":"user"})`);let s=await Ye(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 Hd(t,e){let{status:r,data:n}=await Ye(t,"GET",`/users/${e}`);return r===404||!n?!1:n.type==="Organization"}async function Kd(t,e,r){let{data:n}=await Ye(t,"GET",`/repos/${e}/${r}`);if(!n)throw new Error("GitHub getDefaultBranch: empty response");return n.default_branch}async function Wd(t,e,r,n,o){let{status:i,data:s}=await Ye(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(n)}?ref=${encodeURIComponent(o)}`);return i===404||!s?null:s.sha}async function Yd(t,e,r,n,o,i,s,a){let c={message:i,content:Buffer.from(o,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Ye(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(n)}`,c)}var qd="https://gitlab.com/api/v4";async function We(t,e,r,n){let o={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...n!==void 0?{"Content-Type":"application/json"}:{}}};n!==void 0&&(o.body=JSON.stringify(n));let i=await fetch(qd+r,o),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Vd(t,e,r){let n=r.gitlabToken;if(!n)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let o=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await We(n,"GET",`/projects/${o}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Ma(n,e)} (attach joins an existing Context Repo and never creates one)`);let f=await We(n,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await We(n,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await We(n,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=$t(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await We(n,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await We(n,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Jd="https://api.bitbucket.org/2.0";async function jt(t,e,r,n){let o={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};n?.json!==void 0?(o.body=JSON.stringify(n.json),o.headers["Content-Type"]="application/json"):n?.form&&(o.body=n.form);let i=await fetch(Jd+r,o),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function zd(t,e,r){let n=r.bitbucket;if(!n)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let o=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await jt(n,"GET",o);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await Ga(n,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await jt(n,"POST",o,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=$t(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await jt(n,"GET",`${o}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await jt(n,"POST",`${o}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let u=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Xd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Ie(t){let e=t.trim();if(!e)return null;let r,n;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),n=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),n=a[2]}let o=Xd[r];if(!o)return null;let i=n.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:o,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as Qd}from"node:crypto";import{existsSync as Fa,mkdirSync as Zd,readFileSync as Ha,readdirSync as ef,rmSync as an,writeFileSync as tf}from"node:fs";import{homedir as rf}from"node:os";import{dirname as nf,join as to}from"node:path";var of=24*60*60*1e3;function Ka(){return to(rf(),".codepipe","init-drafts")}function ro(t){let e=Qd("sha256").update(t).digest("hex").slice(0,16);return to(Ka(),`${e}.json`)}function Wa(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=of)}function Ya(t){let e=ro(t);if(!Fa(e))return null;try{let r=JSON.parse(Ha(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Wa(r.savedAt)?(an(e,{force:!0}),null):r}catch{return null}}function no(t){an(ro(t),{force:!0})}function qa(){let t=Ka();if(Fa(t))for(let e of ef(t)){let r=to(t,e);try{let n=JSON.parse(Ha(r,"utf-8"));Wa(n.savedAt)&&an(r,{force:!0})}catch{an(r,{force:!0})}}}var At=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let n=await r();return this.set(e,n),n}clear(){no(this.cwd)}persist(){let e=ro(this.cwd);Zd(nf(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};tf(e,JSON.stringify(r,null,2)+`
|
|
545
|
+
`,{mode:384})}};function Va(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 Ja(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as za}from"node:fs";import{join as Xa}from"node:path";import{simpleGit as Qa}from"simple-git";var sf={info:t=>console.log(t),warn:t=>console.warn(t)};async function cr(t,e,r={}){let n=r.log??sf,o=[];for(let i of e){let s=Xa(t,i.mountAs),a=Uo(i);if(!za(s)){if(r.dryRun){n.info(`would clone ${a} \u2192 ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{n.info(`cloning ${a} \u2192 ${i.mountAs}/`),await Qa().clone(a,s),o.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`clone failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!za(Xa(s,".git"))){n.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=Qa(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!af(l,a)){n.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),o.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){n.info(`would fetch ${i.mountAs}/`),o.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),o.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);n.warn(`fetch failed for ${i.mountAs}: ${f}`),o.push({mountAs:i.mountAs,status:"error",detail:f})}}return o}function af(t,e){return Za(t)===Za(e)}function Za(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function ec(t={}){let e=et();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 cr(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let n of r)console.log(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}var tc=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function F(t){uf(t),process.exit(1)}function le(t){return ao(t)&&F("aborted"),t}function G(t){return ao(t)&&F("aborted"),typeof t=="string"?t:""}async function cc(t={}){sc("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();qa();let r=Ya(e),n,o=!1;r&&Object.keys(r.answers).length>0?le(await Ot({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?($.message("continuing with the saved answers \u2014 only the missing ones are asked"),n=new At(e,r),o=!0):(no(e),n=new At(e)):n=new At(e);let i=t.force===!0?null:await co(e),s=await n.ask("target",async()=>le(await lt({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?$.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):o&&n.get("contextRepo")!==void 0||uc(e,t.force===!0));let c=await n.ask("hubUrl",async()=>G(await W({message:"HUB URL",placeholder:me,initialValue:U("HUB_URL")??me,validate:j=>j.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await n.ask("email",()=>un()),{cliToken:u,accountEmail:f}=await n.ask("bootstrap",()=>pn(c,l)),p=null;s==="farm"&&(p=await pf(c,u));let g=a?ff(a.parsed.repoName):"",d=await n.ask("projectId",async()=>G(await W({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:j=>Xe.test(j.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await n.ask("projectName",async()=>G(await W({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),S=await n.ask("automationLevel",async()=>le(await lt({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"}))),C=await n.ask("youtrack",()=>yc()),T=await n.ask("youtrackProjectKey",async()=>G(await W({message:"YouTrack project key",placeholder:"DEV",validate:j=>j.trim().length>0?void 0:"required"})).trim()),k=await n.ask("youtrackWrites",async()=>le(await Ot({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),b=n.get("tokens")??{},_=()=>n.set("tokens",b),O=await n.ask("repos",()=>yf(b,l,a,{onCred:_,initial:n.get("reposPartial")??[],onProgress:j=>n.set("reposPartial",j)}));n.delete("reposPartial");let R=await wf(await n.ask("contextRepo",()=>mc(d,O,b,l)),d,O,b,l,_,j=>n.set("contextRepo",j)),{spec:h,mode:m}=R;$.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let v=await n.ask("assigneeLogin",async()=>G(await W({message:"your YouTrack login (the assignee value)",...C.login?{initialValue:C.login}:{},validate:j=>j.trim().length>0?void 0:"required"})).trim()),x=await n.ask("claudeToken",()=>Cf(s==="farm")),w={projectId:d,name:y,automationLevel:S,repos:O,youtrackProjectKey:T,ownerEmail:f};$.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let I;try{I=await Et(w,h,{...gc(b),youtrackWrites:k,trackerUrl:C.url,mode:m,log:{info:j=>$.message(j),warn:j=>$.warn(j)}})}catch(j){F(`Context Repo provisioning failed: ${j instanceof Error?j.message:String(j)}`)}w.contextRepo=I,$.success(`Context Repo ready: ${I.owner}/${I.name}@${I.branch}`),$.step(`registering project on ${c}\u2026`);let P;try{P=await St(c,u,w)}catch(j){if(j instanceof N&&j.status===409){$.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{P=await Q(c,u,d)}catch(ae){throw ae instanceof N&&F(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(j instanceof N&&j.status===401)n.delete("cliToken"),F("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(j instanceof N)F(`HUB \u2192 ${j.status} ${j.message}`);else throw j}let D=P.contextRepo??I;$.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let ie=await vf(D),fe={url:C.url,token:C.token};if(s==="farm"){let j=p,ae={...b,...ie?{contextWrite:ie}:{},...x?{claude:{oauthToken:x}}:{},youtrack:fe},Pe=b.github?.token;if(D.host==="github"&&Pe)try{let q=Ws(`devpipe-${d}`);await Ys(D,Pe,q.publicKey,`devpipe-${d}`),ae.contextSsh={privateKey:q.privateKey},$.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(q){$.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 xe={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:ae,contextRepo:D,projectConfig:we(w,k,C.url,v||void 0)},gn=xt(j.farm.publicKey,JSON.stringify(xe));$.step(`handing project ${d} to farm ${j.farm.name}\u2026`);let Je;try{Je=await Fr(c,u,j.farm.farmId,{projectId:d,sealedBundle:gn})}catch(q){throw q instanceof N&&F(q.status===409?`farm ${j.farm.name} is offline \u2014 start it and re-run.`:q.status===504?`farm ${j.farm.name} did not respond in time.`:`HUB \u2192 ${q.status} ${q.message}`),q}Je.ok||F(`farm rejected provisioning: ${Je.error??"unknown error"}`),await so(c,u,d,D,Pe),n.clear(),io(`done. project ${d} is now hosted on farm ${j.farm.name} (daemon ${Je.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}hc(b),await pc(e,D.cloneUrl,D.branch),fc(e),a&&await gf(e);{let j=ct(e,he);kt(j);let ae=we(w,k,C.url,v||void 0),Pe=Yt(j,ae);Pe.length>0&&$.success(`local project config \u2192 .codepipe/{${Pe.join(", ")}}`),nt(d,ae,{info:xe=>$.message(xe),warn:xe=>$.warn(xe)})}await dc(e,P.repos);let Ve={hubUrl:c,cliToken:u,projectId:d,...b,...ie?{contextWrite:ie}:{},...x?{claude:{oauthToken:x}}:{},youtrack:fe};J(Ve),tt({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),$.success(`secrets \u2192 ${rt(d)}`),await so(c,u,d,D,b.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),n.clear(),io("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function so(t,e,r,n,o){let i=await Ja(n,o),s=Va(i),a=await lt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(ao(a)||a!==s.proceedValue))try{let{jobId:c}=await Kr(t,e,r,{reindex:s.reindex});$.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){$.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function pf(t,e){let r;try{r=await Ss(t,e)}catch(c){throw c instanceof N&&F(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let n=r.filter(c=>c.publicKey);n.length===0&&F("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let o=le(await lt({message:"target farm",options:n.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=n.find(c=>c.farmId===o),s;try{s=Mr(i.farmId,i.publicKey)}catch(c){F(c instanceof Error?c.message:String(c))}return le(await Ot({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
537
546
|
${s}
|
|
538
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
547
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||F("farm fingerprint not confirmed \u2014 aborting."),Br(i.farmId,s),{farm:i,fingerprint:s}}async function lc(t){sc(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();uc(e,t.force===!0);let r=G(await W({message:"HUB URL",initialValue:U("HUB_URL")??me,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=await un(),{cliToken:o,accountEmail:i}=await pn(r,n);$.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,o,t.projectId)}catch(f){throw f instanceof N&&F(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||F(`project ${t.projectId} has no Context Repo on HUB`);let a=await yc(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await cn(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,n);hc(c),await pc(e,s.contextRepo.cloneUrl,s.contextRepo.branch),fc(e);{let f=ct(e,he);kt(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=we(p,!0,a.url),d=Yt(f,g);d.length>0&&$.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),nt(t.projectId,g,{info:y=>$.message(y),warn:y=>$.warn(y)})}await dc(e,s.repos);let u={hubUrl:r,cliToken:o,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};J(u),tt({hubUrl:r,cliToken:o,projectId:t.projectId,accountEmail:i},t.projectId),$.success(`secrets \u2192 ${rt(t.projectId)}`),await so(r,o,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),io("done.")}function uc(t,e){if(!_t(t)){rc(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),n=lf(t).filter(o=>!r.has(o));n.length!==0&&(e||F(`cwd ${t} is not empty (contains: ${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""}). use --force to bypass.`))}async function co(t){if(!_t(ct(t,".git")))return null;try{let r=(await ln(t).remote(["get-url","origin"])||"").toString().trim(),n=r?Ie(r):null;return n?{parsed:n,defaultBranch:await df(t)}:null}catch{return null}}async function df(t){let e=ln(t);try{let n=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(n)return n}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function ff(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Xe.test(e)?e:""}function mf(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function gf(t){let e=ct(t,".gitignore"),r=_t(e)?nc(e,"utf-8"):"";if(mf(r))return;if(!le(await Ot({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){$.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let o=r.length===0||r.endsWith(`
|
|
539
548
|
`)?"":`
|
|
540
|
-
`;
|
|
549
|
+
`;oc(e,r+o+`
|
|
541
550
|
# codepipe workspace (added by \`codepipe init\`)
|
|
542
551
|
.codepipe/
|
|
543
|
-
`)
|
|
552
|
+
`),$.success(`.codepipe/ added to ${ic(e)}`)}function hf(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let n=cf(e,r,{detached:!0,stdio:"ignore"});n.on("error",()=>{}),n.unref()}catch{}}async function un(){let t="";try{t=(await ln().raw(["config","--global","user.email"])||"").trim()}catch{}return G(await W({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function pn(t,e){$.step(`connecting account ${e}`);let r;try{r=await Ts(t,e)}catch(s){throw s instanceof Zt&&F(`${e} is not authorized on this HUB yet.
|
|
544
553
|
Sign up at ${t} (registration form on the login screen),
|
|
545
554
|
wait for the operator to approve it by email, then re-run
|
|
546
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated
|
|
555
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&$.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&$.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(hf(r.authorizeUrl),$.message(`a browser tab was opened to confirm this CLI:
|
|
547
556
|
${r.authorizeUrl}
|
|
548
557
|
`+(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
|
|
550
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
558
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&$.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),$.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let n=!1,o=Date.now(),i=o+15*6e4;for(;Date.now()<i;){let s;try{s=await Rs(t,r.requestId)}catch(a){$.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await oo(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&$.message(`connected as ${a} (the account confirmed in the browser).`),$.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&F("the HUB rejected this account"),s.status==="expired"&&F("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){n||(n=!0,i=o+24*60*6e4,$.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
559
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await oo(5e3);continue}await oo(2e3)}F("bootstrap timed out")}async function pc(t,e,r){let n=ct(t,he);if(_t(ct(n,".git"))){$.message(`${n} already cloned \u2014 skipping`);return}_t(n)&&F(`${n} exists but is not a git repo \u2014 remove it and re-run`),rc(n,{recursive:!0}),$.step(`cloning Context Repo \u2192 ${n}`);try{await ln().clone(e,n,["--branch",r]),$.success(`cloned ${e}`)}catch(o){F(`git clone failed: ${o instanceof Error?o.message:String(o)}`)}}async function dc(t,e){if(e.length===0)return;$.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(o=>({name:o.name,host:o.host,owner:o.owner,repoName:o.repoName,defaultBranch:o.defaultBranch??"main",mountAs:o.mountAs??o.name})),n=await cr(t,r,{log:{info:o=>$.message(o),warn:o=>$.warn(o)}});for(let o of n)$.message(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}function fc(t){let e=ct(t,he,".gitignore"),r="";if(_t(e)&&(r=nc(e,"utf-8")),tc.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let o=r.endsWith(`
|
|
551
560
|
`)||r.length===0?"":`
|
|
552
|
-
`,i=
|
|
561
|
+
`,i=tc.join(`
|
|
553
562
|
`)+`
|
|
554
|
-
`;
|
|
555
|
-
`:"")+i)
|
|
563
|
+
`;oc(e,r+o+(r?`
|
|
564
|
+
`:"")+i),$.message(`appended runtime entries to ${ic(e)}`)}async function yf(t,e,r,n={}){let o=[...n.initial??[]],i=n.onCred;if(r&&o.length===0){let{parsed:s,defaultBranch:a}=r;$.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await cn(s.host,t,s.owner,e),i?.();let c=G(await W({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=G(await W({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();o.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),n.onProgress?.(o)}for(;le(await Ot({message:o.length===0?"Add a project repository?":"Want to add another repository?",initialValue:o.length===0}));){let a=G(await W({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||Ie(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=Ie(a);$.message(`${c.host}: ${c.owner}/${c.repoName}`),await cn(c.host,t,c.owner,e),i?.();let l=G(await W({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=G(await W({message:"default branch (optional)",placeholder:"main"})).trim(),f=G(await W({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),f&&f!==l&&(p.mountAs=f),o.push(p),n.onProgress?.(o)}return o}async function mc(t,e,r,n){$.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let o=le(await lt({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));o==="attach"&&$.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=G(await W({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Ce(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!Ie(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=Ie(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await kf(),l=G(await W({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=G(await W({message:"Context Repo name",placeholder:Ce(t),initialValue:Ce(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:o}}function gc(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??gt()}}async function wf(t,e,r,n,o,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await cn(c.host,n,c.owner,o),i?.();let u=ac();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Da(c,gc(n),{explain:l==="attach"});if(f.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(f.detail,1);let p=le(await lt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&F("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await mc(e,r,n,o),s(a)}}async function kf(){return le(await lt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function lr(t,e){let r=ac();r.start(`verifying ${t}\u2026`);try{let n=await e();return r.stop(`${t} OK \u2014 ${n}`),!0}catch(n){return r.stop(`${t} failed \u2014 ${n instanceof Error?n.message:String(n)}`,1),!1}}function hc(t){qt(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Vt(t.gitlab?.token??process.env.GITLAB_TOKEN),Jt(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function cn(t,e,r,n){if(!e[t])if(t==="github"){let o=await bf(r);o?e.github=o:$.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let o=await $f(r,n);o?e.bitbucket=o:$.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let o=await xf();o?e.gitlab=o:$.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function bf(t){for(;;){let e=G(await Nt({message:`GitHub PAT \u2014 blank to skip
|
|
556
565
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
557
566
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
558
567
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
559
568
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
560
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
569
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await lr("GitHub",()=>Ue(e,t?{owner:t}:void 0)))return{token:e};$.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function $f(t,e){for($.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
561
570
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
562
571
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
563
572
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
564
573
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
565
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=
|
|
566
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
574
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let r=G(await W({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:o=>!o||!o.trim()||o.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let n=G(await Nt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!n){$.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await lr("Bitbucket",()=>Le(r,n,t)))return{email:r,apiToken:n};$.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function xf(){for(;;){let t=G(await Nt({message:`GitLab PAT \u2014 blank to skip
|
|
575
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await lr("GitLab",()=>De(t))){let e=await bi(t);return e&&$.warn(e),{token:t}}$.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function vf(t){if(le(await Ot({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
567
576
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
568
577
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
569
|
-
your trusted network.`,initialValue:!1})))for(t.host==="github"
|
|
578
|
+
your trusted network.`,initialValue:!1})))for(t.host==="github"?$.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
570
579
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
571
|
-
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`)
|
|
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=
|
|
573
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=M(await _t({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 pc(){for(;;){let t=M(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=M(await _t({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ar("YouTrack",()=>Be({baseUrl:t,token:e}))){let r=await Li({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as hf}from"node:fs";function W(t){throw new Error(t)}function J(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function cr(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 yf(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=J(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=J(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=J(i.id,"project.id");ze.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=J(i.name,"project.name"),c=J(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((S,E)=>{(!S||typeof S!="object")&&W(`config: project.repos[${E}] must be an object`);let I=S,B=J(I.host,`project.repos[${E}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&W(`config: project.repos[${E}].host must be 'github', 'bitbucket' or 'gitlab'`);let C={name:J(I.name,`project.repos[${E}].name`),host:B,owner:J(I.owner,`project.repos[${E}].owner`),repoName:J(I.repoName,`project.repos[${E}].repoName`)},_=cr(I.defaultBranch,`project.repos[${E}].defaultBranch`);_&&(C.defaultBranch=_);let R=cr(I.mountAs,`project.repos[${E}].mountAs`);return R&&(C.mountAs=R),C}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let u=f,d=cr(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:J(u.owner,"project.contextRepo.owner"),name:cr(u.name,"project.contextRepo.name")??Se(s)},y={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},v=cr(i.youtrackProjectKey,"project.youtrackProjectKey");v&&(y.project.youtrackProjectKey=v),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 x=e.secrets;if(x!==void 0){(typeof x!="object"||x===null)&&W("config: 'secrets' must be an object");let S=x,E={};if(S.github){let I=S.github;E.github={token:J(I.token,"secrets.github.token")}}if(S.bitbucket){let I=S.bitbucket;E.bitbucket={email:J(I.email,"secrets.bitbucket.email"),apiToken:J(I.apiToken,"secrets.bitbucket.apiToken")}}if(S.gitlab){let I=S.gitlab;E.gitlab={token:J(I.token,"secrets.gitlab.token")}}if(S.youtrack){let I=S.youtrack;E.youtrack={url:J(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:J(I.token,"secrets.youtrack.token")}}if(S.contextWrite){let I=S.contextWrite;E.contextWrite={token:J(I.token,"secrets.contextWrite.token")}}y.secrets=E}return y}async function wf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function bf(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 dc(t){let e=!t.configPath||t.configPath==="-"?await wf():hf(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=yf(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 bf(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 Pt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??gt(),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 vt(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 Z(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 f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(V(f),Ze({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${et(s.id)}`),tt(s.id,he(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await Hr(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 fc,intro as mc,isCancel as gc,log as cn,outro as kf,password as hc}from"@clack/prompts";async function $f(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function yc(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await $f(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){mc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),cn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hc({message:"Claude OAuth token"});gc(i)&&(fc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Jn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Cr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ae(t.profile);if(!e){mc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),cn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hc({message:"Claude OAuth token"});gc(i)&&(fc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=L(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}.`):(cn.success("Claude OAuth token saved."),kf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as xf,confirm as vf,intro as Sf,isCancel as wc,log as te,outro as Cf,select as bc,text as qe}from"@clack/prompts";function kc(t){xf(t),process.exit(1)}function Ot(t){return wc(t)&&kc("aborted"),t}function lr(t){return wc(t)&&kc("aborted"),typeof t=="string"?t:""}async function Tf(t,e){let r=Ot(await bc({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=lr(await qe({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=lr(await qe({message:"Context Repo name",placeholder:Se(t),initialValue:Se(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function $c(t={profile:void 0}){let e=Ae(t.profile);Sf(`codepipe project add \u2192 ${e.hubUrl}`);let r=Ot(await qe({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>ze.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Ot(await qe({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),n=Ot(await bc({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=Ot(await qe({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Ot(await vf({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=lr(await qe({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);te.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=lr(await qe({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(),y=lr(await qe({message:"default branch (optional)",placeholder:"main"})).trim(),v={name:g,host:d.host,owner:d.owner,repoName:d.repoName};y&&(v.defaultBranch=y),a.push(v)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await Tf(r,a),p=L(e.projectId);te.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Pt(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??gt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>te.message(u),warn:u=>te.warn(u)}})}catch(u){te.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await vt(e.hubUrl,e.cliToken,c);te.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),tt(r,he(c,s,p?.youtrack?.url),{info:d=>te.message(d),warn:d=>te.warn(d)}),u.contextRepo&&(te.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),te.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&te.error(` error: ${u.provisioningError}`),Cf("done")}catch(u){u instanceof A?(te.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&te.message(JSON.stringify(u.payload,null,2))):te.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{spawn as Rf}from"node:child_process";import{existsSync as xc}from"node:fs";import{homedir as If,hostname as Pf}from"node:os";import{join as uo}from"node:path";async function jf(t,e,r){let o=ne(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 Fr(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??`${Pf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function Ef(t,e){let r=ne(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=ye(r.sealPublicKey);if(!L(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=Sr(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 Af(t,e){let r=process.cwd(),o=uo(r,me);if($r(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(xc(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 Z(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 an(r);if(!On(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=L(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Yr({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=uo(If(),".codepipe",e?uo("profiles",e,"context-config"):"context-config");if(Pr(c.contextDir,l,a),!xc(uo(c.contextDir,"project.yaml"))){bt(c.contextDir);let p={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};Kt(c.contextDir,he(p,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function vc(t){let{cfg:e,profile:r}=vr(t.profile);await Af(e,r),await jf(e,r,t),Ef(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=v=>x=>{for(let S of x.toString("utf-8").split(`
|
|
574
|
-
`))
|
|
575
|
-
`)};
|
|
576
|
-
[up] ${
|
|
577
|
-
`)}async function
|
|
580
|
+
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):$.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
581
|
+
(${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=G(await Nt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await lr("contextWrite",()=>Sf(r,t)))return{token:r};$.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Sf(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},n;try{n=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(n.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!n.ok)throw new Error(`GitHub \u2192 ${n.status} ${n.statusText}`);let o=await n.json();if(o.permissions&&o.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return o.full_name??`${e.owner}/${e.name}`}async function Cf(t){if(xn()?.claude?.oauthToken&&!t)return $.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`)."),"";$.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?`
|
|
582
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=G(await Nt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||$.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):($.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 yc(){for(;;){let t=G(await W({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let n=r.trim();if(!n)return"required";if(!n.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=G(await Nt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await lr("YouTrack",()=>Me({baseUrl:t,token:e}))){let r=await Mi({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}$.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Tf}from"node:fs";function Y(t){throw new Error(t)}function X(t,e){return(typeof t!="string"||t.trim().length===0)&&Y(`config: '${e}' must be a non-empty string`),t.trim()}function ur(t,e){if(t==null)return;typeof t!="string"&&Y(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Rf(t){(!t||typeof t!="object")&&Y("config: expected a JSON object");let e=t,r=X(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Y("config: 'hubUrl' must start with http(s)://");let n=X(e.cliToken,"cliToken"),o=e.project;(!o||typeof o!="object")&&Y("config: 'project' is required");let i=o,s=X(i.id,"project.id");Xe.test(s)||Y("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"&&Y("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Y("config: 'project.repos' must be an array");let u=l.map((T,k)=>{(!T||typeof T!="object")&&Y(`config: project.repos[${k}] must be an object`);let b=T,_=X(b.host,`project.repos[${k}].host`);_!=="github"&&_!=="bitbucket"&&_!=="gitlab"&&Y(`config: project.repos[${k}].host must be 'github', 'bitbucket' or 'gitlab'`);let O={name:X(b.name,`project.repos[${k}].name`),host:_,owner:X(b.owner,`project.repos[${k}].owner`),repoName:X(b.repoName,`project.repos[${k}].repoName`)},R=ur(b.defaultBranch,`project.repos[${k}].defaultBranch`);R&&(O.defaultBranch=R);let h=ur(b.mountAs,`project.repos[${k}].mountAs`);return h&&(O.mountAs=h),O}),f=i.contextRepo;(!f||typeof f!="object")&&Y("config: 'project.contextRepo' is required");let p=f,g=ur(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Y("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:X(p.owner,"project.contextRepo.owner"),name:ur(p.name,"project.contextRepo.name")??Ce(s)},y={hubUrl:r,cliToken:n,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},S=ur(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(y.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&Y("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Y("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let C=e.secrets;if(C!==void 0){(typeof C!="object"||C===null)&&Y("config: 'secrets' must be an object");let T=C,k={};if(T.github){let b=T.github;k.github={token:X(b.token,"secrets.github.token")}}if(T.bitbucket){let b=T.bitbucket;k.bitbucket={email:X(b.email,"secrets.bitbucket.email"),apiToken:X(b.apiToken,"secrets.bitbucket.apiToken")}}if(T.gitlab){let b=T.gitlab;k.gitlab={token:X(b.token,"secrets.gitlab.token")}}if(T.youtrack){let b=T.youtrack;k.youtrack={url:X(b.url,"secrets.youtrack.url").replace(/\/$/,""),token:X(b.token,"secrets.youtrack.token")}}if(T.contextWrite){let b=T.contextWrite;k.contextWrite={token:X(b.token,"secrets.contextWrite.token")}}y.secrets=k}return y}async function If(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Pf(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,n=await Ue(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${n}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(o=>o.host==="bitbucket")?.owner,n=await Le(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${n}`)}if(e.gitlab){let r=await De(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Me({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function wc(t){let e=!t.configPath||t.configPath==="-"?await If():Tf(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Y(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let n=Rf(r),{hubUrl:o,cliToken:i,project:s}=n;console.log(`codepipe init --headless \u2192 ${o} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Pf(n));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=n.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Et(a,s.contextRepo,{githubToken:c,gitlabToken:n.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:n.secrets?.bitbucket??gt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:n.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Y(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${o}\u2026`);let u;try{u=await St(o,i,a)}catch(p){if(p instanceof N&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await Q(o,i,s.id);else if(p instanceof N)Y(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:o,cliToken:i,projectId:s.id,...n.secrets??{}};if(J(f),tt({hubUrl:o,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${rt(s.id)}`),nt(s.id,we(a,s.youtrackWrites??!0,n.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await Kr(o,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as kc,intro as bc,isCancel as $c,log as lo,outro as jf,password as xc}from"@clack/prompts";async function Ef(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function vc(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Ef(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){bc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),lo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await xc({message:"Claude OAuth token"});$c(i)&&(kc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Xo({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Rr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=_e(t.profile);if(!e){bc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),lo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await xc({message:"Claude OAuth token"});$c(i)&&(kc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let o=B(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};o.claude={oauthToken:e},J(o),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(lo.success("Claude OAuth token saved."),jf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Af,confirm as _f,intro as Of,isCancel as Sc,log as ee,outro as Nf,select as Cc,text as qe}from"@clack/prompts";function Tc(t){Af(t),process.exit(1)}function Ut(t){return Sc(t)&&Tc("aborted"),t}function pr(t){return Sc(t)&&Tc("aborted"),typeof t=="string"?t:""}async function Uf(t,e){let r=Ut(await Cc({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),n=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",o=pr(await qe({message:"Context Repo owner (org / group / workspace / user)",placeholder:n||"your-org",initialValue:n,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=pr(await qe({message:"Context Repo name",placeholder:Ce(t),initialValue:Ce(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:o,name:i}}async function Rc(t={profile:void 0}){let e=_e(t.profile);Of(`codepipe project add \u2192 ${e.hubUrl}`);let r=Ut(await qe({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>Xe.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),n=Ut(await qe({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),o=Ut(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=Ut(await qe({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Ut(await _f({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=pr(await qe({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:C=>!C||!C.trim()||Ie(C)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=Ie(p);ee.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=pr(await qe({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:C=>C.trim().length>0?void 0:"required"})).trim(),y=pr(await qe({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:d,host:g.host,owner:g.owner,repoName:g.repoName};y&&(S.defaultBranch=y),a.push(S)}let c={projectId:r,name:n,automationLevel:o,repos:a};i&&(c.youtrackProjectKey=i);let l=await Uf(r,a),u=B(e.projectId);ee.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Et(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??gt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>ee.message(p),warn:p=>ee.warn(p)}})}catch(p){ee.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,ee.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await St(e.hubUrl,e.cliToken,c);ee.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),nt(r,we(c,s,u?.youtrack?.url),{info:g=>ee.message(g),warn:g=>ee.warn(g)}),p.contextRepo&&(ee.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),ee.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&ee.error(` error: ${p.provisioningError}`),Nf("done")}catch(p){p instanceof N?(ee.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&ee.message(JSON.stringify(p.payload,null,2))):ee.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{spawn as Lf}from"node:child_process";import{existsSync as Ic}from"node:fs";import{homedir as Df,hostname as Bf}from"node:os";import{join as dn}from"node:path";async function Mf(t,e,r){let n=ne(e);if(n){if(n.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${n.sandboxId} (${n.name})`);return}throw new Error(`worker config ${He(e)} points at a different HUB (${n.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await Hr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof N&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof N&&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 N?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 st({hub:t.hubUrl,token:o,name:r.name??`${Bf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function Gf(t,e){let r=ne(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let n=ke(r.sealPublicKey);if(!B(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let o=Tr(t,r.sandboxId,n);if(o==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${n}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${o==="pinned"?"auto-pinned":"already pinned"} for ${t} (${n})`)}async function Ff(t,e){let r=process.cwd(),n=dn(r,he);if(vr(t.projectId,r)){console.log(`[up] using the workspace context at ${n}`);return}if(Ic(n)){console.warn(`[up] ${n} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let o;try{o=await Q(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await co(r);if(!No(r,i?.parsed??null,o.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=B(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await Vr({cfg:t,secrets:s,contextDir:n,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=dn(Df(),".codepipe",e?dn("profiles",e,"context-config"):"context-config");if(Er(c.contextDir,l,a),!Ic(dn(c.contextDir,"project.yaml"))){kt(c.contextDir);let u={projectId:t.projectId,name:o.name,automationLevel:o.automationLevel,repos:o.repos,...o.youtrackProjectKey?{youtrackProjectKey:o.youtrackProjectKey}:{}};Yt(c.contextDir,we(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${n}`)}async function Pc(t){let{cfg:e,profile:r}=Cr(t.profile);await Ff(e,r),await Mf(e,r,t),Gf(e.projectId,r);let n=process.argv[1];if(!n)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(g,d)=>{let y=S=>C=>{for(let T of C.toString("utf-8").split(`
|
|
583
|
+
`))T.length>0&&S.write(`${d} ${T}
|
|
584
|
+
`)};g.stdout?.on("data",y(process.stdout)),g.stderr?.on("data",y(process.stderr))},i=(g,d)=>{let y=Lf(process.execPath,[n,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(y,g),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
|
|
585
|
+
[up] ${g} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(g);setTimeout(()=>{for(let{name:d,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let f=c.map(({name:g,child:d})=>new Promise(y=>{d.on("exit",(S,C)=>y({name:g,code:S??(C?1:0)}))})),p=await Promise.race(f);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(f),process.exit(p.code)}import{existsSync as Gc,mkdirSync as qf,readFileSync as Vf,writeFileSync as Jf}from"node:fs";import{homedir as zf}from"node:os";import{dirname as Xf,join as Fc}from"node:path";import*as Dt from"node:readline";import{existsSync as fo,readFileSync as Hf,writeFileSync as Kf}from"node:fs";import{join as fr}from"node:path";import{simpleGit as po}from"simple-git";var jc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Wf="apply-queue.json";function Ec(t){return fr(t,Wf)}function Lt(t){let e=Ec(t);if(!fo(e))return{};try{return JSON.parse(Hf(e,"utf-8"))}catch{return{}}}function Ac(t,e){Kf(Ec(t),JSON.stringify(e,null,2)+`
|
|
586
|
+
`)}async function _c(t,e,r,n,o){let i;try{i=await js(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(C=>C.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=fr(t.root,g.mountAs);if(!fo(fr(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await po(d).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:d})}let a=[];for(let p of s){let g=po(p.dir),d=await Yf(g),y=p.claimRepo;try{await g.fetch()}catch(T){return await uo(a,o),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${dr(T)}`}}let S=`origin/${y.baseRef}`,C;try{C=await Lr(g,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(T){return await uo(a,o),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${dr(T)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:y.branchName,baseSha:S,deliveryCommit:C,startPoint:S})}let c=[];for(let p of a)try{if(n==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([...jc,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([...jc,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await uo(a,o),{ok:!1,message:`apply failed in ${p.mountAs}: ${dr(g)} (rolled back all repos)`}}let l=Lt(t.contextDir);l[r]={mode:n,claimedAt:new Date().toISOString(),repos:c},Ac(t.contextDir,l);let u=c.map(p=>p.mountAs).join(", "),f=n==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${n==="apply"?"applied":"unstashed"} ${r} in ${u}
|
|
578
587
|
${f}
|
|
579
|
-
or: /abort ${r} --reason "..."`}}function
|
|
580
|
-
\u26A0 unfinished local apply: ${
|
|
581
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let
|
|
582
|
-
`))}async function
|
|
583
|
-
`)}`:" (none)");return}if(r==="set"){let i=
|
|
584
|
-
`),t.unread+=1,
|
|
585
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
588
|
+
or: /abort ${r} --reason "..."`}}function mo(t,e){let r=Lt(t);r[e]&&(delete r[e],Ac(t,r))}async function uo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(n){e.warn(`rollback failed in ${r.mountAs}: ${dr(n)} \u2014 check manually`)}}async function Oc(t,e,r){let o=Lt(t.contextDir)[e];if(o){for(let i of o.repos){let s=fr(t.root,i.mountAs);if(!fo(fr(s,".git")))continue;let a=po(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${dr(u)} \u2014 check manually`)}}mo(t.contextDir,e)}}async function Yf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function dr(t){return t instanceof Error?t.message.trim():String(t)}var fn=Fc(zf(),".codepipe","history"),Nc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Hc=500,Uc=40;async function Kc(){let t=et();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=B(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)),Wt(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=Lt(t.contextDir),n=Object.keys(r);n.length>0&&console.log(`
|
|
589
|
+
\u26A0 unfinished local apply: ${n.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
590
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let o=Dt.createInterface({input:process.stdin,output:process.stdout,completer:Qf,history:wm(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:o,unread:0,daemon:void 0,follow:!1,logBuffer:[]};gs(s=>ut(i,s)),i.daemon=qr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>ut(i,s),warn:s=>ut(i,s)},onEvent:s=>dm(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),ho(i),o.prompt(),o.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Zf(i,a)){Mc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,ho(i),o.prompt()}),o.on("close",()=>{Mc(i)})}function Qf(t){let e=Nc.filter(r=>r.startsWith(t));return[e.length?e:Nc,t]}async function Zf(t,e){let[r,...n]=e.split(/\s+/);switch(r){case"/help":return em(),!1;case"/status":return await tm(t),!1;case"/tasks":return await rm(t,n),!1;case"/task":return await nm(t,n),!1;case"/sync":return await om(t),!1;case"/logs":return fm(t,n),!1;case"/monitor":return mm(t),!1;case"/apply":return await Lc(t,n,"apply"),!1;case"/unstash":return await Lc(t,n,"unstash"),!1;case"/applied":return await im(t,n),!1;case"/abort":return await sm(t,n),!1;case"/approve":return await Dc(t,n,"approve"),!1;case"/merge":return await Dc(t,n,"merge"),!1;case"/login":return cm(t,n),!1;case"/secret":return lm(t,n),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function em(){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(`
|
|
591
|
+
`))}async function tm(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let n=Gc(Fc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${n?"present":"missing (run /sync)"}`)}}async function rm(t,e){let r=gm(e,"--phase");try{let n=await Is(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),o=r?n.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):n;if(o.length===0){console.log(" (no tasks)");return}for(let i of o)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(n){gr(n)}}async function nm(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let n=await Ps(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${n.task.phase} \u2014 ${n.task.title}`),n.artifacts.length>0){console.log(" artifacts:");for(let o of n.artifacts)console.log(` ${o.path}`)}}catch(n){gr(n)}}async function om(t){let e=await cr(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 Lc(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}let o=await _c(t.ws,t.secrets,n,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${o.message}`)}async function im(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let o=Lt(t.ws.contextDir)[r],i=hm(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,f;if(l>0?(u=c.slice(0,l),f=c.slice(l+1)):(f=c,u=o?.repos.length===1?am(t,o.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let p=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:u,url:f,number:Number(p[1])})}try{let c=await Es(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);mo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){gr(c)}}async function Dc(t,e,r){let n=e[0];if(!n){console.log(`usage: /${r} <key>`);return}try{let o=await _s(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,n,r);console.log(` ${r} ${n} \u2192 ${o.task.phase}`)}catch(o){gr(o)}}async function sm(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let n=ym(e,"--reason")||"local apply aborted";await Oc(t.ws,r,{info:o=>console.log(o),warn:o=>console.warn(o)});try{let o=await As(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,n);console.log(` ${r} \u2192 ${o.task.phase} (rolled back locally)`)}catch(o){gr(o)}}function am(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function cm(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},J(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 lm(t,e){let[r,n,...o]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
|
|
592
|
+
`)}`:" (none)");return}if(r==="set"){let i=o.join(" ");if(!n||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}um(t.secrets,n,i),J(t.secrets),Wt(t.secrets),console.log(` set ${n}`);return}if(r==="unset"){if(!n){console.log("usage: /secret unset <key>");return}pm(t.secrets,n),J(t.secrets),console.log(` unset ${n}`);return}console.log("usage: /secret set|list|unset")}function um(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 pm(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 dm(t,e){switch(e.kind){case"connected":t.connection="connecting",ut(t,"[hub] connected");break;case"registered":t.connection="registered",ut(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",mr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ut(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",mr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":mr(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?ut(t,`[hub] action ${e.actionType} done`):mr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function ut(t,e){t.logBuffer.push(e),t.logBuffer.length>Hc&&t.logBuffer.shift(),t.follow&&mr(t,e)}function fm(t,e){let r=e[0];if(r==="follow"||r==="on"){go(t,!0);return}if(r==="off"){go(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let n=r?Math.max(1,Math.min(Hc,Number(r)||Uc)):Uc,o=t.logBuffer.slice(-n);if(o.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of o)console.log(` ${i}`);console.log(` \u2014 ${o.length} line(s); /monitor for live stream`)}function mm(t){go(t,!t.follow)}function go(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function mr(t,e){Dt.cursorTo(process.stdout,0),Dt.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
593
|
+
`),t.unread+=1,ho(t),t.rl.prompt(!0)}function ho(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Bc=!1;function Mc(t){Bc||(Bc=!0,km(t.rl),t.daemon.stop(),console.log(`
|
|
594
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function gm(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function hm(t,e){let r=[];for(let n=0;n<t.length;n++)t[n]===e&&t[n+1]&&r.push(t[n+1]);return r}function ym(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function gr(t){t instanceof N?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function wm(){if(!Gc(fn))return[];try{return Vf(fn,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function km(t){let r=(t.history??[]).filter(n=>!/^\/secret\s+set\b/.test(n)&&!/^\/login\b/.test(n));try{qf(Xf(fn),{recursive:!0}),Jf(fn,r.slice().reverse().join(`
|
|
586
595
|
`)+`
|
|
587
|
-
`)}catch{}}import{hostname as
|
|
596
|
+
`)}catch{}}import{hostname as bm}from"node:os";import{cancel as $m,confirm as Wc,intro as xm,isCancel as Vc,log as Bt,multiselect as vm,outro as Yc,password as Sm,select as yo,text as wo}from"@clack/prompts";function hr(t){$m(t),process.exit(1)}function Mt(t){return Vc(t)&&hr("aborted"),t}function mn(t){return Vc(t)&&hr("aborted"),typeof t=="string"?t:""}function ko(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function qc(t,e){try{let{secret:r}=await Hr(t,e);return r}catch(r){throw r instanceof N&&r.status===404&&hr("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 Cm(t,e){if(Mt(await yo({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 o=await Cs(t,e);if(o.length>0)return Mt(await vm({message:"pick the projects (space to toggle, enter to confirm)",options:o.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Bt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(o){Bt.warn(`could not list projects (${o instanceof Error?o.message:String(o)}) \u2014 enter the ids manually`)}return mn(await wo({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:o=>o.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function bo(t){xm("codepipe worker \u2014 set up this machine as a runner");let e=ne(t.profile);e&&(Bt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Mt(await Wc({message:"re-register this worker?",initialValue:!1}))||hr("keeping the existing registration"));let r=Te(t.profile)??Te(),n=mn(await wo({message:"HUB URL",placeholder:me,initialValue:U("HUB_URL")??r?.hubUrl??me,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=r!==null&&r.hubUrl.replace(/\/$/,"")===n,i=Mt(await yo({message:"how to authorize the registration?",options:[...o?[{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:o?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await qc(n,a),Bt.success("account-issued registration token minted");else if(i==="login"){let p=await un();a=(await pn(n,p)).cliToken,s=await qc(n,a),Bt.success("account-issued registration token minted")}else s=mn(await Sm({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||hr("a registration token is required");let c=await Cm(n,a),l=mn(await wo({message:"worker name",initialValue:bm(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=Mt(await yo({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 st({hub:n,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Bt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Mt(await Wc({message:"start the claim-loop now?",initialValue:!0}))){Yc("registered. start later with `codepipe worker`.");return}Yc("starting the claim-loop\u2026"),await ar(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 U("PROFILE")}var te=Rm();Mo(te);Ho();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 Kc()}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 wc({configPath:t.config,skipVerify:t.skipVerify===!0}):await cc({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 Qo({...t,profile:te})}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 lc({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 Zs({profile:te})}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 ec({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 vc({profile:te,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 La({profile:te})}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 Pc({profile:te,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Jc=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Jc.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??U("HUB_URL")??Te(te)?.hubUrl??me,r=t.token??U("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&ko()){await bo({profile:te});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 n=U("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),o=t.name??U("WORKER_NAME"),i=t.llm??U("WORKER_LLM");await st({hub:e,token:r,projects:t.projects?.length?t.projects:n??[],force:t.force===!0,...o?{name:o}:{},...i?{llm:i}:{},...te?{profile:te}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Jc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ne(te)&&ko()){await bo({profile:te});return}await ar(te?{profile:te}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Im=ue.command("project").description("Manage CodePipe projects");Im.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Rc({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();
|