@code-partner/codepipe 0.1.127 → 0.1.128-dev.13.g2847d8e
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 +120 -118
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var ie="0.1.128-dev.13.g2847d8e",pe="https://hub.dev.codepipe.dev";var de=2,$c=1;function ar(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=$c&&t<=de}var be=".devpipe-context.yaml",sn=[{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",be]}];function cr(t=1){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function
|
|
6
|
-
`,{mode:384})}function
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function
|
|
5
|
+
`}function an(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 cn(t,e=sn){let r=[];for(let o of e)if(!(o.version<=t))for(let n of o.addedPaths)r.includes(n)||r.push(n);return r}function ln(t,e=sn){return e.filter(r=>r.version>t)}function lr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ge=/^[a-z][a-z0-9-]{1,30}$/,xc="-codepipe-ctx";function ke(t){return`${t}${xc}`}var Nt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function rt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let o=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return o?o[1]??null:null}var ot="x-bitbucket-api-token-auth";function ur(t){switch(t){case Nt.gitlab:return"oauth2";case Nt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var un=20;function _(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Lf}from"commander";import{homedir as pn}from"node:os";import{mkdirSync as vc,readFileSync as Sc,writeFileSync as Cc,existsSync as oo}from"node:fs";import{dirname as fn,join as pr,resolve as Rc}from"node:path";import{fileURLToPath as Tc}from"node:url";var dn=Rc(fn(Tc(import.meta.url)),"..");function mn(t){let e=pr(dn,".env");if(oo(e)&&process.loadEnvFile(e),t){let r=pr(dn,"profiles",t,".env");oo(r)&&process.loadEnvFile(r)}}function nt(t){let e=_("CONFIG");return e||(t?pr(pn(),".codepipe","profiles",t,"config.json"):pr(pn(),".codepipe","config.json"))}function Re(t){let e=nt(t);if(!oo(e))return null;let r=Sc(e,"utf-8");return JSON.parse(r)}function Me(t,e){let r=nt(e);vc(fn(r),{recursive:!0}),Cc(r,JSON.stringify(t,null,2)+`
|
|
6
|
+
`,{mode:384})}function fe(t){let e=Re(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 ${nt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as hn}from"node:os";import{join as wn}from"node:path";import{existsSync as gn,renameSync as Ic}from"node:fs";function He(t,e,r=o=>console.error(o)){if(gn(e)||!gn(t))return!1;try{return Ic(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}function yn(){He(wn(hn(),".devpipe"),wn(hn(),".codepipe"))}import{homedir as bn}from"node:os";import{existsSync as kn,mkdirSync as $n,readFileSync as xn,writeFileSync as vn}from"node:fs";import{dirname as Sn,join as Cn}from"node:path";function dr(t,e,r){let o=H(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,Z(o),"pinned")}function Fe(t){return Cn(bn(),".codepipe","secrets",`${t}.json`)}function H(t){let e=Fe(t);return kn(e)?JSON.parse(xn(e,"utf-8")):null}function Z(t){let e=Fe(t.projectId);$n(Sn(e),{recursive:!0}),vn(e,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function fr(){return Cn(bn(),".codepipe","shared.json")}function Pc(){let t=fr();return kn(t)?JSON.parse(xn(t,"utf-8")):null}function Rn(t){let e=fr();$n(Sn(e),{recursive:!0}),vn(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function it(t){let e=H(t)?.claude?.oauthToken;return e||Pc()?.claude?.oauthToken}function Ut(t){let e=(r,o)=>{o&&!process.env[r]&&(process.env[r]=o)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function st(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Tn(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=Re(e);r&&!t.force&&(console.error(`already configured at ${nt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Me({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};Z(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${nt(e)}`)}import{homedir as Io}from"node:os";import{join as Ht}from"node:path";import{appendFileSync as Ec,existsSync as In,mkdirSync as jc,renameSync as Pn,statSync as Ac,unlinkSync as _c}from"node:fs";import{Writable as Oc}from"node:stream";import{join as Nc}from"node:path";var En={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},at=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&jc(e.dir,{recursive:!0}),this.currentPath=Nc(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
9
9
|
`)?e:e+`
|
|
10
|
-
`;
|
|
10
|
+
`;Ec(this.currentPath,r,"utf-8")}asWritable(){return new Oc({write:(e,r,o)=>{try{let n=typeof e=="string"?e:e.toString("utf-8");for(let i of n.split(/\r?\n/))i&&this.writeLine(i);o()}catch(n){o(n)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!In(this.currentPath)||Ac(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;In(o)&&(r>=this.cfg.maxFiles?_c(o):Pn(o,`${this.currentPath}.${r+1}`))}Pn(this.currentPath,`${this.currentPath}.1`)}}};function mr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Uc(process.env[`${t}_MAX_BYTES`]??String(En.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):En.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Uc(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),o=(e[2]??"").toLowerCase();return o==="g"?r*1024**3:o==="m"?r*1024**2:o==="k"?r*1024:r}function gr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(o,n)=>(...i)=>{o(...i);try{t.writeLine(Lc(n,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Lc(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Dc(n)).join(" ");return`${r} ${t} ${o}`}function Dc(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Su}from"node:path";import"ws";import{createHash as Bc}from"node:crypto";import{existsSync as Gc,readFileSync as Mc}from"node:fs";import{homedir as Hc,hostname as no}from"node:os";import{join as Fc}from"node:path";function jn(t){return Bc("sha256").update(t).digest("hex").slice(0,12)}function Kc(){let t=_("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Fc(Hc(),".claude","credentials.json");if(!Gc(e))return;let r=JSON.parse(Mc(e,"utf-8")),o=[r.email,r.account?.email,r.user?.email];for(let n of o)if(typeof n=="string"&&n.includes("@"))return n.trim().toLowerCase()}catch{}}function An(t){let e=Kc(),r=_("ACCOUNT_ID")?.trim(),o=_("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=it(t);return n?{accountId:`acct-${jn(n)}`,label:o||no(),...e?{email:e}:{}}:{accountId:`acct-${jn(`host:${no()}`)}`,label:o||no(),...e?{email:e}:{}}}import{existsSync as Wc}from"node:fs";import{join as qc}from"node:path";import{simpleGit as Yc}from"simple-git";async function _n(t,e){if(!Wc(qc(t,".git")))return{status:"skipped"};let r=Yc(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Vc(n)}`}}let o=await r.status();if(!o.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(o.current!==e)return{status:"warn",reason:`on '${o.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function Vc(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as io,readFileSync as On,readdirSync as zc,watch as Jc}from"node:fs";import{join as so}from"node:path";var hr=class{constructor(e,r,o,n,i=6e4){this.contextDir=e;this.projectId=r;this.send=o;this.log=n;this.intervalMs=i}timer=null;watcher=null;debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(io(this.contextDir))try{this.watcher=Jc(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=so(this.contextDir,e);if(!io(r))return null;try{return On(r,"utf-8")}catch{return null}}readPrompts(){let e=so(this.contextDir,"prompts"),r={};if(!io(e))return r;let o;try{o=zc(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=On(so(e,n),"utf-8")}catch{}}return r}};import{existsSync as al,readFileSync as cl,readdirSync as ll}from"node:fs";import{join as Hn}from"node:path";import{simpleGit as ul}from"simple-git";import{existsSync as el,mkdirSync as tl,writeFileSync as Dn}from"node:fs";import{dirname as rl,isAbsolute as ol,join as Gn,normalize as fo}from"node:path";import{simpleGit as Mn}from"simple-git";import{existsSync as Te,mkdirSync as Nn,readFileSync as ao,writeFileSync as ct}from"node:fs";import{homedir as Xc}from"node:os";import{join as me}from"node:path";import{simpleGit as Qc}from"simple-git";var lt=["project.yaml","regimen.yaml"];function co(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=me(t,n);Te(s)||(ct(s,i),r.push(n))}return r}function Ke(t,e,r){let o=me(Xc(),".codepipe","profiles",t,"context-config");return Nn(o,{recursive:!0}),ct(me(o,"project.yaml"),e.projectYaml),ct(me(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Un(t,e,r){if(Te(e))for(let o of lt){let n=me(e,o),i=me(t,o);if(!(!Te(n)||Te(i)))try{ct(i,ao(n)),r.info(`[config] seeded local ${o} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${o}: ${s instanceof Error?s.message:String(s)}`)}}}var Zc=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function wr(t){let e=me(t,".gitignore"),r=Te(e)?ao(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(lt.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
11
11
|
`)?"":`
|
|
12
|
-
`;return
|
|
12
|
+
`;return ct(e,r+i+Zc.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`),!0}async function
|
|
15
|
-
`).map(
|
|
16
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
17
|
-
`),r=e.find(
|
|
18
|
-
`),a=s.findIndex(
|
|
19
|
-
`).replace(/^\n+/,""),
|
|
20
|
-
`);return{content:
|
|
21
|
-
`)?
|
|
22
|
-
`,supersedes:l}}function
|
|
23
|
-
|
|
24
|
-
- **Status:** superseded by ADR-${r}`):o}function
|
|
14
|
+
`),!0}async function Ln(t,e){try{if(!Te(me(t,".git")))return;let r=Qc(t),o=(await r.raw(["ls-files","--",...lt])).split(`
|
|
15
|
+
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;wr(t),await r.raw(["rm","--cached","--quiet","--",...o]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await po(t),e.info(`[config] migrated ${o.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function lo(t){let e=new Map;for(let r of lt){let o=me(t,r);Te(o)&&e.set(r,ao(o))}return e}function uo(t,e){Nn(t,{recursive:!0});for(let[r,o]of e){let n=me(t,r);Te(n)||ct(n,o)}}var Bn=3,nl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function yr(t,e,r){if(!el(Gn(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=sl(t,i.path);tl(rl(s),{recursive:!0}),i.encoding==="base64"?Dn(s,Buffer.from(i.content,"base64")):Dn(s,i.content)}let o=Mn(t);await o.add(["-A","--",".",...lt.map(i=>`:(exclude)${i}`)]),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await po(t))}async function po(t){let e=Mn(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Bn;o++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let n=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${n}`])}catch{let i=await il(e);if(i.length>0&&i.every(s=>nl.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 ${Bn} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function il(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
16
|
+
`).map(r=>r.trim()).filter(Boolean)}function sl(t,e){if(ol(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=fo(Gn(t,e)),o=fo(t+"/");if(r!==fo(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var pl=/^(\d{4})-(.+)\.md$/,dl="0000-template.md";function fl(t){let e=t.split(`
|
|
17
|
+
`),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function ml(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
18
|
+
`),a=s.findIndex(R=>R.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,u=new Set(["status","date","tasks"]),p=[],f="",l=null,d=a>=0?a+1:0;for(let R=d;R<s.length;R++){let v=(s[R]??"").trim();if(v===""){d=R+1;continue}let T=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!T)break;let j=(T[1]??"").trim().toLowerCase(),U=(T[2]??"").trim(),S=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);S&&(l=parseInt(S[1]??"",10)),j==="tasks"&&(f=U),u.has(j)||p.push(v),d=R+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,w=s.slice(d).join(`
|
|
19
|
+
`).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${g}`,...p,"",w].join(`
|
|
20
|
+
`);return{content:k.endsWith(`
|
|
21
|
+
`)?k:k+`
|
|
22
|
+
`,supersedes:l}}function gl(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
|
|
23
|
+
|
|
24
|
+
- **Status:** superseded by ADR-${r}`):o}function hl(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
|
|
25
25
|
`)+`
|
|
26
|
-
`}async function
|
|
27
|
-
`+t.slice(t.length-e)}async function tt(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let n=(await o.json()).login??"ok",s=o.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return n}async function lo(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,i;try{i=await fetch(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(i.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(i.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!i.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${i.status} ${i.statusText}`);if((await i.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function rt(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",i;try{i=await fetch(o,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(i.ok)return t;if(i.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let n=await rl(i);throw i.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${n})`):i.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${n})`):i.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${n})`):new Error(`Bitbucket \u2192 ${i.status} ${i.statusText}${n}`)}async function rl(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ot(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}var io=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let i=await o.json();return{url:i.links?.html?.href??"",number:i.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!i.ok)return null;let s=(await i.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,i=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(i.status===404)throw new Be(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(i.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${i.status} ${await i.text()}`);let n=await i.json();return n.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:n.state==="DECLINED"||n.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,i){let n=o==="squash"?"squash":o==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:n,close_source_branch:i})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,o){if(o&&o.length>0){let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:o}})});if(!n.ok)throw new Error(`bitbucket comment PR #${r}: ${n.status} ${await n.text()}`)}let i=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(!i.ok)throw new Error(`bitbucket decline PR #${r}: ${i.status} ${await i.text()}`)}},so=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let i=await o.json();return{url:i.html_url,number:i.number}}async findOpenPrByBranch(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let n=(await o.json())[0];return n?{url:n.html_url,number:n.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,i=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(i.status===404)throw new Be(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(i.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${i.status} ${await i.text()}`);let n=await i.json();if(n.state==="closed"&&n.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(n.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=n.mergeable===!1||n.mergeable_state==="dirty"?"conflict":n.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:n.head?.sha?await this.fetchCiStatus(e,n.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},i=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[n,s]=await Promise.all([fetch(`${i}/check-runs?per_page=100`,{headers:o}),fetch(`${i}/status`,{headers:o})]),a=!1,c=!1,u=!1;if(n.ok){let p=await n.json();for(let m of p.check_runs??[])u=!0,m.status!=="completed"?a=!0:m.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(m.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(u=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return u?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},i=`https://api.github.com/repos/${e.owner}/${e.repoName}`,n=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${i}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${i}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let u=(await c.json()).workflow_runs??[],p=[];for(let m of u.filter(l=>l.conclusion&&n.includes(l.conclusion))){let l=await fetch(`${i}/actions/runs/${m.id}/jobs?per_page=50`,{headers:o});if(!l.ok)continue;let d=(await l.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${i}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let b=await w.text();p.push(`### CI job: ${g.name}
|
|
26
|
+
`}async function Fn(t,e,r,o=new Date().toISOString().slice(0,10)){try{await ul(t).pull(void 0,void 0,["--rebase"])}catch{}let n=Hn(t,"adr"),i=new Map;if(al(n))for(let l of ll(n)){let d=pl.exec(l);!d||l===dl||i.set(l,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:cl(Hn(n,l),"utf-8")})}let s=Math.max(0,...[...i.values()].map(l=>l.num))+1,a=new Map,c=[],u=[];for(let l of r){if([...i.entries()].find(([,v])=>v.slug===l.slug&&v.content.includes(e))){u.push(l.slug);continue}let g=s++,w=`${String(g).padStart(4,"0")}-${l.slug}.md`,{content:k,supersedes:R}=ml(l.content,g,l.slug,e,o);if(a.set(w,k),i.set(w,{num:g,slug:l.slug,content:k}),c.push(`adr/${w}`),R!==null){let v=[...i.keys()].find(T=>T.startsWith(`${String(R).padStart(4,"0")}-`));if(v&&v!==w){let T=gl(a.get(v)??i.get(v).content,g);a.set(v,T),i.set(v,{...i.get(v),content:T})}}}if(c.length===0)return{promoted:c,skipped:u};let p=[...i.entries()].map(([l,d])=>({num:d.num,file:l,header:fl(d.content)}));a.set("INDEX.md",hl(p));let f=[...a.entries()].map(([l,d])=>({path:`adr/${l}`,content:d}));return await yr(t,f,`adr(${e}): promote ${r.map(l=>l.slug).join(", ")}`),{promoted:c,skipped:u}}import{existsSync as Kn,readFileSync as yl}from"node:fs";import{join as Wn}from"node:path";function bl(t){let e=Wn(t,be);if(!Kn(e))return 0;try{return an(yl(e,"utf-8"))}catch{return 0}}function kl(t,e,r,o=1){let n=e<o,i=n?cn(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function br(t,e){return kl(e,bl(t),r=>Kn(Wn(t,r)))}import{existsSync as Nl,mkdirSync as Ul,mkdtempSync as Ll,rmSync as Dl,writeFileSync as zn}from"node:fs";import{tmpdir as Bl}from"node:os";import{dirname as Gl,join as bo}from"node:path";import{simpleGit as ko}from"simple-git";var We=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function qn(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
27
|
+
`+t.slice(t.length-e)}async function ut(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function yo(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function pt(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await $l(n);throw n.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):n.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):n.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${n.status} ${n.statusText}${i}`)}async function $l(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function dt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Vn(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let o=(await e.json()).scopes??[];return o.length>0&&!o.includes("api")?`GitLab token scopes [${o.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var mo=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.links?.html?.href??"",number:n.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(n.status===404)throw new We(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){let i=o==="squash"?"squash":o==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:n})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:o}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!n.ok)throw new Error(`bitbucket decline PR #${r}: ${n.status} ${await n.text()}`)}},go=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.html_url,number:n.number}}async findOpenPrByBranch(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(n.status===404)throw new We(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,u=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])u=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(u=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return u?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let u=(await c.json()).workflow_runs??[],p=[];for(let f of u.filter(l=>l.conclusion&&i.includes(l.conclusion))){let l=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!l.ok)continue;let d=(await l.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let k=await w.text();p.push(`### CI job: ${g.name}
|
|
28
28
|
|
|
29
|
-
${
|
|
29
|
+
${qn(k,8e3)}`)}}return p.length===0?void 0:qn(p.join(`
|
|
30
30
|
|
|
31
|
-
`),16e3)}catch{return}}async mergePR(e,r,o,
|
|
31
|
+
`),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let u=(await a.json()).head?.ref;u&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${u}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},ho=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!o.ok)throw new Error(`gitlab mr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.web_url??"",number:n.iid}}async findOpenPrByBranch(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let o=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,n=await fetch(o,{method:"GET",headers:this.headers()});if(n.status===404)throw new We(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(n.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=xl(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function xl(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 wo=class{name="mock";async createPullRequest(e,r){let o=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${o}`,number:o}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){throw new Error(Yn(e,r,"merge"))}async closePR(e,r,o){throw new Error(Yn(e,r,"close"))}};function Yn(t,e,r){let o=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${o}`}function $e(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new go(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new mo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ho(e)}return new wo}function ft(t,e,r,o){return[{path:"README.md",content:Al(t,e)},{path:".gitignore",content:Tl()},{path:"CLAUDE.md",content:Pl(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Il()},{path:"knowledge/README.md",content:El()},{path:"knowledge/build.yaml",content:jl()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Rl()},{path:"adr/README.md",content:vl()},{path:"adr/0000-template.md",content:Sl()},{path:"adr/INDEX.md",content:Cl()},{path:be,content:cr()}]}function vl(){return`# ADR \u2014 architecture decision records
|
|
32
32
|
|
|
33
33
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
34
34
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -56,7 +56,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
56
56
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
57
57
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
58
58
|
open a PR to this repository.
|
|
59
|
-
`}function
|
|
59
|
+
`}function Sl(){return`# ADR-NNNN: <title>
|
|
60
60
|
|
|
61
61
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
62
62
|
- **Date:** YYYY-MM-DD
|
|
@@ -78,12 +78,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
78
78
|
## Alternatives considered
|
|
79
79
|
|
|
80
80
|
- **<alternative>** \u2014 why it was rejected.
|
|
81
|
-
`}function
|
|
81
|
+
`}function Cl(){return`# ADR index
|
|
82
82
|
|
|
83
83
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
84
84
|
|
|
85
85
|
(no accepted ADRs yet)
|
|
86
|
-
`}function
|
|
86
|
+
`}function Rl(){return`# Audit
|
|
87
87
|
|
|
88
88
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
89
89
|
project appends only to its own file \u2014
|
|
@@ -92,14 +92,14 @@ project appends only to its own file \u2014
|
|
|
92
92
|
|
|
93
93
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
94
94
|
shared aggregate here.
|
|
95
|
-
`}function
|
|
95
|
+
`}function Ie(t,e,r,o){return{projectYaml:_l(t,r,o),regimenYaml:Ol(t.automationLevel,e)}}function Tl(){return`# codepipe project config is local to each member's workspace
|
|
96
96
|
project.yaml
|
|
97
97
|
regimen.yaml
|
|
98
98
|
|
|
99
99
|
# codepipe runtime
|
|
100
100
|
session.log
|
|
101
101
|
apply-queue.json
|
|
102
|
-
`}function
|
|
102
|
+
`}function Il(){return`# Index prompt
|
|
103
103
|
|
|
104
104
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
105
105
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -156,7 +156,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
156
156
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
157
157
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
158
158
|
empty or unavailable, say so briefly rather than inventing content.
|
|
159
|
-
`}function
|
|
159
|
+
`}function Pl(t){return`# Project context for the CodePipe agent
|
|
160
160
|
|
|
161
161
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
162
162
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -184,7 +184,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
184
184
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
185
185
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
186
186
|
only after the analysis is approved.
|
|
187
|
-
`}function
|
|
187
|
+
`}function El(){return`# Knowledge
|
|
188
188
|
|
|
189
189
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
190
190
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -201,7 +201,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
201
201
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
202
202
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
203
203
|
any merge conflict in it as noise (either side converges on the next run).
|
|
204
|
-
`}function
|
|
204
|
+
`}function jl(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
205
205
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
206
206
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
207
207
|
#
|
|
@@ -217,7 +217,7 @@ any merge conflict in it as noise (either side converges on the next run).
|
|
|
217
217
|
# - name: test
|
|
218
218
|
# run: npm test
|
|
219
219
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
220
|
-
`}function
|
|
220
|
+
`}function Al(t,e){return`# ${e.name}
|
|
221
221
|
|
|
222
222
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
223
223
|
|
|
@@ -243,26 +243,26 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
243
243
|
pipeline \u2014 don't edit them by hand.
|
|
244
244
|
|
|
245
245
|
Automation level: **${t.automationLevel}**.
|
|
246
|
-
`}function
|
|
246
|
+
`}function _l(t,e,r){let o=e?`
|
|
247
247
|
tracker_url: ${e}`:`
|
|
248
|
-
# tracker_url: https://your.youtrack.cloud`,
|
|
248
|
+
# tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
|
|
249
249
|
assignee: ${r}`:`require_assignee: false
|
|
250
|
-
# assignee: your.youtrack.login`,
|
|
250
|
+
# assignee: your.youtrack.login`,i=t.youtrackProjectKey?` project_key: ${t.youtrackProjectKey}${o}
|
|
251
251
|
poll_interval_sec: 60
|
|
252
|
-
#
|
|
253
|
-
#
|
|
252
|
+
# Values of the custom YT \`Stage\` field. CodePipe only pulls tasks with
|
|
253
|
+
# one of these stages into the pipeline.
|
|
254
254
|
source_columns:
|
|
255
255
|
- Develop
|
|
256
|
-
#
|
|
257
|
-
# (
|
|
258
|
-
#
|
|
259
|
-
#
|
|
256
|
+
# Tasks from this YT column land in the dashboard's TODO section
|
|
257
|
+
# (BACKLOG phase) \u2014 they sync, but the pipeline doesn't start until they are
|
|
258
|
+
# promoted with the Develop button or moved into source_columns manually.
|
|
259
|
+
# Optional: remove the key to disable the TODO section.
|
|
260
260
|
backlog_column: Backlog
|
|
261
|
-
#
|
|
262
|
-
#
|
|
263
|
-
#
|
|
264
|
-
# assignee. assignee
|
|
265
|
-
${
|
|
261
|
+
# Sync gate on assignee. require_assignee=false (or the key missing) \u2014
|
|
262
|
+
# behavior unchanged. When true, CodePipe only pulls tasks of the given
|
|
263
|
+
# assignee (YT login) into the pipeline; without assignee \u2014 any task with a
|
|
264
|
+
# non-empty assignee. assignee only takes effect when require_assignee=true.
|
|
265
|
+
${n}`:` # project_key: \u2026
|
|
266
266
|
# tracker_url: https://your.youtrack.cloud
|
|
267
267
|
poll_interval_sec: 60`,s=t.repos.length===0?` [] # add repos here
|
|
268
268
|
`:t.repos.map(a=>` - name: ${a.name}
|
|
@@ -276,7 +276,7 @@ id: ${t.projectId}
|
|
|
276
276
|
name: ${t.name}
|
|
277
277
|
|
|
278
278
|
youtrack:
|
|
279
|
-
${
|
|
279
|
+
${i}
|
|
280
280
|
|
|
281
281
|
adapters:
|
|
282
282
|
tracker: youtrack
|
|
@@ -301,7 +301,7 @@ branch:
|
|
|
301
301
|
|
|
302
302
|
repos:
|
|
303
303
|
${s}
|
|
304
|
-
`}function
|
|
304
|
+
`}function Ol(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
305
305
|
automation:
|
|
306
306
|
level: ${t}
|
|
307
307
|
|
|
@@ -316,16 +316,16 @@ youtrack:
|
|
|
316
316
|
pr_comment: ${o}
|
|
317
317
|
# Mirror dashboard comments back into YouTrack. Off without enabled.
|
|
318
318
|
dashboard_mirror: ${o}
|
|
319
|
-
# YT
|
|
320
|
-
#
|
|
319
|
+
# YT column (Stage) for new drafts published from PLAN.
|
|
320
|
+
# Backlog by default \u2192 the task shows up in the TODO section, not straight in WORK.
|
|
321
321
|
draft_target_status: Backlog
|
|
322
|
-
# YT
|
|
323
|
-
#
|
|
324
|
-
# + status_changes.
|
|
322
|
+
# YT stage (Stage) that CodePipe moves a task to when it enters TRACKING
|
|
323
|
+
# (PR opened / ready for review). Applies only with writes.enabled
|
|
324
|
+
# + status_changes. Review by default.
|
|
325
325
|
review_status: Review
|
|
326
326
|
|
|
327
327
|
gates:
|
|
328
|
-
# Reserved
|
|
328
|
+
# Reserved \u2014 NOT consumed yet. Gating is currently driven solely by
|
|
329
329
|
# automation.level: 'full' auto-passes G1..G4, 'assisted' requires a manual
|
|
330
330
|
# Run/Approve at each. Names and modes mirror docs/PIPELINE.md so a future
|
|
331
331
|
# per-gate parser stays config-compatible. Modes: always | auto_below_hours
|
|
@@ -334,10 +334,11 @@ gates:
|
|
|
334
334
|
G2_solution: { mode: ${r?"never":"always"} }
|
|
335
335
|
G3_implementation: { mode: ${r?"never":"always"} }
|
|
336
336
|
G4_apply: { mode: ${r?"never":"always"} }
|
|
337
|
-
#
|
|
338
|
-
# Develop
|
|
339
|
-
#
|
|
340
|
-
#
|
|
337
|
+
# The first ACTUALLY consumed key of the gates block. When true, a task from
|
|
338
|
+
# Develop parks in the AWAITING_APPROVAL phase (WORK section, "awaiting
|
|
339
|
+
# approval") and doesn't start implementation until a manual Approve /
|
|
340
|
+
# To Backlog in the dashboard. Orthogonal to automation.level. Off by
|
|
341
|
+
# default \u2014 behavior unchanged.
|
|
341
342
|
require_approval: false
|
|
342
343
|
|
|
343
344
|
estimate:
|
|
@@ -415,21 +416,22 @@ parallelism:
|
|
|
415
416
|
# # the previous task's branch (auto-merge without reworking the
|
|
416
417
|
# # tail of the chain).
|
|
417
418
|
# mode: parallel
|
|
418
|
-
`}function
|
|
419
|
-
`)}async function
|
|
420
|
-
${u.trim()}`)}}let
|
|
421
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await
|
|
422
|
-
${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),
|
|
423
|
-
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function Kl(t,e,r){return new Promise((o,i)=>{let n=Ce.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=n.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new pi(s.raw):null;n.end(),o(c)});n.on("error",i),n.setTimeout(r,()=>{n.destroy(),i(new Error("tls connect timeout"))})})}function ho(t,e,r){return new Promise(o=>{let i=Ce.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{i.end(),o(!0)});i.on("error",()=>o(!1)),i.setTimeout(r,()=>{i.destroy(),o(!1)})})}async function Wl(t){try{let e=await fetch(t);return e.ok?new pi(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function hi(t,e=443,r=fi){let o=`${t}:${e}`,i=ui.get(o);if(i)return i;let n=ql(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ui.set(o,n),n}async function ql(t,e,r){if(!di)return!1;let o=8e3;if(await ho(t,e,o))return!0;let i=await Kl(t,e,o),n=Ce.getCACertificates(),s=[];for(let a=0;a<4&&i&&i.subject!==i.issuer;a++){let c=Fl(i);if(!c)break;let u=await Wl(c);if(!u)break;if(s.push(u.toString()),Ce.setDefaultCACertificates([...n,...s]),await ho(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(u.subject===u.issuer)break;i=u}return ho(t,e,o)}function De(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function we(t,e,r){mi();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let i=t.baseUrl+e,n={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(i,n)}catch(s){if(gi(s)&&await hi(new URL(t.baseUrl).host))return await fetch(i,n);throw s}}var yi=t=>new Promise(e=>setTimeout(e,t));function Yl(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Vl(){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 ki(t,e,r,o){let{attempts:i,baseMs:n,capMs:s}=Vl(),a=null;for(let c=1;c<=i;c++){let u=null;try{u=await we(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(u){if(u.ok)return u;let p=await u.text();if(c<i&&Yl(u.status,p)){await yi(Math.min(s,n*2**(c-1)));continue}throw new Error(`${e}: ${u.status} ${p}`)}if(c<i){await yi(Math.min(s,n*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function st(t){let e;try{e=await we(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}var wi=new Map;async function zl(t,e,r){let o=`${e.split("-")[0]}:${r}`,i=wi.get(o);if(i)return i;let n=await we(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!n.ok)throw new Error(`yt resolveStateId ${e}: ${n.status} ${await n.text()}`);let a=(await n.json()).customFields.find(u=>u.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(u=>u.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return wi.set(o,c.id),c.id}async function $i(t,e,r){let o=await zl(t,e,r);await ki(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function xi(t,e,r){return await(await ki(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var bi=new Map;async function Jl(t,e){let r=bi.get(e);if(r)return r;let o=await we(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let n=(await o.json()).find(s=>s.shortName===e);if(!n)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return bi.set(e,n.id),n.id}async function Si(t,e,r,o,i){let n=await Jl(t,e),s=await we(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:n},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:i,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function vi(t,e,r,o){let i=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,n=await we(t,"/api/commands",{method:"POST",body:JSON.stringify({query:i,issues:[{idReadable:e}]})});if(!n.ok)throw new Error(`yt applyIssueLink (${i} on ${e}): ${n.status} ${await n.text()}`)}var Ci="attachments(id,name,url,size,mimeType)",Xl="links(direction,linkType(name),issues(idReadable))",Ri=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ci},${Xl}`,Ql=`id,text,created,author(login),${Ci}`;function Ti(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 Ii(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Pi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),i=`/api/issues?query=${encodeURIComponent(o)}&fields=${Ri}&$top=200`,n=await we(t,i);if(!n.ok)throw new Error(`yt listIssues: ${n.status} ${await n.text()}`);return(await n.json()).map(Ai)}async function Ei(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Ri}`,o=await we(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Ai(await o.json())}async function ji(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Ql}&$top=500`,i=await we(t,o);if(!i.ok)throw new Error(`yt listComments ${e}: ${i.status} ${await i.text()}`);return(await i.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=Ti(s.attachments);return c&&(a.attachments=c),a})}function Zl(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let i of r.issues??[])i.idReadable&&e.push({type:o,targetKey:i.idReadable})}return e.length>0?e:void 0}function Ai(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),i=e.find(c=>c.name==="Type"),n={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(n.description=t.description),o?.value?.login&&(n.assignee=o.value.login),i?.value?.name&&(n.issueType=i.value.name),t.tags&&t.tags.length>0&&(n.tags=t.tags.map(c=>c.name));let s=Ti(t.attachments);s&&(n.attachments=s);let a=Zl(t.links);return a&&(n.links=a),n}var mr=new Map;async function yo(t,e){let o=(mr.get(t)??Promise.resolve()).catch(()=>{}).then(e);mr.set(t,o);try{return await o}finally{mr.get(t)===o&&mr.delete(t)}}async function _i(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",i="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;It(`[exec] ${e.type} task=${i} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let n=e.taskId.split(":",2)[0]??"?";return yo(`${n}/${r.name}`,async()=>{let s=await dr(n,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Et(n,r.name,t.baseDir),{commit:c}=await si(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return Q({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 H("no repo spec");let n=e.taskId.split(":",2)[0]??"?";return yo(`${n}/${r.name}`,async()=>{let s=await dr(n,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Et(n,r.name,t.baseDir),{commit:c,pushed:u}=await ai(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Q({branch:e.branchName,commit:c,pushed:u})})}case"create_pr":{if(!r)return H("no repo spec");let n=ye(r),s=await n.createPullRequest(r,e);return Q({url:s.url,number:s.number,host:n.name})}case"merge_pr":{if(!r)return H("no repo spec");let n=ye(r),s=await n.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Q({prNumber:e.prNumber,host:n.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return H("no repo spec");let n=ye(r);return await n.closePR(r,e.prNumber,e.comment),Q({prNumber:e.prNumber,host:n.name})}case"merge_branch":{if(!r)return H("no repo spec");let n=e.taskId.split(":",2)[0]??"?";return yo(`${n}/${r.name}`,async()=>{let s=await dr(n,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Et(n,r.name,t.baseDir),{mergedSha:c}=await ci(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return Q({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return Q({stub:!0});case"tracker_status":{let n=De();return n?t.trackerIssueId?(await $i(n,t.trackerIssueId,e.newStatus),Q({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let n=De();if(!n)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await xi(n,t.trackerIssueId,e.body);return Q({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let n=De();if(!n)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return H("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Si(n,e.projectKey,e.title,e.body,e.targetStatus);return Q({issueKey:a,issueId:s})}case"apply_tracker_links":{let n=De();if(!n)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await vi(n,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return H(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Q({applied:s})}case"set_parallelism":{if(!t.contextDir)return H("no context repo clone on this CLI");let n=await Jn(t.contextDir,e.maxJobs);return Q({maxJobs:n.maxJobs,unchanged:n.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let n=await ei(t.contextDir,e);return Q({files:n.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Q({reported:!0})):H("no context repo clone on this CLI")}}catch(n){return H(n instanceof Error?n.message:String(n))}}function Q(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}import eu from"ws";function gr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new eu(r)}var A=class extends Error{constructor(r,o,i){super(i);this.status=r;this.payload=o;this.name="HubHttpError"}};async function at(t,e,r){return Me(t,e,"/projects",r)}async function Oi(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Ni(t,e,r,o){return Me(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function hr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Ui(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var jt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Li(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new jt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Bi(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Di(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function Mi(t,e,r,o){let i=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!i.ok)throw new A(i.status,null,`GET cli-task HTTP ${i.status}`);return await i.json()}async function Gi(t,e,r,o){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Hi(t,e,r,o,i){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:i})}async function Fi(t,e,r,o,i){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:i})}async function Ki(t,e,r,o,i){return Me(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:i})}async function yr(t,e,r,o){return Me(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function ne(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Me(t,e,r,o){let i=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),n=await i.text(),s=n?JSON.parse(n):null;if(!i.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${i.status}`;throw new A(i.status,s,a)}return s}function ct(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Wi(t,e){let r=G(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await st({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(n){o.push({name:"youtrack",ok:!1,detail:ct(n)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await tt(r.github.token),o.push({name:"github",ok:!0})}catch(n){o.push({name:"github",ok:!1,detail:ct(n)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await rt(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(n){o.push({name:"bitbucket",ok:!1,detail:ct(n)})}else if(r?.gitlab?.token)try{await ot(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(n){o.push({name:"gitlab",ok:!1,detail:ct(n)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let n=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await lo(n,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:ct(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await lo(n,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:ct(a)})}}let i=Xe(t);if(!i)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let n=await tu(i);o.push(n==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(n=>n.ok),checks:o,checkedAt:Date.now()}}async function tu(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var wr=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let o=[];for(let s of r.prs){let a=ye(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof Be){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 i=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===i)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=ye(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let u=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);u&&(a.ciFailureLog=u)}catch(u){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${u instanceof Error?u.message:String(u)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,i);let n=ru(o);this.log.info(`[track] task=${e} snapshot signalled${n?` \u2192 ${n}`:""} (${o.length} PR(s))`)}};function ru(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var br=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=De();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),i;try{let l=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];i=await Pi(r,{projectKey:e.projectKey,columns:l,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(l){this.log.warn(`[yt-sync] listIssues failed: ${l instanceof Error?l.message:String(l)}`);return}let n=[],s=new Set;for(let l of i){s.add(l.id);let d=await qi(r,l.id,e.sinceMs,this.log);d&&n.push({issueId:l.id,comments:d})}let a=[];for(let l of e.offBoardIssueIds){if(s.has(l))continue;let d=await qi(r,l,e.sinceMs,this.log);if(d&&n.push({issueId:l,comments:d}),e.requireAssignee){let g=await nu(r,l,this.log);g&&a.push(g)}}let c=await this.collectAttachments(i,n,r),u={type:"youtrack_observation",projectId:e.projectId,issues:i,commentsBatch:n,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(u);let p=n.reduce((l,d)=>l+d.comments.length,0),m=c.reduce((l,d)=>l+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${i.length} comments=${p} attachments=${m} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let i=[];for(let n of e){let s=[...n.attachments??[]],a=r.find(p=>p.issueId===n.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],u=new Set;for(let p of s){let m=`${n.id}:${p.id}`;if(this.shippedAttachments.has(m))continue;let l;try{l=await Ii(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${n.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=ou(p.name);u.has(d)&&(d=`${p.id}-${d}`),u.add(d),c.push({name:d,contentBase64:l.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(m)}c.length>0&&i.push({issueId:n.id,files:c})}return i}};function ou(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 nu(t,e,r){try{return await Ei(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function qi(t,e,r,o){try{return await ji(t,e,r)}catch(i){return o.warn(`[yt-sync] listComments ${e} failed: ${i instanceof Error?i.message:String(i)}`),null}}var wo="npm i -g @code-partner/codepipe@latest";function kr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${oe} (protocol ${pe})`);let o=d=>e.onEvent?.(d),i=e.workspace;i?.contextDir&&Pn(i.contextDir,r);let n=Yi("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Yi("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,u=!1,p=new Set,m=l();function l(){let d=gr(t.hubUrl,t.cliToken),g=null,w=new wr(n,x=>{d.readyState===d.OPEN&&d.send(JSON.stringify(x))},r),b=new br(s,x=>{d.readyState===d.OPEN&&d.send(JSON.stringify(x))},r),C=null,v=async()=>{try{let x;try{let y=await ne(t.hubUrl,t.cliToken,t.projectId);x={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await Wi(t.projectId,x);if(d.readyState!==d.OPEN)return;let f={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(f)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(x){r.warn(`[readiness] check failed: ${x instanceof Error?x.message:String(x)}`)}},P=()=>{v(),C=setInterval(()=>void v(),a),typeof C.unref=="function"&&C.unref()},j=()=>{C&&(clearInterval(C),C=null)},L=i?.contextDir?new sr(i.contextDir,t.projectId,x=>{d.readyState===d.OPEN&&d.send(JSON.stringify(x))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let x=Cn(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",f=_("FARM_ID"),y=t.accountEmail??x.email,$={type:"register",projectId:t.projectId,platformVersion:oe,protocolVersion:pe,accountId:x.accountId,accountLabel:x.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&f?{farmId:f}:{}};d.send(JSON.stringify($))}),d.on("message",async x=>{let h=x.toString("utf-8");if(h==="pong"||h==="ping")return;let f;try{f=JSON.parse(h)}catch{return}if(!f||typeof f!="object")return;let y=f.type;if(y==="registered"){let S=f;if(S.ok){if(r.info(`[ws] registered for project ${S.projectId}`),o({kind:"registered",projectId:S.projectId??t.projectId}),w.start(),L?.start(),P(),i?.contextDir){let k=i.contextDir;try{let E=ur(k,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(E)),E.outdated&&(r.warn(`[ctx] context format outdated: v${E.templateVersion} \u2192 v${E.currentVersion}`+(E.missingPaths.length>0?` (missing: ${E.missingPaths.join(", ")})`:"")),u||(u=!0,(async()=>{try{let M;try{M=(await ne(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let ce=await Gn(k,t.projectId,M,r);d.readyState===d.OPEN&&d.send(JSON.stringify(ce))}catch(M){r.warn(`[ctx] context migration failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}})()))}catch(E){r.warn(`[ctx] context-format detect failed (non-fatal): ${E instanceof Error?E.message:String(E)}`)}}}else r.warn(`[ws] register rejected: ${S.reason??"unknown"}`),o({kind:"register_rejected",reason:S.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let S=f;g=Xt(S.protocolVersion);let k=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${S.platformVersion} (protocol ${S.protocolVersion}) \u2014 ${k}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${oe}, protocol ${pe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${wo}`),o({kind:"incompatible",hubVersion:typeof S.platformVersion=="string"?S.platformVersion:null,hubProtocol:typeof S.protocolVersion=="number"?S.protocolVersion:null,updateCommand:wo}));return}if(y==="tracking_targets"){w.setTargets(f.targets);return}if(y==="youtrack_sync_request"){b.setRequest(f);return}if(y==="sync_local"){await su(f,i,d,r);return}if(y==="context_write"){await au(f,i,d,r);return}if(y==="adr_promote"){await cu(f,i,d,r);return}if(y==="sandbox_keys"){let S=G(t.projectId);if(!S){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let k=Xe(t.projectId),E=Vn(f,S,k,r);for(let M of E)d.readyState===d.OPEN&&d.send(JSON.stringify(M));return}if(y!=="dispatch_action")return;let $=f;if(g===!1){let S=`refused: HUB protocol incompatible with CLI v${oe} (protocol ${pe})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:S})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${S}`),r.warn(`[exec] update the CLI to clear this: ${wo}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:S});return}p.add($.actionId);try{let S=await _i({action:$.action,repo:$.repo,trackerIssueId:$.trackerIssueId,contextDir:i?.contextDir,requestConfigReport:L?()=>L.reportNow():void 0}).catch(M=>({status:"failed",error:M instanceof Error?M.message:String(M)}));d.send(JSON.stringify({type:"action_result",actionId:$.actionId,...S}));let k=S.status!=="failed",E=!k&&"error"in S?S.error:void 0;k?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${E??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:k,...E?{error:E}:{}})}finally{p.delete($.actionId)}}),d.on("close",(x,h)=>{let f=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${x}${f?` reason=${f}`:""}`),w.stop(),b.stop(),L?.stop(),j(),f==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:x}),!c&&setTimeout(()=>{m=l()},2e3)}),d.on("error",x=>r.warn(`[ws] error: ${x.message}`)),d}return{stop(){c=!0,m.close()}}}async function su(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let i of t.repos){let n=e.repos.find(u=>u.name===i.repoName),s=iu(e.root,n?.mountAs??i.repoName),a=n?.defaultBranch??i.defaultBranch,c=await Rn(s,a).catch(u=>({status:"warn",reason:u instanceof Error?u.message:String(u)}));c.status==="updated"?o.info(`[sync] ${i.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${i.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${i.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:i.repoName,reason:c.reason??"sync skipped"})))}}async function au(t,e,r,o){let i=(n,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:n};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),i("failed","no context repo clone on this CLI");return}try{await lr(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),i("done")}catch(n){let s=n instanceof Error?n.message:String(n);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),i("failed",s)}}async function cu(t,e,r,o){let i=(n,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:n};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),i("failed","no context repo clone on this CLI");return}try{let n=await Nn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${n.promoted.length}, skipped ${n.skipped.length}`+(n.promoted.length>0?` (${n.promoted.join(", ")})`:"")),i("done")}catch(n){let s=n instanceof Error?n.message:String(n);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),i("failed",s)}}function Yi(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as es,mkdirSync as ts}from"node:fs";import{dirname as rs}from"node:path";import{simpleGit as Ge}from"simple-git";import{execFileSync as lu}from"node:child_process";import{mkdtempSync as uu,mkdirSync as pu,readFileSync as Vi,rmSync as du,writeFileSync as fu}from"node:fs";import{tmpdir as mu}from"node:os";import{dirname as gu,join as zi}from"node:path";function Ji(t="codepipe-context"){let e=uu(zi(mu(),"codepipe-ssh-")),r=zi(e,"id_ed25519");try{return lu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Vi(r,"utf-8"),publicKey:Vi(`${r}.pub`,"utf-8").trim()}}finally{du(e,{recursive:!0,force:!0})}}async function Xi(t,e,r,o="codepipe-context"){let i=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:o,key:r,read_only:!1})});if(i.ok)return;let n=await i.text();if(!(i.status===422&&/already in use/i.test(n)))throw new Error(`add deploy key failed: ${i.status} ${n}`)}function Qi(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 Zi(t,e){pu(gu(t),{recursive:!0});let r=e.endsWith(`
|
|
419
|
+
`}function Ml(t){return`codepipe/context-migration-v${t}`}function Hl(t){let e=ln(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 \`${be}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
|
|
420
|
+
`)}async function Jn(t,e,r,o){let n=ko(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=br(t,e);if(!i.outdated)return i;let s=Ml(i.currentVersion),a=r?.branch??(await n.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await n.fetch().catch(()=>{}),(await n.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Fl(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(u){return o.warn(`[ctx] context migration branch failed (will retry next start): ${u instanceof Error?u.message:String(u)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let u=$e(c),p=await u.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let f=await u.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:Hl(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(u){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${u instanceof Error?u.message:String(u)}`),i}}async function Fl(t,e,r,o,n,i,s){let a=ko(t),c=Ll(bo(Bl(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let u={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(ft(u,p).map(g=>[g.path,g.content])),l=0;for(let g of o.missingPaths){if(g===be)continue;let w=f.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=bo(c,g);Nl(k)||(Ul(Gl(k),{recursive:!0}),zn(k,w),l++)}zn(bo(c,be),cr(o.currentVersion)),l++;let d=ko(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${l} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Dl(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as Kl,createDecipheriv as Wl,createHash as ql,createPrivateKey as Yl,createPublicKey as $o,diffieHellman as Xn,generateKeyPairSync as Qn,hkdfSync as Zn,randomBytes as Vl}from"node:crypto";var ei=Buffer.from("devpipe-sealedbox-v1","utf-8");function ti(){let{publicKey:t,privateKey:e}=Qn("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function mt(t){let e=Buffer.from(t,"base64");return(ql("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function kr(t,e){let r=$o({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=Qn("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Xn({privateKey:n,publicKey:r}),c=Buffer.from(Zn("sha256",a,Buffer.concat([i,s]),ei,32)),u=Vl(12),p=Kl("aes-256-gcm",c,u),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,l=Buffer.concat([p.update(f),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:u.toString("base64"),tag:d.toString("base64"),ct:l.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function ri(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let o=Yl({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=$o({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=$o(o).export({type:"spki",format:"der"}),a=Xn({privateKey:o,publicKey:n}),c=Buffer.from(Zn("sha256",a,Buffer.concat([i,s]),ei,32)),u=Wl("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return u.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([u.update(Buffer.from(r.ct,"base64")),u.final()])}function zl(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let o=e??t.claude?.oauthToken;return o&&(r.claudeOauthToken=o),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function oi(t,e,r,o){let n=zl(e,r);t.sandboxes.length>0&&!n.claudeOauthToken&&o.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!n.contextWrite&&(n.github||n.gitlab||n.bitbucket)&&o.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(n),s=[];for(let a of t.sandboxes){let c=dr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let u;try{u=kr(a.publicKey,i)}catch(p){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:u})}return s}import{existsSync as Jl,readFileSync as Xl,writeFileSync as Ql}from"node:fs";import{join as Zl}from"node:path";import{parseDocument as eu}from"yaml";var ni=64;async function ii(t,e){if(!Number.isInteger(e)||e<1||e>ni)throw new Error(`maxJobs must be an integer in [1, ${ni}], got ${e}`);let r=Zl(t,"regimen.yaml");if(!Jl(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=eu(Xl(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Ql(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as si,readFileSync as ai,writeFileSync as tu}from"node:fs";import{join as xo}from"node:path";import{parseDocument as ci}from"yaml";async function li(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=xo(t,"project.yaml");if(!si(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ci(ai(i,"utf-8"));if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=xo(t,"regimen.yaml");if(!si(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ci(ai(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)tu(xo(t,i.path),i.content);return{files:r.map(i=>i.path)}}var ui=t=>console.log(t);function pi(t){ui=t}function Lt(t,e="info"){ui(t,e)}import{homedir as ru}from"node:os";import{existsSync as ou,mkdirSync as nu}from"node:fs";import{join as vo}from"node:path";import{simpleGit as di}from"simple-git";function Bt(t,e,r){let o=r??vo(ru(),".codepipe","repos");return vo(o,t,e)}async function $r(t,e,r={}){let o=Bt(t,e.name,r.baseDir),n=r.cloneUrlOverride??iu(e);if(!ou(vo(o,".git"))){nu(o,{recursive:!0});let a=di();Lt(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
|
|
421
|
+
${u.trim()}`)}}let i=di(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
|
|
422
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Dt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var fi=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function xr(t,e){let{contextRepoCloneUrl:r,deliveryRef:o,deliverySha:n,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${o}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();n&&a!==n&&Lt(`[git] delivery ${o} resolved ${a.slice(0,10)} (expected ${n.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Dt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Dt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let u=(await t.raw([...fi,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),u}async function mi(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await Dt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await Dt(t,n)){let s=(await t.revparse([n])).trim();return await t.raw(["update-ref",o,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",o,i]).catch(()=>{}),i}async function gi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:u,defaultBranch:p,force:f}=r,l=await mi(t,i,()=>xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:u}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await Dt(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,l]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...fi,"cherry-pick",l])}catch(R){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=R instanceof Error?R.message:String(R);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
423
|
+
${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),k=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(k),await t.push([o,"--delete",n]).catch(()=>{}),{commit:w}}async function hi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:u}=r,p=await mi(t,i,()=>xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),u&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:u}}async function wi(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function iu(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{X509Certificate as ki}from"node:crypto";import{readFileSync as su}from"node:fs";import Pe from"node:tls";var $i=typeof Pe.getCACertificates=="function"&&typeof Pe.setDefaultCACertificates=="function",yi=!1,bi=new Map,xi=t=>console.warn(t);function au(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function vi(t=xi){if(yi)return;yi=!0;let e=_("EXTRA_CA_FILE");if(!(!e||!$i))try{let r=au(su(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Pe.setDefaultCACertificates([...Pe.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function Si(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function cu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
424
|
+
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function lu(t,e,r){return new Promise((o,n)=>{let i=Pe.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new ki(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function So(t,e,r){return new Promise(o=>{let n=Pe.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function uu(t){try{let e=await fetch(t);return e.ok?new ki(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ci(t,e=443,r=xi){let o=`${t}:${e}`,n=bi.get(o);if(n)return n;let i=pu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return bi.set(o,i),i}async function pu(t,e,r){if(!$i)return!1;let o=8e3;if(await So(t,e,o))return!0;let n=await lu(t,e,o),i=Pe.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=cu(n);if(!c)break;let u=await uu(c);if(!u)break;if(s.push(u.toString()),Pe.setDefaultCACertificates([...i,...s]),await So(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(u.subject===u.issuer)break;n=u}return So(t,e,o)}function qe(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ge(t,e,r){vi();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let n=t.baseUrl+e,i={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(n,i)}catch(s){if(Si(s)&&await Ci(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ri=t=>new Promise(e=>setTimeout(e,t));function du(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fu(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function Pi(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=fu(),a=null;for(let c=1;c<=n;c++){let u=null;try{u=await ge(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(u){if(u.ok)return u;let p=await u.text();if(c<n&&du(u.status,p)){await Ri(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${u.status} ${p}`)}if(c<n){await Ri(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function gt(t){let e;try{e=await ge(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Ei(t){try{let e=await ge(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ti=new Map;async function mu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ti.get(o);if(n)return n;let i=await ge(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let a=(await i.json()).customFields.find(u=>u.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(u=>u.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ti.set(o,c.id),c.id}async function ji(t,e,r){let o=await mu(t,e,r);await Pi(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Ai(t,e,r){return await(await Pi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ii=new Map;async function gu(t,e){let r=Ii.get(e);if(r)return r;let o=await ge(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Ii.set(e,i.id),i.id}async function _i(t,e,r,o,n){let i=await gu(t,e),s=await ge(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function Oi(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await ge(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Ni="attachments(id,name,url,size,mimeType)",hu="links(direction,linkType(name),issues(idReadable))",Ui=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ni},${hu}`,wu=`id,text,created,author(login),${Ni}`;function Li(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Di(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Bi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),n=`/api/issues?query=${encodeURIComponent(o)}&fields=${Ui}&$top=200`,i=await ge(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Hi)}async function Gi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Ui}`,o=await ge(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Hi(await o.json())}async function Mi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${wu}&$top=500`,n=await ge(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Li(s.attachments);return c&&(a.attachments=c),a})}function yu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Hi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),n=e.find(c=>c.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),n?.value?.name&&(i.issueType=n.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=Li(t.attachments);s&&(i.attachments=s);let a=yu(t.links);return a&&(i.links=a),i}var vr=new Map;async function Co(t,e){let o=(vr.get(t)??Promise.resolve()).catch(()=>{}).then(e);vr.set(t,o);try{return await o}finally{vr.get(t)===o&&vr.delete(t)}}async function Fi(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",n="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Lt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Bt(i,r.name,t.baseDir),{commit:c}=await gi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return ee({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Bt(i,r.name,t.baseDir),{commit:c,pushed:u}=await hi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:u})})}case"create_pr":{if(!r)return F("no repo spec");let i=$e(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=$e(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=$e(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Bt(i,r.name,t.baseDir),{mergedSha:c}=await wi(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return ee({stub:!0});case"tracker_status":{let i=qe();return i?t.trackerIssueId?(await ji(i,t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=qe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await Ai(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=qe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await _i(i,e.projectKey,e.title,e.body,e.targetStatus);return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=qe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Oi(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await ii(t.contextDir,e.maxJobs);return ee({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await li(t.contextDir,e);return ee({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import bu from"ws";function Sr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new bu(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function ht(t,e,r){return Ye(t,e,"/projects",r)}async function Ki(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Wi(t,e,r,o){return Ye(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Cr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function qi(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Gt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Yi(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new Gt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Vi(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function zi(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function Ji(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function Xi(t,e,r,o){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Qi(t,e,r,o,n){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function Zi(t,e,r,o,n){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function es(t,e,r,o,n){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Rr(t,e,r,o){return Ye(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function se(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Ye(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}function wt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function ts(t,e){let r=H(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await gt({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(i){o.push({name:"youtrack",ok:!1,detail:wt(i)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await ut(r.github.token),o.push({name:"github",ok:!0})}catch(i){o.push({name:"github",ok:!1,detail:wt(i)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await pt(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(i){o.push({name:"bitbucket",ok:!1,detail:wt(i)})}else if(r?.gitlab?.token)try{await dt(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(i){o.push({name:"gitlab",ok:!1,detail:wt(i)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let i=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await yo(i,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:wt(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await yo(i,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:wt(a)})}}let n=it(t);if(!n)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let i=await ku(n);o.push(i==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(i=>i.ok),checks:o,checkedAt:Date.now()}}async function ku(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var Tr=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let o=[];for(let s of r.prs){let a=$e(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof We){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let n=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===n)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=$e(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let u=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);u&&(a.ciFailureLog=u)}catch(u){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${u instanceof Error?u.message:String(u)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=$u(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function $u(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Ir=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=qe();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),n;try{let l=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Bi(r,{projectKey:e.projectKey,columns:l,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(l){this.log.warn(`[yt-sync] listIssues failed: ${l instanceof Error?l.message:String(l)}`);return}let i=[],s=new Set;for(let l of n){s.add(l.id);let d=await rs(r,l.id,e.sinceMs,this.log);d&&i.push({issueId:l.id,comments:d})}let a=[];for(let l of e.offBoardIssueIds){if(s.has(l))continue;let d=await rs(r,l,e.sinceMs,this.log);if(d&&i.push({issueId:l,comments:d}),e.requireAssignee){let g=await vu(r,l,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),u={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(u);let p=i.reduce((l,d)=>l+d.comments.length,0),f=c.reduce((l,d)=>l+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${p} attachments=${f} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let n=[];for(let i of e){let s=[...i.attachments??[]],a=r.find(p=>p.issueId===i.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],u=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let l;try{l=await Di(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${i.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=xu(p.name);u.has(d)&&(d=`${p.id}-${d}`),u.add(d),c.push({name:d,contentBase64:l.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function xu(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function vu(t,e,r){try{return await Gi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function rs(t,e,r,o){try{return await Mi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Ro="npm i -g @code-partner/codepipe@latest";function Pr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ie} (protocol ${de})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Ln(n.contextDir,r);let i=os("CLI_TRACKING_POLL_INTERVAL_SEC"),s=os("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,u=!1,p=new Set,f=l();function l(){let d=Sr(t.hubUrl,t.cliToken),g=null,w=new Tr(i,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),k=new Ir(s,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),R=null,v=async()=>{try{let S;try{let y=await se(t.hubUrl,t.cliToken,t.projectId);S={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await ts(t.projectId,S);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},T=()=>{v(),R=setInterval(()=>void v(),a),typeof R.unref=="function"&&R.unref()},j=()=>{R&&(clearInterval(R),R=null)},U=n?.contextDir?new hr(n.contextDir,t.projectId,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let S=An(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",m=_("FARM_ID"),y=t.accountEmail??S.email,$={type:"register",projectId:t.projectId,platformVersion:ie,protocolVersion:de,accountId:S.accountId,accountLabel:S.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&m?{farmId:m}:{}};d.send(JSON.stringify($))}),d.on("message",async S=>{let h=S.toString("utf-8");if(h==="pong"||h==="ping")return;let m;try{m=JSON.parse(h)}catch{return}if(!m||typeof m!="object")return;let y=m.type;if(y==="registered"){let b=m;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),o({kind:"registered",projectId:b.projectId??t.projectId}),w.start(),U?.start(),T(),n?.contextDir){let N=n.contextDir;try{let E=br(N,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(E)),E.outdated&&(r.warn(`[ctx] context format outdated: v${E.templateVersion} \u2192 v${E.currentVersion}`+(E.missingPaths.length>0?` (missing: ${E.missingPaths.join(", ")})`:"")),u||(u=!0,(async()=>{try{let M;try{M=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let le=await Jn(N,t.projectId,M,r);d.readyState===d.OPEN&&d.send(JSON.stringify(le))}catch(M){r.warn(`[ctx] context migration failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}})()))}catch(E){r.warn(`[ctx] context-format detect failed (non-fatal): ${E instanceof Error?E.message:String(E)}`)}}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),o({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let b=m;g=ar(b.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${N}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ie}, protocol ${de}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ro}`),o({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:Ro}));return}if(y==="tracking_targets"){w.setTargets(m.targets);return}if(y==="youtrack_sync_request"){k.setRequest(m);return}if(y==="sync_local"){await Cu(m,n,d,r);return}if(y==="context_write"){await Ru(m,n,d,r);return}if(y==="adr_promote"){await Tu(m,n,d,r);return}if(y==="sandbox_keys"){let b=H(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let N=it(t.projectId),E=oi(m,b,N,r);for(let M of E)d.readyState===d.OPEN&&d.send(JSON.stringify(M));return}if(y!=="dispatch_action")return;let $=m;if(g===!1){let b=`refused: HUB protocol incompatible with CLI v${ie} (protocol ${de})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:b})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${Ro}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:b});return}p.add($.actionId);try{let b=await Fi({action:$.action,repo:$.repo,trackerIssueId:$.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0}).catch(M=>({status:"failed",error:M instanceof Error?M.message:String(M)}));d.send(JSON.stringify({type:"action_result",actionId:$.actionId,...b}));let N=b.status!=="failed",E=!N&&"error"in b?b.error:void 0;N?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${E??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:N,...E?{error:E}:{}})}finally{p.delete($.actionId)}}),d.on("close",(S,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${m?` reason=${m}`:""}`),w.stop(),k.stop(),U?.stop(),j(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:S}),!c&&setTimeout(()=>{f=l()},2e3)}),d.on("error",S=>r.warn(`[ws] error: ${S.message}`)),d}return{stop(){c=!0,f.close()}}}async function Cu(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(u=>u.name===n.repoName),s=Su(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await _n(s,a).catch(u=>({status:"warn",reason:u instanceof Error?u.message:String(u)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Ru(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await yr(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Tu(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Fn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function os(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as us,mkdirSync as ps}from"node:fs";import{dirname as ds}from"node:path";import{simpleGit as Ve}from"simple-git";import{execFileSync as Iu}from"node:child_process";import{mkdtempSync as Pu,mkdirSync as Eu,readFileSync as ns,rmSync as ju,writeFileSync as Au}from"node:fs";import{tmpdir as _u}from"node:os";import{dirname as Ou,join as is}from"node:path";function ss(t="codepipe-context"){let e=Pu(is(_u(),"codepipe-ssh-")),r=is(e,"id_ed25519");try{return Iu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ns(r,"utf-8"),publicKey:ns(`${r}.pub`,"utf-8").trim()}}finally{ju(e,{recursive:!0,force:!0})}}async function as(t,e,r,o="codepipe-context"){let n=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:o,key:r,read_only:!1})});if(n.ok)return;let i=await n.text();if(!(n.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${n.status} ${i}`)}function cs(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function ls(t,e){Eu(Ou(t),{recursive:!0});let r=e.endsWith(`
|
|
424
425
|
`)?e:e+`
|
|
425
|
-
`;return
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
`))
|
|
429
|
-
`)){let
|
|
426
|
+
`;return Au(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Nu(t,e,r="x-access-token"){let o=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,n=t.match(/^git@([^:]+):(.+)$/);if(n)return`https://${o}@${n[1]}/${n[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${o}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${o}@${s[1]}`:t}function Uu(t,e){return e?.contextWrite?.token?{user:ur(t),secret:e.contextWrite.token}:t===Nt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Nt.bitbucket?e?.bitbucket?.apiToken?{user:ot,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function fs(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){return n.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return n.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Uu(rt(s.cloneUrl),r);if(a){let c=await Lu({ctx:s,contextDir:o,cred:a,log:n});if(c)return c;n.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Du({ctx:s,contextDir:o,privateKey:r.contextSsh.privateKey,log:n});if(c)return c;n.warn("[ctx] SSH deploy-key clone failed")}return n.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function Lu(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Nu(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=u=>u.split(o.secret).join("***").split(a).join("***");try{if(us(`${r}/.git`)){let p=Ve(r);await p.remote(["set-url","origin",i]),await p.fetch("origin",s),await p.checkout(s);let f=lo(r);await p.reset(["--hard",`origin/${s}`]),uo(r,f),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ps(ds(r),{recursive:!0}),await Ve().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);let u=Ve(r);await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local")}catch(u){return n.warn(`[ctx] Context Repo clone/update failed: ${c(u instanceof Error?u.message:String(u))}`),null}return{root:r,contextDir:r,repos:[]}}async function Du(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=ls(i,o),a=cs(e.cloneUrl),c=e.branch;try{if(us(`${r}/.git`)){let p=Ve(r);await p.addConfig("core.sshCommand",s,!1,"local"),await p.remote(["set-url","origin",a]),await p.fetch("origin",c),await p.checkout(c);let f=lo(r);await p.reset(["--hard",`origin/${c}`]),uo(r,f),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ps(ds(r),{recursive:!0}),await Ve().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ve(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);let u=Ve(r);return await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local"),{root:r,contextDir:r,repos:[]}}catch(u){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${u instanceof Error?u.message:String(u)}`),null}}import{existsSync as Er,readFileSync as ms,writeFileSync as Bu}from"node:fs";import{dirname as Gu,join as Ee}from"node:path";import{parse as Mu}from"yaml";var je=".codepipe",To=".devpipe";function Hu(t=process.cwd()){let e=t;for(;;){if(Er(Ee(e,je,"project.yaml")))return e;if(Er(Ee(e,To,"project.yaml")))return He(Ee(e,To),Ee(e,je))&&Ku(e),e;let r=Gu(e);if(r===e)return null;e=r}}function Fu(t){let e=Ee(t,je);return Er(e)?e:Ee(t,To)}function Ku(t){let e=Ee(t,".gitignore");if(!Er(e))return;let r=ms(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
|
|
427
|
+
`);o!==r&&Bu(e,o)}function Mt(t=process.cwd()){let e=Hu(t);if(!e)return null;let r=Fu(e),o=Wu(ms(Ee(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function gs(t,e=process.cwd()){try{let r=Mt(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Wu(t){let e=Mu(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),u=String(a.name??c);if(!u||!c)continue;let p=a.host,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:u,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??u)})}return{projectId:r,name:o,repos:i}}function hs(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`}function jr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@github.com:"),n(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Ar(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@gitlab.com:"),n(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function _r(t,e=process.env){if(!t)return!1;let r=`https://${ot}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}async function ws(t={profile:void 0}){let e=fe(t.profile),r=H(e.projectId);r&&Ut(r),jr(r?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ar(r?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),_r(r?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Ht(Io(),".codepipe","logs"),n=t.profile?`cli-daemon-${t.profile}`:"cli-daemon",i=mr("CLI_LOG",n,o);if(i.enabled){let f=new at(i);gr(f),console.log(`[log] file logging \u2192 ${f.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let s=null,a=gs(e.projectId);if(a&&(s={root:a.root,contextDir:a.contextDir,repos:a.spec.repos},console.log(`[ctx] workspace found at ${a.root} \u2014 using its Context Repo clone`)),!s){let f=Ht(Io(),".codepipe",t.profile?Ht("profiles",t.profile,"context"):"context");if(s=await fs({cfg:e,secrets:r,contextDir:f,log:{info:l=>console.log(l),warn:l=>console.warn(l)}}),s?.contextDir){let l=Ht(Io(),".codepipe",t.profile?Ht("profiles",t.profile,"context-config"):"context-config");Un(s.contextDir,l,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let c=Pr(e,{...s?{workspace:s}:{},onEvent:f=>{f.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 p(f){u||(u=!0,console.log(`
|
|
428
|
+
[${f}] shutting down`),c.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}import{hostname as Qu}from"node:os";import{spawnSync as qu}from"node:child_process";function Yu(){try{return qu("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ys(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Yu(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as yt}from"node:os";import{mkdirSync as Vu,readFileSync as bs,writeFileSync as zu,existsSync as Po}from"node:fs";import{dirname as Ju,join as Ae}from"node:path";Po(".env")&&process.loadEnvFile(".env");function _e(t){let e=_("SANDBOX_CONFIG");if(e)return e;let r=Ae(yt(),".codepipe","worker");return t?Ae(r,"profiles",t,"config.json"):Ae(r,"config.json")}function ks(){return Ae(yt(),".devpipe-sandbox","config.json")}function Or(){He(Ae(yt(),".devpipe"),Ae(yt(),".codepipe")),_("SANDBOX_CONFIG")||He(Ae(yt(),".devpipe-sandbox"),Ae(yt(),".codepipe-sandbox"))}function te(t){let e=_e(t);return Po(e)?JSON.parse(bs(e,"utf-8")):!t&&!_("SANDBOX_CONFIG")&&Po(ks())?JSON.parse(bs(ks(),"utf-8")):null}function $s(t,e){let r=_e(e);Vu(Ju(r),{recursive:!0}),zu(r,JSON.stringify(t,null,2)+`
|
|
429
|
+
`,{mode:384})}import Xu from"ws";var bt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Xu(e)}};async function ze(t){Or();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 ${_e(t.profile)}.`),process.exit(1));let r=t.name??Qu(),o=ys({projects:t.projects??[],llm:t.llm??null}),n=new bt(t.hub.replace(/\/$/,"")),i=ti(),s=mt(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});$s({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 ${_e(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 Dp,readFileSync as ta,readdirSync as Bp,writeFileSync as Gp}from"node:fs";import{dirname as Mp,join as Kr,resolve as Hp}from"node:path";import{spawn as Zu}from"node:child_process";import{existsSync as ep}from"node:fs";var kt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Nr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},tp=5e3,Ft=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Nr;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let g of e.addDirs??[])r.push("--add-dir",g);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",u=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let w=ip(g.rate_limit_info);w&&(!u||w.utilization>u.utilization)&&(u=w);return}if(g.type==="assistant"){let w=g.message;typeof w?.model=="string"&&(c=w.model);let k=w?.usage;k&&(a+=1,s.input+=re(k.input_tokens),s.output+=re(k.output_tokens),s.cacheRead+=re(k.cache_read_input_tokens),s.cacheCreate+=re(k.cache_creation_input_tokens))}}},f=e.role,l=e.onActivity,d=g=>{if(l)for(let w of ap(g,e.workspaceDir))try{l(w)}catch{}};return l?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let k=Zu(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let R=!1,v=null,T=()=>{R=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),k.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},tp)};e.signal?.addEventListener("abort",T,{once:!0});let j=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",T)},U="";k.stdout.on("data",S=>{o.push(S),U+=S;let h;for(;(h=U.indexOf(`
|
|
430
|
+
`))!==-1;){let m=U.slice(0,h).trim();if(U=U.slice(h+1),m){let y=xs(m);p(y),y&&d(y)}}}),k.stderr.on("data",S=>{o.push(S),n.push(S);for(let h of S.split(`
|
|
431
|
+
`)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),k.on("error",S=>{j(),w(S)}),k.on("close",S=>{if(j(),R){w(new Nr);return}if(U.trim()){let m=xs(U.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(S!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,y=typeof i?.subtype=="string"?i.subtype:void 0,$=typeof i?.result=="string"?i.result:void 0;w(new kt(rp(S,i,n.join("")),{code:S,apiErrorStatus:m,subtype:y,resultText:$,retryAfterMs:op(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:sp(i,s,a,c),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&ep(o))}};function xs(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let o=e.subtype??"";return console.log(`[claude] system ${o}`),e}if(r==="assistant"){let o=e.message;for(let n of o?.content??[]){let i=n.type;if(i==="text"){let s=String(n.text??"").trim();s&&console.log(`[claude] text: ${Oe(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=np(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=Ss(n.content);console.log(`[claude] tool_result (error)${i?`: ${Oe(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let o=e.subtype??"",n=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${o} turns=${n} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${Oe(JSON.stringify(e),200)}`),e}function rp(t,e,r){let o=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let n=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;n?o.push(Oe(n,500)):typeof s=="string"&&s!=="success"&&o.push(s),typeof i=="number"&&o.push(`(api_status=${i})`)}return o.length===1&&r.trim()&&o.push(Oe(r.trim().split(`
|
|
430
432
|
`).slice(-5).join(`
|
|
431
|
-
`),500)),o.join(" \u2014 ")}function
|
|
432
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
433
|
+
`),500)),o.join(" \u2014 ")}function op(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",o=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),n=o?Number(o[1]??o[2]):NaN;return Number.isFinite(n)&&n>0?n*1e3:void 0}function Ss(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function np(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Oe(r,80)}`}return""}function Oe(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ip(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=re(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:re(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:o,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(n.surpassedThreshold=e.surpassedThreshold),n}function sp(t,e,r,o){let n=lr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=re(i.input_tokens),n.outputTokens=re(i.output_tokens),n.cacheReadInputTokens=re(i.cache_read_input_tokens),n.cacheCreationInputTokens=re(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=re(t?.total_cost_usd),n.numTurns=t&&re(t.num_turns)>0?re(t.num_turns):r,n.durationMs=re(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var vs=200;function ap(t,e){let r=Date.now(),o=t.type;if(o==="system"){let n=String(t.subtype??"").trim();return n?[{ts:r,kind:"system",text:n}]:[]}if(o==="assistant"){let n=t.message,i=[];for(let s of n?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:Oe(c,vs)})}else if(a==="tool_use"){let c=String(s.name??""),u=s.input,p=u?.file_path??u?.path??u?.notebook_path,f=cp(p,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Oe(Ss(s.content),vs):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(o==="result"){let n=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...n?{text:n}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function cp(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 lp,writeFileSync as Kt}from"node:fs";import{dirname as up,join as Wt}from"node:path";function Cs(t,e,r){let o=Wt(t,e);lp(up(o),{recursive:!0}),Kt(o,r)}var qt=class{name(){return"mock"}async run(e){let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=pp(o,n,i);Kt(Wt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Kt(Wt(e.workspaceDir,"SOLUTION.md"),dp(o,n,i,a)),s.push("SOLUTION.md"),Kt(Wt(e.workspaceDir,"QUESTIONS.md"),fp(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Cs(e.workspaceDir,"changes/sample.patch",mp(o,n,a)),s.push("changes/sample.patch"),Cs(e.workspaceDir,"diff-summary.md",gp(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Kt(Wt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
|
|
434
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:lr()}}};function pp(t,e,r){return`# ${t} \u2014 Estimate
|
|
433
435
|
|
|
434
436
|
**Title:** ${e}
|
|
435
437
|
|
|
@@ -450,7 +452,7 @@ production-grade estimates.)
|
|
|
450
452
|
${r.split(`
|
|
451
453
|
`).slice(0,8).join(`
|
|
452
454
|
`).trim()||"(empty)"}
|
|
453
|
-
`}function
|
|
455
|
+
`}function dp(t,e,r,o){let n=o?`
|
|
454
456
|
## Reviewer rework instruction
|
|
455
457
|
|
|
456
458
|
> ${o.split(`
|
|
@@ -461,7 +463,7 @@ This pass addresses the points above.
|
|
|
461
463
|
`:"";return`# ${t} \u2014 Solution
|
|
462
464
|
|
|
463
465
|
**Title:** ${e}
|
|
464
|
-
${
|
|
466
|
+
${n}
|
|
465
467
|
## Plan
|
|
466
468
|
1. Locate the relevant module(s) in the project repo.
|
|
467
469
|
2. Apply the minimum diff that satisfies the DoD in the YouTrack task.
|
|
@@ -479,10 +481,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
479
481
|
${r.split(`
|
|
480
482
|
`).slice(0,8).join(`
|
|
481
483
|
`).trim()||"(empty)"}
|
|
482
|
-
`}function
|
|
484
|
+
`}function fp(t){return`# ${t} \u2014 Open questions
|
|
483
485
|
|
|
484
486
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
485
|
-
`}function
|
|
487
|
+
`}function mp(t,e,r){let o=r?` (rework: ${r.split(`
|
|
486
488
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
487
489
|
index 0000000..1111111 100644
|
|
488
490
|
--- a/CHANGELOG.md
|
|
@@ -493,7 +495,7 @@ index 0000000..1111111 100644
|
|
|
493
495
|
+- mock-runner placeholder change for slice 5 testing.
|
|
494
496
|
+
|
|
495
497
|
# Changelog
|
|
496
|
-
`}function
|
|
498
|
+
`}function gp(t,e,r){return`# ${t} \u2014 Diff summary
|
|
497
499
|
|
|
498
500
|
**Title:** ${e}
|
|
499
501
|
${r?`
|
|
@@ -504,77 +506,77 @@ ${r?`
|
|
|
504
506
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
505
507
|
|
|
506
508
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
507
|
-
`}function
|
|
509
|
+
`}function Rs(t){switch(t){case"mock":return new qt;case"claude-headless":return new Ft;default:return null}}function Ps(t=process.env){return{maxAttempts:Ur(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ur(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ur(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ur(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var hp=new Set([429,500,502,503,529]),Ts=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,wp=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,yp=new Set(["error_max_turns"]);function bp(t){if(t instanceof kt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return wp.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&yp.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:hp.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Ts.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:o??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return Ts.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Is=/(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 Es(t){if(t instanceof kt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Is.test(o)}let e=t instanceof Error?t.message:String(t);return Is.test(e)}function kp(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let o=e.baseDelayMs*2**(t-1),n=Math.min(o,e.maxDelayMs);return Math.round(n/2+Math.random()*(n/2))}async function js(t,e,r){let o=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),n=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=bp(a),u=s>=r.policy.maxAttempts;if(!c.retryable||u||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=kp(s,r.policy,c.retryAfterMs);if(Date.now()+p>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await o(p)}}function Ur(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as $p,rmSync as xp,writeFileSync as As}from"node:fs";import{tmpdir as vp}from"node:os";import{join as Eo}from"node:path";function Lr(t){return`[url "https://${t}/"]
|
|
508
510
|
insteadOf = git@${t}:
|
|
509
511
|
insteadOf = ssh://git@${t}/
|
|
510
|
-
`}var
|
|
512
|
+
`}var Sp=Lr("github.com"),Cp=Lr("bitbucket.org"),Rp=Lr("gitlab.com");function _s(t,e){if(t.length===0)return null;let r=$p(Eo(vp(),"devpipe-gitcreds-")),o=Eo(r,"credentials"),n=Eo(r,"gitconfig");return As(o,t.join(`
|
|
511
513
|
`)+`
|
|
512
|
-
`,{mode:384}),
|
|
514
|
+
`,{mode:384}),As(n,`[credential]
|
|
513
515
|
helper = store --file=${o}
|
|
514
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:
|
|
515
|
-
`).map(u=>u.trim()).filter(u=>u.length>0),c=await
|
|
516
|
-
${s.join("").trim()||"(no stderr)"}`))})})}function
|
|
517
|
-
${a.join("").trim()||"(no stderr)"}`))})})}function
|
|
518
|
-
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of
|
|
519
|
-
`+e.subarray(e.length-
|
|
516
|
+
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{xp(r,{recursive:!0,force:!0})}catch{}}}}function jo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Sp)),t.bitbucket?.apiToken&&(e.push(`https://${ot}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Cp)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Rp)),_s(e,r)}function Os(t,e){if(t.contextWrite?.token){let r=rt(e)??"github.com",o=ur(r);return _s([`https://${o}:${t.contextWrite.token}@${r}`],[Lr(r)])}return jo(t)}import{spawn as Us}from"node:child_process";import{existsSync as Dr,mkdirSync as Br,readFileSync as Tp,rmSync as Ao,symlinkSync as Ip}from"node:fs";import{homedir as Pp}from"node:os";import{dirname as Gr,join as Je}from"node:path";function Ls(){return Je(Pp(),".codepipe-sandbox","repos")}function Ns(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 Ds(t,e,r,o,n){if(Dr(Je(t,".git"))){let i=async s=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await Y(t,["reset","--hard",`origin/${s}`],n),await Y(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!Ns(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Dr(t)&&Ao(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!Ns(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Dr(t)&&Ao(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function Bs(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Mr="CodePipe Agent",Hr="codepipe@codepartner.ee";async function Gs(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let o=(await he(r,["write-tree"])).trim(),n=(await he(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Mr,GIT_AUTHOR_EMAIL:Hr,GIT_COMMITTER_NAME:Mr,GIT_COMMITTER_EMAIL:Hr};return(await he(r,["commit-tree",o,"-m",e],i)).trim()}async function Ms(t,e,r,o,n){try{await Y(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw rt(o)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Hs(t,e){return he(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Fs(t,e,r,o,n){await Y(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await Y(t.workspacePath,["checkout","--force",r])}async function _o(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Mr,GIT_AUTHOR_EMAIL:Hr,GIT_COMMITTER_NAME:Mr,GIT_COMMITTER_EMAIL:Hr};(await he(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(u=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(u)}`)}),await Y(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Y(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(u){s=u instanceof Error?u.message:String(u)}let a=(await he(o,["diff","--name-only","--diff-filter=U"])).split(`
|
|
517
|
+
`).map(u=>u.trim()).filter(u=>u.length>0),c=await he(o,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Y(t,e,r){return new Promise((o,n)=>{let i=Us("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",n),i.on("close",a=>{if(a===0)return o();n(new Error(`git ${e[0]} failed (exit ${a}):
|
|
518
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function he(t,e,r){return new Promise((o,n)=>{let i=Us("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",n),i.on("close",c=>{if(c===0)return o(s.join(""));n(new Error(`git ${e[0]} failed (exit ${c}):
|
|
519
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function Ks(t,e){Dr(t)&&Ao(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0}),Ip(e,t,"dir")}async function Ws(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Br(Gr(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function qs(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=Je(Ls(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Ds(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let u=(await he(a,["rev-parse","HEAD"])).trim(),p=Je(t,"code",s.name);o==="direct"?(Ks(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${u.slice(0,10)}`)):(await Ws(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${u.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:u})}return i}async function Ys(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=Je(Ls(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Ds(i,r.cloneUrl,r.ref,void 0,n)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=Je(t,"context");o==="direct"?(Ks(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await Ws(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await he(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function Vs(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await Y(r,["add","-A",...o]).catch(()=>{});let n;try{n=await he(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
|
|
520
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Tp(Je(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Ep}from"node:fs";import{join as jp}from"node:path";var Oo=8*1024,$t=class extends Error{},Yt="meta/build-result.json";function zs(t){let e=jp(t,Yt),r;try{r=Ep(e,"utf-8")}catch{throw new $t(`BUILD produced no ${Yt} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new $t(`${Yt} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new $t(`${Yt} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new $t(`${Yt}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let f=p,l=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(l===null||d===null)return[];let g={name:l,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?Ap(n.logTail):"",u={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)u.failedStep=n.failedStep;else if(!i){let p=a.find(f=>f.exitCode!==0);p&&(u.failedStep=p.name)}return u}function Ap(t){let e=Buffer.from(t,"utf-8");return e.length<=Oo?t:`\u2026 [${e.length-Oo} bytes elided] \u2026
|
|
521
|
+
`+e.subarray(e.length-Oo).toString("utf-8")}import{lstatSync as _p,mkdtempSync as Op,readFileSync as Np,readdirSync as Xs,rmSync as Js}from"node:fs";import{tmpdir as Up}from"node:os";import{join as Fr,relative as Lp}from"node:path";var Qs=new Set(["code","context"]);function Zs(t){let e=Op(Fr(Up(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Js(e,{recursive:!0,force:!0}),listFiles:()=>ea(e,e),readFile:r=>Np(Fr(e,r),"utf-8"),clean:()=>{for(let r of Xs(e))Qs.has(r)||Js(Fr(e,r),{recursive:!0,force:!0})}}}function ea(t,e){let r=[];for(let o of Xs(e)){let n=Fr(e,o),i=_p(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Qs.has(o))continue;r.push(...ea(t,n))}else r.push(Lp(t,n))}return r}var Wr=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Fp=new Set(["implement","resolve-conflict"]);function Kp(t){let e=Buffer.from(t,"utf-8");if(e.length<=Wr)return t;let r=Math.floor(Wr/4),o=Wr-r,n=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-o).toString("utf-8"),s=e.length-r-o;return`${n}
|
|
520
522
|
|
|
521
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
523
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${Wr} bytes for upload] \u2026
|
|
522
524
|
|
|
523
|
-
${
|
|
525
|
+
${i}`}async function Vt(t={}){Or();let e=te(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=mr("SANDBOX_LOG","sandbox",Hp("./logs"));if(o.enabled){let h=new at(o);gr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${ie} (protocol ${de})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Rs(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Ps();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new bt(e.hubUrl,e.token),a=!1,c=new AbortController,u=null,p=null,f=!1,l=null,d=null,g=!1,w=()=>{let h=s.openControlSocket();return l=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ie,protocolVersion:de};h.send(JSON.stringify(m))}),h.on("message",m=>{let y=m.toString("utf-8"),$=null;try{let b=JSON.parse(y);b&&typeof b=="object"&&($=b)}catch{}if($&&$.type==="hello"){let b=$;d=ar(b.protocolVersion);let N=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${N}`),d&&(g=!1);return}if($&&$.type==="pause_job"){let b=typeof $.jobId=="string"?$.jobId:"";b&&b===u?(console.warn(`[ws] pause_job ${b} \u2014 aborting agent`),f=!0,p?.abort()):console.log(`[ws] pause_job ${b} \u2014 not the active job, ignoring`),b&&h.send(JSON.stringify({type:"job_paused",jobId:b}));return}console.log(`[ws] ${y}`)}),h.on("close",(m,y)=>{console.log(`[ws] closed code=${m} reason=${y?.toString()||""}`),l===h&&(l=null),!a&&setTimeout(w,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},k=w(),R=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ie}, protocol ${de}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await s.claim(c.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 sandbox token rejected. exiting."),a=!0;break}if(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3));continue}let m=await h.json();await v(s,m)}catch(h){if(c.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3))}}};async function v(h,m){u=m.jobId,p=new AbortController,f=!1;let y=!1,$=null,b=null,N=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),E=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(y=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let ue=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} heartbeat error: ${ue}`)}};E();let M=setInterval(()=>{E()},N),le=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(j(m.prompt," \u2502 "));let we=[],C=null,ne=400,ve=25,De=500,At=()=>{if(C&&(clearTimeout(C),C=null),we.length===0)return;let L=we.splice(0,we.length),ue=l;if(!ue||ue.readyState!==ue.OPEN)return;let Se={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:L};try{ue.send(JSON.stringify(Se))}catch{}},et=L=>{we.push(L),we.length>De&&we.shift(),we.length>=ve?At():C||(C=setTimeout(At,ne))},z=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Qr=new Set,Zr=null;try{if(!n){y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:le,finishedAt:new Date().toISOString()});return}let L=Zs(m.jobId);console.log(`[job] ${m.jobId} workspace=${L.dir}`);let ue=T(m,r);$=ue.gitCreds,b=ue.contextGitCreds;let Se=$?.env,Qo=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,Ce=[],sr=null,eo=null;try{let I="worktree";Ce=await qs(L.dir,m.projectId,m.projectRepos,I,Se);let P=await Ys(L.dir,m.projectId,m.contextRepo,I,Se);eo=P,sr=P?.workspacePath??null}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} materialize failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let Zo=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let I=m.contextRepo?.cloneUrl;if(!I||!Se)throw new Error(I?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let P of m.deliveries){let G=Ce.find(oe=>oe.name===P.name);G&&(await Fs(G,P.deliveryRef,P.deliverySha,I,Se),console.log(`[job] ${m.jobId} ${G.name}: checked out delivery ${P.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await Zo()}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} delivery checkout failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let en=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},tn="";if(m.role==="resolve-conflict")try{let I=[];for(let P of Ce){let G=en[P.name];if(!G)continue;let oe=await _o(P,G,Se);console.log(`[job] ${m.jobId} ${P.name}: merged ${G} into ${P.ref} \u2014 ${oe.length} conflicted file(s)`),oe.length>0?I.push(`- **${P.name}**:`,...oe.map(tt=>` - \`${tt}\``)):I.push(`- **${P.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}tn=`
|
|
524
526
|
|
|
525
527
|
## Conflicts to resolve
|
|
526
528
|
|
|
527
|
-
`+(
|
|
529
|
+
`+(I.length>0?I.join(`
|
|
528
530
|
`):"(no task branches to merge)")+`
|
|
529
|
-
`}catch(
|
|
530
|
-
`).map(y=>
|
|
531
|
-
`)}function
|
|
532
|
-
[${h}] shutting down`),c.abort();let f=new AbortController,y=setTimeout(()=>f.abort(),3e3);(async()=>{let $=u;if($)try{await s.releaseJob($,`sandbox ${h}`,f.signal),console.log(`[${h}] released job ${$}`)}catch(S){let k=S instanceof Error?S.message:String(S);console.warn(`[${h}] release failed: ${k} (sweeper will reclaim)`)}clearTimeout(y),b.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>x("SIGINT")),process.on("SIGTERM",()=>x("SIGTERM")),await C()}async function Fs(t={profile:void 0}){let e=de(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=gr(e.hubUrl,e.cliToken),o=await new Promise(n=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),n({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let u={type:"register",projectId:e.projectId};r.send(JSON.stringify(u))}),r.on("message",u=>{let p=u.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let m=JSON.parse(p);m.type==="registered"?(a=!!m.ok,clearTimeout(c),r.send("ping")):m.type}catch{}}),r.on("error",u=>s.push(`error:${u.message}`)),r.on("close",(u,p)=>{s.push(`close:${u}:${p?.toString()||""}`),clearTimeout(c),n({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let n of o.events)console.log(` ${n}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let n=await ne(e.hubUrl,e.cliToken,e.projectId);if(n.duplicateIntake){let s=n.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 i=Z(t.profile);i?i.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${i.sandboxId} (${i.name}), llm=${i.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${i.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as ht,mkdirSync as na,readFileSync as ia,readdirSync as zp,writeFileSync as sa}from"node:fs";import{join as We,resolve as aa}from"node:path";import{setTimeout as Jp}from"node:timers/promises";import{cancel as Xp,confirm as yt,intro as ca,isCancel as Eo,log as R,outro as Io,password as Mt,select as wt,spinner as Qp,text as F}from"@clack/prompts";import{simpleGit as jo}from"simple-git";async function gt(t,e,r){return e.host==="github"?kp(t,e,r):e.host==="gitlab"?Tp(t,e,r):Pp(t,e,r)}var bp="https://api.github.com";async function mt(t,e,r,o){let i={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(i.body=JSON.stringify(o),i.headers["Content-Type"]="application/json");let n=await fetch(bp+r,i),s=await n.text(),a=s?JSON.parse(s):null;if(n.status>=400&&n.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${n.status} ${c}`)}return{status:n.status,data:a}}async function kp(t,e,r){let o=r.githubToken;if(!o)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let i=await $p(o,e,r),n=await Sp(o,i.owner,i.name);r.log.info(`scaffolding Context Repo files \u2192 ${i.owner}/${i.name}@${n}`);let s=nt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await vp(o,i.owner,i.name,a.path,n)||await Cp(o,i.owner,i.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,n);return{host:"github",owner:i.owner,name:i.name,cloneUrl:i.sshUrl,branch:n}}async function $p(t,e,r){let o=await mt(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: Context Repo ${e.owner}/${e.name} not found (or the token cannot see it) \u2014 check owner/name and that the token has read/write access to the existing repo`);let i=await xp(t,e.owner),n=i?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${i?"org":"user"})`);let s=await mt(t,"POST",n,{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 xp(t,e){let{status:r,data:o}=await mt(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function Sp(t,e,r){let{data:o}=await mt(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function vp(t,e,r,o,i){let{status:n,data:s}=await mt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(i)}`);return n===404||!s?null:s.sha}async function Cp(t,e,r,o,i,n,s,a){let c={message:n,content:Buffer.from(i,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await mt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Rp="https://gitlab.com/api/v4";async function ft(t,e,r,o){let i={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(i.body=JSON.stringify(o));let n=await fetch(Rp+r,i),s=await n.text(),a=s?JSON.parse(s):null;if(n.status>=400&&n.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${n.status} ${c}`)}return{status:n.status,data:a}}async function Tp(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let i=encodeURIComponent(`${e.owner}/${e.name}`),n,s=await ft(o,"GET",`/projects/${i}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),n=s.data;else{if(r.mode==="attach")throw new Error(`attach: Context Repo ${e.owner}/${e.name} not found (or the token cannot see it) \u2014 check owner/name and that the token has read/write access to the existing project`);let m=await ft(o,"GET","/user"),l={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(m.data?.username!==e.owner){let g=await ft(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);l.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await ft(o,"POST","/projects",l);if(!d.data)throw new Error("GitLab create project: empty response");n=d.data}let a=n.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=nt(t,e,r.youtrackWrites,r.trackerUrl),u=new Set;for(let m=1;;m++){let d=(await ft(o,"GET",`/projects/${n.id}/repository/tree?recursive=true&per_page=100&page=${m}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)u.add(g.path);if(d.length<100)break}let p=c.filter(m=>!u.has(m.path)).map(m=>({action:"create",file_path:m.path,content:m.content}));return p.length>0?await ft(o,"POST",`/projects/${n.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:n.path,cloneUrl:n.ssh_url_to_repo,branch:a}}var Ip="https://api.bitbucket.org/2.0";async function Ur(t,e,r,o){let i={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(i.body=JSON.stringify(o.json),i.headers["Content-Type"]="application/json"):o?.form&&(i.body=o.form);let n=await fetch(Ip+r,i),s=await n.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(n.status>=400&&n.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${n.status} ${s}`);return{status:n.status,data:a}}async function Pp(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let i=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,n,s=await Ur(o,"GET",i);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),n=s.data;else{if(r.mode==="attach")throw new Error(`attach: Context Repo ${e.owner}/${e.name} not found (or the credential cannot see it) \u2014 check workspace/name and that the API token has read/write access to the existing repo`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let m=await Ur(o,"POST",i,{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`);n=m.data}let a=n.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=nt(t,e,r.youtrackWrites,r.trackerUrl),u=[];for(let m of c)(await Ur(o,"GET",`${i}/src/${encodeURIComponent(a)}/${m.path}?format=meta`)).status===404&&u.push(m);if(u.length>0){let m=new URLSearchParams;m.set("message","chore(codepipe): scaffold context repo files"),m.set("branch",a);for(let d of u)m.set(d.path,d.content);if((await Ur(o,"POST",`${i}/src`,{form:m})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=n.links?.clone?.find(m=>m.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:n.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Ep={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Ke(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let i=Ep[r];if(!i)return null;let n=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(n.length<2)return null;let s=n[n.length-1].replace(/\.git$/,"");return s?{host:i,owner:n.slice(0,-1).join("/"),repoName:s}:null}function Ks(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 Ws(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{homedir as jp}from"node:os";import{existsSync as Ap,mkdirSync as _p,readFileSync as Op,writeFileSync as Np}from"node:fs";import{dirname as Up,join as Lp}from"node:path";function Ro(){return _("FARM_PINS")??Lp(jp(),".codepipe","farm-pins.json")}function qs(){let t=Ro();if(!Ap(t))return{};try{return JSON.parse(Op(t,"utf-8"))}catch{return{}}}function Bp(t){let e=Ro();_p(Up(e),{recursive:!0}),Np(e,JSON.stringify(t,null,2)+`
|
|
533
|
-
`,{mode:384})}function
|
|
534
|
-
|
|
531
|
+
`}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} conflict merge failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let yc=U(m.prompt,Ce,sr)+tn,to=[...Ce.map(I=>I.workspacePath),...sr?[sr]:[]];to.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${to.join(", ")}`),z&&(Zr=setInterval(()=>{let P=l;if(!P||P.readyState!==P.OPEN)return;let G;try{G=Bp(Kr(L.dir,"drafts")).filter(oe=>oe.endsWith(".json")).sort()}catch{return}for(let oe of G){if(Qr.has(oe))continue;if(Qr.size>=un)break;let tt;try{let Q=JSON.parse(ta(Kr(L.dir,"drafts",oe),"utf-8")),O=typeof Q.localRef=="string"?Q.localRef:"",q=typeof Q.title=="string"?Q.title:"",Be=typeof Q.body=="string"?Q.body:"";if(!O||!q)continue;tt={localRef:O,title:q,body:Be,...Q.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Q.links)?{links:Q.links}:{}}}catch{continue}Qr.add(oe);let _t={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:z,child:tt};try{P.send(JSON.stringify(_t))}catch{}}},1500));try{let I=await js(n,{workspaceDir:L.dir,role:m.role,prompt:yc,addDirs:to,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Qo?{env:Qo}:{},signal:p.signal,onActivity:et},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{L.clean();for(let O of Ce)try{await Bs(O);let q=en[O.name];m.role==="resolve-conflict"&&q&&await _o(O,q,Se)}catch(q){let Be=q instanceof Error?q.message:String(q);console.warn(`[job] ${m.jobId} worktree reset failed (${O.name}): ${Be}`)}try{await Zo()}catch(O){let q=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${q}`)}},aborted:()=>y||f}),P=[];if(Fp.has(m.role)&&Ce.length>0){let O=m.metadata??{},q=typeof O.commitMessage=="string"?O.commitMessage:`${m.taskId}: changes`,Be=m.contextRepo?.cloneUrl,rn=b?.env;if(!Be||!rn)throw new Error("delivery requested but "+(Be?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let bc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let ye of Ce){let Ot=await Gs(ye,q);if(!Ot){console.log(`[job] ${m.jobId} ${ye.name}: no changes \u2014 no delivery`);continue}let ro=`codepipe/deliveries/${bc}/${m.jobId}/${ye.name}`;await Ms(ye,Ot,ro,Be,rn),P.push({name:ye.name,deliveryRef:ro,deliverySha:Ot,baseSha:ye.baseSha}),console.log(`[job] ${m.jobId} ${ye.name}: delivered ${Ot.slice(0,10)} \u2192 ${ro}`);let on=await Hs(ye,Ot);if(on.trim().length>0){let kc=Kr("display",`${ye.name}.diff`),nn=Kr(L.dir,kc);Dp(Mp(nn),{recursive:!0}),Gp(nn,on)}}}if(m.role==="resolve-conflict"&&P.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let G;m.role==="build"&&(G=zs(L.dir),console.log(`[job] ${m.jobId} build verdict: ok=${G.ok}`+(G.failedStep?` failedStep=${G.failedStep}`:"")));let oe=I.artifactPaths.length>0?I.artifactPaths:L.listFiles(),tt=Array.from(new Set(oe)),_t;if(eo)try{let O=await Vs(eo,m.role==="index"?["adr/SOURCES.md"]:[]);O.length>0&&(_t=O,console.log(`[job] ${m.jobId} captured ${O.length} knowledge file(s) for Context Repo`))}catch(O){let q=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${q}`)}let Q={jobId:m.jobId,status:"succeeded",artifacts:tt.map(O=>({path:O,contentBase64:ta(`${L.dir}/${O}`).toString("base64")})),..._t?{contextWrites:_t}:{},...P.length>0?{deliveries:P}:{},log:Kp(I.log),startedAt:le,finishedAt:new Date().toISOString(),usage:I.usage,...I.rateLimit?{rateLimit:I.rateLimit}:{},...G?{build:G}:{}};if(y||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(Q),console.log(`[job] ${m.jobId} done \u2014 uploaded ${Q.artifacts.length} artifact(s):`);for(let O of Q.artifacts){let q=Buffer.from(O.contentBase64,"base64").length;console.log(` \xB7 ${O.path} (${q} bytes)`)}Q.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(I){let P=I instanceof Error?I.message:String(I);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(y)console.warn(`[job] ${m.jobId} failed after claim lost (${P}) \u2014 skipping result upload`);else{let G=Es(I);console.warn(G?`[job] ${m.jobId} failed: ${P} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${P}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:P},startedAt:le,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(M),Zr&&clearInterval(Zr),At(),u=null,p=null,$?.cleanup(),b?.cleanup()}}function T(h,m){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let y;try{y=JSON.parse(ri(m,h.credBundle).toString("utf-8"))}catch(E){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${E instanceof Error?E.message:String(E)}`),{gitCreds:null,contextGitCreds:null}}let $=jo(y);$&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let b=Os(y,h.contextRepo.cloneUrl),N={gitCreds:$,contextGitCreds:b};return y.claudeOauthToken&&(N.claudeOauthToken=y.claudeOauthToken),N}function j(h,m){return h.split(`
|
|
532
|
+
`).map(y=>m+y).join(`
|
|
533
|
+
`)}function U(h,m,y){let $=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,y??"")}let S=h=>{if(a)return;a=!0,console.log(`
|
|
534
|
+
[${h}] shutting down`),c.abort();let m=new AbortController,y=setTimeout(()=>m.abort(),3e3);(async()=>{let $=u;if($)try{await s.releaseJob($,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${$}`)}catch(b){let N=b instanceof Error?b.message:String(b);console.warn(`[${h}] release failed: ${N} (sweeper will reclaim)`)}clearTimeout(y),k.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>S("SIGINT")),process.on("SIGTERM",()=>S("SIGTERM")),await R()}async function ra(t={profile:void 0}){let e=fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Sr(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let u={type:"register",projectId:e.projectId};r.send(JSON.stringify(u))}),r.on("message",u=>{let p=u.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",u=>s.push(`error:${u.message}`)),r.on("close",(u,p)=>{s.push(`close:${u}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=te(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as Ct,mkdirSync as Sa,readFileSync as Ca,readdirSync as $d,writeFileSync as Ra}from"node:fs";import{join as Xe,resolve as Ta}from"node:path";import{setTimeout as xd}from"node:timers/promises";import{cancel as vd,confirm as Rt,intro as Ia,isCancel as Mo,log as x,outro as Bo,password as Jt,select as Qe,spinner as Pa,text as K}from"@clack/prompts";import{simpleGit as Vr}from"simple-git";async function vt(t,e,r){return e.host==="github"?qp(t,e,r):e.host==="gitlab"?Zp(t,e,r):td(t,e,r)}async function oa(t,e,r={}){let o=r.explain??!0,n=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Ue(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await na(e.githubToken,t):n}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Ne(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await ia(e.gitlabToken,t):n}}return e.bitbucket?(await xt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await sa(e.bitbucket,t):n}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function na(t,e){let r=!1;try{r=(await Ue(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function ia(t,e){let r=!1;try{r=(await Ne(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 sa(t,e){let r=!1;try{r=(await xt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var Wp="https://api.github.com";async function Ue(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(Wp+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function qp(t,e,r){let o=r.githubToken;if(!o)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let n=await Yp(o,e,r),i=await zp(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=ft(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Jp(o,n.owner,n.name,a.path,i)||await Xp(o,n.owner,n.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:n.owner,name:n.name,cloneUrl:n.sshUrl,branch:i}}async function Yp(t,e,r){let o=await Ue(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await na(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Vp(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await Ue(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Vp(t,e){let{status:r,data:o}=await Ue(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function zp(t,e,r){let{data:o}=await Ue(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Jp(t,e,r,o,n){let{status:i,data:s}=await Ue(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Xp(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Ue(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Qp="https://gitlab.com/api/v4";async function Ne(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(Qp+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Zp(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ne(o,"GET",`/projects/${n}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await ia(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ne(o,"GET","/user"),l={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let g=await Ne(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);l.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await Ne(o,"POST","/projects",l);if(!d.data)throw new Error("GitLab create project: empty response");i=d.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ft(t,e,r.youtrackWrites,r.trackerUrl),u=new Set;for(let f=1;;f++){let d=(await Ne(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)u.add(g.path);if(d.length<100)break}let p=c.filter(f=>!u.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Ne(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var ed="https://api.bitbucket.org/2.0";async function xt(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(ed+r,n),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function td(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await xt(o,"GET",n);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await sa(o,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await xt(o,"POST",n,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ft(t,e,r.youtrackWrites,r.trackerUrl),u=[];for(let f of c)(await xt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&u.push(f);if(u.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of u)f.set(d.path,d.content);if((await xt(o,"POST",`${n}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function xe(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=rd[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as od}from"node:crypto";import{existsSync as aa,mkdirSync as nd,readFileSync as ca,readdirSync as id,rmSync as qr,writeFileSync as sd}from"node:fs";import{homedir as ad}from"node:os";import{dirname as cd,join as No}from"node:path";var ld=24*60*60*1e3;function la(){return No(ad(),".codepipe","init-drafts")}function Uo(t){let e=od("sha256").update(t).digest("hex").slice(0,16);return No(la(),`${e}.json`)}function ua(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=ld)}function pa(t){let e=Uo(t);if(!aa(e))return null;try{let r=JSON.parse(ca(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:ua(r.savedAt)?(qr(e,{force:!0}),null):r}catch{return null}}function Lo(t){qr(Uo(t),{force:!0})}function da(){let t=la();if(aa(t))for(let e of id(t)){let r=No(t,e);try{let o=JSON.parse(ca(r,"utf-8"));ua(o.savedAt)&&qr(r,{force:!0})}catch{qr(r,{force:!0})}}}var St=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let o=await r();return this.set(e,o),o}clear(){Lo(this.cwd)}persist(){let e=Uo(this.cwd);nd(cd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sd(e,JSON.stringify(r,null,2)+`
|
|
535
|
+
`,{mode:384})}};function fa(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function ma(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{homedir as ud}from"node:os";import{existsSync as pd,mkdirSync as dd,readFileSync as fd,writeFileSync as md}from"node:fs";import{dirname as gd,join as hd}from"node:path";function Do(){return _("FARM_PINS")??hd(ud(),".codepipe","farm-pins.json")}function ga(){let t=Do();if(!pd(t))return{};try{return JSON.parse(fd(t,"utf-8"))}catch{return{}}}function wd(t){let e=Do();dd(gd(e),{recursive:!0}),md(e,JSON.stringify(t,null,2)+`
|
|
536
|
+
`,{mode:384})}function yd(t){return ga()[t]}function ha(t,e){let r=ga();r[t]=e,wd(r)}function wa(t,e){let r=mt(e),o=yd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Do()}.`);return r}import{existsSync as ya}from"node:fs";import{join as ba}from"node:path";import{simpleGit as ka}from"simple-git";var bd={info:t=>console.log(t),warn:t=>console.warn(t)};async function zt(t,e,r={}){let o=r.log??bd,n=[];for(let i of e){let s=ba(t,i.mountAs),a=hs(i);if(!ya(s)){if(r.dryRun){o.info(`would clone ${a} \u2192 ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{o.info(`cloning ${a} \u2192 ${i.mountAs}/`),await ka().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!ya(ba(s,".git"))){o.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=ka(s),u="";try{u=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{u=""}if(!kd(u,a)){o.warn(`${i.mountAs}/ origin (${u||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:u});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function kd(t,e){return $a(t)===$a(e)}function $a(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function xa(t={}){let e=Mt();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 zt(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var va=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function B(t){vd(t),process.exit(1)}function ae(t){return Mo(t)&&B("aborted"),t}function D(t){return Mo(t)&&B("aborted"),typeof t=="string"?t:""}async function Ea(t={}){Ia("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();da();let r=pa(e),o,n=!1;r&&Object.keys(r.answers).length>0?ae(await Rt({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"),o=new St(e,r),n=!0):(Lo(e),o=new St(e)):o=new St(e);let i=t.force===!0?null:await Cd(e),s=await o.ask("target",async()=>ae(await Qe({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)`):n&&o.get("contextRepo")!==void 0||Aa(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:pe,initialValue:_("HUB_URL")??pe,validate:C=>C.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),u=await o.ask("email",()=>_a()),p=await o.ask("cliToken",()=>zr(c,u)),f=null;s==="farm"&&(f=await Sd(c,p));let l=a?Td(a.parsed.repoName):"",d=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:l||"acme",...l?{initialValue:l}:{},validate:C=>Ge.test(C.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:C=>C.trim().length>0?void 0:"required"})).trim()),w=await o.ask("automationLevel",async()=>ae(await Qe({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await o.ask("youtrack",()=>Ga()),R=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:C=>C.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ae(await Rt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},j=()=>o.set("tokens",T),U=await o.ask("repos",()=>Ed(T,u,a,{onCred:j,initial:o.get("reposPartial")??[],onProgress:C=>o.set("reposPartial",C)}));o.delete("reposPartial");let S=await jd(await o.ask("contextRepo",()=>La(d,U,T,u)),d,U,T,u,j,C=>o.set("contextRepo",C)),{spec:h,mode:m}=S;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 o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:C=>C.trim().length>0?void 0:"required"})).trim()),$={projectId:d,name:g,automationLevel:w,repos:U,youtrackProjectKey:R,ownerEmail:u};x.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let b;try{b=await vt($,h,{...Da(T),youtrackWrites:v,trackerUrl:k.url,mode:m,log:{info:C=>x.message(C),warn:C=>x.warn(C)}})}catch(C){B(`Context Repo provisioning failed: ${C instanceof Error?C.message:String(C)}`)}$.contextRepo=b,x.success(`Context Repo ready: ${b.owner}/${b.name}@${b.branch}`),x.step(`registering project on ${c}\u2026`);let N;try{N=await ht(c,p,$)}catch(C){if(C instanceof A&&C.status===409){x.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{N=await se(c,p,d)}catch(ne){throw ne instanceof A&&B(`HUB \u2192 ${ne.status} ${ne.message}`),ne}}else if(C instanceof A&&C.status===401)o.delete("cliToken"),B("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(C instanceof A)B(`HUB \u2192 ${C.status} ${C.message}`);else throw C}let E=N.contextRepo??b;x.success(`project ${N.projectId} ready (${N.provisioningStatus})`);let M=await Ud(E),le={url:k.url,token:k.token};if(s==="farm"){let C=f,ne={...T,...M?{contextWrite:M}:{},youtrack:le},ve=T.github?.token;if(E.host==="github"&&ve)try{let z=ss(`devpipe-${d}`);await as(E,ve,z.publicKey,`devpipe-${d}`),ne.contextSsh={privateKey:z.privateKey},x.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(z){x.warn(`could not set up Context Repo SSH deploy key (${z instanceof Error?z.message:String(z)}); the farm will fall back to the token path.`)}let De={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:ne,contextRepo:E,projectConfig:Ie($,v,k.url,y||void 0)},At=kr(C.farm.publicKey,JSON.stringify(De));x.step(`handing project ${d} to farm ${C.farm.name}\u2026`);let et;try{et=await Wi(c,p,C.farm.farmId,{projectId:d,sealedBundle:At})}catch(z){throw z instanceof A&&B(z.status===409?`farm ${C.farm.name} is offline \u2014 start it and re-run.`:z.status===504?`farm ${C.farm.name} did not respond in time.`:`HUB \u2192 ${z.status} ${z.message}`),z}et.ok||B(`farm rejected provisioning: ${et.error??"unknown error"}`),await Go(c,p,d,E,ve),o.clear(),Bo(`done. project ${d} is now hosted on farm ${C.farm.name} (daemon ${et.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Ba(T),await Oa(e,E.cloneUrl,E.branch),Ua(e),a&&await Pd(e);{let C=Xe(e,je);wr(C);let ne=Ie($,v,k.url,y||void 0),ve=co(C,ne);ve.length>0&&x.success(`local project config \u2192 .codepipe/{${ve.join(", ")}}`),Ke(d,ne,{info:De=>x.message(De),warn:De=>x.warn(De)})}await Na(e,N.repos);let we={hubUrl:c,cliToken:p,projectId:d,...T,...M?{contextWrite:M}:{},youtrack:le};Z(we),Me({hubUrl:c,cliToken:p,projectId:d,accountEmail:u},d),x.success(`secrets \u2192 ${Fe(d)}`),await Go(c,p,d,E,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Bo(`done. next: \`codepipe\` (interactive) or \`codepipe --profile ${d} daemon\`.`)}async function Go(t,e,r,o,n){let i=await ma(o,n),s=fa(i),a=await Qe({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Mo(a)||a!==s.proceedValue))try{let{jobId:c}=await Rr(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 Sd(t,e){let r;try{r=await Ki(t,e)}catch(c){throw c instanceof A&&B(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&B("no farms registered on this HUB. Register one first: on the farm host run `codepipe-farm register --hub <url> --token <HUB_FARM_REG_TOKEN>` and `codepipe-farm start`.");let n=ae(await Qe({message:"target farm",options:o.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=o.find(c=>c.farmId===n),s;try{s=wa(i.farmId,i.publicKey)}catch(c){B(c instanceof Error?c.message:String(c))}return ae(await Rt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
535
537
|
${s}
|
|
536
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
538
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||B("farm fingerprint not confirmed \u2014 aborting."),ha(i.farmId,s),{farm:i,fingerprint:s}}async function ja(t){Ia(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Aa(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:_("HUB_URL")??pe,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await _a(),n=await zr(r,o);x.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await se(r,n,t.projectId)}catch(p){throw p instanceof A&&B(`HUB \u2192 ${p.status} ${p.message}`),p}i.contextRepo||B(`project ${t.projectId} has no Context Repo on HUB`);let s=await Ga(),a={},c=new Set(i.repos.map(p=>p.host));c.add(i.contextRepo.host);for(let p of c)await Yr(p,a,p===i.contextRepo.host?i.contextRepo.owner:i.repos.find(f=>f.host===p)?.owner,o);Ba(a),await Oa(e,i.contextRepo.cloneUrl,i.contextRepo.branch),Ua(e);{let p=Xe(e,je);wr(p);let f={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{}},l=Ie(f,!0,s.url),d=co(p,l);d.length>0&&x.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),Ke(t.projectId,l,{info:g=>x.message(g),warn:g=>x.warn(g)})}await Na(e,i.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...a,youtrack:{url:s.url,token:s.token}};Z(u),Me({hubUrl:r,cliToken:n,projectId:t.projectId},t.projectId),x.success(`secrets \u2192 ${Fe(t.projectId)}`),await Go(r,n,t.projectId,i.contextRepo,a.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Bo("done.")}function Aa(t,e){if(!Ct(t)){Sa(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=$d(t).filter(n=>!r.has(n));o.length!==0&&(e||B(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Cd(t){if(!Ct(Xe(t,".git")))return null;try{let r=(await Vr(t).remote(["get-url","origin"])||"").toString().trim(),o=r?xe(r):null;return o?{parsed:o,defaultBranch:await Rd(t)}:null}catch{return null}}async function Rd(t){let e=Vr(t);try{let o=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(o)return o}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function Td(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ge.test(e)?e:""}function Id(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Pd(t){let e=Xe(t,".gitignore"),r=Ct(e)?Ca(e,"utf-8"):"";if(Id(r))return;if(!ae(await Rt({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 n=r.length===0||r.endsWith(`
|
|
537
539
|
`)?"":`
|
|
538
|
-
`;
|
|
540
|
+
`;Ra(e,r+n+`
|
|
539
541
|
# codepipe workspace (added by \`codepipe init\`)
|
|
540
542
|
.codepipe/
|
|
541
|
-
`),
|
|
543
|
+
`),x.success(`.codepipe/ added to ${Ta(e)}`)}async function _a(){let t="";try{t=(await Vr().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Email (admin email of this HUB)",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function zr(t,e){x.step(`sending magic link to ${e}`);let r;try{r=await Yi(t,e)}catch(n){throw n instanceof Gt&&B(`${e} is not authorized on this HUB yet.
|
|
542
544
|
Sign up at ${t} (registration form on the login screen),
|
|
543
545
|
wait for the operator to approve it by email, then re-run
|
|
544
|
-
\`codepipe init\` with the same email.`),
|
|
546
|
+
\`codepipe init\` with the same email.`),n}x.message(`click the link in your inbox to confirm. polling\u2026 (request ${r.requestId})`);let o=Date.now();for(;Date.now()-o<15*6e4;){let n=await Vi(t,r.requestId);if(n.status==="confirmed"&&n.cliToken)return x.success("confirmed"),n.cliToken;n.status==="rejected"&&B("HUB rejected this email \u2014 not the admin"),n.status==="expired"&&B("link expired \u2014 re-run init"),await xd(2e3)}B("bootstrap timed out after 15 minutes")}async function Oa(t,e,r){let o=Xe(t,je);if(Ct(Xe(o,".git"))){x.message(`${o} already cloned \u2014 skipping`);return}Ct(o)&&B(`${o} exists but is not a git repo \u2014 remove it and re-run`),Sa(o,{recursive:!0}),x.step(`cloning Context Repo \u2192 ${o}`);try{await Vr().clone(e,o,["--branch",r]),x.success(`cloned ${e}`)}catch(n){B(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Na(t,e){if(e.length===0)return;x.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await zt(t,r,{log:{info:n=>x.message(n),warn:n=>x.warn(n)}});for(let n of o)x.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function Ua(t){let e=Xe(t,je,".gitignore"),r="";if(Ct(e)&&(r=Ca(e,"utf-8")),va.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
|
|
545
547
|
`)||r.length===0?"":`
|
|
546
|
-
`,
|
|
548
|
+
`,i=va.join(`
|
|
547
549
|
`)+`
|
|
548
|
-
`;
|
|
549
|
-
`:"")+
|
|
550
|
+
`;Ra(e,r+n+(r?`
|
|
551
|
+
`:"")+i),x.message(`appended runtime entries to ${Ta(e)}`)}async function Ed(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;x.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Yr(s.host,t,s.owner,e),i?.();let c=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=D(await K({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:u,mountAs:"."}),o.onProgress?.(n)}for(;ae(await Rt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=D(await K({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:d=>!d||!d.trim()||xe(d)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=xe(a);x.message(`${c.host}: ${c.owner}/${c.repoName}`),await Yr(c.host,t,c.owner,e),i?.();let u=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"default branch (optional)",placeholder:"main"})).trim(),f=D(await K({message:"local folder name (sibling of .codepipe/, optional)",placeholder:u})).trim(),l={name:u,host:c.host,owner:c.owner,repoName:c.repoName};p&&(l.defaultBranch=p),f&&f!==u&&(l.mountAs=f),n.push(l),o.onProgress?.(n)}return n}async function La(t,e,r,o){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 n=ae(await Qe({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&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=D(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:ke(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!xe(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=xe(c);a=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:i,owner:s,name:c}}else{let c=await Ad(),u=D(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"Context Repo name",placeholder:ke(t),initialValue:ke(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:u,name:p}}return{spec:a,mode:n}}function Da(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??st()}}async function jd(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:u}=a;await Yr(c.host,o,c.owner,n),i?.();let p=Pa();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await oa(c,Da(o),{explain:u==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(u==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let l=ae(await Qe({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(l==="abort"&&B("aborted"),l==="create")return a={spec:c,mode:"create"},s(a),a;a=await La(e,r,o,n),s(a)}}async function Ad(){return ae(await Qe({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Xt(t,e){let r=Pa();r.start(`verifying ${t}\u2026`);try{let o=await e();return r.stop(`${t} OK \u2014 ${o}`),!0}catch(o){return r.stop(`${t} failed \u2014 ${o instanceof Error?o.message:String(o)}`,1),!1}}function Ba(t){jr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ar(t.gitlab?.token??process.env.GITLAB_TOKEN),_r(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Yr(t,e,r,o){if(!e[t])if(t==="github"){let n=await _d(r);n?e.github=n:x.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Od(r,o);n?e.bitbucket=n: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 n=await Nd();n?e.gitlab=n:x.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function _d(t){for(;;){let e=D(await Jt({message:`GitHub PAT \u2014 blank to skip
|
|
550
552
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
551
553
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
552
554
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
553
555
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
554
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
556
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Xt("GitHub",()=>ut(e,t?{owner:t}:void 0)))return{token:e};x.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Od(t,e){for(x.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
555
557
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
556
558
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
557
559
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
558
560
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
559
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=
|
|
560
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
561
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let r=D(await K({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:n=>!n||!n.trim()||n.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let o=D(await Jt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){x.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Xt("Bitbucket",()=>pt(r,o,t)))return{email:r,apiToken:o};x.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Nd(){for(;;){let t=D(await Jt({message:`GitLab PAT \u2014 blank to skip
|
|
562
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Xt("GitLab",()=>dt(t))){let e=await Vn(t);return e&&x.warn(e),{token:t}}x.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ud(t){if(ae(await Rt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
561
563
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
562
564
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
563
|
-
your trusted network.`,initialValue:!1})))for(t.host==="github"?
|
|
565
|
+
your trusted network.`,initialValue:!1})))for(t.host==="github"?x.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
564
566
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
565
|
-
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):
|
|
566
|
-
(${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=U(await Mt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Gt("contextWrite",()=>pd(r,t)))return{token:r};R.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function pd(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(n){throw new Error(`cannot reach api.github.com (${n instanceof Error?n.message:String(n)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(o.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=await o.json();if(i.permissions&&i.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return i.full_name??`${e.owner}/${e.name}`}async function ha(){for(;;){let t=U(await F({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=U(await Mt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Gt("YouTrack",()=>st({baseUrl:t,token:e})))return{url:t,token:e};R.warn("re-enter the YouTrack URL / token.")}}import{mkdirSync as dd,readFileSync as fd,writeFileSync as ya}from"node:fs";import{homedir as md}from"node:os";import{join as Ao}from"node:path";function K(t){throw new Error(t)}function Y(t,e){return(typeof t!="string"||t.trim().length===0)&&K(`config: '${e}' must be a non-empty string`),t.trim()}function Ht(t,e){if(t==null)return;typeof t!="string"&&K(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function gd(t){(!t||typeof t!="object")&&K("config: expected a JSON object");let e=t,r=Y(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||K("config: 'hubUrl' must start with http(s)://");let o=Y(e.cliToken,"cliToken"),i=e.project;(!i||typeof i!="object")&&K("config: 'project' is required");let n=i,s=Y(n.id,"project.id");_e.test(s)||K("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=Y(n.name,"project.name"),c=Y(n.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&K("config: 'project.automationLevel' must be 'assisted' or 'full'");let u=n.repos;Array.isArray(u)||K("config: 'project.repos' must be an array");let p=u.map((v,P)=>{(!v||typeof v!="object")&&K(`config: project.repos[${P}] must be an object`);let j=v,L=Y(j.host,`project.repos[${P}].host`);L!=="github"&&L!=="bitbucket"&&L!=="gitlab"&&K(`config: project.repos[${P}].host must be 'github', 'bitbucket' or 'gitlab'`);let x={name:Y(j.name,`project.repos[${P}].name`),host:L,owner:Y(j.owner,`project.repos[${P}].owner`),repoName:Y(j.repoName,`project.repos[${P}].repoName`)},h=Ht(j.defaultBranch,`project.repos[${P}].defaultBranch`);h&&(x.defaultBranch=h);let f=Ht(j.mountAs,`project.repos[${P}].mountAs`);return f&&(x.mountAs=f),x}),m=n.contextRepo;(!m||typeof m!="object")&&K("config: 'project.contextRepo' is required");let l=m,d=Ht(l.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&K("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:Y(l.owner,"project.contextRepo.owner"),name:Ht(l.name,"project.contextRepo.name")??$e(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},b=Ht(n.youtrackProjectKey,"project.youtrackProjectKey");b&&(w.project.youtrackProjectKey=b),n.index!==void 0&&(typeof n.index!="boolean"&&K("config: 'project.index' must be a boolean"),w.project.index=n.index),n.youtrackWrites!==void 0&&(typeof n.youtrackWrites!="boolean"&&K("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=n.youtrackWrites);let C=e.secrets;if(C!==void 0){(typeof C!="object"||C===null)&&K("config: 'secrets' must be an object");let v=C,P={};if(v.github){let j=v.github;P.github={token:Y(j.token,"secrets.github.token")}}if(v.bitbucket){let j=v.bitbucket;P.bitbucket={email:Y(j.email,"secrets.bitbucket.email"),apiToken:Y(j.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let j=v.gitlab;P.gitlab={token:Y(j.token,"secrets.gitlab.token")}}if(v.youtrack){let j=v.youtrack;P.youtrack={url:Y(j.url,"secrets.youtrack.url").replace(/\/$/,""),token:Y(j.token,"secrets.youtrack.token")}}if(v.contextWrite){let j=v.contextWrite;P.contextWrite={token:Y(j.token,"secrets.contextWrite.token")}}w.secrets=P}return w}async function hd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function yd(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await tt(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(i=>i.host==="bitbucket")?.owner,o=await rt(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await ot(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await st({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function wa(t){let e=!t.configPath||t.configPath==="-"?await hd():fd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(l){K(`config: invalid JSON \u2014 ${l instanceof Error?l.message:String(l)}`)}let o=gd(r),{hubUrl:i,cliToken:n,project:s}=o;console.log(`codepipe init --headless \u2192 ${i} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await yd(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,u;try{u=await gt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??Qe(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:l=>console.log(` ${l}`),warn:l=>console.warn(` ${l}`)}})}catch(l){K(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`)}a.contextRepo=u,console.log(`Context Repo ready: ${u.owner}/${u.name}@${u.branch}`),console.log(`registering project on ${i}\u2026`);let p;try{p=await at(i,n,a)}catch(l){if(l instanceof A&&l.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await ne(i,n,s.id);else if(l instanceof A)K(`HUB \u2192 ${l.status} ${l.message}`);else throw l}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let m={hubUrl:i,cliToken:n,projectId:s.id,...o.secrets??{}};X(m),Oe({hubUrl:i,cliToken:n,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ue(s.id)}`);{let l=Ao(md(),".codepipe","profiles",s.id,"context-config");dd(l,{recursive:!0});let d=ve(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url);ya(Ao(l,"project.yaml"),d.projectYaml),ya(Ao(l,"regimen.yaml"),d.regimenYaml),console.log(`local project config staged \u2192 ${l}`)}if(s.index)try{let{jobId:l}=await yr(i,n,s.id,{reindex:!1});console.log(`index job enqueued (job ${l}); runs once a SANDBOX claims it.`)}catch(l){console.warn(`could not enqueue index job: ${l instanceof Error?l.message:String(l)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as ba,intro as ka,isCancel as $a,log as _o,outro as wd,password as xa}from"@clack/prompts";async function bd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Sa(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await bd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){ka("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),_o.message("Run `claude setup-token` and paste the token below (input hidden).");let n=await xa({message:"Claude OAuth token"});$a(n)&&(ba("aborted"),process.exit(1)),e=n.trim()}e||(console.error("login: no token provided"),process.exit(1)),bn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${or()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=de(t.profile);if(!e){ka(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),_o.message("Run `claude setup-token` and paste the token below (input hidden).");let n=await xa({message:"Claude OAuth token"});$a(n)&&(ba("aborted"),process.exit(1)),e=n.trim()}e||(console.error("login: no token provided"),process.exit(1));let i=G(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};i.claude={oauthToken:e},X(i),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(_o.success("Claude OAuth token saved."),wd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as kd,confirm as $d,intro as xd,isCancel as Ca,log as te,outro as Sd,select as Ra,text as je}from"@clack/prompts";import{mkdirSync as vd,writeFileSync as va}from"node:fs";import{homedir as Cd}from"node:os";import{join as Oo}from"node:path";function Ta(t){kd(t),process.exit(1)}function bt(t){return Ca(t)&&Ta("aborted"),t}function Ft(t){return Ca(t)&&Ta("aborted"),typeof t=="string"?t:""}async function Rd(t,e){let r=bt(await Ra({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",i=Ft(await je({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),n=Ft(await je({message:"Context Repo name",placeholder:$e(t),initialValue:$e(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:i,name:n}}async function Ia(t={profile:void 0}){let e=de(t.profile);xd(`codepipe project add \u2192 ${e.hubUrl}`);let r=bt(await je({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:l=>_e.test(l.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=bt(await je({message:"project name (human-readable)",placeholder:"CodePartner",validate:l=>l.trim().length>0?void 0:"required"})).trim(),i=bt(await Ra({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"})),n=bt(await je({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=bt(await $d({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let l=Ft(await je({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:C=>!C||!C.trim()||Ke(C)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!l)break;let d=Ke(l);te.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=Ft(await je({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:C=>C.trim().length>0?void 0:"required"})).trim(),w=Ft(await je({message:"default branch (optional)",placeholder:"main"})).trim(),b={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(b.defaultBranch=w),a.push(b)}let c={projectId:r,name:o,automationLevel:i,repos:a};n&&(c.youtrackProjectKey=n);let u=await Rd(r,a),p=G(e.projectId);te.info(`provisioning Context Repo ${u.owner}/${u.name} (${u.host})\u2026`);let m;try{m=await gt(c,u,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??Qe(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:l=>te.message(l),warn:l=>te.warn(l)}})}catch(l){te.error(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}c.contextRepo=m,te.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let l=await at(e.hubUrl,e.cliToken,c);te.success(`project "${l.projectId}" \u2014 ${l.provisioningStatus}`);{let d=Oo(Cd(),".codepipe","profiles",r,"context-config");vd(d,{recursive:!0});let g=ve(c,s,p?.youtrack?.url);va(Oo(d,"project.yaml"),g.projectYaml),va(Oo(d,"regimen.yaml"),g.regimenYaml),te.message(`local project config staged \u2192 ${d}`)}l.contextRepo&&(te.message(` context repo: ${l.contextRepo.owner}/${l.contextRepo.name} (${l.contextRepo.cloneUrl})`),te.message(` branch: ${l.contextRepo.branch}`)),l.provisioningError&&te.error(` error: ${l.provisioningError}`),Sd("done")}catch(l){l instanceof A?(te.error(`HUB \u2192 ${l.status} ${l.message}`),l.payload&&typeof l.payload=="object"&&te.message(JSON.stringify(l.payload,null,2))):te.error(l instanceof Error?l.message:String(l)),process.exit(1)}}import{spawn as Td}from"node:child_process";import{hostname as Id}from"node:os";async function Pd(t,e){let r=Z(e.profile);if(r){if(r.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${r.sandboxId} (${r.name})`);return}throw new Error(`worker config ${Te(e.profile)} points at a different HUB (${r.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await hr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i}await He({hub:t.hubUrl,token:o,name:e.name??`${Id()}-up`,llm:e.llm??"claude-headless",projects:e.projects??[],...e.profile?{profile:e.profile}:{}})}function Ed(t,e){let r=Z(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=it(r.sealPublicKey);if(!G(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let i=rr(t,r.sandboxId,o);if(i==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${i==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function Pa(t){let e=de(t.profile);await Pd(e,t),Ed(e.projectId,t.profile);let r=process.argv[1];if(!r)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(l,d)=>{let g=w=>b=>{for(let C of b.toString("utf-8").split(`
|
|
567
|
-
`))
|
|
568
|
-
`)};l.stdout?.on("data",g(process.stdout)),l.stderr?.on("data",g(process.stderr))},
|
|
569
|
-
[up] ${l} \u2014 stopping both roles`);for(let{child:d}of a)d.exitCode===null&&d.kill(l);setTimeout(()=>{for(let{name:d,child:g}of a)g.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=a.map(({name:l,child:d})=>new Promise(g=>{d.on("exit",(w,
|
|
570
|
-
`)}async function
|
|
571
|
-
${
|
|
572
|
-
or: /abort ${r} --reason "..."`}}function
|
|
567
|
+
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
|
|
568
|
+
(${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=D(await Jt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Xt("contextWrite",()=>Ld(r,t)))return{token:r};x.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ld(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(o.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let n=await o.json();if(n.permissions&&n.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return n.full_name??`${e.owner}/${e.name}`}async function Ga(){for(;;){let t=D(await K({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=D(await Jt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Xt("YouTrack",()=>gt({baseUrl:t,token:e}))){let r=await Ei({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}x.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Dd}from"node:fs";function W(t){throw new Error(t)}function V(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function Qt(t,e){if(t==null)return;typeof t!="string"&&W(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Bd(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=V(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=V(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=V(i.id,"project.id");Ge.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=V(i.name,"project.name"),c=V(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let u=i.repos;Array.isArray(u)||W("config: 'project.repos' must be an array");let p=u.map((v,T)=>{(!v||typeof v!="object")&&W(`config: project.repos[${T}] must be an object`);let j=v,U=V(j.host,`project.repos[${T}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${T}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:V(j.name,`project.repos[${T}].name`),host:U,owner:V(j.owner,`project.repos[${T}].owner`),repoName:V(j.repoName,`project.repos[${T}].repoName`)},h=Qt(j.defaultBranch,`project.repos[${T}].defaultBranch`);h&&(S.defaultBranch=h);let m=Qt(j.mountAs,`project.repos[${T}].mountAs`);return m&&(S.mountAs=m),S}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let l=f,d=Qt(l.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&W("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:V(l.owner,"project.contextRepo.owner"),name:Qt(l.name,"project.contextRepo.name")??ke(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},k=Qt(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(w.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let R=e.secrets;if(R!==void 0){(typeof R!="object"||R===null)&&W("config: 'secrets' must be an object");let v=R,T={};if(v.github){let j=v.github;T.github={token:V(j.token,"secrets.github.token")}}if(v.bitbucket){let j=v.bitbucket;T.bitbucket={email:V(j.email,"secrets.bitbucket.email"),apiToken:V(j.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let j=v.gitlab;T.gitlab={token:V(j.token,"secrets.gitlab.token")}}if(v.youtrack){let j=v.youtrack;T.youtrack={url:V(j.url,"secrets.youtrack.url").replace(/\/$/,""),token:V(j.token,"secrets.youtrack.token")}}if(v.contextWrite){let j=v.contextWrite;T.contextWrite={token:V(j.token,"secrets.contextWrite.token")}}w.secrets=T}return w}async function Gd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Md(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await ut(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(n=>n.host==="bitbucket")?.owner,o=await pt(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await dt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await gt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ma(t){let e=!t.configPath||t.configPath==="-"?await Gd():Dd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(l){W(`config: invalid JSON \u2014 ${l instanceof Error?l.message:String(l)}`)}let o=Bd(r),{hubUrl:n,cliToken:i,project:s}=o;console.log(`codepipe init --headless \u2192 ${n} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Md(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,u;try{u=await vt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??st(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:l=>console.log(` ${l}`),warn:l=>console.warn(` ${l}`)}})}catch(l){W(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`)}a.contextRepo=u,console.log(`Context Repo ready: ${u.owner}/${u.name}@${u.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await ht(n,i,a)}catch(l){if(l instanceof A&&l.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await se(n,i,s.id);else if(l instanceof A)W(`HUB \u2192 ${l.status} ${l.message}`);else throw l}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(Z(f),Me({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Fe(s.id)}`),Ke(s.id,Ie(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:l=>console.log(l),warn:l=>console.warn(l)}),s.index)try{let{jobId:l}=await Rr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${l}); runs once a SANDBOX claims it.`)}catch(l){console.warn(`could not enqueue index job: ${l instanceof Error?l.message:String(l)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Ha,intro as Fa,isCancel as Ka,log as Ho,outro as Hd,password as Wa}from"@clack/prompts";async function Fd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function qa(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Fd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fa("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 Wa({message:"Claude OAuth token"});Ka(i)&&(Ha("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Rn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${fr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=fe(t.profile);if(!e){Fa(`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 Wa({message:"Claude OAuth token"});Ka(i)&&(Ha("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},Z(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ho.success("Claude OAuth token saved."),Hd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Kd,confirm as Wd,intro as qd,isCancel as Ya,log as J,outro as Yd,select as Va,text as Le}from"@clack/prompts";function za(t){Kd(t),process.exit(1)}function Tt(t){return Ya(t)&&za("aborted"),t}function Zt(t){return Ya(t)&&za("aborted"),typeof t=="string"?t:""}async function Vd(t,e){let r=Tt(await Va({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=Zt(await Le({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Zt(await Le({message:"Context Repo name",placeholder:ke(t),initialValue:ke(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function Ja(t={profile:void 0}){let e=fe(t.profile);qd(`codepipe project add \u2192 ${e.hubUrl}`);let r=Tt(await Le({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:l=>Ge.test(l.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Tt(await Le({message:"project name (human-readable)",placeholder:"CodePartner",validate:l=>l.trim().length>0?void 0:"required"})).trim(),n=Tt(await Va({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=Tt(await Le({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Tt(await Wd({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let l=Zt(await Le({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:R=>!R||!R.trim()||xe(R)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!l)break;let d=xe(l);J.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=Zt(await Le({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:R=>R.trim().length>0?void 0:"required"})).trim(),w=Zt(await Le({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(k.defaultBranch=w),a.push(k)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let u=await Vd(r,a),p=H(e.projectId);J.info(`provisioning Context Repo ${u.owner}/${u.name} (${u.host})\u2026`);let f;try{f=await vt(c,u,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??st(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:l=>J.message(l),warn:l=>J.warn(l)}})}catch(l){J.error(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}c.contextRepo=f,J.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let l=await ht(e.hubUrl,e.cliToken,c);J.success(`project "${l.projectId}" \u2014 ${l.provisioningStatus}`),Ke(r,Ie(c,s,p?.youtrack?.url),{info:d=>J.message(d),warn:d=>J.warn(d)}),l.contextRepo&&(J.message(` context repo: ${l.contextRepo.owner}/${l.contextRepo.name} (${l.contextRepo.cloneUrl})`),J.message(` branch: ${l.contextRepo.branch}`)),l.provisioningError&&J.error(` error: ${l.provisioningError}`),Yd("done")}catch(l){l instanceof A?(J.error(`HUB \u2192 ${l.status} ${l.message}`),l.payload&&typeof l.payload=="object"&&J.message(JSON.stringify(l.payload,null,2))):J.error(l instanceof Error?l.message:String(l)),process.exit(1)}}import{spawn as zd}from"node:child_process";import{hostname as Jd}from"node:os";async function Xd(t,e){let r=te(e.profile);if(r){if(r.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${r.sandboxId} (${r.name})`);return}throw new Error(`worker config ${_e(e.profile)} points at a different HUB (${r.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await Cr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(n){throw n instanceof A&&n.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):n instanceof A&&n.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):n}await ze({hub:t.hubUrl,token:o,name:e.name??`${Jd()}-up`,llm:e.llm??"claude-headless",projects:e.projects??[],...e.profile?{profile:e.profile}:{}})}function Qd(t,e){let r=te(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=mt(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=dr(t,r.sandboxId,o);if(n==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${n==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function Xa(t){let e=fe(t.profile);await Xd(e,t),Qd(e.projectId,t.profile);let r=process.argv[1];if(!r)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(l,d)=>{let g=w=>k=>{for(let R of k.toString("utf-8").split(`
|
|
569
|
+
`))R.length>0&&w.write(`${d} ${R}
|
|
570
|
+
`)};l.stdout?.on("data",g(process.stdout)),l.stderr?.on("data",g(process.stderr))},n=(l,d)=>{let g=zd(process.execPath,[r,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,l),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let i=n("[cli]",[...t.profile?["--profile",t.profile]:[],"daemon"]),s=n("[worker]",[...t.profile?["--profile",t.profile]:[],"worker","start"]),a=[{name:"daemon",child:i},{name:"worker",child:s}],c=!1,u=l=>{if(!c){c=!0,console.log(`
|
|
571
|
+
[up] ${l} \u2014 stopping both roles`);for(let{child:d}of a)d.exitCode===null&&d.kill(l);setTimeout(()=>{for(let{name:d,child:g}of a)g.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=a.map(({name:l,child:d})=>new Promise(g=>{d.on("exit",(w,k)=>g({name:l,code:w??(k?1:0)}))})),f=await Promise.race(p);c||(console.log(`[up] ${f.name} exited (code ${f.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(f.code)}import{existsSync as lc,mkdirSync as of,readFileSync as nf,writeFileSync as sf}from"node:fs";import{homedir as af}from"node:os";import{dirname as cf,join as uc}from"node:path";import*as Pt from"node:readline";import{existsSync as Wo,readFileSync as Zd,writeFileSync as ef}from"node:fs";import{join as tr}from"node:path";import{simpleGit as Ko}from"simple-git";var Qa=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],tf="apply-queue.json";function Za(t){return tr(t,tf)}function It(t){let e=Za(t);if(!Wo(e))return{};try{return JSON.parse(Zd(e,"utf-8"))}catch{return{}}}function ec(t,e){ef(Za(t),JSON.stringify(e,null,2)+`
|
|
572
|
+
`)}async function tc(t,e,r,o,n){let i;try{i=await Xi(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(l){return{ok:!1,message:`claim failed: ${l instanceof Error?l.message:String(l)}`}}let s=[];for(let l of i.repos){let d=t.spec.repos.find(R=>R.name===l.repoName);if(!d)return{ok:!1,message:`repo "${l.repoName}" not in project.yaml \u2014 run /sync`};let g=tr(t.root,d.mountAs);if(!Wo(tr(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Ko(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:l,spec:d,dir:g})}let a=[];for(let l of s){let d=Ko(l.dir),g=await rf(d),w=l.claimRepo;try{await d.fetch()}catch(v){return await Fo(a,n),{ok:!1,message:`fetch failed in ${l.spec.mountAs}: ${er(v)}`}}let k=`origin/${w.baseRef}`,R;try{R=await xr(d,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(v){return await Fo(a,n),{ok:!1,message:`fetch delivery failed in ${l.spec.mountAs}: ${er(v)}`}}a.push({git:d,dir:l.dir,mountAs:l.spec.mountAs,originalRef:g,branch:w.branchName,baseSha:k,deliveryCommit:R,startPoint:k})}let c=[];for(let l of a)try{if(o==="apply"){await l.git.checkout(["-B",l.branch,l.startPoint]),await l.git.raw([...Qa,"cherry-pick",l.deliveryCommit]);let d=(await l.git.revparse(["HEAD"])).trim();c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha,appliedSha:d})}else await l.git.checkout(["--detach",l.startPoint]),await l.git.raw([...Qa,"cherry-pick","--no-commit",l.deliveryCommit]),await l.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha})}catch(d){return await l.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Fo(a,n),{ok:!1,message:`apply failed in ${l.mountAs}: ${er(d)} (rolled back all repos)`}}let u=It(t.contextDir);u[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},ec(t.contextDir,u);let p=c.map(l=>l.mountAs).join(", "),f=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${p}
|
|
573
|
+
${f}
|
|
574
|
+
or: /abort ${r} --reason "..."`}}function qo(t,e){let r=It(t);r[e]&&(delete r[e],ec(t,r))}async function Fo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(o){e.warn(`rollback failed in ${r.mountAs}: ${er(o)} \u2014 check manually`)}}async function rc(t,e,r){let n=It(t.contextDir)[e];if(n){for(let i of n.repos){let s=tr(t.root,i.mountAs);if(!Wo(tr(s,".git")))continue;let a=Ko(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),u=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",u]),await a.reset(["--hard",u]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${er(p)} \u2014 check manually`)}}qo(t.contextDir,e)}}async function rf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function er(t){return t instanceof Error?t.message.trim():String(t)}var Jr=uc(af(),".codepipe","history"),oc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],pc=500,nc=40;async function dc(){let t=Mt();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=H(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Ut(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=It(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
|
|
573
575
|
\u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
574
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let
|
|
575
|
-
`))}async function
|
|
576
|
-
`)}`:" (none)");return}if(r==="set"){let n
|
|
577
|
-
`),t.unread+=1,
|
|
578
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
576
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Pt.createInterface({input:process.stdin,output:process.stdout,completer:lf,history:Pf(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};pi(s=>Ze(i,s)),i.daemon=Pr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Ze(i,s),warn:s=>Ze(i,s)},onEvent:s=>vf(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),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await uf(i,a)){cc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Vo(i),n.prompt()}),n.on("close",()=>{cc(i)})}function lf(t){let e=oc.filter(r=>r.startsWith(t));return[e.length?e:oc,t]}async function uf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return pf(),!1;case"/status":return await df(t),!1;case"/tasks":return await ff(t,o),!1;case"/task":return await mf(t,o),!1;case"/sync":return await gf(t),!1;case"/logs":return Sf(t,o),!1;case"/monitor":return Cf(t),!1;case"/apply":return await ic(t,o,"apply"),!1;case"/unstash":return await ic(t,o,"unstash"),!1;case"/applied":return await hf(t,o),!1;case"/abort":return await wf(t,o),!1;case"/approve":return await sc(t,o,"approve"),!1;case"/merge":return await sc(t,o,"merge"),!1;case"/login":return bf(t,o),!1;case"/secret":return kf(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function pf(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
|
|
577
|
+
`))}async function df(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let o=lc(uc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function ff(t,e){let r=Rf(e,"--phase");try{let o=await zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),n=r?o.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):o;if(n.length===0){console.log(" (no tasks)");return}for(let i of n)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(o){or(o)}}async function mf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await Ji(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${o.task.phase} \u2014 ${o.task.title}`),o.artifacts.length>0){console.log(" artifacts:");for(let n of o.artifacts)console.log(` ${n.path}`)}}catch(o){or(o)}}async function gf(t){let e=await zt(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 ic(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await tc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function hf(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=It(t.ws.contextDir)[r],i=Tf(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 u=c.indexOf("="),p,f;if(u>0?(p=c.slice(0,u),f=c.slice(u+1)):(f=c,p=n?.repos.length===1?yf(t,n.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let l=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!l){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(l[1])})}try{let c=await Qi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);qo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){or(c)}}async function sc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await es(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){or(n)}}async function wf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=If(e,"--reason")||"local apply aborted";await rc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await Zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){or(n)}}function yf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function bf(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},Z(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function kf(t,e){let[r,o,...n]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
|
|
578
|
+
`)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}$f(t.secrets,o,i),Z(t.secrets),Ut(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}xf(t.secrets,o),Z(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function $f(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 xf(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 vf(t,e){switch(e.kind){case"connected":t.connection="connecting",Ze(t,"[hub] connected");break;case"registered":t.connection="registered",Ze(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",rr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Ze(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",rr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":rr(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?Ze(t,`[hub] action ${e.actionType} done`):rr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Ze(t,e){t.logBuffer.push(e),t.logBuffer.length>pc&&t.logBuffer.shift(),t.follow&&rr(t,e)}function Sf(t,e){let r=e[0];if(r==="follow"||r==="on"){Yo(t,!0);return}if(r==="off"){Yo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(pc,Number(r)||nc)):nc,n=t.logBuffer.slice(-o);if(n.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of n)console.log(` ${i}`);console.log(` \u2014 ${n.length} line(s); /monitor for live stream`)}function Cf(t){Yo(t,!t.follow)}function Yo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function rr(t,e){Pt.cursorTo(process.stdout,0),Pt.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
579
|
+
`),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 ac=!1;function cc(t){ac||(ac=!0,Ef(t.rl),t.daemon.stop(),console.log(`
|
|
580
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function Rf(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Tf(t,e){let r=[];for(let o=0;o<t.length;o++)t[o]===e&&t[o+1]&&r.push(t[o+1]);return r}function If(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function or(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Pf(){if(!lc(Jr))return[];try{return nf(Jr,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Ef(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{of(cf(Jr),{recursive:!0}),sf(Jr,r.slice().reverse().join(`
|
|
579
581
|
`)+`
|
|
580
|
-
`)}catch{}}import{hostname as lf}from"node:os";import{cancel as uf,confirm as Wa,intro as pf,isCancel as Va,log as xt,multiselect as df,outro as qa,password as ff,select as Go,text as Hr}from"@clack/prompts";function zt(t){uf(t),process.exit(1)}function St(t){return Va(t)&&zt("aborted"),t}function Vt(t){return Va(t)&&zt("aborted"),typeof t=="string"?t:""}function Ho(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Ya(t,e){try{let{secret:r}=await hr(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&zt("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 mf(t,e){if(St(await Go({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 i=await Ui(t,e);if(i.length>0)return St(await df({message:"pick the projects (space to toggle, enter to confirm)",options:i.map(n=>({value:n.id,label:`${n.id} \u2014 ${n.name}`})),required:!0}));xt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(i){xt.warn(`could not list projects (${i instanceof Error?i.message:String(i)}) \u2014 enter the ids manually`)}return Vt(await Hr({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:i=>i.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Fo(t){pf("codepipe worker \u2014 set up this machine as a runner");let e=Z(t.profile);e&&(xt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),St(await Wa({message:"re-register this worker?",initialValue:!1}))||zt("keeping the existing registration"));let r=xe(t.profile)??xe(),o=Vt(await Hr({message:"HUB URL",placeholder:ue,initialValue:_("HUB_URL")??r?.hubUrl??ue,validate:l=>l.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),i=r!==null&&r.hubUrl.replace(/\/$/,"")===o,n=St(await Go({message:"how to authorize the registration?",options:[...i?[{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:i?"local":"login"})),s,a=null;if(n==="local")a=r.cliToken,s=await Ya(o,a),xt.success("account-issued registration token minted");else if(n==="login"){let l=Vt(await Hr({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await Mr(o,l),s=await Ya(o,a),xt.success("account-issued registration token minted")}else s=Vt(await ff({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||zt("a registration token is required");let c=await mf(o,a),u=Vt(await Hr({message:"worker name",initialValue:lf(),validate:l=>l.trim().length>0?void 0:"required"})).trim(),p=St(await Go({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 He({hub:o,token:s,name:u,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),xt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!St(await Wa({message:"start the claim-loop now?",initialValue:!0}))){qa("registered. start later with `codepipe worker`.");return}qa("starting the claim-loop\u2026"),await Bt(t.profile?{profile:t.profile}:{})}function hf(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var z=hf();an(z);pn();var ie=new gf;ie.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(oe).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 Ka()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ie.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 wa({configPath:t.config,skipVerify:t.skipVerify===!0}):await la({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ie.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await kn({...t,profile:z})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ie.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ua({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ie.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ns({profile:z})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ie.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 ta({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ie.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 Sa({profile:z,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ie.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Fs({profile:z})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ie.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await Pa({profile:z,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var za=ie.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");za.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??xe(z)?.hubUrl??ue,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Ho()){await Fo({profile:z});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),i=t.name??_("WORKER_NAME"),n=t.llm??_("WORKER_LLM");await He({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...i?{name:i}:{},...n?{llm:n}:{},...z?{profile:z}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});za.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!Z(z)&&Ho()){await Fo({profile:z});return}await Bt(z?{profile:z}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var yf=ie.command("project").description("Manage CodePipe projects");yf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ia({profile:z})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ie.parseAsync();
|
|
582
|
+
`)}catch{}}import{hostname as jf}from"node:os";import{cancel as Af,confirm as fc,intro as _f,isCancel as hc,log as Et,multiselect as Of,outro as mc,password as Nf,select as zo,text as Xr}from"@clack/prompts";function ir(t){Af(t),process.exit(1)}function jt(t){return hc(t)&&ir("aborted"),t}function nr(t){return hc(t)&&ir("aborted"),typeof t=="string"?t:""}function Jo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function gc(t,e){try{let{secret:r}=await Cr(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&ir("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Uf(t,e){if(jt(await zo({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let n=await qi(t,e);if(n.length>0)return jt(await Of({message:"pick the projects (space to toggle, enter to confirm)",options:n.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Et.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){Et.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return nr(await Xr({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:n=>n.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Xo(t){_f("codepipe worker \u2014 set up this machine as a runner");let e=te(t.profile);e&&(Et.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),jt(await fc({message:"re-register this worker?",initialValue:!1}))||ir("keeping the existing registration"));let r=Re(t.profile)??Re(),o=nr(await Xr({message:"HUB URL",placeholder:pe,initialValue:_("HUB_URL")??r?.hubUrl??pe,validate:l=>l.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=jt(await zo({message:"how to authorize the registration?",options:[...n?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:n?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await gc(o,a),Et.success("account-issued registration token minted");else if(i==="login"){let l=nr(await Xr({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await zr(o,l),s=await gc(o,a),Et.success("account-issued registration token minted")}else s=nr(await Nf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ir("a registration token is required");let c=await Uf(o,a),u=nr(await Xr({message:"worker name",initialValue:jf(),validate:l=>l.trim().length>0?void 0:"required"})).trim(),p=jt(await zo({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 ze({hub:o,token:s,name:u,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Et.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!jt(await fc({message:"start the claim-loop now?",initialValue:!0}))){mc("registered. start later with `codepipe worker`.");return}mc("starting the claim-loop\u2026"),await Vt(t.profile?{profile:t.profile}:{})}function Df(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var X=Df();mn(X);yn();var ce=new Lf;ce.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ie).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 dc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.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 Ma({configPath:t.config,skipVerify:t.skipVerify===!0}):await Ea({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.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 Tn({...t,profile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.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 ja({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ce.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ws({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.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 xa({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await qa({profile:X,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ra({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await Xa({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var wc=ce.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");wc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??Re(X)?.hubUrl??pe,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Jo()){await Xo({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??_("WORKER_NAME"),i=t.llm??_("WORKER_LLM");await ze({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...X?{profile:X}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});wc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!te(X)&&Jo()){await Xo({profile:X});return}await Vt(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Bf=ce.command("project").description("Manage CodePipe projects");Bf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ja({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.parseAsync();
|