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