@code-partner/codepipe 0.1.138-dev.75.g9a5c0ba → 0.1.138-dev.77.g76ea172
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 +104 -95
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var fe="0.1.138-dev.77.g76ea172",Ce="https://hub.dev.codepipe.dev";var Te=4,nu=4;function Lr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=nu&&t<=Te}var Re=".codepipe-context.yaml",lr=".devpipe-context.yaml",ii=[{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",Re]},{version:2,summary:"Rename the format-version stamp .devpipe-context.yaml \u2192 .codepipe-context.yaml (drop the devpipe-brand leftover)",addedPaths:[Re]}];function Dr(t=2){return`# CodePipe Context Repo format version.
|
|
3
3
|
# Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
|
|
4
4
|
template_version: ${t}
|
|
5
|
-
`}function
|
|
6
|
-
`);o!==r&&
|
|
7
|
-
`,{mode:384})}function
|
|
8
|
-
`,{mode:384})}function
|
|
9
|
-
`,{mode:384})}function Tt(t){let e=U(t)?.claude?.oauthToken;return e||
|
|
5
|
+
`}function si(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 ai(t,e=ii){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 ci(t,e=ii){return e.filter(r=>r.version>t)}var li=["estimate","analyze","implement","resolve-conflict","rework","draft","build","index","analysis","chat"];function ut(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var We="opus",Br="sonnet",iu="haiku",Fo=[We,Br,iu],ui={analyze:We,implement:We,"resolve-conflict":We,rework:We,estimate:Br,build:Br,draft:Br,index:We,analysis:We,chat:We};var su=[{id:"llm",label:"LLM",fields:[],groups:[{id:"llm.models",label:"Models by role",help:"Model per pipeline stage. Empty \u21D2 the role's recommended default applies.",fields:[{id:"llm.models.default",file:"regimen.yaml",path:["llm","models","default"],type:"model",label:"default (catch-all)",nullable:!0,suggestions:[...Fo],help:"Overrides the recommended defaults for every role not listed below."},...li.map(t=>({id:`llm.models.${t}`,file:"regimen.yaml",path:["llm","models",t],type:"model",label:t,nullable:!0,suggestions:[...Fo],help:`recommended: ${ui[t]}`}))]}]},{id:"gates",label:"Gates",help:"Approval gate before the pipeline starts (orthogonal to automation).",fields:[{id:"gates.require_approval",file:"regimen.yaml",path:["gates","require_approval"],type:"boolean",label:"Require approval before start",nullable:!1,help:"When on, a task taken from Develop waits in AWAITING_APPROVAL for a manual Approve before analysis starts. Off \u21D2 intake auto-starts the pipeline."}]},{id:"automation",label:"Automation",help:"How far the pipeline advances the G1\u2013G4 gates without a manual Run/Approve. Independent of the approval gate above.",fields:[{id:"automation.level",file:"regimen.yaml",path:["automation","level"],type:"enum",label:"Automation level",nullable:!1,suggestions:["assisted","full"],help:"assisted \u21D2 manual Run/Approve at each of G1\u2013G4; full \u21D2 gates auto-pass."}]}];function pi(t=su){let e=[];for(let r of t)e.push(...r.fields),r.groups&&e.push(...pi(r.groups));return e}function au(t,e){let r=JSON.stringify(e);return pi().find(o=>o.file===t&&JSON.stringify(o.path)===r)}function di(t){let e=au(t.file,t.path);if(!e)return{ok:!1,error:`unknown setting path: ${t.file}:${t.path.join(".")}`};let r=t.value,o=e.type==="model"||e.type==="enum"||e.type==="string";if(r===null||o&&typeof r=="string"&&r.trim().length===0)return e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} cannot be cleared`};switch(e.type){case"model":case"string":return typeof r!="string"?{ok:!1,error:`${e.id} must be a string`}:{ok:!0,field:e,value:r.trim()};case"enum":{if(typeof r!="string")return{ok:!1,error:`${e.id} must be a string`};let i=r.trim();return e.suggestions?.includes(i)?{ok:!0,field:e,value:i}:{ok:!1,error:`${e.id} must be one of: ${(e.suggestions??[]).join(", ")}`}}case"number":return typeof r!="number"||!Number.isFinite(r)||!Number.isInteger(r)?{ok:!1,error:`${e.id} must be an integer`}:e.min!==void 0&&r<e.min?{ok:!1,error:`${e.id} must be \u2265 ${e.min}`}:e.max!==void 0&&r>e.max?{ok:!1,error:`${e.id} must be \u2264 ${e.max}`}:{ok:!0,field:e,value:r};case"boolean":return typeof r!="boolean"?{ok:!1,error:`${e.id} must be a boolean`}:{ok:!0,field:e,value:r};case"string_list":{if(!Array.isArray(r))return{ok:!1,error:`${e.id} must be a list`};let i=r.map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return i.length===0?e.nullable?{ok:!0,field:e,value:null}:{ok:!1,error:`${e.id} must be a non-empty list`}:{ok:!0,field:e,value:i}}}}var pt=/^[a-z][a-z0-9-]{1,30}$/,cu="-codepipe-ctx";function De(t){return`${t}${cu}`}var lu=[{name:"rework",pattern:/^@(?:codepipe|devpipe)\s+rework:\s*(.+)$/im,description:"Send the task back to ANALYZING with a new instruction.",hasArg:!0},{name:"approve",pattern:/^@(?:codepipe|devpipe)\s+approve\s*$/im,description:"Merge every PR for this task (TRACKING only)."},{name:"reject",pattern:/^@(?:codepipe|devpipe)\s+reject(?::\s*(.+))?\s*$/im,description:"Abandon this task: close any open PR(s) and move it to DONE (reason rejected_and_closed). Valid from any non-terminal phase; from early phases it just skips the task.",hasArg:!0},{name:"merge",pattern:/^@(?:codepipe|devpipe)\s+merge\s*$/im,description:"Merge the task branch into the default branch without a PR (direct apply path, apply.pull_request=false; TRACKING only)."},{name:"rebase",pattern:/^@(?:codepipe|devpipe)\s+rebase\s*$/im,description:"Re-apply the patch on top of the latest base branch and force-push. Use after a PR merge conflict or APPLYING failure."},{name:"update",pattern:/^@(?:codepipe|devpipe)\s+update(?::\s*(.+))?\s*$/im,description:"Update a conflicting PR: resolve conflicts against the current base branch (TRACKING only). Optional `: <instruction>` is forwarded to the agent.",hasArg:!0},{name:"apply",pattern:/^@(?:codepipe|devpipe)\s+apply:\s*(local|auto)\s*$/im,description:"Override apply mode for this task: local (you apply by hand) or auto.",hasArg:!0}];function Mr(t){for(let e of lu){let r=t.match(e.pattern);if(r)return{name:e.name,args:(r[1]??"").trim()}}return null}var ur={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function St(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 dt="x-bitbucket-api-token-auth";function Gr(t){switch(t){case ur.gitlab:return"oauth2";case ur.bitbucket:return"x-token-auth";default:return"x-access-token"}}var fi=20;function L(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as yh}from"commander";import{homedir as wi}from"node:os";import{mkdirSync as bu,readFileSync as ku,writeFileSync as $u,existsSync as Ko}from"node:fs";import{dirname as ki,join as Kr,resolve as xu}from"node:path";import{fileURLToPath as vu}from"node:url";import{existsSync as Fr,readFileSync as gi,readdirSync as pu,writeFileSync as du}from"node:fs";import{dirname as fu,join as qe}from"node:path";import{parse as mu}from"yaml";import{existsSync as mi,renameSync as uu}from"node:fs";function ft(t,e,r=o=>console.error(o)){if(mi(e)||!mi(t))return!1;try{return uu(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}var Ie=".codepipe",Ho=".devpipe";function gu(t=process.cwd()){let e=t;for(;;){if(Fr(qe(e,Ie,"project.yaml")))return e;if(Fr(qe(e,Ho,"project.yaml")))return ft(qe(e,Ho),qe(e,Ie))&&yu(e),e;let r=fu(e);if(r===e)return null;e=r}}function hu(t){let e=qe(t,Ie);return Fr(e)?e:qe(t,Ho)}function yu(t){let e=qe(t,".gitignore");if(!Fr(e))return;let r=gi(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
|
|
6
|
+
`);o!==r&&du(e,o)}function me(t=process.cwd()){let e=gu(t);if(!e)return null;let r=hu(e),o=wu(gi(qe(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function hi(t,e,r){return pu(t).filter(n=>n!==".DS_Store").length===0?!0:e?r.some(n=>n.host===e.host&&n.owner===e.owner&&n.repoName===e.repoName):!1}function Hr(t,e=process.cwd()){try{let r=me(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??""),l=String(a.name??c);if(!l||!c)continue;let u=a.host,f=u==="bitbucket"?"bitbucket":u==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:o,repos:i}}function yi(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}var bi=xu(ki(vu(import.meta.url)),"..");function $i(t){let e=Kr(bi,".env");if(Ko(e)&&process.loadEnvFile(e),t){let r=Kr(bi,"profiles",t,".env");Ko(r)&&process.loadEnvFile(r)}}function Ct(t){let e=L("CONFIG");return e||(t?Kr(wi(),".codepipe","profiles",t,"config.json"):Kr(wi(),".codepipe","config.json"))}function ke(t){let e=Ct(t);if(!Ko(e))return null;let r=ku(e,"utf-8");return JSON.parse(r)}function Be(t,e){let r=Ct(e);bu(ki(r),{recursive:!0}),$u(r,JSON.stringify(t,null,2)+`
|
|
7
|
+
`,{mode:384})}function Wr(t){if(t)return{cfg:ge(t),profile:t};let e;try{e=me()?.spec.projectId||void 0}catch{}if(e){let r=ke(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:ge(void 0),profile:void 0}}function ge(t){let e=ke(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 ${Ct(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as xi}from"node:os";import{join as vi}from"node:path";function Si(){ft(vi(xi(),".devpipe"),vi(xi(),".codepipe"))}import{homedir as Ci}from"node:os";import{existsSync as Ti,mkdirSync as Ri,readFileSync as Ii,writeFileSync as ji}from"node:fs";import{dirname as Pi,join as Ei}from"node:path";function qr(t,e,r){let o=U(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,V(o),"pinned")}function Ai(t,e){let r=U(t);return r?.sandboxPins?.[e]?(delete r.sandboxPins[e],V(r),!0):!1}function je(t){return Ei(Ci(),".codepipe","secrets",`${t}.json`)}function U(t){let e=je(t);return Ti(e)?JSON.parse(Ii(e,"utf-8")):null}function V(t){let e=je(t.projectId);Ri(Pi(e),{recursive:!0}),ji(e,JSON.stringify(t,null,2)+`
|
|
8
|
+
`,{mode:384})}function Yr(){return Ei(Ci(),".codepipe","shared.json")}function Wo(){let t=Yr();return Ti(t)?JSON.parse(Ii(t,"utf-8")):null}function _i(t){let e=Yr();Ri(Pi(e),{recursive:!0}),ji(e,JSON.stringify(t,null,2)+`
|
|
9
|
+
`,{mode:384})}function Tt(t){let e=U(t)?.claude?.oauthToken;return e||Wo()?.claude?.oauthToken}function pr(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 Rt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Oi(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=ke(e);r&&!t.force&&(console.error(`already configured at ${Ct(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Be({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};V(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${Ct(e)}`)}import{homedir as $n}from"node:os";import{join as xr}from"node:path";import{appendFileSync as Su,existsSync as Ni,mkdirSync as Cu,renameSync as Ui,statSync as Tu,unlinkSync as Ru}from"node:fs";import{Writable as Iu}from"node:stream";import{join as ju}from"node:path";var Li={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},It=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Cu(e.dir,{recursive:!0}),this.currentPath=ju(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
|
|
10
10
|
`)?e:e+`
|
|
11
|
-
|
|
11
|
+
`;Su(this.currentPath,r,"utf-8")}asWritable(){return new Iu({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||!Ni(this.currentPath)||Tu(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Ni(o)&&(r>=this.cfg.maxFiles?Ru(o):Ui(o,`${this.currentPath}.${r+1}`))}Ui(this.currentPath,`${this.currentPath}.1`)}}};function Vr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Pu(process.env[`${t}_MAX_BYTES`]??String(Li.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Li.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Pu(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 zr(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(Eu(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 Eu(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Au(n)).join(" ");return`${r} ${t} ${o}`}function Au(t){try{return JSON.stringify(t)}catch{return String(t)}}import{existsSync as Pa,rmSync as Wd}from"node:fs";import{join as $r}from"node:path";import{simpleGit as qd}from"simple-git";import"ws";import{createHash as _u}from"node:crypto";import{existsSync as Ou,readFileSync as Nu}from"node:fs";import{homedir as Uu,hostname as qo}from"node:os";import{join as Lu}from"node:path";function Di(t){return _u("sha256").update(t).digest("hex").slice(0,12)}function Du(){let t=L("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Lu(Uu(),".claude","credentials.json");if(!Ou(e))return;let r=JSON.parse(Nu(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 Bi(t){let e=Du(),r=L("ACCOUNT_ID")?.trim(),o=L("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=Tt(t);return n?{accountId:`acct-${Di(n)}`,label:o||qo(),...e?{email:e}:{}}:{accountId:`acct-${Di(`host:${qo()}`)}`,label:o||qo(),...e?{email:e}:{}}}import{existsSync as Bu}from"node:fs";import{join as Mu}from"node:path";import{simpleGit as Gu}from"simple-git";async function Mi(t,e){if(!Bu(Mu(t,".git")))return{status:"skipped"};let r=Gu(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Fu(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 Fu(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as Yo,readFileSync as Gi,readdirSync as Hu,watch as Ku}from"node:fs";import{join as Vo}from"node:path";var Jr=class{constructor(e,r,o,n,i=6e4){this.contextDir=e;this.projectId=r;this.send=o;this.log=n;this.intervalMs=i}timer=null;watcher=null;debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(Yo(this.contextDir))try{this.watcher=Ku(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=Vo(this.contextDir,e);if(!Yo(r))return null;try{return Gi(r,"utf-8")}catch{return null}}readPrompts(){let e=Vo(this.contextDir,"prompts"),r={};if(!Yo(e))return r;let o;try{o=Hu(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Gi(Vo(e,n),"utf-8")}catch{}}return r}};import{existsSync as Vi,readFileSync as zi,readdirSync as ep}from"node:fs";import{join as Ji}from"node:path";import{simpleGit as tp}from"simple-git";import{existsSync as Vu,mkdirSync as zu,writeFileSync as Ki}from"node:fs";import{dirname as Ju,isAbsolute as Xu,join as qi,normalize as Zo}from"node:path";import{simpleGit as Yi}from"simple-git";import{existsSync as Ye,mkdirSync as Fi,readFileSync as zo,writeFileSync as jt}from"node:fs";import{homedir as Wu}from"node:os";import{join as Pe}from"node:path";import{simpleGit as qu}from"simple-git";var Pt=["project.yaml","regimen.yaml"];function dr(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=Pe(t,n);Ye(s)||(jt(s,i),r.push(n))}return r}function mt(t,e,r){let o=Pe(Wu(),".codepipe","profiles",t,"context-config");return Fi(o,{recursive:!0}),jt(Pe(o,"project.yaml"),e.projectYaml),jt(Pe(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Xr(t,e,r){if(Ye(e))for(let o of Pt){let n=Pe(e,o),i=Pe(t,o);if(!(!Ye(n)||Ye(i)))try{jt(i,zo(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 Yu=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function Et(t){let e=Pe(t,".gitignore"),r=Ye(e)?zo(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(Pt.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
|
|
12
12
|
`)?"":`
|
|
13
|
-
`;return jt(e,r+i+
|
|
13
|
+
`;return jt(e,r+i+Yu.join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`),!0}async function
|
|
16
|
-
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;Et(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
|
|
17
|
-
`).map(r=>r.trim()).filter(Boolean)}function
|
|
18
|
-
`),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function
|
|
15
|
+
`),!0}async function Hi(t,e){try{if(!Ye(Pe(t,".git")))return;let r=qu(t),o=(await r.raw(["ls-files","--",...Pt])).split(`
|
|
16
|
+
`).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;Et(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 Qo(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 Jo(t){let e=new Map;for(let r of Pt){let o=Pe(t,r);Ye(o)&&e.set(r,zo(o))}return e}function Xo(t,e){Fi(t,{recursive:!0});for(let[r,o]of e){let n=Pe(t,r);Ye(n)||jt(n,o)}}var Wi=3,Qu=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function At(t,e,r){if(!Vu(qi(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Ve(t,i.path);zu(Ju(s),{recursive:!0}),i.encoding==="base64"?Ki(s,Buffer.from(i.content,"base64")):Ki(s,i.content)}let o=Yi(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...Pt]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await Qo(t))}async function Qo(t){let e=Yi(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Wi;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 Zu(e);if(i.length>0&&i.every(s=>Qu.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 ${Wi} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Zu(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
|
|
17
|
+
`).map(r=>r.trim()).filter(Boolean)}function Ve(t,e){if(Xu(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Zo(qi(t,e)),o=Zo(t+"/");if(r!==Zo(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var rp=/^(\d{4})-(.+)\.md$/,op="0000-template.md";function np(t){let e=t.split(`
|
|
18
|
+
`),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function ip(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
|
|
19
19
|
`),a=s.findIndex(w=>w.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),u=[],f="",p=null,g=a>=0?a+1:0;for(let w=g;w<s.length;w++){let y=(s[w]??"").trim();if(y===""){g=w+1;continue}let b=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(y);if(!b)break;let x=(b[1]??"").trim().toLowerCase(),O=(b[2]??"").trim(),j=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(y);j&&(p=parseInt(j[1]??"",10)),x==="tasks"&&(f=O),l.has(x)||u.push(y),g=w+1}let d=f?f.includes(o)?f:`${f}, ${o}`:o,h=s.slice(g).join(`
|
|
20
20
|
`).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${d}`,...u,"",h].join(`
|
|
21
21
|
`);return{content:S.endsWith(`
|
|
22
22
|
`)?S:S+`
|
|
23
|
-
`,supersedes:p}}function
|
|
23
|
+
`,supersedes:p}}function sp(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
|
|
24
24
|
|
|
25
|
-
- **Status:** superseded by ADR-${r}`):o}function
|
|
25
|
+
- **Status:** superseded by ADR-${r}`):o}function ap(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
|
|
26
26
|
`)+`
|
|
27
|
-
`}async function
|
|
28
|
-
`+t.slice(t.length-e)}async function Ve(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 Jr(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 ze(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 lp(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 lp(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Je(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 ts(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 Zo=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 mt(`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()}`)}},en=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 mt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let f of u.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let f of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${n}/actions/jobs/${d.id}/logs`,{headers:o});if(!h.ok)continue;let S=await h.text();u.push(`### CI job: ${d.name}
|
|
27
|
+
`}async function Xi(t,e,r,o=new Date().toISOString().slice(0,10)){try{await tp(t).pull(void 0,void 0,["--rebase"])}catch{}let n=[],i=[];for(let d of r){let h=Ve(t,`tasks/${e}/adr/DRAFT-${d}.md`);if(!Vi(h)){i.push(d);continue}n.push({slug:d,content:zi(h,"utf-8")})}let s=Ji(t,"adr"),a=new Map;if(Vi(s))for(let d of ep(s)){let h=rp.exec(d);!h||d===op||a.set(d,{num:parseInt(h[1]??"",10),slug:h[2]??"",content:zi(Ji(s,d),"utf-8")})}let c=Math.max(0,...[...a.values()].map(d=>d.num))+1,l=new Map,u=[],f=[];for(let d of n){if([...a.entries()].find(([,x])=>x.slug===d.slug&&x.content.includes(e))){f.push(d.slug);continue}let S=c++,w=`${String(S).padStart(4,"0")}-${d.slug}.md`,{content:y,supersedes:b}=ip(d.content,S,d.slug,e,o);if(l.set(w,y),a.set(w,{num:S,slug:d.slug,content:y}),u.push(`adr/${w}`),b!==null){let x=[...a.keys()].find(O=>O.startsWith(`${String(b).padStart(4,"0")}-`));if(x&&x!==w){let O=sp(l.get(x)??a.get(x).content,S);l.set(x,O),a.set(x,{...a.get(x),content:O})}}}if(u.length===0)return{promoted:u,skipped:f,missing:i};let p=[...a.entries()].map(([d,h])=>({num:h.num,file:d,header:np(h.content)}));l.set("INDEX.md",ap(p));let g=[...l.entries()].map(([d,h])=>({path:`adr/${d}`,content:h}));return await At(t,g,`adr(${e}): promote ${n.map(d=>d.slug).join(", ")}`),{promoted:u,skipped:f,missing:i}}import{existsSync as Qi,readFileSync as lp}from"node:fs";import{join as Zi}from"node:path";function up(t){for(let e of[Re,lr]){let r=Zi(t,e);if(Qi(r))try{return si(lp(r,"utf-8"))}catch{return 0}}return 0}function pp(t,e,r,o=2){let n=e<o,i=n?ai(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Qr(t,e){return pp(e,up(t),r=>Qi(Zi(t,r)))}import{existsSync as os,mkdirSync as Tp,mkdtempSync as Rp,rmSync as ns,writeFileSync as is}from"node:fs";import{tmpdir as Ip}from"node:os";import{dirname as jp,join as eo}from"node:path";import{simpleGit as nn}from"simple-git";var gt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function es(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
|
|
28
|
+
`+t.slice(t.length-e)}async function ze(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 Zr(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 Je(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 dp(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 dp(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Xe(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 rs(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 en=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let 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 gt(`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()}`)}},tn=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 gt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let u=await i.json();for(let f of u.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let u=await s.json();(u.total_count??0)>0&&(l=!0,u.state==="pending"?a=!0:(u.state==="failure"||u.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],u=[];for(let f of l.filter(p=>p.conclusion&&i.includes(p.conclusion))){let p=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!p.ok)continue;let g=(await p.json()).jobs??[];for(let d of g.filter(h=>h.conclusion==="failure")){let h=await fetch(`${n}/actions/jobs/${d.id}/logs`,{headers:o});if(!h.ok)continue;let S=await h.text();u.push(`### CI job: ${d.name}
|
|
29
29
|
|
|
30
|
-
${
|
|
30
|
+
${es(S,8e3)}`)}}return u.length===0?void 0:es(u.join(`
|
|
31
31
|
|
|
32
|
-
`),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},
|
|
32
|
+
`),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},rn=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 gt(`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=fp(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=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,s,a=await fetch(i,{headers:this.headers()});if(a.ok){let u=await a.json().catch(()=>null);s=u?.sha??u?.diff_refs?.head_sha}let c=await fetch(`${i}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n,...s?{sha:s}:{}})});if(!c.ok)throw new Error(`gitlab merge MR !${r}: ${c.status} ${await c.text()}`);let l=await c.json().catch(()=>null);return l?.merge_commit_sha?{mergedSha:l.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 fp(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}var on=class{name="mock";async createPullRequest(e,r){let 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(ts(e,r,"merge"))}async closePR(e,r,o){throw new Error(ts(e,r,"close"))}};function ts(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 Me(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new tn(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new en(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new rn(e)}return new on}function _t(t,e,r,o){return[{path:"README.md",content:vp(t,e)},{path:".gitignore",content:wp()},{path:"CLAUDE.md",content:kp(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:bp()},{path:"knowledge/README.md",content:$p()},{path:"knowledge/build.yaml",content:xp()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:yp()},{path:"adr/README.md",content:mp()},{path:"adr/0000-template.md",content:gp()},{path:"adr/INDEX.md",content:hp()},{path:Re,content:Dr()}]}function mp(){return`# ADR \u2014 architecture decision records
|
|
33
33
|
|
|
34
34
|
Accepted architectural decisions of this project \u2014 its **framework**. The
|
|
35
35
|
agent reads this section (start with \`INDEX.md\`) at the beginning of every
|
|
@@ -57,7 +57,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
|
|
|
57
57
|
canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
|
|
58
58
|
is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
|
|
59
59
|
open a PR to this repository.
|
|
60
|
-
`}function
|
|
60
|
+
`}function gp(){return`# ADR-NNNN: <title>
|
|
61
61
|
|
|
62
62
|
- **Status:** accepted | superseded by ADR-NNNN
|
|
63
63
|
- **Date:** YYYY-MM-DD
|
|
@@ -79,12 +79,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
|
|
|
79
79
|
## Alternatives considered
|
|
80
80
|
|
|
81
81
|
- **<alternative>** \u2014 why it was rejected.
|
|
82
|
-
`}function
|
|
82
|
+
`}function hp(){return`# ADR index
|
|
83
83
|
|
|
84
84
|
<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
|
|
85
85
|
|
|
86
86
|
(no accepted ADRs yet)
|
|
87
|
-
`}function
|
|
87
|
+
`}function yp(){return`# Audit
|
|
88
88
|
|
|
89
89
|
Pipeline event logs. Naming is per-writer: each codepipe
|
|
90
90
|
project appends only to its own file \u2014
|
|
@@ -93,14 +93,14 @@ project appends only to its own file \u2014
|
|
|
93
93
|
|
|
94
94
|
\u2014 so several team members' CLIs never contend on one file. Do not create a
|
|
95
95
|
shared aggregate here.
|
|
96
|
-
`}function
|
|
96
|
+
`}function Ee(t,e,r,o){return{projectYaml:Sp(t,r,o),regimenYaml:Cp(t.automationLevel,e)}}function wp(){return`# codepipe project config is local to each member's workspace
|
|
97
97
|
project.yaml
|
|
98
98
|
regimen.yaml
|
|
99
99
|
|
|
100
100
|
# codepipe runtime
|
|
101
101
|
session.log
|
|
102
102
|
apply-queue.json
|
|
103
|
-
`}function
|
|
103
|
+
`}function bp(){return`# Index prompt
|
|
104
104
|
|
|
105
105
|
You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
|
|
106
106
|
navigation map of this project's repositories and save it to the Context Repo, so
|
|
@@ -157,7 +157,7 @@ current working directory; write nothing else under the Context Repo.
|
|
|
157
157
|
Keep both durable and skimmable \u2014 they are read at the start of every future
|
|
158
158
|
task. Prefer structure (headings, bullet lists) over prose. If a repository is
|
|
159
159
|
empty or unavailable, say so briefly rather than inventing content.
|
|
160
|
-
`}function
|
|
160
|
+
`}function kp(t){return`# Project context for the CodePipe agent
|
|
161
161
|
|
|
162
162
|
Instructions for AI agents working on **${t.name}** tasks. Claude Code
|
|
163
163
|
auto-loads this file when the Context Repo is mounted. Keep it short and
|
|
@@ -185,7 +185,7 @@ project's architectural invariants: read them at the start of a task and treat
|
|
|
185
185
|
them as binding. New or changed decisions do **not** go here directly \u2014 during
|
|
186
186
|
analysis you draft them as task artifacts, and they are promoted into \`adr/\`
|
|
187
187
|
only after the analysis is approved.
|
|
188
|
-
`}function
|
|
188
|
+
`}function $p(){return`# Knowledge
|
|
189
189
|
|
|
190
190
|
Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
|
|
191
191
|
**memory** across tasks. Architectural decisions, domain rules,
|
|
@@ -202,7 +202,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
|
|
|
202
202
|
concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
|
|
203
203
|
REGENERATED from the entries by the index job: don't hand-edit it, and treat
|
|
204
204
|
any merge conflict in it as noise (either side converges on the next run).
|
|
205
|
-
`}function
|
|
205
|
+
`}function xp(){return`# BUILD phase config. Discovered & maintained by the agent.
|
|
206
206
|
# Steps run in a rootless Podman container in the SANDBOX, before the PR.
|
|
207
207
|
# Success = every step exits 0. Credentials are NOT available inside the container.
|
|
208
208
|
#
|
|
@@ -218,7 +218,7 @@ any merge conflict in it as noise (either side converges on the next run).
|
|
|
218
218
|
# - name: test
|
|
219
219
|
# run: npm test
|
|
220
220
|
# timeout_sec: 600 # per-step timeout (optional, default 600)
|
|
221
|
-
`}function
|
|
221
|
+
`}function vp(t,e){return`# ${e.name}
|
|
222
222
|
|
|
223
223
|
Context Repo for the **${t.name}** project (CodePipe).
|
|
224
224
|
|
|
@@ -244,7 +244,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
|
|
|
244
244
|
pipeline \u2014 don't edit them by hand.
|
|
245
245
|
|
|
246
246
|
Automation level: **${t.automationLevel}**.
|
|
247
|
-
`}function
|
|
247
|
+
`}function Sp(t,e,r){let o=e?`
|
|
248
248
|
tracker_url: ${e}`:`
|
|
249
249
|
# tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
|
|
250
250
|
assignee: ${r}`:`require_assignee: false
|
|
@@ -310,7 +310,7 @@ branch:
|
|
|
310
310
|
|
|
311
311
|
repos:
|
|
312
312
|
${s}
|
|
313
|
-
`}function
|
|
313
|
+
`}function Cp(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
|
|
314
314
|
automation:
|
|
315
315
|
level: ${t}
|
|
316
316
|
|
|
@@ -425,32 +425,32 @@ parallelism:
|
|
|
425
425
|
# # the previous task's branch (auto-merge without reworking the
|
|
426
426
|
# # tail of the chain).
|
|
427
427
|
# mode: parallel
|
|
428
|
-
`}function
|
|
429
|
-
`)}async function
|
|
430
|
-
${l.trim()}`)}}let i=
|
|
431
|
-
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function
|
|
432
|
-
${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([o,"--delete",n]).catch(()=>{}),{commit:h}}async function
|
|
433
|
-
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function Jp(t,e,r){return new Promise((o,n)=>{let i=Xe.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 xs(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function cn(t,e,r){return new Promise(o=>{let n=Xe.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 Xp(t){try{let e=await fetch(t);return e.ok?new xs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Rs(t,e=443,r=Ss){let o=`${t}:${e}`,n=$s.get(o);if(n)return n;let i=Qp(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return $s.set(o,i),i}async function Qp(t,e,r){if(!vs)return!1;let o=8e3;if(await cn(t,e,o))return!0;let n=await Jp(t,e,o),i=Xe.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=zp(n);if(!c)break;let l=await Xp(c);if(!l)break;if(s.push(l.toString()),Xe.setDefaultCACertificates([...i,...s]),await cn(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;n=l}return cn(t,e,o)}function Ee(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function me(t,e,r){Cs();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(Ts(s)&&await Rs(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Is=t=>new Promise(e=>setTimeout(e,t));function Zp(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function ed(){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 ln(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=ed(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await me(t,r,o)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<n&&Zp(l.status,u)){await Is(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<n){await Is(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Qe(t){let e;try{e=await me(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 Es(t){try{let e=await me(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var fr="Stage",js=new Map;async function td(t,e,r,o){let n=`${e.split("-")[0]}:${o}:${r}`,i=js.get(n);if(i)return i;let s=await me(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===o);if(!c)throw new Error(`yt: issue ${e} has no ${o} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${o} bundle for ${e}`);return js.set(n,l.id),l.id}async function As(t,e,r,o=fr){let n=await td(t,e,r,o);await ln(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:o,$type:"StateIssueCustomField",value:{id:n,$type:"StateBundleElement"}}]})})}async function _s(t,e,r){return await(await ln(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Os(t,e,r){let o={};r.summary!==void 0&&(o.summary=r.summary),r.description!==void 0&&(o.description=r.description),await ln(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(o)})}var Ps=new Map;async function Ns(t,e){let r=Ps.get(e);if(r)return r;let o=await me(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 Ps.set(e,i.id),i.id}async function Us(t,e,r,o,n,i=fr){let s=await Ns(t,e),a=await me(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:o,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ls(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await me(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 Ds="attachments(id,name,url,size,mimeType)",rd="links(direction,linkType(name),issues(idReadable))",Bs=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ds},${rd}`,od=`id,text,created,author(login),${Ds}`;function Ms(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 Gs(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 Fs(t,e){let r=e.stageField??fr,o=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");o.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);o.push(`updated: ${c} .. *`)}e.assignee?o.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&o.push("has: Assignee");let n=o.join(" "),i=`/api/issues?query=${encodeURIComponent(n)}&fields=${Bs}&$top=200`,s=await me(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ks(c,r))}async function ro(t,e,r=fr){let o=`/api/issues/${encodeURIComponent(e)}?fields=${Bs}`,n=await me(t,o);if(n.status===404)return null;if(!n.ok)throw new Error(`yt getIssue ${e}: ${n.status} ${await n.text()}`);return Ks(await n.json(),r)}async function Hs(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${od}&$top=500`,n=await me(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=Ms(s.attachments);return c&&(a.attachments=c),a})}function nd(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 Ks(t,e=fr){let r=t.customFields??[],o=r.find(l=>l.name===e),n=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:o?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),n?.value?.login&&(s.assignee=n.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Ms(t.attachments);a&&(s.attachments=a);let c=nd(t.links);return c&&(s.links=c),s}async function Ws(t,e){let r=await id(t,e);return r.length>0?r:sd(t,e)}async function id(t,e){let r=await Ns(t,e),o=await me(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!o.ok)return[];let n=await o.json(),i=[];for(let s of n)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:qs(s.bundle)});return i}async function sd(t,e){let r=`project: ${e}`,o=await me(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!o.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${o.status} ${await o.text()}`);let n=await o.json(),i=[];for(let s of n[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:qs(s.projectCustomField?.bundle)});return i}function qs(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function ke(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Ys(t,e){let r=U(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Qe({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:ke(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:ke(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await Ve(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:ke(c)}),n.push({kind:"github",present:!0,ok:!1,detail:ke(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await ze(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:ke(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:ke(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Je(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:ke(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:ke(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Jr(c,u.owner,u.repoName),o.push({name:`repo:${u.name}`,ok:!0})}catch(f){o.push({name:`repo:${u.name}`,ok:!1,detail:ke(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Jr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(u){o.push({name:"context-repo",ok:!1,detail:ke(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Jr(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:ke(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Tt(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await un(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function un(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function mr(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 gr(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 hr(t,e=process.env){if(!t)return!1;let r=`https://${pt}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function pn(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Vs(t,e=process.env){return pn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>mr(t,e),e)}function zs(t,e=process.env){return pn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>gr(t,e),e)}function Js(t,e=process.env){return pn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${pt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>hr(t,e),e)}function Xs(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=eo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},W(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Pe(e.sealKey.publicKey)}}async function Qs(t,e,r,o){let n;try{n=JSON.parse(to(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Ve(n.token);return i.github={token:n.token},Nt(i,()=>{process.env.GH_TOKEN=n.token,Vs(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Je(n.token);return i.gitlab={token:n.token},Nt(i,()=>{process.env.GITLAB_TOKEN=n.token,zs(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await ze(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},Nt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Js(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Qe({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},Nt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await un(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},Nt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},Nt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Nt(t,e){W(t),e()}import{existsSync as ad,readFileSync as cd,statSync as Zs}from"node:fs";var ea=2*1024*1024;function ld(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ta(t,e){let r=Ye(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!ad(r)||!Zs(r).isFile())throw new Error(`file not found: ${e}`);let{size:o}=Zs(r);if(o>ea)throw new Error(`file too large: ${e} is ${o} bytes (limit ${ea})`);let n=cd(r);return ld(n)?{content:n.toString("utf-8"),encoding:"utf8",sizeBytes:n.length}:{content:n.toString("base64"),encoding:"base64",sizeBytes:n.length}}import{existsSync as ud,readFileSync as pd,writeFileSync as dd}from"node:fs";import{join as fd}from"node:path";import{parseDocument as md}from"yaml";async function ra(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let n of e){let i=pi(n);if(!i.ok)throw new Error(i.error);let s=r.get(n.file)??[];s.push({path:i.field.path,value:i.value}),r.set(n.file,s)}let o=[];for(let[n,i]of r){let s=fd(t,n);if(!ud(s))throw new Error(`${n} not found in context repo (${t})`);let a=md(pd(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);dd(s,a.toString()),o.push(n)}return{files:o}}import{existsSync as gd,readFileSync as hd,writeFileSync as yd}from"node:fs";import{join as wd}from"node:path";import{parseDocument as bd}from"yaml";var oa=64;async function na(t,e){if(!Number.isInteger(e)||e<1||e>oa)throw new Error(`maxJobs must be an integer in [1, ${oa}], got ${e}`);let r=wd(t,"regimen.yaml");if(!gd(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=bd(hd(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),yd(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as dn,readFileSync as fn,writeFileSync as kd}from"node:fs";import{join as oo}from"node:path";import{parseDocument as mn}from"yaml";async function ia(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=oo(t,"project.yaml");if(!dn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=mn(fn(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=oo(t,"regimen.yaml");if(!dn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=mn(fn(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)kd(oo(t,i.path),i.content);return{files:r.map(i=>i.path)}}function no(t){if(!t)return"Stage";try{let e=oo(t,"project.yaml");if(!dn(e))return"Stage";let o=mn(fn(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof o=="string"&&o.trim().length>0?o.trim():"Stage"}catch{return"Stage"}}import{existsSync as sa,readFileSync as $d,readdirSync as xd}from"node:fs";function vd(t,e,r){let o=[];for(let n of r){let i=n.issue.key,s=Rd(t,i,n.attachments);o.push({path:`tasks/${i}/task.md`,content:Sd(n.issue,e,s)}),o.push({path:`tasks/${i}/comments.jsonl`,content:Td(Cd(t,i,n.comments))});for(let a of n.attachments)o.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return o}async function io(t,e,r){if(r.length===0)return;let o=vd(t,e,r),n=r.map(i=>i.issue.key);await At(t,o,`sync(${n.join(", ")}): task data`)}function Sd(t,e,r){let o=new Date(t.updatedAt).toISOString(),n=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${o}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){n.push("## Attachments","");for(let i of r)n.push(`- [${i}](attachments/${encodeURI(i)})`);n.push("")}return n.join(`
|
|
434
|
-
`)}function
|
|
435
|
-
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&o.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=
|
|
428
|
+
`}function Pp(t){return`codepipe/context-migration-v${t}`}function Ep(t){let e=ci(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 \`${Re}\` stamp (renamed from \`${lr}\``,"when the legacy file is present). 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(`
|
|
429
|
+
`)}async function ss(t,e,r,o){let n=nn(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Qr(t,e);if(!i.outdated)return i;let s=Pp(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 Ap(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return o.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Me(c),u=await l.findOpenPrByBranch?.(c,s)??null;if(u)return o.info(`[ctx] migration PR already open: ${u.url}`),{...i,migrationPrUrl:u.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Ep(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function Ap(t,e,r,o,n,i,s){let a=nn(t),c=Rp(eo(Ip(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={projectId:e,name:e,automationLevel:"assisted",repos:[]},u={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(_t(l,u).map(h=>[h.path,h.content])),p=0;for(let h of o.missingPaths){if(h===Re)continue;let S=f.get(h);if(S==null){s.warn(`[ctx] migration: no template for ${h} \u2014 skipped`);continue}let w=eo(c,h);os(w)||(Tp(jp(w),{recursive:!0}),is(w,S),p++)}is(eo(c,Re),Dr(o.currentVersion)),p++;let g=eo(c,lr);os(g)&&(ns(g,{force:!0}),p++);let d=nn(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 (${p} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),ns(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{existsSync as _p,readFileSync as Op,writeFileSync as Np}from"node:fs";import{homedir as Up}from"node:os";import{join as as}from"node:path";import{parseDocument as Lp}from"yaml";function Dp(t){let e={name:t.name,host:t.host,owner:t.owner,repo:t.repoName,mount_as:t.mountAs??t.name};return t.defaultBranch&&(e.default_branch=t.defaultBranch),e}function Bp(t,e){let r=Lp(t);return r.set("repos",e.map(Dp)),r.toString()}function Mp(t,e){let r=[as(Up(),".codepipe","profiles",t,"context-config","project.yaml")];return e&&r.push(as(e,"project.yaml")),r}function fr(t,e,r){let o=[],n=[];for(let i of Mp(t,r))if(_p(i))try{let s=Op(i,"utf-8"),a=Bp(s,e);a!==s&&(Np(i,a),o.push(i))}catch(s){n.push({path:i,error:s instanceof Error?s.message:String(s)})}return{updated:o,errors:n}}import{homedir as Gp}from"node:os";import{existsSync as Fp,mkdirSync as Hp}from"node:fs";import{join as sn}from"node:path";import{simpleGit as us}from"simple-git";var cs=t=>console.log(t);function ls(t){cs=t}function mr(t,e="info"){cs(t,e)}function $e(t,e,r){let o=r??sn(Gp(),".codepipe","repos");return sn(o,t,e)}async function to(t,e,r={}){let o=$e(t,e.name,r.baseDir),n=r.cloneUrlOverride??an(e);if(!Fp(sn(o,".git"))){Hp(o,{recursive:!0});let a=us();mr(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
|
|
430
|
+
${l.trim()}`)}}let i=us(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
|
|
431
|
+
${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function gr(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ps=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function ro(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&&mr(`[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 gr(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await gr(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...ps,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ds(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await gr(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await gr(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 fs(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:u,force:f}=r,p=await ds(t,i,()=>ro(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let g=`origin/${c}`;if(await gr(t,g)||(g=`origin/${u??c}`),(await t.revparse([g])).trim()===s)await t.raw(["branch","-f",a,p]),await t.checkout(a);else{await t.checkout(["-B",a,g]);try{await t.raw([...ps,"cherry-pick",p])}catch(w){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let y=w instanceof Error?w.message:String(w);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
|
|
432
|
+
${y.trim()}`)}}let h=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([o,"--delete",n]).catch(()=>{}),{commit:h}}async function ms(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,u=await ds(t,i,()=>ro(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,u]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:u,pushed:l}}async function gs(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 an(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{createCipheriv as Kp,createDecipheriv as Wp,createHash as qp,createPrivateKey as Yp,createPublicKey as cn,diffieHellman as hs,generateKeyPairSync as ys,hkdfSync as ws,randomBytes as Vp}from"node:crypto";var bs=Buffer.from("devpipe-sealedbox-v1","utf-8");function oo(){let{publicKey:t,privateKey:e}=ys("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function Ae(t){let e=Buffer.from(t,"base64");return(qp("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function Ot(t,e){let r=cn({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=ys("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=hs({privateKey:n,publicKey:r}),c=Buffer.from(ws("sha256",a,Buffer.concat([i,s]),bs,32)),l=Vp(12),u=Kp("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,p=Buffer.concat([u.update(f),u.final()]),g=u.getAuthTag(),d={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:g.toString("base64"),ct:p.toString("base64")};return Buffer.from(JSON.stringify(d),"utf-8").toString("base64")}function no(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=Yp({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=cn({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=cn(o).export({type:"spki",format:"der"}),a=hs({privateKey:o,publicKey:n}),c=Buffer.from(ws("sha256",a,Buffer.concat([i,s]),bs,32)),l=Wp("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}function zp(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 ks(t,e,r,o){let n=zp(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=qr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=Ot(a.publicKey,i)}catch(u){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${u instanceof Error?u.message:String(u)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:l})}return s}import{X509Certificate as vs}from"node:crypto";import{readFileSync as Jp}from"node:fs";import Qe from"node:tls";var Ss=typeof Qe.getCACertificates=="function"&&typeof Qe.setDefaultCACertificates=="function",$s=!1,xs=new Map,Cs=t=>console.warn(t);function Xp(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Ts(t=Cs){if($s)return;$s=!0;let e=L("EXTRA_CA_FILE");if(!(!e||!Ss))try{let r=Xp(Jp(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Qe.setDefaultCACertificates([...Qe.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 Rs(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 Qp(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
|
|
433
|
+
`)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function Zp(t,e,r){return new Promise((o,n)=>{let i=Qe.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 vs(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function ln(t,e,r){return new Promise(o=>{let n=Qe.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 ed(t){try{let e=await fetch(t);return e.ok?new vs(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Is(t,e=443,r=Cs){let o=`${t}:${e}`,n=xs.get(o);if(n)return n;let i=td(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return xs.set(o,i),i}async function td(t,e,r){if(!Ss)return!1;let o=8e3;if(await ln(t,e,o))return!0;let n=await Zp(t,e,o),i=Qe.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=Qp(n);if(!c)break;let l=await ed(c);if(!l)break;if(s.push(l.toString()),Qe.setDefaultCACertificates([...i,...s]),await ln(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;n=l}return ln(t,e,o)}function _e(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function he(t,e,r){Ts();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(Rs(s)&&await Is(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var js=t=>new Promise(e=>setTimeout(e,t));function rd(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function od(){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 un(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=od(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await he(t,r,o)}catch(u){a=new Error(`${e}: ${u instanceof Error?u.message:String(u)}`)}if(l){if(l.ok)return l;let u=await l.text();if(c<n&&rd(l.status,u)){await js(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${u}`)}if(c<n){await js(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Ze(t){let e;try{e=await he(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function As(t){try{let e=await he(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var hr="Stage",Ps=new Map;async function nd(t,e,r,o){let n=`${e.split("-")[0]}:${o}:${r}`,i=Ps.get(n);if(i)return i;let s=await he(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!s.ok)throw new Error(`yt resolveStateId ${e}: ${s.status} ${await s.text()}`);let c=(await s.json()).customFields.find(u=>u.name===o);if(!c)throw new Error(`yt: issue ${e} has no ${o} custom field`);let l=c.projectCustomField.bundle.values.find(u=>u.name===r);if(!l)throw new Error(`yt: state "${r}" not found in ${o} bundle for ${e}`);return Ps.set(n,l.id),l.id}async function _s(t,e,r,o=hr){let n=await nd(t,e,r,o);await un(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:o,$type:"StateIssueCustomField",value:{id:n,$type:"StateBundleElement"}}]})})}async function Os(t,e,r){return await(await un(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}async function Ns(t,e,r){let o={};r.summary!==void 0&&(o.summary=r.summary),r.description!==void 0&&(o.description=r.description),await un(t,`yt updateIssue ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify(o)})}var Es=new Map;async function Us(t,e){let r=Es.get(e);if(r)return r;let o=await he(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Es.set(e,i.id),i.id}async function Ls(t,e,r,o,n,i=hr){let s=await Us(t,e),a=await he(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:s},summary:r,description:o,customFields:[{name:i,$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!a.ok)throw new Error(`yt createIssue: ${a.status} ${await a.text()}`);let c=await a.json();return{id:c.id,key:c.idReadable}}async function Ds(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await he(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Bs="attachments(id,name,url,size,mimeType)",id="links(direction,linkType(name),issues(idReadable))",Ms=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Bs},${id}`,sd=`id,text,created,author(login),${Bs}`;function Gs(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 Fs(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 Hs(t,e){let r=e.stageField??hr,o=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let c=e.columns.map(l=>`{${l}}`).join(", ");o.push(`${r}: ${c}`)}if(e.updatedSince){let c=new Date(e.updatedSince).toISOString().slice(0,10);o.push(`updated: ${c} .. *`)}e.assignee?o.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&o.push("has: Assignee");let n=o.join(" "),i=`/api/issues?query=${encodeURIComponent(n)}&fields=${Ms}&$top=200`,s=await he(t,i);if(!s.ok)throw new Error(`yt listIssues: ${s.status} ${await s.text()}`);return(await s.json()).map(c=>Ws(c,r))}async function io(t,e,r=hr){let o=`/api/issues/${encodeURIComponent(e)}?fields=${Ms}`,n=await he(t,o);if(n.status===404)return null;if(!n.ok)throw new Error(`yt getIssue ${e}: ${n.status} ${await n.text()}`);return Ws(await n.json(),r)}async function Ks(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${sd}&$top=500`,n=await he(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Gs(s.attachments);return c&&(a.attachments=c),a})}function ad(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 Ws(t,e=hr){let r=t.customFields??[],o=r.find(l=>l.name===e),n=r.find(l=>l.name==="Assignee"),i=r.find(l=>l.name==="Type"),s={id:t.id,key:t.idReadable,title:t.summary,status:o?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(s.description=t.description),n?.value?.login&&(s.assignee=n.value.login),i?.value?.name&&(s.issueType=i.value.name),t.tags&&t.tags.length>0&&(s.tags=t.tags.map(l=>l.name));let a=Gs(t.attachments);a&&(s.attachments=a);let c=ad(t.links);return c&&(s.links=c),s}async function qs(t,e){let r=await cd(t,e);return r.length>0?r:ld(t,e)}async function cd(t,e){let r=await Us(t,e),o=await he(t,`/api/admin/projects/${encodeURIComponent(r)}/customFields?fields=$type,field(name),bundle(values(name,archived))&$top=100`);if(!o.ok)return[];let n=await o.json(),i=[];for(let s of n)s.$type==="StateProjectCustomField"&&s.field?.name&&i.push({name:s.field.name,values:Ys(s.bundle)});return i}async function ld(t,e){let r=`project: ${e}`,o=await he(t,`/api/issues?query=${encodeURIComponent(r)}&fields=customFields(name,$type,projectCustomField(bundle(values(name,archived))))&$top=1`);if(!o.ok)throw new Error(`yt fetchProjectStateFields ${e}: ${o.status} ${await o.text()}`);let n=await o.json(),i=[];for(let s of n[0]?.customFields??[])s.$type==="StateIssueCustomField"&&s.name&&i.push({name:s.name,values:Ys(s.projectCustomField?.bundle)});return i}function Ys(t){return(t?.values??[]).filter(e=>!!e.name&&e.archived!==!0).map(e=>e.name)}function xe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Vs(t,e){let r=U(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Ze({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:xe(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await ze(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:xe(c)}),n.push({kind:"github",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Je(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:xe(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Xe(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:xe(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:xe(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let u of e?.repos??[])if(u.host==="github")try{await Zr(c,u.owner,u.repoName),o.push({name:`repo:${u.name}`,ok:!0})}catch(f){o.push({name:`repo:${u.name}`,ok:!1,detail:xe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Zr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(u){o.push({name:"context-repo",ok:!1,detail:xe(u)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Zr(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:xe(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=Tt(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await pn(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function pn(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function yr(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 wr(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 br(t,e=process.env){if(!t)return!1;let r=`https://${dt}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function dn(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function zs(t,e=process.env){return dn(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>yr(t,e),e)}function Js(t,e=process.env){return dn(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>wr(t,e),e)}function Xs(t,e=process.env){return dn(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${dt}:${encodeURIComponent(t)}@bitbucket.org/`,()=>br(t,e),e)}function Qs(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=oo();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:Ae(e.sealKey.publicKey)}}async function Zs(t,e,r,o){let n;try{n=JSON.parse(no(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await ze(n.token);return i.github={token:n.token},Nt(i,()=>{process.env.GH_TOKEN=n.token,zs(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Xe(n.token);return i.gitlab={token:n.token},Nt(i,()=>{process.env.GITLAB_TOKEN=n.token,Js(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Je(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},Nt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Xs(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Ze({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},Nt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await pn(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},Nt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},Nt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function Nt(t,e){V(t),e()}import{existsSync as ud,readFileSync as pd,statSync as ea}from"node:fs";var ta=2*1024*1024;function dd(t){return Buffer.from(t.toString("utf-8"),"utf-8").equals(t)}function ra(t,e){let r=Ve(t,e);if(e.split("/").some(i=>i===".git"))throw new Error(`not a context file: ${e}`);if(!ud(r)||!ea(r).isFile())throw new Error(`file not found: ${e}`);let{size:o}=ea(r);if(o>ta)throw new Error(`file too large: ${e} is ${o} bytes (limit ${ta})`);let n=pd(r);return dd(n)?{content:n.toString("utf-8"),encoding:"utf8",sizeBytes:n.length}:{content:n.toString("base64"),encoding:"base64",sizeBytes:n.length}}import{existsSync as fd,readFileSync as md,writeFileSync as gd}from"node:fs";import{join as hd}from"node:path";import{parseDocument as yd}from"yaml";async function oa(t,e){if(e.length===0)return{files:[]};let r=new Map;for(let n of e){let i=di(n);if(!i.ok)throw new Error(i.error);let s=r.get(n.file)??[];s.push({path:i.field.path,value:i.value}),r.set(n.file,s)}let o=[];for(let[n,i]of r){let s=hd(t,n);if(!fd(s))throw new Error(`${n} not found in context repo (${t})`);let a=yd(md(s,"utf-8"));for(let c of i)c.value===null?a.deleteIn(c.path):a.setIn(c.path,c.value);gd(s,a.toString()),o.push(n)}return{files:o}}import{existsSync as wd,readFileSync as bd,writeFileSync as kd}from"node:fs";import{join as $d}from"node:path";import{parseDocument as xd}from"yaml";var na=64;async function ia(t,e){if(!Number.isInteger(e)||e<1||e>na)throw new Error(`maxJobs must be an integer in [1, ${na}], got ${e}`);let r=$d(t,"regimen.yaml");if(!wd(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=xd(bd(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),kd(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as fn,readFileSync as mn,writeFileSync as vd}from"node:fs";import{join as so}from"node:path";import{parseDocument as gn}from"yaml";async function sa(t,e){let r=[];if(e.stageField!==void 0||e.sourceColumns!==void 0||e.rejectColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=so(t,"project.yaml");if(!fn(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=gn(mn(i,"utf-8"));if(e.stageField!==void 0){let a=typeof e.stageField=="string"?e.stageField.trim():"";a&&a!=="Stage"?s.setIn(["youtrack","stage_field"],a):s.deleteIn(["youtrack","stage_field"])}if(e.rejectColumns!==void 0){let a=e.rejectColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);a.length>0?s.setIn(["youtrack","reject_columns"],a):s.deleteIn(["youtrack","reject_columns"])}if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=so(t,"regimen.yaml");if(!fn(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=gn(mn(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)vd(so(t,i.path),i.content);return{files:r.map(i=>i.path)}}function ao(t){if(!t)return"Stage";try{let e=so(t,"project.yaml");if(!fn(e))return"Stage";let o=gn(mn(e,"utf-8")).getIn(["youtrack","stage_field"]);return typeof o=="string"&&o.trim().length>0?o.trim():"Stage"}catch{return"Stage"}}import{existsSync as aa,readFileSync as Sd,readdirSync as Cd}from"node:fs";function Td(t,e,r){let o=[];for(let n of r){let i=n.issue.key,s=Pd(t,i,n.attachments);o.push({path:`tasks/${i}/task.md`,content:Rd(n.issue,e,s)}),o.push({path:`tasks/${i}/comments.jsonl`,content:jd(Id(t,i,n.comments))});for(let a of n.attachments)o.push({path:`tasks/${i}/attachments/${a.name}`,content:a.contentBase64,encoding:"base64"})}return o}async function co(t,e,r){if(r.length===0)return;let o=Td(t,e,r),n=r.map(i=>i.issue.key);await At(t,o,`sync(${n.join(", ")}): task data`)}function Rd(t,e,r){let o=new Date(t.updatedAt).toISOString(),n=[`# ${t.key}: ${t.title}`,"",`- **Project:** \`${e}\``,`- **Tracker status:** ${t.status||"(unknown)"}`,`- **Assignee:** ${t.assignee??"(unassigned)"}`,`- **Updated:** ${o}`,"","---","",t.description??"_(no description)_",""];if(r.length>0){n.push("## Attachments","");for(let i of r)n.push(`- [${i}](attachments/${encodeURI(i)})`);n.push("")}return n.join(`
|
|
434
|
+
`)}function Id(t,e,r){let o=new Map,n=Ve(t,`tasks/${e}/comments.jsonl`);if(aa(n))for(let i of Sd(n,"utf-8").split(`
|
|
435
|
+
`)){let s=i.trim();if(s)try{let a=JSON.parse(s);a&&typeof a.id=="string"&&o.set(a.id,a)}catch{}}for(let i of r){let s={id:i.id,author:i.author,origin:"youtrack",body:i.body,createdAt:new Date(i.createdAt).toISOString()},a=Mr(i.body);a&&(s.parsedCommand=a),o.set(i.id,s)}return[...o.values()].sort((i,s)=>i.createdAt.localeCompare(s.createdAt))}function jd(t){return t.map(e=>JSON.stringify(e)).join(`
|
|
436
436
|
`)+(t.length>0?`
|
|
437
|
-
`:"")}function
|
|
438
|
-
`,{mode:384})}function Ud(t){return ca()[t]}function ao(t,e){let r=ca();r[t]=e,Nd(r)}function co(t,e){let r=Pe(e),o=Ud(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 ${hn()}.`);return r}import Ld from"ws";function lo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Ld(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function Ze(t,e,r){return Be(t,e,"/projects",r)}async function la(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 uo(t,e,r,o){return Be(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function ua(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function po(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 pa(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 yr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function da(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 yr(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function fa(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 ma(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 ga(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 ha(t,e,r,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function ya(t,e,r,o,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function wa(t,e,r,o,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ba(t,e,r,o,n){return Be(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function fo(t,e,r,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function yn(t,e,r,o){await Be(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function ka(t,e,r,o){return Be(t,e,`/projects/${encodeURIComponent(r)}/repos`,o)}async function $a(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function F(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 Be(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function Ca(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=Pe(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");co(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return n("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await F(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Sa(r,"project.yaml"),g=Sa(r,"regimen.yaml");xa(p)&&xa(g)?c={projectYaml:va(p,"utf-8"),regimenYaml:va(g,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Ot(e.farmPublicKey,JSON.stringify(l));ao(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await uo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var mo=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=De(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 mt){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=De(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=Dd(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function Dd(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var go=class t{constructor(e,r,o,n={contextDir:null}){this.intervalMs=e;this.send=r;this.log=o;this.options=n}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let e=Ee();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 b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Fs(r,{projectKey:e.projectKey,columns:b,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(b){this.log.warn(`[yt-sync] listIssues failed: ${b instanceof Error?b.message:String(b)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let b of n){if(s.add(b.id),a.has(b.status))continue;let x=await Ra(r,b.id,e.sinceMs,this.log);x&&i.set(b.id,x)}let c=[];for(let b of e.offBoardIssueIds){if(s.has(b))continue;let x=await Ra(r,b,e.sinceMs,this.log);if(x&&x.length>0&&i.set(b,x),e.requireAssignee||x&&x.length>0){let O=await Gd(r,b,e.stageField,this.log);if(O)c.push(O);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=n.filter(b=>!a.has(b.status)),{attachmentsByIssue:u,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(b=>({issue:b,comments:i.get(b.id)??[],attachments:u.get(b.id)??[]}));try{await io(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let b of f)this.shippedAttachments.add(b)}catch(b){let x=b instanceof Error?b.message:String(b);this.abandonTick(`context task sync failed: ${x}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[b,x]of i){let O=x.filter(v=>!g(v.id));if(O.length===0)continue;d.push({issueId:b,comments:O.map(Bd)});let j=O.flatMap(v=>{let m=Lr(v.body);return m?[{commentId:v.id,author:v.author,name:m.name,args:m.args,createdAt:v.createdAt}]:[]});j.length>0&&h.push({issueId:b,commands:j})}let S={type:"youtrack_observation",projectId:e.projectId,issues:n.map(Ta),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ta)}:{},observedAtMs:o};this.send(S);let w=d.reduce((b,x)=>b+x.comments.length,0),y=h.reduce((b,x)=>b+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,o){let n=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Gs(o,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=Md(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&n.set(s.id,c)}return{attachmentsByIssue:n,attachmentKeys:i}}};function Ta(t){let{description:e,...r}=t;return r}function Bd(t){let{body:e,...r}=t;return r}function Md(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 Gd(t,e,r,o){try{return await ro(t,e,r)}catch(n){return o.warn(`[yt-sync] getIssue ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}async function Ra(t,e,r,o){try{return await Hs(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var wn="npm i -g @code-partner/codepipe@latest";function ho(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${pe} (protocol ${Se})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Fi(n.contextDir,r);let i=Ia("CLI_TRACKING_POLL_INTERVAL_SEC"),s=Ia("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,u=new Set,f=new Set,p=g();function g(){let d=lo(t.hubUrl,t.cliToken),h=null,S=new mo(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),w=new go(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:n?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,b=async()=>{try{let m;try{let C=await F(t.hubUrl,t.cliToken,t.projectId);m={repos:C.repos,contextRepo:C.contextRepo}}catch(C){r.warn(`[readiness] could not fetch project summary for push checks: ${C instanceof Error?C.message:String(C)}`)}let R=await Ys(t.projectId,m);if(d.readyState!==d.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,checkedAt:R.checkedAt};if(d.send(JSON.stringify(k)),R.ready)r.info("[readiness] ready");else{let C=R.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${C.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},x=()=>{b(),y=setInterval(()=>void b(),a),typeof y.unref=="function"&&y.unref()},O=()=>{y&&(clearInterval(y),y=null)},j=n?.contextDir?new Yr(n.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,v=async()=>{let m=n?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let R;try{R=(await F(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let k=await is(m,t.projectId,R,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(k)),k};return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let m=Di(t.projectId),R=L("ORIGIN")==="farm"?"farm":"local",k=L("FARM_ID"),C=t.accountEmail??m.email,I;try{let P=Xs(t.projectId);P&&(I=P.publicKey,r.info(`[cred-channel] key fingerprint: ${P.fingerprint}`))}catch(P){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${P instanceof Error?P.message:String(P)}`)}let $={type:"register",projectId:t.projectId,platformVersion:pe,protocolVersion:Se,accountId:m.accountId,accountLabel:m.label,origin:R,inFlightActionIds:[...u],...C?{accountEmail:C}:{},...R==="farm"&&k?{farmId:k}:{},...I?{sealPublicKey:I}:{}};d.send(JSON.stringify($))}),d.on("message",async m=>{let R=m.toString("utf-8");if(R==="pong"||R==="ping")return;let k;try{k=JSON.parse(R)}catch{return}if(!k||typeof k!="object")return;let C=k.type;if(C==="registered"){let $=k;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),S.start(),j?.start(),x(),bn(t,n,r),n?.contextDir)try{let P=zr(n.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,v().catch(()=>{})))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(C==="hello"){let $=k;h=Or($.protocolVersion);let P=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${P}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${pe}, protocol ${Se}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${wn}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:wn}));return}if(C==="tracking_targets"){S.setTargets(k.targets);return}if(C==="youtrack_sync_request"){w.setRequest(k);return}if(C==="youtrack_force_sync"){w.forceSync();return}if(C==="sync_local"){await qd(k,n,d,r);return}if(C==="provision_repo"){let $=k;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await Kd(t,n,$.repo,r),await bn(t,n,r);return}if(C==="remove_repo"){let $=k;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await bn(t,n,r),$.purge&&Wd(t,n,$.repoName,r);return}if(C==="context_write"){await Yd(k,n,d,r);return}if(C==="adr_promote"){await Vd(k,n,d,r);return}if(C==="cred_update"){let $=k,P=U(t.projectId),B=P?.sealKey?await Qs(t.projectId,$.kind,$.sealed,P.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},K={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(K)),B.ok?(r.info(`[cred] ${$.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),b()):r.warn(`[cred] ${$.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(C==="move_to_farm"){let $=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let P=await Ca(t,$,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.ok?r.info(`[farm-move] done \u2014 farm daemon ${P.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${P.error??"unknown error"}`);return}if(C==="tracker_fields_request"){let $=k,P={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},B=Ee();if(!B)P.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{P.fields=await Ws(B,$.projectKey),P.ok=!0}catch(K){P.error=K instanceof Error?K.message:String(K)}d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.ok||r.warn(`[yt-fields] listing failed: ${P.error??"unknown"}`);return}if(C==="sandbox_keys"){let $=U(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let P=Tt(t.projectId),B=bs(k,$,P,r);for(let K of B)d.readyState===d.OPEN&&d.send(JSON.stringify(K));return}if(C!=="dispatch_action")return;let I=k;if(h===!1){let $=`refused: HUB protocol incompatible with CLI v${pe} (protocol ${Se})`;d.send(JSON.stringify({type:"action_result",actionId:I.actionId,status:"failed",error:$})),r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${wn}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:!1,error:$});return}u.add(I.actionId);try{let $=await aa({action:I.action,repo:I.repo,trackerIssueId:I.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:j?()=>j.reportNow():void 0,refreshContextStatus:n?.contextDir?v:void 0}).catch(K=>({status:"failed",error:K instanceof Error?K.message:String(K)}));I.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&f.add($.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:I.actionId,...$}));let P=$.status!=="failed",B=!P&&"error"in $?$.error:void 0;P?r.info(`[exec] ${I.actionId} (${I.action.type}) \u2192 done`):r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 FAILED: ${B??"?"}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:P,...B?{error:B}:{}})}finally{u.delete(I.actionId)}}),d.on("close",(m,R)=>{let k=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${k?` reason=${k}`:""}`),S.stop(),w.stop(),j?.stop(),O(),k==="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:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function bn(t,e,r){try{let o=await F(t.hubUrl,t.cliToken,t.projectId),{updated:n,errors:i}=ur(t.projectId,o.repos,e?.contextDir);for(let s of n)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(o){r.warn(`[repo] repo-set reconcile skipped: ${o instanceof Error?o.message:String(o)}`)}}async function Kd(t,e,r,o){let n=r.mountAs??r.name;if(n==="."){o.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?wr(e.root,n):be(t.projectId,r.name);if(ja(wr(i,".git"))){o.info(`[repo] ${r.name} already present at ${i}`);return}try{await Hd().clone(sn(r),i),o.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){o.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function Wd(t,e,r,o){let n=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?wr(e.root,n):be(t.projectId,r);if(e&&i===e.root){o.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!ja(wr(i,".git"))){o.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Fd(i,{recursive:!0,force:!0}),o.info(`[repo] purged local clone ${i}`)}catch(s){o.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function qd(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=wr(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await Bi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Yd(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 At(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 Vd(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 Ji(e.contextDir,t.taskKey,t.slugs);if(o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;o.warn(`[adr] adr_promote ${t.id}: ${s}`),n("failed",s);return}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 Ia(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Ua,mkdirSync as La}from"node:fs";import{dirname as Da}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as zd}from"node:child_process";import{mkdtempSync as Jd,mkdirSync as Xd,readFileSync as Pa,rmSync as Qd,writeFileSync as Zd}from"node:fs";import{tmpdir as ef}from"node:os";import{dirname as tf,join as Ea}from"node:path";function Aa(t="codepipe-context"){let e=Jd(Ea(ef(),"codepipe-ssh-")),r=Ea(e,"id_ed25519");try{return zd("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Pa(r,"utf-8"),publicKey:Pa(`${r}.pub`,"utf-8").trim()}}finally{Qd(e,{recursive:!0,force:!0})}}async function _a(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 Oa(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function Na(t,e){Xd(tf(t),{recursive:!0});let r=e.endsWith(`
|
|
437
|
+
`:"")}function Pd(t,e,r){let o=[],n=Ve(t,`tasks/${e}/attachments`);if(aa(n))for(let i of Cd(n))o.push(i);for(let i of r)o.includes(i.name)||o.push(i.name);return o}var lo=new Map;async function hn(t,e){let o=(lo.get(t)??Promise.resolve()).catch(()=>{}).then(e);lo.set(t,o);try{return await o}finally{lo.get(t)===o&&lo.delete(t)}}async function ca(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;mr(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return hn(`${i}/${r.name}`,async()=>{let s=await to(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c}=await fs(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 i=e.taskId.split(":",2)[0]??"?";return hn(`${i}/${r.name}`,async()=>{let s=await to(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{commit:c,pushed:l}=await ms(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:l})})}case"create_pr":{if(!r)return H("no repo spec");let i=Me(r),s=await i.createPullRequest(r,e);return Q({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return H("no repo spec");let i=Me(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Q({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return H("no repo spec");let i=Me(r);return await i.closePR(r,e.prNumber,e.comment),Q({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return hn(`${i}/${r.name}`,async()=>{let s=await to(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=$e(i,r.name,t.baseDir),{mergedSha:c}=await gs(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 i=_e();return i?t.trackerIssueId?(await _s(i,t.trackerIssueId,e.newStatus,ao(t.contextDir)),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 i=_e();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await Os(i,t.trackerIssueId,e.body);return Q({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=_e();if(!i)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 Ls(i,e.projectKey,e.title,e.body,e.targetStatus,ao(t.contextDir));return Q({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=_e();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ds(i,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 i=await ia(t.contextDir,e.maxJobs);return Q({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_project_setting":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await oa(t.contextDir,e.edits);return Q({files:i.files})}case"tracker_edit":{let i=_e();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.contextDir)return H("no context repo clone on this CLI");let s=ao(t.contextDir);await Ns(i,e.issueKey,{...e.title!==void 0?{summary:e.title}:{},...e.body!==void 0?{description:e.body}:{}});let a=await io(i,e.issueKey,s);return a&&await co(t.contextDir,e.projectId,[{issue:a,comments:[],attachments:[]}]),Q({issueKey:e.issueKey})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await sa(t.contextDir,e);return Q({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Q({reported:!0})):H("no context repo clone on this CLI");case"refresh_context_status":{if(!t.refreshContextStatus)return H("no context repo clone on this CLI");let i=await t.refreshContextStatus();return Q({outdated:i.outdated,templateVersion:i.templateVersion})}case"read_context_file":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=ra(t.contextDir,e.path);return Q({path:e.path,...i})}default:return H(`unsupported action type: ${e.type}`)}}catch(i){return H(i instanceof Error?i.message:String(i))}}function Q(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}import{existsSync as va,readFileSync as Sa}from"node:fs";import{join as Ca}from"node:path";import{homedir as Ed}from"node:os";import{existsSync as Ad,mkdirSync as _d,readFileSync as Od,writeFileSync as Nd}from"node:fs";import{dirname as Ud,join as Ld}from"node:path";function yn(){return L("FARM_PINS")??Ld(Ed(),".codepipe","farm-pins.json")}function la(){let t=yn();if(!Ad(t))return{};try{return JSON.parse(Od(t,"utf-8"))}catch{return{}}}function Dd(t){let e=yn();_d(Ud(e),{recursive:!0}),Nd(e,JSON.stringify(t,null,2)+`
|
|
438
|
+
`,{mode:384})}function Bd(t){return la()[t]}function uo(t,e){let r=la();r[t]=e,Dd(r)}function po(t,e){let r=Ae(e),o=Bd(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 ${yn()}.`);return r}import Md from"ws";function fo(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new Md(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function et(t,e,r){return Ge(t,e,"/projects",r)}async function ua(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 mo(t,e,r,o){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function pa(t,e){let r=await fetch(`${t}/sandbox/me`,{headers:{Authorization:`Bearer ${e}`}});if(r.ok)return"ok";if(r.status===401)return"unknown";if(r.status===404)return"unsupported";throw new A(r.status,null,`GET /sandbox/me HTTP ${r.status}`)}async function go(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 da(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 kr=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function fa(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 kr(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function ma(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 ga(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 ha(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 ya(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function wa(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function ba(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ka(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function ho(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function wn(t,e,r,o){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function $a(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/repos`,o)}async function xa(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/repos/${encodeURIComponent(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e}`}}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function K(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 Ge(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function Ta(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=Ae(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");po(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return n("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await K(t.hubUrl,t.cliToken,t.projectId),c;if(r){let p=Ca(r,"project.yaml"),g=Ca(r,"regimen.yaml");va(p)&&va(g)?c={projectYaml:Sa(p,"utf-8"),regimenYaml:Sa(g,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},u=Ot(e.farmPublicKey,JSON.stringify(l));uo(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await mo(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:u});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var yo=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=Me(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 gt){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=Me(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=Gd(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function Gd(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var wo=class t{constructor(e,r,o,n={contextDir:null}){this.intervalMs=e;this.send=r;this.log=o;this.options=n}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;abandonedTicks=0;static MAX_ABANDONED_TICKS=3;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async forceSync(){if(!this.request){this.log.info("[yt-sync] force requested but no sync_request yet \u2014 ignored");return}this.log.info("[yt-sync] force sync requested (manual)"),await this.tick()}async tick(){if(this.running||!this.request)return;let e=_e();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 b=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.doneColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Hs(r,{projectKey:e.projectKey,columns:b,...e.stageField?{stageField:e.stageField}:{},...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(b){this.log.warn(`[yt-sync] listIssues failed: ${b instanceof Error?b.message:String(b)}`);return}let i=new Map,s=new Set,a=new Set(e.doneColumns??[]);for(let b of n){if(s.add(b.id),a.has(b.status))continue;let x=await Ia(r,b.id,e.sinceMs,this.log);x&&i.set(b.id,x)}let c=[];for(let b of e.offBoardIssueIds){if(s.has(b))continue;let x=await Ia(r,b,e.sinceMs,this.log);if(x&&x.length>0&&i.set(b,x),e.requireAssignee||x&&x.length>0){let O=await Kd(r,b,e.stageField,this.log);if(O)c.push(O);else if(x&&x.length>0){this.abandonTick("off-board issue fetch failed with new comments");return}}}let l=n.filter(b=>!a.has(b.status)),{attachmentsByIssue:u,attachmentKeys:f}=await this.collectAttachments(l,i,r);if(!this.options.contextDir){this.abandonTick("no Context Repo clone (headless / clone failed) \u2014 cannot deliver task content");return}let p=[...l,...c].map(b=>({issue:b,comments:i.get(b.id)??[],attachments:u.get(b.id)??[]}));try{await co(this.options.contextDir,e.projectId,p),this.abandonedTicks=0;for(let b of f)this.shippedAttachments.add(b)}catch(b){let x=b instanceof Error?b.message:String(b);this.abandonTick(`context task sync failed: ${x}`);return}let g=this.options.isSelfComment??(()=>!1),d=[],h=[];for(let[b,x]of i){let O=x.filter(v=>!g(v.id));if(O.length===0)continue;d.push({issueId:b,comments:O.map(Fd)});let j=O.flatMap(v=>{let m=Mr(v.body);return m?[{commentId:v.id,author:v.author,name:m.name,args:m.args,createdAt:v.createdAt}]:[]});j.length>0&&h.push({issueId:b,commands:j})}let S={type:"youtrack_observation",projectId:e.projectId,issues:n.map(Ra),commentsBatch:d,...h.length>0?{commandsBatch:h}:{},...e.requireAssignee&&c.length>0?{offBoardIssues:c.map(Ra)}:{},observedAtMs:o};this.send(S);let w=d.reduce((b,x)=>b+x.comments.length,0),y=h.reduce((b,x)=>b+x.commands.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${w} commands=${y} (sinceMs=${e.sinceMs})`)}abandonTick(e){this.abandonedTicks++,this.abandonedTicks<=t.MAX_ABANDONED_TICKS?this.log.warn(`[yt-sync] ${e} \u2014 tick abandoned (${this.abandonedTicks}/${t.MAX_ABANDONED_TICKS}), will retry`):this.log.warn(`[yt-sync] ERROR: ${e} \u2014 still failing after ${this.abandonedTicks} ticks; the project is STALLED until the Context Repo clone is restored`)}async collectAttachments(e,r,o){let n=new Map,i=[];for(let s of e){let a=[...s.attachments??[]];for(let u of r.get(s.id)??[])a.push(...u.attachments??[]);if(a.length===0)continue;let c=[],l=new Set;for(let u of a){let f=`${s.id}:${u.id}`;if(this.shippedAttachments.has(f))continue;let p;try{p=await Fs(o,u.url)}catch(d){this.log.warn(`[yt-sync] attachment ${u.name} (${s.id}) download failed: ${d instanceof Error?d.message:String(d)}`);continue}let g=Hd(u.name);l.has(g)&&(g=`${u.id}-${g}`),l.add(g),c.push({name:g,contentBase64:p.toString("base64")}),i.push(f)}c.length>0&&n.set(s.id,c)}return{attachmentsByIssue:n,attachmentKeys:i}}};function Ra(t){let{description:e,...r}=t;return r}function Fd(t){let{body:e,...r}=t;return r}function Hd(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 Kd(t,e,r,o){try{return await io(t,e,r)}catch(n){return o.warn(`[yt-sync] getIssue ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}async function Ia(t,e,r,o){try{return await Ks(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var bn="npm i -g @code-partner/codepipe@latest";function bo(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${fe} (protocol ${Te})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Hi(n.contextDir,r);let i=ja("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ja("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,u=new Set,f=new Set,p=g();function g(){let d=fo(t.hubUrl,t.cliToken),h=null,S=new yo(i,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r),w=new wo(s,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r,{contextDir:n?.contextDir??null,isSelfComment:m=>f.has(m)}),y=null,b=async()=>{try{let m;try{let C=await K(t.hubUrl,t.cliToken,t.projectId);m={repos:C.repos,contextRepo:C.contextRepo}}catch(C){r.warn(`[readiness] could not fetch project summary for push checks: ${C instanceof Error?C.message:String(C)}`)}let R=await Vs(t.projectId,m);if(d.readyState!==d.OPEN)return;let k={type:"cli_readiness",projectId:t.projectId,ready:R.ready,checks:R.checks,creds:R.creds,checkedAt:R.checkedAt};if(d.send(JSON.stringify(k)),R.ready)r.info("[readiness] ready");else{let C=R.checks.filter(I=>!I.ok).map(I=>`${I.name}(${I.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${C.join(", ")}`)}}catch(m){r.warn(`[readiness] check failed: ${m instanceof Error?m.message:String(m)}`)}},x=()=>{b(),y=setInterval(()=>void b(),a),typeof y.unref=="function"&&y.unref()},O=()=>{y&&(clearInterval(y),y=null)},j=n?.contextDir?new Jr(n.contextDir,t.projectId,m=>{d.readyState===d.OPEN&&d.send(JSON.stringify(m))},r):null,v=async()=>{let m=n?.contextDir;if(!m)throw new Error("no context repo clone on this CLI");let R;try{R=(await K(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let k=await ss(m,t.projectId,R,r);return d.readyState===d.OPEN&&d.send(JSON.stringify(k)),k};return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let m=Bi(t.projectId),R=L("ORIGIN")==="farm"?"farm":"local",k=L("FARM_ID"),C=t.accountEmail??m.email,I;try{let P=Qs(t.projectId);P&&(I=P.publicKey,r.info(`[cred-channel] key fingerprint: ${P.fingerprint}`))}catch(P){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${P instanceof Error?P.message:String(P)}`)}let $={type:"register",projectId:t.projectId,platformVersion:fe,protocolVersion:Te,accountId:m.accountId,accountLabel:m.label,origin:R,inFlightActionIds:[...u],...C?{accountEmail:C}:{},...R==="farm"&&k?{farmId:k}:{},...I?{sealPublicKey:I}:{}};d.send(JSON.stringify($))}),d.on("message",async m=>{let R=m.toString("utf-8");if(R==="pong"||R==="ping")return;let k;try{k=JSON.parse(R)}catch{return}if(!k||typeof k!="object")return;let C=k.type;if(C==="registered"){let $=k;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),S.start(),j?.start(),x(),kn(t,n,r),n?.contextDir)try{let P=Qr(n.contextDir,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,v().catch(()=>{})))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(C==="hello"){let $=k;h=Lr($.protocolVersion);let P=h?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${P}`),h||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${fe}, protocol ${Te}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${bn}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:bn}));return}if(C==="tracking_targets"){S.setTargets(k.targets);return}if(C==="youtrack_sync_request"){w.setRequest(k);return}if(C==="youtrack_force_sync"){w.forceSync();return}if(C==="sync_local"){await zd(k,n,d,r);return}if(C==="provision_repo"){let $=k;r.info(`[repo] provision_repo: ${$.repo.name} (${$.repo.host}:${$.repo.owner}/${$.repo.repoName})`),await Yd(t,n,$.repo,r),await kn(t,n,r);return}if(C==="remove_repo"){let $=k;r.info(`[repo] remove_repo: ${$.repoName}${$.purge?" (purge)":""}`),await kn(t,n,r),$.purge&&Vd(t,n,$.repoName,r);return}if(C==="context_write"){await Jd(k,n,d,r);return}if(C==="adr_promote"){await Xd(k,n,d,r);return}if(C==="cred_update"){let $=k,P=U(t.projectId),B=P?.sealKey?await Zs(t.projectId,$.kind,$.sealed,P.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},q={type:"cred_update_result",updateId:$.updateId,projectId:t.projectId,ok:B.ok,...B.detail?{detail:B.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(q)),B.ok?(r.info(`[cred] ${$.kind} replaced${B.detail?` \u2014 ${B.detail}`:""}`),b()):r.warn(`[cred] ${$.kind} replacement rejected: ${B.detail??"unknown"}`);return}if(C==="move_to_farm"){let $=k;r.info(`[farm-move] request to move ${t.projectId} onto farm ${$.farmName} (${$.farmId})`);let P=await Ta(t,$,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.ok?r.info(`[farm-move] done \u2014 farm daemon ${P.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${P.error??"unknown error"}`);return}if(C==="tracker_fields_request"){let $=k,P={type:"tracker_fields_result",requestId:$.requestId,projectId:t.projectId,ok:!1},B=_e();if(!B)P.error="YOUTRACK_URL/YOUTRACK_TOKEN not set on this CLI";else try{P.fields=await qs(B,$.projectKey),P.ok=!0}catch(q){P.error=q instanceof Error?q.message:String(q)}d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.ok||r.warn(`[yt-fields] listing failed: ${P.error??"unknown"}`);return}if(C==="sandbox_keys"){let $=U(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let P=Tt(t.projectId),B=ks(k,$,P,r);for(let q of B)d.readyState===d.OPEN&&d.send(JSON.stringify(q));return}if(C!=="dispatch_action")return;let I=k;if(h===!1){let $=`refused: HUB protocol incompatible with CLI v${fe} (protocol ${Te})`;d.send(JSON.stringify({type:"action_result",actionId:I.actionId,status:"failed",error:$})),r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${bn}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:!1,error:$});return}u.add(I.actionId);try{let $=await ca({action:I.action,repo:I.repo,trackerIssueId:I.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:j?()=>j.reportNow():void 0,refreshContextStatus:n?.contextDir?v:void 0}).catch(q=>({status:"failed",error:q instanceof Error?q.message:String(q)}));I.action.type==="tracker_comment"&&$.status==="done"&&"result"in $&&typeof $.result?.commentId=="string"&&f.add($.result.commentId),d.send(JSON.stringify({type:"action_result",actionId:I.actionId,...$}));let P=$.status!=="failed",B=!P&&"error"in $?$.error:void 0;P?r.info(`[exec] ${I.actionId} (${I.action.type}) \u2192 done`):r.warn(`[exec] ${I.actionId} (${I.action.type}) \u2192 FAILED: ${B??"?"}`),o({kind:"action",actionId:I.actionId,actionType:I.action.type,ok:P,...B?{error:B}:{}})}finally{u.delete(I.actionId)}}),d.on("close",(m,R)=>{let k=R?.toString("utf-8")??"";if(r.info(`[ws] closed code=${m}${k?` reason=${k}`:""}`),S.stop(),w.stop(),j?.stop(),O(),k==="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:m}),!c&&setTimeout(()=>{p=g()},2e3)}),d.on("error",m=>r.warn(`[ws] error: ${m.message}`)),d}return{stop(){c=!0,p.close()}}}async function kn(t,e,r){try{let o=await K(t.hubUrl,t.cliToken,t.projectId),{updated:n,errors:i}=fr(t.projectId,o.repos,e?.contextDir);for(let s of n)r.info(`[repo] restaged repo set in ${s}`);for(let s of i)r.warn(`[repo] could not restage ${s.path}: ${s.error}`)}catch(o){r.warn(`[repo] repo-set reconcile skipped: ${o instanceof Error?o.message:String(o)}`)}}async function Yd(t,e,r,o){let n=r.mountAs??r.name;if(n==="."){o.info(`[repo] ${r.name} mounts in place (mount_as: .) \u2014 nothing to clone`);return}let i=e?$r(e.root,n):$e(t.projectId,r.name);if(Pa($r(i,".git"))){o.info(`[repo] ${r.name} already present at ${i}`);return}try{await qd().clone(an(r),i),o.info(`[repo] cloned ${r.name} \u2192 ${i}`)}catch(s){o.warn(`[repo] clone of ${r.name} failed (will retry lazily): ${s instanceof Error?s.message.trim():String(s)}`)}}function Vd(t,e,r,o){let n=e?.repos.find(s=>s.name===r)?.mountAs??r,i=e?$r(e.root,n):$e(t.projectId,r);if(e&&i===e.root){o.warn(`[repo] ${r} maps to the workspace root \u2014 skipping purge`);return}if(!Pa($r(i,".git"))){o.info(`[repo] no local clone to purge for ${r} (${i})`);return}try{Wd(i,{recursive:!0,force:!0}),o.info(`[repo] purged local clone ${i}`)}catch(s){o.warn(`[repo] purge of ${i} failed: ${s instanceof Error?s.message:String(s)}`)}}async function zd(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=$r(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await Mi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Jd(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 At(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 Xd(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 Xi(e.contextDir,t.taskKey,t.slugs);if(o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),i.missing.length>0){let s=`draft file(s) missing in clone: ${i.missing.map(a=>`tasks/${t.taskKey}/adr/DRAFT-${a}.md`).join(", ")}`;o.warn(`[adr] adr_promote ${t.id}: ${s}`),n("failed",s);return}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 ja(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as La,mkdirSync as Da}from"node:fs";import{dirname as Ba}from"node:path";import{simpleGit as Ut}from"simple-git";import{execFileSync as Qd}from"node:child_process";import{mkdtempSync as Zd,mkdirSync as ef,readFileSync as Ea,rmSync as tf,writeFileSync as rf}from"node:fs";import{tmpdir as of}from"node:os";import{dirname as nf,join as Aa}from"node:path";function _a(t="codepipe-context"){let e=Zd(Aa(of(),"codepipe-ssh-")),r=Aa(e,"id_ed25519");try{return Qd("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Ea(r,"utf-8"),publicKey:Ea(`${r}.pub`,"utf-8").trim()}}finally{tf(e,{recursive:!0,force:!0})}}async function Oa(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 Na(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function Ua(t,e){ef(nf(t),{recursive:!0});let r=e.endsWith(`
|
|
439
439
|
`)?e:e+`
|
|
440
|
-
`;return
|
|
441
|
-
[${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as
|
|
442
|
-
`,{mode:384})}import
|
|
443
|
-
`}async function
|
|
440
|
+
`;return rf(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function sf(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 af(t,e){return e?.contextWrite?.token?{user:Gr(t),secret:e.contextWrite.token}:t===ur.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===ur.bitbucket?e?.bitbucket?.apiToken?{user:dt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ko(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await K(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=af(St(s.cloneUrl),r);if(a){let c=await cf({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 lf({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 cf(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=sf(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=l=>l.split(o.secret).join("***").split(a).join("***");try{if(La(`${r}/.git`)){let l=Ut(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let u=Jo(r);await l.reset(["--hard",`origin/${s}`]),Xo(r,u),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Da(Ba(r),{recursive:!0}),await Ut().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Ma(r)}catch(l){return n.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function lf(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Ua(i,o),a=Na(e.cloneUrl),c=e.branch;try{if(La(`${r}/.git`)){let l=Ut(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let u=Jo(r);await l.reset(["--hard",`origin/${c}`]),Xo(r,u),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Da(Ba(r),{recursive:!0}),await Ut().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ut(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Ma(r),{root:r,contextDir:r,repos:[]}}catch(l){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function Ma(t){let e=Ut(t);await e.raw(["config","user.email"]).then(o=>o.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Ga(t={profile:void 0}){let{cfg:e,profile:r}=Wr(t.profile),o=U(e.projectId);o&&pr(o),yr(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),wr(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),br(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=xr($n(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Vr("CLI_LOG",i,n);if(s.enabled){let p=new It(s);zr(p),console.log(`[log] file logging \u2192 ${p.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=Hr(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let p=xr($n(),".codepipe",r?xr("profiles",r,"context"):"context");if(await wn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await ko({cfg:e,secrets:o,contextDir:p,log:{info:g=>console.log(g),warn:g=>console.warn(g)}}),a||await wn(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let g=xr($n(),".codepipe",r?xr("profiles",r,"context-config"):"context-config");Xr(a.contextDir,g,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let l=bo(e,{...a?{workspace:a}:{},onEvent:p=>{p.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function f(p){u||(u=!0,console.log(`
|
|
441
|
+
[${p}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as yf}from"node:os";import{spawnSync as uf}from"node:child_process";function pf(){try{return uf("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Fa(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:pf(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as Lt}from"node:os";import{mkdirSync as df,readFileSync as Ha,writeFileSync as ff,existsSync as xn}from"node:fs";import{dirname as mf,join as tt}from"node:path";xn(".env")&&process.loadEnvFile(".env");function gf(){let t=process.env.SANDBOX_PLANNING_LANE;return t===void 0?!0:!/^(0|false|no|off)$/i.test(t.trim())}function ve(t){let e=L("SANDBOX_CONFIG");if(e)return e;let r=tt(Lt(),".codepipe","worker");return t?tt(r,"profiles",t,"config.json"):tt(r,"config.json")}function Ka(){return tt(Lt(),".devpipe-sandbox","config.json")}function $o(){ft(tt(Lt(),".devpipe"),tt(Lt(),".codepipe")),L("SANDBOX_CONFIG")||ft(tt(Lt(),".devpipe-sandbox"),tt(Lt(),".codepipe-sandbox"))}function ie(t){let e=ve(t),r=null;return xn(e)?r=JSON.parse(Ha(e,"utf-8")):!t&&!L("SANDBOX_CONFIG")&&xn(Ka())&&(r=JSON.parse(Ha(Ka(),"utf-8"))),r?(r.planningLane=gf(),r):null}function Wa(t,e){let r=ve(e);df(mf(r),{recursive:!0}),ff(r,JSON.stringify(t,null,2)+`
|
|
442
|
+
`,{mode:384})}import hf from"ws";var Dt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};e&&(o.signal=e);let n=r?`${this.hubUrl}/jobs/claim?lane=${encodeURIComponent(r)}`:`${this.hubUrl}/jobs/claim`;return fetch(n,o)}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 hf(e)}};async function ht(t){$o();let e=ie(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${ve(t.profile)}.`),process.exit(1));let r=t.name??yf(),o=Fa({projects:t.projects??[],llm:t.llm??null}),n=new Dt(t.hub.replace(/\/$/,"")),i=oo(),s=Ae(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Wa({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 ${ve(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 cm,readFileSync as Pn,readdirSync as lm,writeFileSync as um}from"node:fs";import{dirname as pm,join as Tr,resolve as dm}from"node:path";import{spawn as vf}from"node:child_process";import{existsSync as Sf}from"node:fs";import{spawn as wf}from"node:child_process";var qa=16e3,Ya=5e3,Va=Number(process.env.SANDBOX_CHAT_IDLE_MS??30*6e4),bf="\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u043B \u0434\u0438\u0430\u043B\u043E\u0433. \u0422\u0435\u043F\u0435\u0440\u044C, \u043E\u043F\u0438\u0440\u0430\u044F\u0441\u044C \u043D\u0430 \u0432\u0441\u0451, \u0447\u0442\u043E \u043C\u044B \u043E\u0431\u0441\u0443\u0434\u0438\u043B\u0438, \u043D\u0430\u043F\u0438\u0448\u0438 \u0444\u0430\u0439\u043B DRAFT.md \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0440\u0430\u0431\u043E\u0447\u0435\u0439 \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0438 \u043F\u043E \u043E\u043F\u0438\u0441\u0430\u043D\u043D\u043E\u043C\u0443 \u043A\u043E\u043D\u0442\u0440\u0430\u043A\u0442\u0443 (\u0441\u0442\u0440\u043E\u043A\u0430 1 \u2014 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A \u226480 \u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432 \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C, \u0441\u0442\u0440\u043E\u043A\u0430 2 \u043F\u0443\u0441\u0442\u0430\u044F, \u0434\u0430\u043B\u044C\u0448\u0435 \u0442\u0435\u043B\u043E \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u043E\u043C \u0432 Markdown) \u0438 \u0437\u0430\u0432\u0435\u0440\u0448\u0438 \u0440\u0430\u0431\u043E\u0442\u0443. \u0411\u043E\u043B\u044C\u0448\u0435 \u043D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043F\u0438\u0448\u0438.";function vn(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function kf(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}function $f(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function yt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Sn(t){return JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:t}]}})+`
|
|
443
|
+
`}async function za(t,e){if(!e.interactive)throw new Error("runInteractiveClaude called without an interactive channel");if(e.signal?.aborted)throw new Fe;let r=["--input-format","stream-json","--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let c of e.addDirs??[])r.push("--add-dir",c);let o=e.onActivity,n=c=>{if(o)try{o(c)}catch{}},i=[],s=null,a=c=>{let l=Date.now(),u=c.type;if(u==="assistant"){let f=c.message;for(let p of f?.content??[]){let g=p.type;if(g==="text"){let d=String(p.text??"").trim();d&&n({ts:l,kind:"text",author:"agent",text:vn(d,qa)})}else if(g==="tool_use"){let d=String(p.name??""),h=p.input?.file_path??p.input?.path,S=kf(h,e.workspaceDir);n({ts:l,kind:"tool",author:"agent",tool:d,...S?{file:S}:{}})}}return}if(u==="user"){let f=c.message;for(let p of f?.content??[])if(p.type==="tool_result"){let g=p.is_error===!0,d=g?vn($f(p.content),200):"";n({ts:l,kind:"tool_result",author:"agent",isError:g,...d?{text:d}:{}})}return}if(u==="result"){s=c;let f=String(c.subtype??"").trim();n({ts:l,kind:"result",author:"agent",...f?{text:f}:{}});return}if(u==="system"){let f=String(c.subtype??"").trim();f&&n({ts:l,kind:"system",author:"agent",text:f})}};return n({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),new Promise((c,l)=>{let u=wf(t,r,{cwd:e.workspaceDir,stdio:["pipe","pipe","pipe"],env:{...process.env,...e.env??{}}});u.stdout.setEncoding("utf-8"),u.stderr.setEncoding("utf-8");let f=!1,p=!1,g=null,d=()=>{f=!0,u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),Ya)};e.signal?.addEventListener("abort",d,{once:!0});let h=null,S=()=>{h&&clearTimeout(h),h=setTimeout(()=>{p=!0,console.warn(`[claude:chat] idle for ${Va}ms \u2014 ending session`),u.kill("SIGTERM"),g=setTimeout(()=>u.kill("SIGKILL"),Ya)},Va)},w=()=>{g&&clearTimeout(g),h&&clearTimeout(h),e.signal?.removeEventListener("abort",d)},y=!0,b=j=>{if(!(!y||u.stdin.destroyed))try{u.stdin.write(j)}catch{}};b(Sn(e.prompt)),S(),(async()=>{try{for await(let j of e.interactive.inbox){if(f||!y)break;if(S(),j.kind==="user")n({ts:Date.now(),kind:"text",author:"user",text:vn(j.text,qa)}),b(Sn(j.text));else{b(Sn(bf)),y=!1;try{u.stdin.end()}catch{}break}}}catch{}})();let x="",O=j=>{let v;try{v=JSON.parse(j)}catch{return}a(v)};u.stdout.on("data",j=>{i.push(j),S(),x+=j;let v;for(;(v=x.indexOf(`
|
|
444
444
|
`))!==-1;){let m=x.slice(0,v).trim();x=x.slice(v+1),m&&O(m)}}),u.stderr.on("data",j=>{i.push(j);for(let v of j.split(`
|
|
445
|
-
`)){let m=v.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",j=>{w(),l(j)}),u.on("close",j=>{if(w(),f){l(new
|
|
446
|
-
`))!==-1;){let m=O.slice(0,v).trim();if(O=O.slice(v+1),m){let R=
|
|
447
|
-
`)){let m=v.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),S.on("error",j=>{x(),h(j)}),S.on("close",j=>{if(x(),w){h(new
|
|
445
|
+
`)){let m=v.trim();m&&console.warn(`[claude:chat:stderr] ${m}`)}}),u.on("error",j=>{w(),l(j)}),u.on("close",j=>{if(w(),f){l(new Fe);return}if(p){l(new Error("chat session ended: idle for too long without a reply"));return}x.trim()&&O(x.trim()),console.log(`[claude:chat] exit code=${j}`),c({artifactPaths:[],log:i.join(""),usage:xf(s)})})})}function xf(t){let e=ut();if(!t)return e;let r=typeof t.usage=="object"?t.usage:null;return r&&(e.inputTokens=yt(r.input_tokens),e.outputTokens=yt(r.output_tokens),e.cacheReadInputTokens=yt(r.cache_read_input_tokens),e.cacheCreationInputTokens=yt(r.cache_creation_input_tokens)),e.totalCostUsd=yt(t.total_cost_usd),e.numTurns=yt(t.num_turns),e.durationMs=yt(t.duration_ms),e.model=typeof t.model=="string"?t.model:"",e}var Bt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Fe=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Cf=5e3,vr=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.interactive)return za(this.binary,e);if(e.signal?.aborted)throw new Fe;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let d of e.addDirs??[])r.push("--add-dir",d);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",l=null,u=d=>{if(d){if(d.type==="result"){i=d;return}if(d.type==="rate_limit_event"){let h=jf(d.rate_limit_info);h&&(!l||h.utilization>l.utilization)&&(l=h);return}if(d.type==="assistant"){let h=d.message;typeof h?.model=="string"&&(c=h.model);let S=h?.usage;S&&(a+=1,s.input+=ae(S.input_tokens),s.output+=ae(S.output_tokens),s.cacheRead+=ae(S.cache_read_input_tokens),s.cacheCreate+=ae(S.cache_creation_input_tokens))}}},f=e.role,p=e.onActivity,g=d=>{if(p)for(let h of Ef(d,e.workspaceDir))try{p(h)}catch{}};return p?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((d,h)=>{let S=vf(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});S.stdout.setEncoding("utf-8"),S.stderr.setEncoding("utf-8");let w=!1,y=null,b=()=>{w=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),S.kill("SIGTERM"),y=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},Cf)};e.signal?.addEventListener("abort",b,{once:!0});let x=()=>{y&&clearTimeout(y),e.signal?.removeEventListener("abort",b)},O="";S.stdout.on("data",j=>{o.push(j),O+=j;let v;for(;(v=O.indexOf(`
|
|
446
|
+
`))!==-1;){let m=O.slice(0,v).trim();if(O=O.slice(v+1),m){let R=Ja(m);u(R),R&&g(R)}}}),S.stderr.on("data",j=>{o.push(j),n.push(j);for(let v of j.split(`
|
|
447
|
+
`)){let m=v.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),S.on("error",j=>{x(),h(j)}),S.on("close",j=>{if(x(),w){h(new Fe);return}if(O.trim()){let m=Ja(O.trim());u(m),m&&g(m)}let v=i?.is_error===!0;if(j!==0||v){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,R=typeof i?.subtype=="string"?i.subtype:void 0,k=typeof i?.result=="string"?i.result:void 0;h(new Bt(Tf(j,i,n.join("")),{code:j,apiErrorStatus:m,subtype:R,resultText:k,retryAfterMs:Rf(i)}));return}console.log("[claude] exit code=0"),d({artifactPaths:[],log:o.join(""),usage:Pf(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&Sf(o))}};function Ja(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: ${rt(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=If(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=Qa(n.content);console.log(`[claude] tool_result (error)${i?`: ${rt(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)} ${rt(JSON.stringify(e),200)}`),e}function Tf(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(rt(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(rt(r.trim().split(`
|
|
448
448
|
`).slice(-5).join(`
|
|
449
|
-
`),500)),o.join(" \u2014 ")}function
|
|
450
|
-
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:
|
|
449
|
+
`),500)),o.join(" \u2014 ")}function Rf(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 Qa(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function If(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=${rt(r,80)}`}return""}function rt(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ae(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function jf(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ae(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:ae(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 Pf(t,e,r,o){let n=ut(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=ae(i.input_tokens),n.outputTokens=ae(i.output_tokens),n.cacheReadInputTokens=ae(i.cache_read_input_tokens),n.cacheCreationInputTokens=ae(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=ae(t?.total_cost_usd),n.numTurns=t&&ae(t.num_turns)>0?ae(t.num_turns):r,n.durationMs=ae(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Xa=200;function Ef(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:rt(c,Xa)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,u=l?.file_path??l?.path??l?.notebook_path,f=Af(u,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?rt(Qa(s.content),Xa):"";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 Af(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 _f,writeFileSync as Mt}from"node:fs";import{dirname as Of,join as Gt}from"node:path";function Za(t,e,r){let o=Gt(t,e);_f(Of(o),{recursive:!0}),Mt(o,r)}var Sr=class{name(){return"mock"}async run(e){if(e.interactive)return this.runInteractive(e);let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=Nf(o,n,i);Mt(Gt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Mt(Gt(e.workspaceDir,"SOLUTION.md"),Uf(o,n,i,a)),s.push("SOLUTION.md"),Mt(Gt(e.workspaceDir,"QUESTIONS.md"),Lf(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Za(e.workspaceDir,"changes/sample.patch",Df(o,n,a)),s.push("changes/sample.patch"),Za(e.workspaceDir,"diff-summary.md",Bf(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Mt(Gt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
|
|
450
|
+
`),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:ut()}}async runInteractive(e){let r=e.onActivity,o=i=>{r?.({ts:Date.now(),kind:"text",author:"agent",text:i}),r?.({ts:Date.now(),kind:"result",author:"agent",text:"success"})};r?.({ts:Date.now(),kind:"start",author:"agent",text:"chat session started"}),o("\u041F\u0440\u0438\u0432\u0435\u0442! \u041E\u043F\u0438\u0448\u0438\u0442\u0435 \u0437\u0430\u0434\u0430\u0447\u0443, \u043A\u043E\u0442\u043E\u0440\u0443\u044E \u0445\u043E\u0442\u0438\u0442\u0435 \u0441\u0444\u043E\u0440\u043C\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C.");let n="\u0427\u0435\u0440\u043D\u043E\u0432\u0438\u043A \u0438\u0437 \u0447\u0430\u0442\u0430";for await(let i of e.interactive.inbox){if(e.signal?.aborted)throw new Fe;if(i.kind==="user")r?.({ts:Date.now(),kind:"text",author:"user",text:i.text}),i.text.trim()&&(n=i.text.trim().slice(0,80)),o(`\u041F\u043E\u043D\u044F\u043B: **${i.text.trim()}**. \u0427\u0442\u043E-\u043D\u0438\u0431\u0443\u0434\u044C \u0435\u0449\u0451 \u0443\u0442\u043E\u0447\u043D\u0438\u0442\u044C?`);else break}return Mt(Gt(e.workspaceDir,"DRAFT.md"),`${n}
|
|
451
451
|
|
|
452
452
|
\u0421\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0432 \u0438\u043D\u0442\u0435\u0440\u0430\u043A\u0442\u0438\u0432\u043D\u043E\u043C \u0447\u0430\u0442\u0435 (mock runner).
|
|
453
|
-
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:
|
|
453
|
+
`),{artifactPaths:["DRAFT.md"],log:"mock chat session finalized DRAFT.md",usage:ut()}}};function Nf(t,e,r){return`# ${t} \u2014 Estimate
|
|
454
454
|
|
|
455
455
|
**Title:** ${e}
|
|
456
456
|
|
|
@@ -471,7 +471,7 @@ production-grade estimates.)
|
|
|
471
471
|
${r.split(`
|
|
472
472
|
`).slice(0,8).join(`
|
|
473
473
|
`).trim()||"(empty)"}
|
|
474
|
-
`}function
|
|
474
|
+
`}function Uf(t,e,r,o){let n=o?`
|
|
475
475
|
## Reviewer rework instruction
|
|
476
476
|
|
|
477
477
|
> ${o.split(`
|
|
@@ -500,10 +500,10 @@ TBD (mock runner does not yet inspect project code).
|
|
|
500
500
|
${r.split(`
|
|
501
501
|
`).slice(0,8).join(`
|
|
502
502
|
`).trim()||"(empty)"}
|
|
503
|
-
`}function
|
|
503
|
+
`}function Lf(t){return`# ${t} \u2014 Open questions
|
|
504
504
|
|
|
505
505
|
(none \u2014 mock runner did not surface ambiguities.)
|
|
506
|
-
`}function
|
|
506
|
+
`}function Df(t,e,r){let o=r?` (rework: ${r.split(`
|
|
507
507
|
`)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
|
|
508
508
|
index 0000000..1111111 100644
|
|
509
509
|
--- a/CHANGELOG.md
|
|
@@ -514,7 +514,7 @@ index 0000000..1111111 100644
|
|
|
514
514
|
+- mock-runner placeholder change for slice 5 testing.
|
|
515
515
|
+
|
|
516
516
|
# Changelog
|
|
517
|
-
`}function
|
|
517
|
+
`}function Bf(t,e,r){return`# ${t} \u2014 Diff summary
|
|
518
518
|
|
|
519
519
|
**Title:** ${e}
|
|
520
520
|
${r?`
|
|
@@ -525,88 +525,97 @@ ${r?`
|
|
|
525
525
|
- \`CHANGELOG.md\` \u2014 added entry for ${t}.
|
|
526
526
|
|
|
527
527
|
(Mock-runner output. Replace with claude-headless for production patches.)
|
|
528
|
-
`}function
|
|
528
|
+
`}function ec(t){switch(t){case"mock":return new Sr;case"claude-headless":return new vr;default:return null}}function oc(t=process.env){return{maxAttempts:xo(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:xo(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:xo(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:xo(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var Mf=new Set([429,500,502,503,529]),tc=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,Gf=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,Ff=new Set(["error_max_turns"]);function Hf(t){if(t instanceof Bt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return Gf.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&Ff.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Mf.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:tc.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 tc.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var rc=/(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 nc(t){if(t instanceof Bt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&rc.test(o)}let e=t instanceof Error?t.message:String(t);return rc.test(e)}function Kf(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 ic(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=Hf(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let u=Kf(s,r.policy,c.retryAfterMs);if(Date.now()+u>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 ${u}ms`),await r.onBeforeRetry(),await o(u)}}function xo(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as Wf,rmSync as qf,writeFileSync as sc}from"node:fs";import{tmpdir as Yf}from"node:os";import{join as Cn}from"node:path";function vo(t){return`[url "https://${t}/"]
|
|
529
529
|
insteadOf = git@${t}:
|
|
530
530
|
insteadOf = ssh://git@${t}/
|
|
531
|
-
`}var
|
|
531
|
+
`}var Vf=vo("github.com"),zf=vo("bitbucket.org"),Jf=vo("gitlab.com");function ac(t,e){if(t.length===0)return null;let r=Wf(Cn(Yf(),"devpipe-gitcreds-")),o=Cn(r,"credentials"),n=Cn(r,"gitconfig");return sc(o,t.join(`
|
|
532
532
|
`)+`
|
|
533
|
-
`,{mode:384}),
|
|
533
|
+
`,{mode:384}),sc(n,`[credential]
|
|
534
534
|
helper = store --file=${o}
|
|
535
|
-
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{
|
|
536
|
-
`).map(
|
|
537
|
-
|
|
538
|
-
${
|
|
539
|
-
|
|
540
|
-
|
|
535
|
+
`+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{qf(r,{recursive:!0,force:!0})}catch{}}}}function Tn(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Vf)),t.bitbucket?.apiToken&&(e.push(`https://${dt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(zf)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Jf)),ac(e,r)}function cc(t,e){if(t.contextWrite?.token){let r=St(e)??"github.com",o=Gr(r);return ac([`https://${o}:${t.contextWrite.token}@${r}`],[vo(r)])}return Tn(t)}import{spawn as uc}from"node:child_process";import{existsSync as So,mkdirSync as Co,readFileSync as Xf,rmSync as Rn,symlinkSync as Qf}from"node:fs";import{homedir as Zf}from"node:os";import{dirname as To,join as wt}from"node:path";function pc(){return wt(Zf(),".codepipe-sandbox","repos")}var Ft=new Map;function dc(t,e){let o=(Ft.get(t)??Promise.resolve()).then(e,e),n=o.then(()=>{Ft.get(t)===n&&Ft.delete(t)},()=>{Ft.get(t)===n&&Ft.delete(t)});return Ft.set(t,n),o}function lc(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 fc(t,e,r,o,n){if(So(wt(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||!lc(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}So(t)&&Rn(t,{recursive:!0,force:!0}),Co(To(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||!lc(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),So(t)&&Rn(t,{recursive:!0,force:!0}),Co(To(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function mc(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Ht="CodePipe Agent",Kt="codepipe@codepartner.ee";async function gc(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let o=(await ne(r,["write-tree"])).trim(),n=(await ne(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};return(await ne(r,["commit-tree",o,"-m",e],i)).trim()}async function hc(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 St(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 yc(t,e){return ne(t.workspacePath,["diff","--binary",t.baseSha,e])}async function wc(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 bc(t,e,r,o,n,i){let s=t.workspacePath;await Y(s,["fetch",n,`+refs/heads/${e}:refs/codepipe-build-delivery`],i);let a=(await ne(s,["rev-parse","refs/codepipe-build-delivery"])).trim();a!==r&&console.warn(`[git] delivery ${e} resolved ${a.slice(0,10)} (expected ${r.slice(0,10)})`);let c=d=>ne(s,["rev-parse","-q","--verify",`${d}^{commit}`]).then(()=>!0).catch(()=>!1);if(!await c(o)&&((await ne(s,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(s,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],i).catch(h=>{console.warn(`[git] moved-base apply: --unshallow ${t.ref} failed: ${String(h)}`)}),await c(o)||await Y(s,["fetch","origin",o],i).catch(()=>{}),!await c(o)))throw new Error(`moved-base apply: delivery base ${o.slice(0,10)} is unreachable \u2014 cannot re-apply the previous iteration onto the fresh ${t.ref}`);let l={...i??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt},u=(await ne(s,["rev-parse","refs/codepipe-build-delivery^{tree}"])).trim(),f=(await ne(s,["commit-tree",u,"-p",o,"-m","delivery"],l)).trim();await Y(s,["cherry-pick","--quit"],l).catch(()=>{});let p=null;try{await Y(s,["cherry-pick","--no-commit",f],l)}catch(d){p=d instanceof Error?d.message:String(d)}let g=(await ne(s,["diff","--name-only","--diff-filter=U"])).split(`
|
|
536
|
+
`).map(d=>d.trim()).filter(d=>d.length>0);if(p&&g.length===0)throw await Y(s,["cherry-pick","--abort"],l).catch(()=>{}),new Error(`moved-base apply: cherry-pick of the previous delivery onto ${t.ref} failed: ${p}`);return g}async function In(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Ht,GIT_AUTHOR_EMAIL:Kt,GIT_COMMITTER_NAME:Ht,GIT_COMMITTER_EMAIL:Kt};(await ne(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(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),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(l){s=l instanceof Error?l.message:String(l)}let a=(await ne(o,["diff","--name-only","--diff-filter=U"])).split(`
|
|
537
|
+
`).map(l=>l.trim()).filter(l=>l.length>0),c=await ne(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=uc("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}):
|
|
538
|
+
${s.join("").trim()||"(no stderr)"}`))})})}function ne(t,e,r){return new Promise((o,n)=>{let i=uc("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}):
|
|
539
|
+
${a.join("").trim()||"(no stderr)"}`))})})}function kc(t,e){So(t)&&Rn(t,{recursive:!0,force:!0}),Co(To(t),{recursive:!0}),Qf(e,t,"dir")}async function $c(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Co(To(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function xc(t,e,r,o="worktree",n){return r.length===0?[]:dc(e,async()=>{let i=[];for(let s of r){let a=wt(pc(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await fc(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await ne(a,["rev-parse","HEAD"])).trim(),u=wt(t,"code",s.name);o==="direct"?(kc(u,a),console.log(`[git] code: linked ${u} \u2192 ${a} @ ${l.slice(0,10)}`)):(await $c(a,c,u),console.log(`[git] code: worktree ${u} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:u,cachePath:a,ref:c,baseSha:l})}return i})}async function vc(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=r;return dc(e,async()=>{let s=wt(pc(),e,"_context");console.log(`[git] context: ensure ${i.cloneUrl} @ ${i.ref} \u2192 ${s}`);try{await fc(s,i.cloneUrl,i.ref,void 0,n)}catch(l){throw new Error(`failed to materialize context repo (${i.cloneUrl}): `+(l instanceof Error?l.message:String(l)))}let a=wt(t,"context");o==="direct"?(kc(a,s),console.log(`[git] context: linked ${a} \u2192 ${s}`)):(await $c(s,i.ref,a),console.log(`[git] context: worktree ${a} \u2190 ${s}`));let c=(await ne(s,["rev-parse","HEAD"])).trim();return{workspacePath:a,cachePath:s,baseSha:c}})}async function Sc(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await Y(r,["add","-A",...o]).catch(()=>{});let n;try{n=await ne(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
|
|
540
|
+
`).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Xf(wt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as em}from"node:fs";import{join as tm}from"node:path";var jn=8*1024,Wt=class extends Error{},Cr="meta/build-result.json";function Cc(t){let e=tm(t,Cr),r;try{r=em(e,"utf-8")}catch{throw new Wt(`BUILD produced no ${Cr} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(u){throw new Wt(`${Cr} is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(!o||typeof o!="object")throw new Wt(`${Cr} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Wt(`${Cr}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(u=>{if(!u||typeof u!="object")return[];let f=u,p=typeof f.name=="string"?f.name:null,g=typeof f.exitCode=="number"?f.exitCode:null;if(p===null||g===null)return[];let d={name:p,exitCode:g};return typeof f.durationMs=="number"&&(d.durationMs=f.durationMs),[d]}),c=typeof n.logTail=="string"?rm(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let u=a.find(f=>f.exitCode!==0);u&&(l.failedStep=u.name)}return l}function rm(t){let e=Buffer.from(t,"utf-8");return e.length<=jn?t:`\u2026 [${e.length-jn} bytes elided] \u2026
|
|
541
|
+
`+e.subarray(e.length-jn).toString("utf-8")}import{lstatSync as om,mkdtempSync as nm,readFileSync as im,readdirSync as Rc,rmSync as Tc}from"node:fs";import{tmpdir as sm}from"node:os";import{join as Ro,relative as am}from"node:path";var Ic=new Set(["code","context"]);function jc(t){let e=nm(Ro(sm(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Tc(e,{recursive:!0,force:!0}),listFiles:()=>Pc(e,e),readFile:r=>im(Ro(e,r),"utf-8"),clean:()=>{for(let r of Rc(e))Ic.has(r)||Tc(Ro(e,r),{recursive:!0,force:!0})}}}function Pc(t,e){let r=[];for(let o of Rc(e)){let n=Ro(e,o),i=om(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Ic.has(o))continue;r.push(...Pc(t,n))}else r.push(am(t,n))}return r}var Io=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),fm=new Set(["implement","resolve-conflict"]);function mm(t){let e=Buffer.from(t,"utf-8");if(e.length<=Io)return t;let r=Math.floor(Io/4),o=Io-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}
|
|
541
542
|
|
|
542
|
-
\u2026 [${s} bytes elided \u2014 log capped at ${
|
|
543
|
+
\u2026 [${s} bytes elided \u2014 log capped at ${Io} bytes for upload] \u2026
|
|
543
544
|
|
|
544
|
-
${i}`}function
|
|
545
|
+
${i}`}function gm(){let t=[],e=!1,r=null,o=i=>{if(r){let s=r;r=null,s({value:i,done:!1})}else t.push(i)},n=()=>{if(r){let i=r;r=null,i({value:void 0,done:!0})}};return{push(i){e||o(i)},finalize(){e||(o({kind:"finalize"}),e=!0)},close(){e=!0,t.length=0,n()},iterable:{[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):e?Promise.resolve({value:void 0,done:!0}):new Promise(i=>{r=i})}}}}}}async function Rr(t={}){$o();let e=ie(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=Vr("SANDBOX_LOG","sandbox",dm("./logs"));if(o.enabled){let v=new It(o);zr(v),console.log(`[log] file logging \u2192 ${v.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${fe} (protocol ${Te})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=ec(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=oc();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new Dt(e.hubUrl,e.token),a=!1,c=new AbortController,l=new Map,u=null,f=null,p=!1,g=()=>{let v=s.openControlSocket();return u=v,v.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:fe,protocolVersion:Te};v.send(JSON.stringify(m))}),v.on("message",m=>{let R=m.toString("utf-8"),k=null;try{let C=JSON.parse(R);C&&typeof C=="object"&&(k=C)}catch{}if(k&&k.type==="hello"){let C=k;f=Lr(C.protocolVersion);let I=f?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${C.platformVersion} (protocol ${C.protocolVersion}) \u2014 ${I}`),f&&(p=!1);return}if(k&&k.type==="pause_job"){let C=typeof k.jobId=="string"?k.jobId:"",I=C?l.get(C):void 0;I?(console.warn(`[ws] pause_job ${C} \u2014 aborting agent`),I.paused=!0,I.abort.abort()):console.log(`[ws] pause_job ${C} \u2014 not a running job, ignoring`),C&&v.send(JSON.stringify({type:"job_paused",jobId:C}));return}if(k&&(k.type==="chat_user_message"||k.type==="chat_finalize")){let C=typeof k.jobId=="string"?k.jobId:"",I=C?l.get(C):void 0;if(I?.chatInbox)if(k.type==="chat_user_message"){let $=typeof k.text=="string"?k.text:"";$.trim()&&I.chatInbox.push({kind:"user",text:$})}else I.chatInbox.finalize();else console.log(`[ws] ${String(k.type)} ${C} \u2014 not a live chat job, ignoring`);return}console.log(`[ws] ${R}`)}),v.on("close",(m,R)=>{console.log(`[ws] closed code=${m} reason=${R?.toString()||""}`),u===v&&(u=null),!a&&setTimeout(g,2e3)}),v.on("error",m=>console.warn(`[ws] error: ${m.message}`)),v},d=g(),h=async v=>{for(;!a;){if(f===!1){p||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${fe}, protocol ${Te}) \u2014 not claiming jobs until versions align.`),p=!0),await new Promise(m=>setTimeout(m,5e3));continue}try{let m=await s.claim(c.signal,v);if(m.status===204)continue;if(m.status===401){console.error("[claim] 401 unauthorized \u2014 the HUB does not know this worker registration. It was removed; re-register with `codepipe up --reregister` (or `codepipe worker register --force`). exiting."),process.exitCode=1,a=!0;break}if(!m.ok){console.warn(`[claim:${v}] ${m.status} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3));continue}let R=await m.json();await S(s,R)}catch(m){if(c.signal.aborted)break;let R=m instanceof Error?m.message:String(m);console.warn(`[claim:${v}] error: ${R} \u2014 backoff 5s`),await new Promise(k=>setTimeout(k,5e3))}}};async function S(v,m){let R={abort:new AbortController,paused:!1};m.role==="chat"&&(R.chatInbox=gm()),l.set(m.jobId,R);let k=!1,C=null,I=null,$=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await v.heartbeat(m.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(F){let be=F instanceof Error?F.message:String(F);console.warn(`[job] ${m.jobId} heartbeat error: ${be}`)}};P();let B=setInterval(()=>{P()},$),q=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(y(m.prompt," \u2502 "));let Se=[],at=null,E=400,pe=25,He=500,Ne=()=>{if(at&&(clearTimeout(at),at=null),Se.length===0)return;let F=Se.splice(0,Se.length),be=u;if(!be||be.readyState!==be.OPEN)return;let Ue={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:F};try{be.send(JSON.stringify(Ue))}catch{}},Uo=F=>{Se.push(F),Se.length>He&&Se.shift(),Se.length>=pe?Ne():at||(at=setTimeout(Ne,E))},ct=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,te=new Set,Lo=null;try{if(!n){k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:q,finishedAt:new Date().toISOString()});return}let F=jc(m.jobId);console.log(`[job] ${m.jobId} workspace=${F.dir}`);let be=w(m,r);C=be.gitCreds,I=be.contextGitCreds;let Ue=C?.env,Qn=be.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:be.claudeOauthToken}:void 0,Ke=[],ir=null,Do=null;try{let N="worktree";Ke=await xc(F.dir,m.projectId,m.projectRepos,N,Ue);let _=await vc(F.dir,m.projectId,m.contextRepo,N,Ue);Do=_,ir=_?.workspacePath??null}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} materialize failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${_}`},startedAt:q,finishedAt:new Date().toISOString()}),F.dispose();return}let Zn=async()=>{if(!m.deliveries||m.deliveries.length===0)return[];let N=m.contextRepo?.cloneUrl;if(!N||!Ue)throw new Error(N?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");let _=[];for(let M of m.deliveries){let G=Ke.find(de=>de.name===M.name);if(G){if(m.role==="implement"&&M.baseSha&&M.baseSha!==G.baseSha){let de=await bc(G,M.deliveryRef,M.deliverySha,M.baseSha,N,Ue);console.log(`[job] ${m.jobId} ${G.name}: base moved ${M.baseSha.slice(0,10)} \u2192 ${G.baseSha.slice(0,10)} \u2014 re-applied delivery ${M.deliverySha.slice(0,10)} (${de.length} conflicted file(s))`),de.length>0&&_.push(`- **${G.name}**:`,...de.map(sr=>` - \`${sr}\``));continue}await wc(G,M.deliveryRef,M.deliverySha,N,Ue),console.log(`[job] ${m.jobId} ${G.name}: checked out delivery ${M.deliverySha.slice(0,10)} for ${m.role}`)}}return _},Bo=[];if(m.role==="build"||m.role==="implement")try{Bo=await Zn()}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} delivery checkout failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${_}`},startedAt:q,finishedAt:new Date().toISOString()}),F.dispose();return}let ei=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},ti="";if(m.role==="resolve-conflict")try{let N=[];for(let _ of Ke){let M=ei[_.name];if(!M)continue;let G=await In(_,M,Ue);console.log(`[job] ${m.jobId} ${_.name}: merged ${M} into ${_.ref} \u2014 ${G.length} conflicted file(s)`),G.length>0?N.push(`- **${_.name}**:`,...G.map(de=>` - \`${de}\``)):N.push(`- **${_.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}ti=`
|
|
545
546
|
|
|
546
547
|
## Conflicts to resolve
|
|
547
548
|
|
|
548
549
|
`+(N.length>0?N.join(`
|
|
549
550
|
`):"(no task branches to merge)")+`
|
|
550
|
-
`}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} conflict merge failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:
|
|
551
|
+
`}catch(N){let _=N instanceof Error?N.message:String(N);console.warn(`[job] ${m.jobId} conflict merge failed: ${_}`),k||await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${_}`},startedAt:q,finishedAt:new Date().toISOString()}),F.dispose();return}let eu=Bo.length>0?`
|
|
552
|
+
|
|
553
|
+
## Base branch moved \u2014 conflicts to resolve
|
|
554
|
+
|
|
555
|
+
The base branch advanced since the previous iteration; its delivery was re-applied on top of the fresh base. These files now contain git conflict markers (\`<<<<<<<\`) \u2014 resolve them (keep both the base branch's changes and this task's changes) as part of this job:
|
|
556
|
+
|
|
557
|
+
`+Bo.join(`
|
|
558
|
+
`)+`
|
|
559
|
+
`:"",tu=x(b(m.prompt,Ke,ir),ir,m.taskId)+ti+eu,Mo=[...Ke.map(N=>N.workspacePath),...ir?[ir]:[]];Mo.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${Mo.join(", ")}`),ct&&(Lo=setInterval(()=>{let _=u;if(!_||_.readyState!==_.OPEN)return;let M;try{M=lm(Tr(F.dir,"drafts")).filter(G=>G.endsWith(".json")).sort()}catch{return}for(let G of M){if(te.has(G))continue;if(te.size>=fi)break;let de;try{let ce=JSON.parse(Pn(Tr(F.dir,"drafts",G),"utf-8")),lt=typeof ce.localRef=="string"?ce.localRef:"",D=typeof ce.title=="string"?ce.title:"",oe=typeof ce.body=="string"?ce.body:"";if(!lt||!D)continue;de={localRef:lt,title:D,body:oe,...ce.isEpic===!0?{isEpic:!0}:{},...Array.isArray(ce.links)?{links:ce.links}:{}}}catch{continue}te.add(G);let sr={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:ct,child:de};try{_.send(JSON.stringify(sr))}catch{}}},1500));try{let N={workspaceDir:F.dir,role:m.role,prompt:tu,addDirs:Mo,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Qn?{env:Qn}:{},signal:R.abort.signal,onActivity:Uo},_=R.chatInbox?await n.run({...N,interactive:{inbox:R.chatInbox.iterable}}):await ic(n,N,{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{F.clean();for(let D of Ke)try{await mc(D);let oe=ei[D.name];m.role==="resolve-conflict"&&oe&&await In(D,oe,Ue)}catch(oe){let ar=oe instanceof Error?oe.message:String(oe);console.warn(`[job] ${m.jobId} worktree reset failed (${D.name}): ${ar}`)}try{await Zn()}catch(D){let oe=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${oe}`)}},aborted:()=>k||R.paused}),M=[];if(fm.has(m.role)&&Ke.length>0){let D=m.metadata??{},oe=typeof D.commitMessage=="string"?D.commitMessage:`${m.taskId}: changes`,ar=m.contextRepo?.cloneUrl,ri=I?.env;if(!ar||!ri)throw new Error("delivery requested but "+(ar?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let ru=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let Le of Ke){let cr=await gc(Le,oe);if(!cr){console.log(`[job] ${m.jobId} ${Le.name}: no changes \u2014 no delivery`);continue}let Go=`codepipe/deliveries/${ru}/${m.jobId}/${Le.name}`;await hc(Le,cr,Go,ar,ri),M.push({name:Le.name,deliveryRef:Go,deliverySha:cr,baseSha:Le.baseSha}),console.log(`[job] ${m.jobId} ${Le.name}: delivered ${cr.slice(0,10)} \u2192 ${Go}`);let oi=await yc(Le,cr);if(oi.trim().length>0){let ou=Tr("display",`${Le.name}.diff`),ni=Tr(F.dir,ou);cm(pm(ni),{recursive:!0}),um(ni,oi)}}}if(m.role==="resolve-conflict"&&M.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=Cc(F.dir),console.log(`[job] ${m.jobId} build verdict: ok=${G.ok}`+(G.failedStep?` failedStep=${G.failedStep}`:"")));let de=_.artifactPaths.length>0?_.artifactPaths:F.listFiles(),sr=Array.from(new Set(de)),ce;if(Do)try{let D=await Sc(Do,m.role==="index"?["adr/SOURCES.md"]:[]);D.length>0&&(ce=D,console.log(`[job] ${m.jobId} captured ${D.length} knowledge file(s) for Context Repo`))}catch(D){let oe=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${oe}`)}let lt={jobId:m.jobId,status:"succeeded",artifacts:sr.map(D=>({path:D,contentBase64:Pn(`${F.dir}/${D}`).toString("base64")})),...ce?{contextWrites:ce}:{},...M.length>0?{deliveries:M}:{},log:mm(_.log),startedAt:q,finishedAt:new Date().toISOString(),usage:_.usage,..._.rateLimit?{rateLimit:_.rateLimit}:{},...G?{build:G}:{}};if(k||R.paused)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${R.paused?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await v.submitResult(lt),console.log(`[job] ${m.jobId} done \u2014 uploaded ${lt.artifacts.length} artifact(s):`);for(let D of lt.artifacts){let oe=Buffer.from(D.contentBase64,"base64").length;console.log(` \xB7 ${D.path} (${oe} bytes)`)}lt.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(N){let _=N instanceof Error?N.message:String(N);if(R.paused)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${m.jobId} failed after claim lost (${_}) \u2014 skipping result upload`);else{let M=nc(N);console.warn(M?`[job] ${m.jobId} failed: ${_} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${_}`),await v.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:_},startedAt:q,finishedAt:new Date().toISOString(),...M?{authError:!0}:{}})}}finally{F.dispose()}}finally{clearInterval(B),Lo&&clearInterval(Lo),Ne(),R.chatInbox?.close(),l.delete(m.jobId),C?.cleanup(),I?.cleanup()}}function w(v,m){if(!v.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${v.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let R;try{R=JSON.parse(no(m,v.credBundle).toString("utf-8"))}catch($){return console.warn(`[job] ${v.jobId} failed to open credBundle: ${$ instanceof Error?$.message:String($)}`),{gitCreds:null,contextGitCreds:null}}let k=Tn(R);k&&console.log(`[job] ${v.jobId} cred bundle opened \u2014 git creds configured`);let C=cc(R,v.contextRepo.cloneUrl),I={gitCreds:k,contextGitCreds:C};return R.claudeOauthToken&&(I.claudeOauthToken=R.claudeOauthToken),I}function y(v,m){return v.split(`
|
|
551
560
|
`).map(R=>m+R).join(`
|
|
552
|
-
`)}function b(v,m,R){let k=m[0]?.workspacePath??"";return v.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,R??"")}function x(v,m,R){let k=v,C=R.includes("::")?"":R.split(":",2)[1]??"",I=$=>{if(!m||!C)return"";try{return
|
|
553
|
-
[${v}] shutting down`),c.abort();let m=[...l.keys()];for(let C of l.values())C.abort.abort();let R=new AbortController,k=setTimeout(()=>R.abort(),3e3);(async()=>(await Promise.all(m.map(async C=>{try{await s.releaseJob(C,`sandbox ${v}`,R.signal),console.log(`[${v}] released job ${C}`)}catch(I){let $=I instanceof Error?I.message:String(I);console.warn(`[${v}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let j=[h("implementation")];e.planningLane!==!1?j.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(j)}async function jc(t={profile:void 0}){let e=fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=lo(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of 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 F(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=ne(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Om}from"node:child_process";import{existsSync as Yt,mkdirSync as Vc,readFileSync as zc,readdirSync as Nm,writeFileSync as Jc}from"node:fs";import{join as wt,resolve as Xc}from"node:path";import{setTimeout as _n}from"node:timers/promises";import{cancel as Um,confirm as Vt,intro as Qc,isCancel as Un,log as T,outro as On,password as zt,select as bt,spinner as Zc,text as Q}from"@clack/prompts";import{simpleGit as Po}from"simple-git";async function Wt(t,e,r){return e.host==="github"?mm(t,e,r):e.host==="gitlab"?$m(t,e,r):vm(t,e,r)}async function Pc(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 ot(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Ec(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 rt(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Ac(e.gitlabToken,t):n}}return e.bitbucket?(await Kt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await _c(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 Ec(t,e){let r=!1;try{r=(await ot(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 Ac(t,e){let r=!1;try{r=(await rt(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 _c(t,e){let r=!1;try{r=(await Kt(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 fm="https://api.github.com";async function ot(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(fm+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 mm(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 gm(o,e,r),i=await ym(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=_t(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await wm(o,n.owner,n.name,a.path,i)||await bm(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 gm(t,e,r){let o=await ot(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 Ec(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await hm(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 ot(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 hm(t,e){let{status:r,data:o}=await ot(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function ym(t,e,r){let{data:o}=await ot(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function wm(t,e,r,o,n){let{status:i,data:s}=await ot(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function bm(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 ot(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var km="https://gitlab.com/api/v4";async function rt(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(km+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 $m(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 rt(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 Ac(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await rt(o,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await rt(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await rt(o,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=_t(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await rt(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await rt(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var xm="https://api.bitbucket.org/2.0";async function Kt(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(xm+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 vm(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 Kt(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 _c(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 Kt(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=_t(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Kt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await Kt(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 u=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Sm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ge(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=Sm[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 Cm}from"node:crypto";import{existsSync as Oc,mkdirSync as Tm,readFileSync as Nc,readdirSync as Rm,rmSync as Io,writeFileSync as Im}from"node:fs";import{homedir as jm}from"node:os";import{dirname as Pm,join as Pn}from"node:path";var Em=24*60*60*1e3;function Uc(){return Pn(jm(),".codepipe","init-drafts")}function En(t){let e=Cm("sha256").update(t).digest("hex").slice(0,16);return Pn(Uc(),`${e}.json`)}function Lc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Em)}function Dc(t){let e=En(t);if(!Oc(e))return null;try{let r=JSON.parse(Nc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Lc(r.savedAt)?(Io(e,{force:!0}),null):r}catch{return null}}function An(t){Io(En(t),{force:!0})}function Bc(){let t=Uc();if(Oc(t))for(let e of Rm(t)){let r=Pn(t,e);try{let o=JSON.parse(Nc(r,"utf-8"));Lc(o.savedAt)&&Io(r,{force:!0})}catch{Io(r,{force:!0})}}}var qt=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(){An(this.cwd)}persist(){let e=En(this.cwd);Tm(Pm(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Im(e,JSON.stringify(r,null,2)+`
|
|
554
|
-
`,{mode:384})}};function Mc(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 Gc(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as Fc}from"node:fs";import{join as Hc}from"node:path";import{simpleGit as Kc}from"simple-git";var Am={info:t=>console.log(t),warn:t=>console.warn(t)};async function Cr(t,e,r={}){let o=r.log??Am,n=[];for(let i of e){let s=Hc(t,i.mountAs),a=hi(i);if(!Fc(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 Kc().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!Fc(Hc(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=Kc(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!_m(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function _m(t,e){return Wc(t)===Wc(e)}function Wc(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function qc(t={}){let e=de();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await Cr(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var Yc=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function q(t){Um(t),process.exit(1)}function he(t){return Un(t)&&q("aborted"),t}function H(t){return Un(t)&&q("aborted"),typeof t=="string"?t:""}async function el(t={}){Qc("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Bc();let r=Dc(e),o,n=!1;r&&Object.keys(r.answers).length>0?he(await Vt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new qt(e,r),n=!0):(An(e),o=new qt(e)):o=new qt(e);let i=t.force===!0?null:await Ln(e),s=await o.ask("target",async()=>he(await bt({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?T.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||rl(e,t.force===!0));let c=await o.ask("hubUrl",async()=>H(await Q({message:"HUB URL",placeholder:ve,initialValue:L("HUB_URL")??ve,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>Jt()),{cliToken:u,accountEmail:f}=await o.ask("bootstrap",()=>Xt(c,l)),p=null;s==="farm"&&(p=await Lm(c,u));let g=a?Bm(a.parsed.repoName):"",d=await o.ask("projectId",async()=>H(await Q({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>ut.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await o.ask("projectName",async()=>H(await Q({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await o.ask("automationLevel",async()=>he(await bt({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"}))),w=await o.ask("youtrack",()=>ll()),y=await o.ask("youtrackProjectKey",async()=>H(await Q({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),b=await o.ask("youtrackWrites",async()=>he(await Vt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),x=o.get("tokens")??{},O=()=>o.set("tokens",x),j=await o.ask("repos",()=>Hm(x,l,a,{onCred:O,initial:o.get("reposPartial")??[],onProgress:E=>o.set("reposPartial",E)}));o.delete("reposPartial");let v=await Km(await o.ask("contextRepo",()=>sl(d,j,x,l)),d,j,x,l,O,E=>o.set("contextRepo",E)),{spec:m,mode:R}=v;T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await o.ask("assigneeLogin",async()=>H(await Q({message:"your YouTrack login (the assignee value)",...w.login?{initialValue:w.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),C=await o.ask("claudeToken",()=>Xm(s==="farm")),I={projectId:d,name:h,automationLevel:S,repos:j,youtrackProjectKey:y};T.step(`${R==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Wt(I,m,{...al(x),youtrackWrites:b,trackerUrl:w.url,mode:R,log:{info:E=>T.message(E),warn:E=>T.warn(E)}})}catch(E){q(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}I.contextRepo=$,T.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),T.step(`registering project on ${c}\u2026`);let P;try{P=await Ze(c,u,I)}catch(E){if(E instanceof A&&E.status===409){T.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{P=await F(c,u,d)}catch(ue){throw ue instanceof A&&q(`HUB \u2192 ${ue.status} ${ue.message}`),ue}}else if(E instanceof A&&E.status===401)o.delete("cliToken"),q("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)q(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=P.contextRepo??$;T.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let K=await zm(B),xe={url:w.url,token:w.token};if(s==="farm"){let E=p,ue={...x,...K?{contextWrite:K}:{},...C?{claude:{oauthToken:C}}:{},youtrack:xe},Ge=x.github?.token;if(B.host==="github"&&Ge)try{let ee=Aa(`devpipe-${d}`);await _a(B,Ge,ee.publicKey,`devpipe-${d}`),ue.contextSsh={privateKey:ee.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(ee){T.warn(`could not set up Context Repo SSH deploy key (${ee instanceof Error?ee.message:String(ee)}); the farm will fall back to the token path.`)}let Oe={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:ue,contextRepo:B,projectConfig:je(I,b,w.url,k||void 0)},No=Ot(E.farm.publicKey,JSON.stringify(Oe));T.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let at;try{at=await uo(c,u,E.farm.farmId,{projectId:d,sealedBundle:No})}catch(ee){throw ee instanceof A&&q(ee.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:ee.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${ee.status} ${ee.message}`),ee}at.ok||q(`farm rejected provisioning: ${at.error??"unknown error"}`),await Nn(c,u,d,B,Ge),o.clear(),On(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${at.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}cl(x),await ol(e,B.cloneUrl,B.branch),il(e),a&&await Gm(e);{let E=wt(e,Te);Et(E);let ue=je(I,b,w.url,k||void 0),Ge=lr(E,ue);Ge.length>0&&T.success(`local project config \u2192 .codepipe/{${Ge.join(", ")}}`),ft(d,ue,{info:Oe=>T.message(Oe),warn:Oe=>T.warn(Oe)})}await nl(e,P.repos);let st={hubUrl:c,cliToken:u,projectId:d,...x,...K?{contextWrite:K}:{},...C?{claude:{oauthToken:C}}:{},youtrack:xe};W(st),Le({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),T.success(`secrets \u2192 ${Re(d)}`),await Nn(c,u,d,B,x.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),On("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Nn(t,e,r,o,n){let i=await Gc(o,n),s=Mc(i),a=await bt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Un(a)||a!==s.proceedValue))try{let{jobId:c}=await fo(t,e,r,{reindex:s.reindex});T.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){T.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Lm(t,e){let r;try{r=await la(t,e)}catch(c){throw c instanceof A&&q(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&q("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let n=he(await bt({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=co(i.farmId,i.publicKey)}catch(c){q(c instanceof Error?c.message:String(c))}return he(await Vt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
561
|
+
`)}function b(v,m,R){let k=m[0]?.workspacePath??"";return v.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,R??"")}function x(v,m,R){let k=v,C=R.includes("::")?"":R.split(":",2)[1]??"",I=$=>{if(!m||!C)return"";try{return Pn(Tr(m,"tasks",C,$),"utf-8").trim()}catch{return""}};if(k.includes("{{solutionMd}}")){let $=I("SOLUTION.md")||"(SOLUTION.md missing \u2014 proceed from the task description)";k=k.replace(/\{\{solutionMd\}\}/g,()=>$)}if(k.includes("{{taskDescription}}")){let $=I("task.md")||"(task description unavailable \u2014 see tasks/<KEY>/task.md in the context repo)";k=k.replace(/\{\{taskDescription\}\}/g,()=>$)}return k}let O=v=>{if(a)return;a=!0,console.log(`
|
|
562
|
+
[${v}] shutting down`),c.abort();let m=[...l.keys()];for(let C of l.values())C.abort.abort();let R=new AbortController,k=setTimeout(()=>R.abort(),3e3);(async()=>(await Promise.all(m.map(async C=>{try{await s.releaseJob(C,`sandbox ${v}`,R.signal),console.log(`[${v}] released job ${C}`)}catch(I){let $=I instanceof Error?I.message:String(I);console.warn(`[${v}] release failed: ${$} (sweeper will reclaim)`)}})),clearTimeout(k),d.close(),setTimeout(()=>process.exit(0),200)))()};process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM"));let j=[h("implementation")];e.planningLane!==!1?j.push(h("planning")):console.log("[claim] planning lane disabled (SANDBOX_PLANNING_LANE=false)"),await Promise.all(j)}async function Ec(t={profile:void 0}){let e=ge(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=fo(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let u=l.toString("utf-8");if(s.push(`msg:${u}`),u!=="pong")try{let f=JSON.parse(u);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",l=>s.push(`error:${l.message}`)),r.on("close",(l,u)=>{s.push(`close:${l}:${u?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of 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 K(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=ie(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Lm}from"node:child_process";import{existsSync as zt,mkdirSync as Jc,readFileSync as Xc,readdirSync as Dm,writeFileSync as Qc}from"node:fs";import{join as bt,resolve as Zc}from"node:path";import{setTimeout as On}from"node:timers/promises";import{cancel as Bm,confirm as Jt,intro as el,isCancel as Ln,log as T,outro as Nn,password as Xt,select as kt,spinner as tl,text as Z}from"@clack/prompts";import{simpleGit as Eo}from"simple-git";async function Yt(t,e,r){return e.host==="github"?ym(t,e,r):e.host==="gitlab"?Sm(t,e,r):Tm(t,e,r)}async function Ac(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 nt(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await _c(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 ot(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Oc(e.gitlabToken,t):n}}return e.bitbucket?(await qt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Nc(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 _c(t,e){let r=!1;try{r=(await nt(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 Oc(t,e){let r=!1;try{r=(await ot(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 Nc(t,e){let r=!1;try{r=(await qt(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 hm="https://api.github.com";async function nt(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(hm+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 ym(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 wm(o,e,r),i=await km(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=_t(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await $m(o,n.owner,n.name,a.path,i)||await xm(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 wm(t,e,r){let o=await nt(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 _c(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await bm(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 nt(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 bm(t,e){let{status:r,data:o}=await nt(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function km(t,e,r){let{data:o}=await nt(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function $m(t,e,r,o,n){let{status:i,data:s}=await nt(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function xm(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 nt(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var vm="https://gitlab.com/api/v4";async function ot(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(vm+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 Sm(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 ot(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 Oc(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await ot(o,"GET","/user"),p={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let d=await ot(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(d.status===404||!d.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);p.namespace_id=d.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let g=await ot(o,"POST","/projects",p);if(!g.data)throw new Error("GitLab create project: empty response");i=g.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=_t(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let g=(await ot(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let d of g)l.add(d.path);if(g.length<100)break}let u=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return u.length>0?await ot(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:u}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Cm="https://api.bitbucket.org/2.0";async function qt(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(Cm+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 Tm(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 qt(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 Nc(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 qt(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=_t(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await qt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let g of l)f.set(g.path,g.content);if((await qt(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 u=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:u??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Rm={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ye(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=Rm[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 Im}from"node:crypto";import{existsSync as Uc,mkdirSync as jm,readFileSync as Lc,readdirSync as Pm,rmSync as jo,writeFileSync as Em}from"node:fs";import{homedir as Am}from"node:os";import{dirname as _m,join as En}from"node:path";var Om=24*60*60*1e3;function Dc(){return En(Am(),".codepipe","init-drafts")}function An(t){let e=Im("sha256").update(t).digest("hex").slice(0,16);return En(Dc(),`${e}.json`)}function Bc(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Om)}function Mc(t){let e=An(t);if(!Uc(e))return null;try{let r=JSON.parse(Lc(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Bc(r.savedAt)?(jo(e,{force:!0}),null):r}catch{return null}}function _n(t){jo(An(t),{force:!0})}function Gc(){let t=Dc();if(Uc(t))for(let e of Pm(t)){let r=En(t,e);try{let o=JSON.parse(Lc(r,"utf-8"));Bc(o.savedAt)&&jo(r,{force:!0})}catch{jo(r,{force:!0})}}}var Vt=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(){_n(this.cwd)}persist(){let e=An(this.cwd);jm(_m(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Em(e,JSON.stringify(r,null,2)+`
|
|
563
|
+
`,{mode:384})}};function Fc(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 Hc(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as Kc}from"node:fs";import{join as Wc}from"node:path";import{simpleGit as qc}from"simple-git";var Nm={info:t=>console.log(t),warn:t=>console.warn(t)};async function Ir(t,e,r={}){let o=r.log??Nm,n=[];for(let i of e){let s=Wc(t,i.mountAs),a=yi(i);if(!Kc(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 qc().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!Kc(Wc(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=qc(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Um(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(u){let f=u instanceof Error?u.message:String(u);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function Um(t,e){return Yc(t)===Yc(e)}function Yc(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Vc(t={}){let e=me();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 Ir(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 zc=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function z(t){Bm(t),process.exit(1)}function we(t){return Ln(t)&&z("aborted"),t}function W(t){return Ln(t)&&z("aborted"),typeof t=="string"?t:""}async function rl(t={}){el("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Gc();let r=Mc(e),o,n=!1;r&&Object.keys(r.answers).length>0?we(await Jt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(T.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new Vt(e,r),n=!0):(_n(e),o=new Vt(e)):o=new Vt(e);let i=t.force===!0?null:await Dn(e),s=await o.ask("target",async()=>we(await kt({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?T.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||nl(e,t.force===!0));let c=await o.ask("hubUrl",async()=>W(await Z({message:"HUB URL",placeholder:Ce,initialValue:L("HUB_URL")??Ce,validate:E=>E.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>Qt()),{cliToken:u,accountEmail:f}=await o.ask("bootstrap",()=>Zt(c,l)),p=null;s==="farm"&&(p=await Mm(c,u));let g=a?Fm(a.parsed.repoName):"",d=await o.ask("projectId",async()=>W(await Z({message:"project id (slug)",placeholder:g||"acme",...g?{initialValue:g}:{},validate:E=>pt.test(E.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),h=await o.ask("projectName",async()=>W(await Z({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),S=await o.ask("automationLevel",async()=>we(await kt({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"}))),w=await o.ask("youtrack",()=>pl()),y=await o.ask("youtrackProjectKey",async()=>W(await Z({message:"YouTrack project key",placeholder:"DEV",validate:E=>E.trim().length>0?void 0:"required"})).trim()),b=await o.ask("youtrackWrites",async()=>we(await Jt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),x=o.get("tokens")??{},O=()=>o.set("tokens",x),j=await o.ask("repos",()=>qm(x,l,a,{onCred:O,initial:o.get("reposPartial")??[],onProgress:E=>o.set("reposPartial",E)}));o.delete("reposPartial");let v=await Ym(await o.ask("contextRepo",()=>cl(d,j,x,l)),d,j,x,l,O,E=>o.set("contextRepo",E)),{spec:m,mode:R}=v;T.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let k=await o.ask("assigneeLogin",async()=>W(await Z({message:"your YouTrack login (the assignee value)",...w.login?{initialValue:w.login}:{},validate:E=>E.trim().length>0?void 0:"required"})).trim()),C=await o.ask("claudeToken",()=>eg(s==="farm")),I={projectId:d,name:h,automationLevel:S,repos:j,youtrackProjectKey:y};T.step(`${R==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let $;try{$=await Yt(I,m,{...ll(x),youtrackWrites:b,trackerUrl:w.url,mode:R,log:{info:E=>T.message(E),warn:E=>T.warn(E)}})}catch(E){z(`Context Repo provisioning failed: ${E instanceof Error?E.message:String(E)}`)}I.contextRepo=$,T.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),T.step(`registering project on ${c}\u2026`);let P;try{P=await et(c,u,I)}catch(E){if(E instanceof A&&E.status===409){T.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{P=await K(c,u,d)}catch(pe){throw pe instanceof A&&z(`HUB \u2192 ${pe.status} ${pe.message}`),pe}}else if(E instanceof A&&E.status===401)o.delete("cliToken"),z("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(E instanceof A)z(`HUB \u2192 ${E.status} ${E.message}`);else throw E}let B=P.contextRepo??$;T.success(`project ${P.projectId} ready (${P.provisioningStatus})`);let q=await Qm(B),Se={url:w.url,token:w.token};if(s==="farm"){let E=p,pe={...x,...q?{contextWrite:q}:{},...C?{claude:{oauthToken:C}}:{},youtrack:Se},He=x.github?.token;if(B.host==="github"&&He)try{let te=_a(`devpipe-${d}`);await Oa(B,He,te.publicKey,`devpipe-${d}`),pe.contextSsh={privateKey:te.privateKey},T.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(te){T.warn(`could not set up Context Repo SSH deploy key (${te instanceof Error?te.message:String(te)}); the farm will fall back to the token path.`)}let Ne={projectId:d,config:{hubUrl:c,cliToken:u,projectId:d},secrets:pe,contextRepo:B,projectConfig:Ee(I,b,w.url,k||void 0)},Uo=Ot(E.farm.publicKey,JSON.stringify(Ne));T.step(`handing project ${d} to farm ${E.farm.name}\u2026`);let ct;try{ct=await mo(c,u,E.farm.farmId,{projectId:d,sealedBundle:Uo})}catch(te){throw te instanceof A&&z(te.status===409?`farm ${E.farm.name} is offline \u2014 start it and re-run.`:te.status===504?`farm ${E.farm.name} did not respond in time.`:`HUB \u2192 ${te.status} ${te.message}`),te}ct.ok||z(`farm rejected provisioning: ${ct.error??"unknown error"}`),await Un(c,u,d,B,He),o.clear(),Nn(`done. project ${d} is now hosted on farm ${E.farm.name} (daemon ${ct.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}ul(x),await il(e,B.cloneUrl,B.branch),al(e),a&&await Km(e);{let E=bt(e,Ie);Et(E);let pe=Ee(I,b,w.url,k||void 0),He=dr(E,pe);He.length>0&&T.success(`local project config \u2192 .codepipe/{${He.join(", ")}}`),mt(d,pe,{info:Ne=>T.message(Ne),warn:Ne=>T.warn(Ne)})}await sl(e,P.repos);let at={hubUrl:c,cliToken:u,projectId:d,...x,...q?{contextWrite:q}:{},...C?{claude:{oauthToken:C}}:{},youtrack:Se};V(at),Be({hubUrl:c,cliToken:u,projectId:d,accountEmail:f},d),T.success(`secrets \u2192 ${je(d)}`),await Un(c,u,d,B,x.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Nn("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function Un(t,e,r,o,n){let i=await Hc(o,n),s=Fc(i),a=await kt({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Ln(a)||a!==s.proceedValue))try{let{jobId:c}=await ho(t,e,r,{reindex:s.reindex});T.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){T.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Mm(t,e){let r;try{r=await ua(t,e)}catch(c){throw c instanceof A&&z(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&z("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let n=we(await kt({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=po(i.farmId,i.publicKey)}catch(c){z(c instanceof Error?c.message:String(c))}return we(await Jt({message:`confirm farm ${i.name} cred-channel fingerprint:
|
|
555
564
|
${s}
|
|
556
|
-
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||
|
|
565
|
+
(compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||z("farm fingerprint not confirmed \u2014 aborting."),uo(i.farmId,s),{farm:i,fingerprint:s}}async function ol(t){el(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();nl(e,t.force===!0);let r=W(await Z({message:"HUB URL",initialValue:L("HUB_URL")??Ce,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await Qt(),{cliToken:n,accountEmail:i}=await Zt(r,o);T.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await K(r,n,t.projectId)}catch(f){throw f instanceof A&&z(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||z(`project ${t.projectId} has no Context Repo on HUB`);let a=await pl(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await Po(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(p=>p.host===f)?.owner,o);ul(c),await il(e,s.contextRepo.cloneUrl,s.contextRepo.branch),al(e);{let f=bt(e,Ie);Et(f);let p={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},g=Ee(p,!0,a.url),d=dr(f,g);d.length>0&&T.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),mt(t.projectId,g,{info:h=>T.message(h),warn:h=>T.warn(h)})}await sl(e,s.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(u),Be({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),T.success(`secrets \u2192 ${je(t.projectId)}`),await Un(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Nn("done.")}function nl(t,e){if(!zt(t)){Jc(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Dm(t).filter(n=>!r.has(n));o.length!==0&&(e||z(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Dn(t){if(!zt(bt(t,".git")))return null;try{let r=(await Eo(t).remote(["get-url","origin"])||"").toString().trim(),o=r?ye(r):null;return o?{parsed:o,defaultBranch:await Gm(t)}:null}catch{return null}}async function Gm(t){let e=Eo(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 Fm(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return pt.test(e)?e:""}function Hm(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Km(t){let e=bt(t,".gitignore"),r=zt(e)?Xc(e,"utf-8"):"";if(Hm(r))return;if(!we(await Jt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){T.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
|
|
557
566
|
`)?"":`
|
|
558
|
-
`;
|
|
567
|
+
`;Qc(e,r+n+`
|
|
559
568
|
# codepipe workspace (added by \`codepipe init\`)
|
|
560
569
|
.codepipe/
|
|
561
|
-
`),T.success(`.codepipe/ added to ${
|
|
570
|
+
`),T.success(`.codepipe/ added to ${Zc(e)}`)}function Wm(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=Lm(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function Qt(){let t="";try{t=(await Eo().raw(["config","--global","user.email"])||"").trim()}catch{}return W(await Z({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function Zt(t,e){T.step(`connecting account ${e}`);let r;try{r=await fa(t,e)}catch(s){throw s instanceof kr&&z(`${e} is not authorized on this HUB yet.
|
|
562
571
|
Sign up at ${t} (registration form on the login screen),
|
|
563
572
|
wait for the operator to approve it by email, then re-run
|
|
564
|
-
\`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(
|
|
573
|
+
\`codepipe init\` with the same email.`),s}r.accountCreated&&T.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&T.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(Wm(r.authorizeUrl),T.message(`a browser tab was opened to confirm this CLI:
|
|
565
574
|
${r.authorizeUrl}
|
|
566
575
|
`+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
|
|
567
|
-
otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let o=!1,n=Date.now(),i=n+15*6e4;for(;Date.now()<i;){let s;try{s=await
|
|
568
|
-
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await
|
|
576
|
+
otherwise use the emailed link the page offers.`))),r.approvalRequired&&T.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),T.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let o=!1,n=Date.now(),i=n+15*6e4;for(;Date.now()<i;){let s;try{s=await ma(t,r.requestId)}catch(a){T.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await On(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&T.message(`connected as ${a} (the account confirmed in the browser).`),T.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&z("the HUB rejected this account"),s.status==="expired"&&z("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,T.message(`email confirmed. waiting for the operator to approve your account\u2026
|
|
577
|
+
(you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await On(5e3);continue}await On(2e3)}z("bootstrap timed out")}async function il(t,e,r){let o=bt(t,Ie);if(zt(bt(o,".git"))){T.message(`${o} already cloned \u2014 skipping`);return}zt(o)&&z(`${o} exists but is not a git repo \u2014 remove it and re-run`),Jc(o,{recursive:!0}),T.step(`cloning Context Repo \u2192 ${o}`);try{await Eo().clone(e,o,["--branch",r]),T.success(`cloned ${e}`)}catch(n){z(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function sl(t,e){if(e.length===0)return;T.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 Ir(t,r,{log:{info:n=>T.message(n),warn:n=>T.warn(n)}});for(let n of o)T.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function al(t){let e=bt(t,Ie,".gitignore"),r="";if(zt(e)&&(r=Xc(e,"utf-8")),zc.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
|
|
569
578
|
`)||r.length===0?"":`
|
|
570
|
-
`,i=
|
|
579
|
+
`,i=zc.join(`
|
|
571
580
|
`)+`
|
|
572
|
-
`;
|
|
573
|
-
`:"")+i),T.message(`appended runtime entries to ${
|
|
581
|
+
`;Qc(e,r+n+(r?`
|
|
582
|
+
`:"")+i),T.message(`appended runtime entries to ${Zc(e)}`)}async function qm(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;T.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Po(s.host,t,s.owner,e),i?.();let c=W(await Z({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:u=>u.trim().length>0?void 0:"required"})).trim(),l=W(await Z({message:"default branch",placeholder:a,initialValue:a,validate:u=>u.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:l,mountAs:"."}),o.onProgress?.(n)}for(;we(await Jt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=W(await Z({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:g=>!g||!g.trim()||ye(g)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=ye(a);T.message(`${c.host}: ${c.owner}/${c.repoName}`),await Po(c.host,t,c.owner,e),i?.();let l=W(await Z({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:g=>g.trim().length>0?void 0:"required"})).trim(),u=W(await Z({message:"default branch (optional)",placeholder:"main"})).trim(),f=W(await Z({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),p={name:l,host:c.host,owner:c.owner,repoName:c.repoName};u&&(p.defaultBranch=u),f&&f!==l&&(p.mountAs=f),n.push(p),o.onProgress?.(n)}return n}async function cl(t,e,r,o){T.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=we(await kt({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"&&T.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=W(await Z({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:De(t),validate:u=>{let f=(u??"").trim();if(!f)return"required";if(!ye(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=ye(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await Vm(),l=W(await Z({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),u=W(await Z({message:"Context Repo name",placeholder:De(t),initialValue:De(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:u}}return{spec:a,mode:n}}function ll(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??Rt()}}async function Ym(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await Po(c.host,o,c.owner,n),i?.();let u=tl();u.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Ac(c,ll(o),{explain:l==="attach"});if(f.found===!0)return u.stop(`${c.owner}/${c.name} found${l==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return u.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(l==="create")return u.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;u.stop(f.detail,1);let p=we(await kt({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(p==="abort"&&z("aborted"),p==="create")return a={spec:c,mode:"create"},s(a),a;a=await cl(e,r,o,n),s(a)}}async function Vm(){return we(await kt({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function jr(t,e){let r=tl();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 ul(t){yr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),wr(t.gitlab?.token??process.env.GITLAB_TOKEN),br(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Po(t,e,r,o){if(!e[t])if(t==="github"){let n=await zm(r);n?e.github=n:T.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Jm(r,o);n?e.bitbucket=n:T.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 Xm();n?e.gitlab=n:T.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function zm(t){for(;;){let e=W(await Xt({message:`GitHub PAT \u2014 blank to skip
|
|
574
583
|
classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
|
|
575
584
|
fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
|
|
576
585
|
if org: approve token in org Settings \u2192 Personal access tokens.
|
|
577
586
|
(Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
|
|
578
|
-
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await
|
|
587
|
+
set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await jr("GitHub",()=>ze(e,t?{owner:t}:void 0)))return{token:e};T.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Jm(t,e){for(T.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
|
|
579
588
|
How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
|
|
580
589
|
'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
|
|
581
590
|
read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
|
|
582
591
|
(+ admin:repository:bitbucket if this token will provision the Context Repo).
|
|
583
|
-
The token is shown ONCE \u2014 copy it right away.`);;){let r=
|
|
584
|
-
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await
|
|
592
|
+
The token is shown ONCE \u2014 copy it right away.`);;){let r=W(await Z({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=W(await Xt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){T.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await jr("Bitbucket",()=>Je(r,o,t)))return{email:r,apiToken:o};T.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Xm(){for(;;){let t=W(await Xt({message:`GitLab PAT \u2014 blank to skip
|
|
593
|
+
scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await jr("GitLab",()=>Xe(t))){let e=await rs(t);return e&&T.warn(e),{token:t}}T.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Qm(t){if(we(await Jt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
|
|
585
594
|
Without it the SANDBOX pushes delivery commits with the project ${t.host}
|
|
586
595
|
credential. A scoped token hardens setups where the SANDBOX runs outside
|
|
587
596
|
your trusted network.`,initialValue:!1})))for(t.host==="github"?T.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
|
|
588
597
|
permissions Contents: Read and write + Workflows: Read and write (Workflows is
|
|
589
598
|
required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):T.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
|
|
590
|
-
(${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=
|
|
591
|
-
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=H(await zt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||T.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(T.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function ll(){for(;;){let t=H(await Q({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=H(await zt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Tr("YouTrack",()=>Qe({baseUrl:t,token:e}))){let r=await Es({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Qm}from"node:fs";function Z(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&Z(`config: '${e}' must be a non-empty string`),t.trim()}function Rr(t,e){if(t==null)return;typeof t!="string"&&Z(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Zm(t){(!t||typeof t!="object")&&Z("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||Z("config: 'hubUrl' must start with http(s)://");let o=re(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&Z("config: 'project' is required");let i=n,s=re(i.id,"project.id");ut.test(s)||Z("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=re(i.name,"project.name"),c=re(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&Z("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||Z("config: 'project.repos' must be an array");let u=l.map((y,b)=>{(!y||typeof y!="object")&&Z(`config: project.repos[${b}] must be an object`);let x=y,O=re(x.host,`project.repos[${b}].host`);O!=="github"&&O!=="bitbucket"&&O!=="gitlab"&&Z(`config: project.repos[${b}].host must be 'github', 'bitbucket' or 'gitlab'`);let j={name:re(x.name,`project.repos[${b}].name`),host:O,owner:re(x.owner,`project.repos[${b}].owner`),repoName:re(x.repoName,`project.repos[${b}].repoName`)},v=Rr(x.defaultBranch,`project.repos[${b}].defaultBranch`);v&&(j.defaultBranch=v);let m=Rr(x.mountAs,`project.repos[${b}].mountAs`);return m&&(j.mountAs=m),j}),f=i.contextRepo;(!f||typeof f!="object")&&Z("config: 'project.contextRepo' is required");let p=f,g=Rr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&Z("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:re(p.owner,"project.contextRepo.owner"),name:Rr(p.name,"project.contextRepo.name")??Ue(s)},h={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},S=Rr(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(h.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&Z("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&Z("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&Z("config: 'secrets' must be an object");let y=w,b={};if(y.github){let x=y.github;b.github={token:re(x.token,"secrets.github.token")}}if(y.bitbucket){let x=y.bitbucket;b.bitbucket={email:re(x.email,"secrets.bitbucket.email"),apiToken:re(x.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let x=y.gitlab;b.gitlab={token:re(x.token,"secrets.gitlab.token")}}if(y.youtrack){let x=y.youtrack;b.youtrack={url:re(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(x.token,"secrets.youtrack.token")}}if(y.contextWrite){let x=y.contextWrite;b.contextWrite={token:re(x.token,"secrets.contextWrite.token")}}h.secrets=b}return h}async function eg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function tg(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await Ve(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 ze(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Je(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Qe({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function ul(t){let e=!t.configPath||t.configPath==="-"?await eg():Qm(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){Z(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let o=Zm(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 tg(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Wt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??Rt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){Z(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let u;try{u=await Ze(n,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await F(n,i,s.id);else if(p instanceof A)Z(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(W(f),Le({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Re(s.id)}`),ft(s.id,je(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await fo(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as pl,intro as dl,isCancel as fl,log as Dn,outro as rg,password as ml}from"@clack/prompts";async function og(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function gl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await og(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){dl("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Dn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ml({message:"Claude OAuth token"});fl(i)&&(pl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Ai({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Kr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=fe(t.profile);if(!e){dl(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Dn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await ml({message:"Claude OAuth token"});fl(i)&&(pl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},W(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Dn.success("Claude OAuth token saved."),rg("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as ng,confirm as ig,intro as sg,isCancel as hl,log as ie,outro as ag,select as yl,text as nt}from"@clack/prompts";function wl(t){ng(t),process.exit(1)}function Qt(t){return hl(t)&&wl("aborted"),t}function Ir(t){return hl(t)&&wl("aborted"),typeof t=="string"?t:""}async function cg(t,e){let r=Qt(await yl({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=Ir(await nt({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Ir(await nt({message:"Context Repo name",placeholder:Ue(t),initialValue:Ue(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function bl(t={profile:void 0}){let e=fe(t.profile);sg(`codepipe project add \u2192 ${e.hubUrl}`);let r=Qt(await nt({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>ut.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Qt(await nt({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),n=Qt(await yl({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=Qt(await nt({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Qt(await ig({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Ir(await nt({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:w=>!w||!w.trim()||ge(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=ge(p);ie.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=Ir(await nt({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),h=Ir(await nt({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:d,host:g.host,owner:g.owner,repoName:g.repoName};h&&(S.defaultBranch=h),a.push(S)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await cg(r,a),u=U(e.projectId);ie.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Wt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Rt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>ie.message(p),warn:p=>ie.warn(p)}})}catch(p){ie.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,ie.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await Ze(e.hubUrl,e.cliToken,c);ie.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),ft(r,je(c,s,u?.youtrack?.url),{info:g=>ie.message(g),warn:g=>ie.warn(g)}),p.contextRepo&&(ie.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),ie.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&ie.error(` error: ${p.provisioningError}`),ag("done")}catch(p){p instanceof A?(ie.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&ie.message(JSON.stringify(p.payload,null,2))):ie.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as lg,rmSync as ug}from"node:fs";import{confirm as pg,intro as dg,isCancel as fg,log as it,outro as mg,spinner as gg}from"@clack/prompts";function _e(t){it.error(t),process.exit(1)}var kl=t=>t.trim().replace(/\/+$/,"");async function $l(t){dg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??de()?.spec.projectId??void 0;e||_e("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=we(e);r||_e(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let o=kl(r.hubUrl),n=r.projectId,i=kl(t.hub);i.startsWith("http")||_e("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??n,c=s===e;c&&a===n&&i===o&&_e(`profile '${e}' is already on ${o} \u2014 nothing to move.`);let l;{let w=gg();w.start(`reading project ${n} from ${o}\u2026`);try{l=await F(o,r.cliToken,n),w.stop(`read project ${n} (${l.name})`)}catch(y){throw w.stop("could not read the source project",1),y instanceof A&&_e(`source HUB ${o} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||_e(`project ${n} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(n),f=(t.account??r.accountEmail??await Jt()).trim().toLowerCase();if(it.message(`move project '${n}'
|
|
599
|
+
(${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=W(await Xt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await jr("contextWrite",()=>Zm(r,t)))return{token:r};T.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Zm(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 eg(t){if(Wo()?.claude?.oauthToken&&!t)return T.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";T.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
|
|
600
|
+
Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=W(await Xt({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||T.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(T.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function pl(){for(;;){let t=W(await Z({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=W(await Xt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await jr("YouTrack",()=>Ze({baseUrl:t,token:e}))){let r=await As({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}T.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as tg}from"node:fs";function ee(t){throw new Error(t)}function re(t,e){return(typeof t!="string"||t.trim().length===0)&&ee(`config: '${e}' must be a non-empty string`),t.trim()}function Pr(t,e){if(t==null)return;typeof t!="string"&&ee(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function rg(t){(!t||typeof t!="object")&&ee("config: expected a JSON object");let e=t,r=re(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||ee("config: 'hubUrl' must start with http(s)://");let o=re(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&ee("config: 'project' is required");let i=n,s=re(i.id,"project.id");pt.test(s)||ee("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=re(i.name,"project.name"),c=re(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&ee("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||ee("config: 'project.repos' must be an array");let u=l.map((y,b)=>{(!y||typeof y!="object")&&ee(`config: project.repos[${b}] must be an object`);let x=y,O=re(x.host,`project.repos[${b}].host`);O!=="github"&&O!=="bitbucket"&&O!=="gitlab"&&ee(`config: project.repos[${b}].host must be 'github', 'bitbucket' or 'gitlab'`);let j={name:re(x.name,`project.repos[${b}].name`),host:O,owner:re(x.owner,`project.repos[${b}].owner`),repoName:re(x.repoName,`project.repos[${b}].repoName`)},v=Pr(x.defaultBranch,`project.repos[${b}].defaultBranch`);v&&(j.defaultBranch=v);let m=Pr(x.mountAs,`project.repos[${b}].mountAs`);return m&&(j.mountAs=m),j}),f=i.contextRepo;(!f||typeof f!="object")&&ee("config: 'project.contextRepo' is required");let p=f,g=Pr(p.host,"project.contextRepo.host")??"github";g!=="github"&&g!=="bitbucket"&&g!=="gitlab"&&ee("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let d={host:g,owner:re(p.owner,"project.contextRepo.owner"),name:Pr(p.name,"project.contextRepo.name")??De(s)},h={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:u,contextRepo:d}},S=Pr(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(h.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&ee("config: 'project.index' must be a boolean"),h.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&ee("config: 'project.youtrackWrites' must be a boolean"),h.project.youtrackWrites=i.youtrackWrites);let w=e.secrets;if(w!==void 0){(typeof w!="object"||w===null)&&ee("config: 'secrets' must be an object");let y=w,b={};if(y.github){let x=y.github;b.github={token:re(x.token,"secrets.github.token")}}if(y.bitbucket){let x=y.bitbucket;b.bitbucket={email:re(x.email,"secrets.bitbucket.email"),apiToken:re(x.apiToken,"secrets.bitbucket.apiToken")}}if(y.gitlab){let x=y.gitlab;b.gitlab={token:re(x.token,"secrets.gitlab.token")}}if(y.youtrack){let x=y.youtrack;b.youtrack={url:re(x.url,"secrets.youtrack.url").replace(/\/$/,""),token:re(x.token,"secrets.youtrack.token")}}if(y.contextWrite){let x=y.contextWrite;b.contextWrite={token:re(x.token,"secrets.contextWrite.token")}}h.secrets=b}return h}async function og(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function ng(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await ze(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 Je(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Xe(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Ze({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function dl(t){let e=!t.configPath||t.configPath==="-"?await og():tg(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(p){ee(`config: invalid JSON \u2014 ${p instanceof Error?p.message:String(p)}`)}let o=rg(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 ng(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Yt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??Rt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:p=>console.log(` ${p}`),warn:p=>console.warn(` ${p}`)}})}catch(p){ee(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let u;try{u=await et(n,i,a)}catch(p){if(p instanceof A&&p.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),u=await K(n,i,s.id);else if(p instanceof A)ee(`HUB \u2192 ${p.status} ${p.message}`);else throw p}console.log(`project ${u.projectId} ready (${u.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(V(f),Be({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${je(s.id)}`),mt(s.id,Ee(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:p=>console.log(p),warn:p=>console.warn(p)}),s.index)try{let{jobId:p}=await ho(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${p}); runs once a SANDBOX claims it.`)}catch(p){console.warn(`could not enqueue index job: ${p instanceof Error?p.message:String(p)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as fl,intro as ml,isCancel as gl,log as Bn,outro as ig,password as hl}from"@clack/prompts";async function sg(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function yl(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await sg(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){ml("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Bn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hl({message:"Claude OAuth token"});gl(i)&&(fl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),_i({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Yr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=ge(t.profile);if(!e){ml(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Bn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hl({message:"Claude OAuth token"});gl(i)&&(fl("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},V(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Bn.success("Claude OAuth token saved."),ig("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as ag,confirm as cg,intro as lg,isCancel as wl,log as se,outro as ug,select as bl,text as it}from"@clack/prompts";function kl(t){ag(t),process.exit(1)}function er(t){return wl(t)&&kl("aborted"),t}function Er(t){return wl(t)&&kl("aborted"),typeof t=="string"?t:""}async function pg(t,e){let r=er(await bl({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=Er(await it({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=Er(await it({message:"Context Repo name",placeholder:De(t),initialValue:De(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function $l(t={profile:void 0}){let e=ge(t.profile);lg(`codepipe project add \u2192 ${e.hubUrl}`);let r=er(await it({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:p=>pt.test(p.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=er(await it({message:"project name (human-readable)",placeholder:"CodePartner",validate:p=>p.trim().length>0?void 0:"required"})).trim(),n=er(await bl({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=er(await it({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=er(await cg({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let p=Er(await it({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:w=>!w||!w.trim()||ye(w)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!p)break;let g=ye(p);se.message(`${g.host}: ${g.owner}/${g.repoName}`);let d=Er(await it({message:"repo logical name (used inside Context Repo paths)",placeholder:g.repoName,initialValue:g.repoName,validate:w=>w.trim().length>0?void 0:"required"})).trim(),h=Er(await it({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:d,host:g.host,owner:g.owner,repoName:g.repoName};h&&(S.defaultBranch=h),a.push(S)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await pg(r,a),u=U(e.projectId);se.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Yt(c,l,{githubToken:u?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:u?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:u?.bitbucket??Rt(),youtrackWrites:s,trackerUrl:u?.youtrack?.url,log:{info:p=>se.message(p),warn:p=>se.warn(p)}})}catch(p){se.error(`Context Repo provisioning failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}c.contextRepo=f,se.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let p=await et(e.hubUrl,e.cliToken,c);se.success(`project "${p.projectId}" \u2014 ${p.provisioningStatus}`),mt(r,Ee(c,s,u?.youtrack?.url),{info:g=>se.message(g),warn:g=>se.warn(g)}),p.contextRepo&&(se.message(` context repo: ${p.contextRepo.owner}/${p.contextRepo.name} (${p.contextRepo.cloneUrl})`),se.message(` branch: ${p.contextRepo.branch}`)),p.provisioningError&&se.error(` error: ${p.provisioningError}`),ug("done")}catch(p){p instanceof A?(se.error(`HUB \u2192 ${p.status} ${p.message}`),p.payload&&typeof p.payload=="object"&&se.message(JSON.stringify(p.payload,null,2))):se.error(p instanceof Error?p.message:String(p)),process.exit(1)}}import{existsSync as dg,rmSync as fg}from"node:fs";import{confirm as mg,intro as gg,isCancel as hg,log as st,outro as yg,spinner as wg}from"@clack/prompts";function Oe(t){st.error(t),process.exit(1)}var xl=t=>t.trim().replace(/\/+$/,"");async function vl(t){gg("codepipe project move \u2014 repoint a project at another HUB");let e=t.fromProfile??t.cliProfile??me()?.spec.projectId??void 0;e||Oe("no source project \u2014 pass --from-profile <id> (or run inside a project's workspace folder).");let r=ke(e);r||Oe(`source profile '${e}' is not initialised on this machine (~/.codepipe/profiles/${e}/config.json is missing).`);let o=xl(r.hubUrl),n=r.projectId,i=xl(t.hub);i.startsWith("http")||Oe("--hub must be an http(s):// URL");let s=t.toProfile??e,a=t.project??n,c=s===e;c&&a===n&&i===o&&Oe(`profile '${e}' is already on ${o} \u2014 nothing to move.`);let l;{let w=wg();w.start(`reading project ${n} from ${o}\u2026`);try{l=await K(o,r.cliToken,n),w.stop(`read project ${n} (${l.name})`)}catch(y){throw w.stop("could not read the source project",1),y instanceof A&&Oe(`source HUB ${o} \u2192 ${y.status} ${y.message}. The source HUB must be reachable with a valid token to move a project.`),y}}l.contextRepo||Oe(`project ${n} has no Context Repo recorded on the source HUB \u2014 cannot re-register it elsewhere.`);let u=U(n),f=(t.account??r.accountEmail??await Qt()).trim().toLowerCase();if(st.message(`move project '${n}'
|
|
592
601
|
from : ${o} (profile ${e})
|
|
593
602
|
to : ${i} (profile ${s}, project ${a}, account ${f})
|
|
594
603
|
\u2022 the source registration on the old HUB is left intact (non-destructive)
|
|
595
604
|
\u2022 task/job history is NOT copied \u2014 the project starts clean on the target HUB
|
|
596
|
-
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${o}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${o}`)),!t.yes){let w=await
|
|
597
|
-
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await
|
|
598
|
-
Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${o.sandboxId} \u2014 replacing the registration`),
|
|
605
|
+
`+(c?` \u2022 profile '${e}' is repointed \u2014 it will no longer talk to ${o}`:` \u2022 a new profile '${s}' is written; '${e}' keeps pointing at ${o}`)),!t.yes){let w=await mg({message:"Continue?",initialValue:!0});(hg(w)||!w)&&Oe("aborted")}!c&&a===n&&st.warn(`source and destination share the same project id, so they share one secrets file (${je(a)}). Running both profiles at the same time will conflict \u2014 pass --project <newId> for a parallel setup, or keep only one active.`);let{cliToken:p,accountEmail:g}=await Zt(i,f),d={projectId:a,name:l.name,automationLevel:l.automationLevel,repos:l.repos,contextRepo:l.contextRepo,ownerEmail:g,...l.youtrackProjectKey?{youtrackProjectKey:l.youtrackProjectKey}:{}};st.step(`registering project on ${i}\u2026`);let h;try{h=await et(i,p,d)}catch(w){if(w instanceof A&&w.status===409){st.warn(`project ${a} already exists on ${i} \u2014 reusing it`);try{h=await K(i,p,a)}catch(y){throw y instanceof A&&Oe(`target HUB \u2192 ${y.status} ${y.message}`),y}}else if(w instanceof A&&w.status===403)Oe(`project ${a} already exists on ${i} under a different owner \u2014 choose a different --project id or move it under the right account.`);else if(w instanceof A)Oe(`target HUB \u2192 ${w.status} ${w.message}`);else throw w}st.success(`project ${h.projectId} ready on ${i} (${h.provisioningStatus})`),Be({hubUrl:i,cliToken:p,projectId:a,accountEmail:g},s);let S={...u??{},hubUrl:i,cliToken:p,projectId:a};if(delete S.sandboxPins,V(S),st.success(`profile '${s}' \u2192 ${je(a)}`),c){let w=ve(s);dg(w)&&(fg(w),st.message("removed the stale worker registration for this profile \u2014 `codepipe up` will register a fresh worker on the target HUB"))}yg(`done. next: \`codepipe up --profile ${s}\` \u2014 starts the daemon and a worker on ${i}.`)}import{existsSync as Mn,rmSync as bg,statSync as kg}from"node:fs";import{join as Ao,relative as $g,resolve as xg}from"node:path";import{cancel as vg,intro as Cl,isCancel as Sg,log as J,outro as Tl,text as $t}from"@clack/prompts";import{simpleGit as Rl}from"simple-git";function le(t){vg(t),process.exit(1)}function xt(t){return Sg(t)&&le("aborted"),typeof t=="string"?t:""}async function Sl(t){try{let e=await Rl(t).remote(["get-url","origin"]);return e&&e.trim()||null}catch{return null}}function Cg(t,e){return t?e==="github"?!!t.github?.token:e==="gitlab"?!!t.gitlab?.token:!!t.bitbucket?.apiToken:!1}async function Tg(t,e){let r=U(t.projectId)??{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId};if(Cg(r,e)){J.message(`reusing existing ${e} credentials`);return}if(J.warn(`no ${e} credentials yet for this project \u2014 adding them now`),e==="bitbucket"){let o=xt(await $t({message:"Atlassian account email (Bitbucket)",validate:i=>i.trim()?void 0:"required"})).trim(),n=xt(await $t({message:"Bitbucket API token (scoped)",validate:i=>i.trim()?void 0:"required"})).trim();r.bitbucket={email:o,apiToken:n}}else{let o=xt(await $t({message:`${e} access token (read access to the repo)`,validate:n=>n.trim()?void 0:"required"})).trim();e==="github"?r.github={token:o}:r.gitlab={token:o}}V(r),J.success(`saved ${e} credentials`)}async function Il(t){let e=ge(t.profile);Cl(`codepipe repo add \u2192 project ${e.projectId}`);let r=me()??void 0,o;try{o=(await K(e.hubUrl,e.cliToken,e.projectId)).repos}catch(y){le(`could not read project from HUB: ${y instanceof Error?y.message:String(y)}`)}let n=t.target?.trim();if(!n){let y=await Sl(process.cwd());y?(n=process.cwd(),J.message(`using the current directory (${y})`)):n=xt(await $t({message:"path to an existing clone, or a repo clone URL",placeholder:"../api | git@github.com:acme/api.git",validate:b=>b.trim()?void 0:"required"})).trim()}let i=null,s,a,c,l;if(Mn(n)&&kg(n).isDirectory()){i=xg(n);let y=await Sl(i);y||le(`${i} is not a git repository (no origin remote)`);let b=ye(y);b||le(`origin ${y} is not on a supported host (github / gitlab / bitbucket)`),{host:a,owner:c,repoName:l}=b,s=y,J.message(`${a}: ${c}/${l} (already cloned at ${i})`)}else{let y=ye(n);y||le(`"${n}" is neither an existing directory nor a supported clone URL`),{host:a,owner:c,repoName:l}=y,s=n,J.message(`${a}: ${c}/${l}`)}let u=xt(await $t({message:"repo logical name (used inside Context Repo paths)",placeholder:l,initialValue:l,validate:y=>y.trim()?void 0:"required"})).trim();o.some(y=>y.name===u)&&le(`a repo named "${u}" is already registered`);let f=xt(await $t({message:"default branch (optional)",placeholder:"main"})).trim(),p=u;if(i&&r&&(i===r.root||i.startsWith(r.root+"/"))){let y=$g(r.root,i);p=y===""?".":y}let g=xt(await $t({message:"mount_as (directory relative to the workspace root)",placeholder:p,initialValue:p})).trim()||p;o.some(y=>(y.mountAs??y.name)===g)&&le(`mount_as "${g}" is already used by another repo`),await Tg(e,a);let d={name:u,host:a,owner:c,repoName:l,mountAs:g,...f?{defaultBranch:f}:{}};if(!i){let y=r?Ao(r.root,g):$e(e.projectId,u);if(Mn(Ao(y,".git")))J.message(`already cloned at ${y}`);else{J.info(`cloning ${s} \u2192 ${y} \u2026`);try{await Rl().clone(s,y),J.success(`cloned into ${y}`)}catch(b){le(`clone failed: ${b instanceof Error?b.message.trim():String(b)}
|
|
606
|
+
check that your ${a} credentials grant read access to ${c}/${l}`)}}}let h;try{h=await $a(e.hubUrl,e.cliToken,e.projectId,d)}catch(y){y instanceof A&&le(`HUB \u2192 ${y.status} ${y.message}`),le(y instanceof Error?y.message:String(y))}let{updated:S,errors:w}=fr(e.projectId,h.repos,r?.contextDir);for(let y of S)J.message(`updated ${y}`);for(let y of w)J.warn(`could not update ${y.path}: ${y.error}`);J.success(`added "${u}" \u2014 project now has ${h.repos.length} repo(s)`),Tl("done")}async function jl(t){let e=ge(t.profile);Cl(`codepipe repo remove \u2192 project ${e.projectId}`);let r=me()??void 0,o;try{let c=(await K(e.hubUrl,e.cliToken,e.projectId)).repos.find(l=>l.name===t.name);o=c?c.mountAs??c.name:void 0}catch{}let n;try{n=await xa(e.hubUrl,e.cliToken,e.projectId,t.name)}catch(a){a instanceof A&&(a.status===404&&le(`no repo named "${t.name}" in this project`),le(`HUB \u2192 ${a.status} ${a.message}`)),le(a instanceof Error?a.message:String(a))}let{updated:i,errors:s}=fr(e.projectId,n.repos,r?.contextDir);for(let a of i)J.message(`updated ${a}`);for(let a of s)J.warn(`could not update ${a.path}: ${a.error}`);if(t.purge)if(o===".")J.warn(`"${t.name}" is mounted in place (mount_as: .) \u2014 refusing to delete the workspace; skipping --purge`);else{let a=r&&o?Ao(r.root,o):$e(e.projectId,t.name);if(Mn(Ao(a,".git")))try{bg(a,{recursive:!0,force:!0}),J.message(`deleted local clone ${a}`)}catch(c){J.warn(`could not delete ${a}: ${c instanceof Error?c.message:String(c)}`)}else J.message(`no local clone found to purge (${a})`)}J.success(`removed "${t.name}" \u2014 ${n.repos.length} repo(s) left`),Tl("done")}async function Pl(t){let e=ge(t.profile),r;try{r=(await K(e.hubUrl,e.cliToken,e.projectId)).repos}catch(o){console.error(`could not read project from HUB: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}if(r.length===0){console.log(`project ${e.projectId} has no repos yet \u2014 add one with \`codepipe repo add\``);return}console.log(`project ${e.projectId} \u2014 ${r.length} repo(s):`);for(let o of r){let n=o.mountAs??o.name,i=o.defaultBranch?` @${o.defaultBranch}`:"";console.log(` ${o.name} ${o.host}:${o.owner}/${o.repoName}${i} \u2192 ${n}`)}}import{spawn as Rg}from"node:child_process";import{existsSync as El}from"node:fs";import{homedir as Ig,hostname as jg}from"node:os";import{join as _o}from"node:path";async function Pg(t,e,r){let o=ie(e);if(!o)return!0;if(o.hubUrl!==t.hubUrl.replace(/\/$/,""))throw new Error(`worker config ${ve(e)} points at a different HUB (${o.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`);let n;try{n=await pa(t.hubUrl.replace(/\/$/,""),o.token)}catch(i){return console.warn(`[up] could not verify the worker registration (${i instanceof Error?i.message:String(i)}) \u2014 continuing`),!1}if(n==="unsupported")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(n==="ok")return console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`),!1;if(!r.reregister)throw new Error(`the HUB no longer knows this worker registration (${o.sandboxId}) \u2014 it was removed on ${t.hubUrl}, but ${ve(e)} still holds its token.
|
|
607
|
+
Re-register it: codepipe up --reregister (or delete that file and run codepipe up)`);return console.log(`[up] --reregister: the HUB no longer knows ${o.sandboxId} \u2014 replacing the registration`),Ai(t.projectId,o.sandboxId)&&console.log(`[up] removed the stale cred-channel pin for ${o.sandboxId}`),!0}async function Eg(t,e,r){let o=ie(e)!==null;if(!await Pg(t,e,r))return;console.log(o?"[up] re-registering the worker \u2014 requesting an account-issued token from HUB":"[up] no worker registration \u2014 requesting an account-issued token from HUB");let n;try{({secret:n}=await go(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await ht({hub:t.hubUrl,token:n,name:r.name??`${jg()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...o?{force:!0}:{},...e?{profile:e}:{}})}function Ag(t,e){let r=ie(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=Ae(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=qr(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 _g(t,e){let r=process.cwd(),o=_o(r,Ie);if(Hr(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(El(o)){console.warn(`[up] ${o} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let n;try{n=await K(t.hubUrl,t.cliToken,t.projectId)}catch(u){console.warn(`[up] could not fetch the project summary (${u instanceof Error?u.message:String(u)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await Dn(r);if(!hi(r,i?.parsed??null,n.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:u=>console.log(u),warn:u=>console.warn(u)},c=await ko({cfg:t,secrets:s,contextDir:o,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=_o(Ig(),".codepipe",e?_o("profiles",e,"context-config"):"context-config");if(Xr(c.contextDir,l,a),!El(_o(c.contextDir,"project.yaml"))){Et(c.contextDir);let u={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};dr(c.contextDir,Ee(u,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function Al(t){let{cfg:e,profile:r}=Wr(t.profile);await _g(e,r),await Eg(e,r,t),Ag(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(g,d)=>{let h=S=>w=>{for(let y of w.toString("utf-8").split(`
|
|
599
608
|
`))y.length>0&&S.write(`${d} ${y}
|
|
600
|
-
`)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=
|
|
601
|
-
[up] ${g} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(g);setTimeout(()=>{for(let{name:d,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let f=c.map(({name:g,child:d})=>new Promise(h=>{d.on("exit",(S,w)=>h({name:g,code:S??(w?1:0)}))})),p=await Promise.race(f);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(f),process.exit(p.code)}import{existsSync as
|
|
602
|
-
`)}async function
|
|
609
|
+
`)};g.stdout?.on("data",h(process.stdout)),g.stderr?.on("data",h(process.stderr))},i=(g,d)=>{let h=Rg(process.execPath,[o,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return n(h,g),h};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,u=g=>{if(!l){l=!0,console.log(`
|
|
610
|
+
[up] ${g} \u2014 stopping both roles`);for(let{child:d}of c)d.exitCode===null&&d.kill(g);setTimeout(()=>{for(let{name:d,child:h}of c)h.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),h.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let f=c.map(({name:g,child:d})=>new Promise(h=>{d.on("exit",(S,w)=>h({name:g,code:S??(w?1:0)}))})),p=await Promise.race(f);l||(console.log(`[up] ${p.name} exited (code ${p.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(f),process.exit(p.code)}import{existsSync as Kl,mkdirSync as Dg,readFileSync as Bg,writeFileSync as Mg}from"node:fs";import{homedir as Gg}from"node:os";import{dirname as Fg,join as Wl}from"node:path";import*as rr from"node:readline";import{existsSync as Hn,readFileSync as Og,writeFileSync as Ng}from"node:fs";import{join as _r}from"node:path";import{simpleGit as Fn}from"simple-git";var _l=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Ug="apply-queue.json";function Ol(t){return _r(t,Ug)}function tr(t){let e=Ol(t);if(!Hn(e))return{};try{return JSON.parse(Og(e,"utf-8"))}catch{return{}}}function Nl(t,e){Ng(Ol(t),JSON.stringify(e,null,2)+`
|
|
611
|
+
`)}async function Ul(t,e,r,o,n){let i;try{i=await ya(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(p){return{ok:!1,message:`claim failed: ${p instanceof Error?p.message:String(p)}`}}let s=[];for(let p of i.repos){let g=t.spec.repos.find(w=>w.name===p.repoName);if(!g)return{ok:!1,message:`repo "${p.repoName}" not in project.yaml \u2014 run /sync`};let d=_r(t.root,g.mountAs);if(!Hn(_r(d,".git")))return{ok:!1,message:`${g.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Fn(d).status()).isClean())return{ok:!1,message:`${g.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:p,spec:g,dir:d})}let a=[];for(let p of s){let g=Fn(p.dir),d=await Lg(g),h=p.claimRepo;try{await g.fetch()}catch(y){return await Gn(a,n),{ok:!1,message:`fetch failed in ${p.spec.mountAs}: ${Ar(y)}`}}let S=`origin/${h.baseRef}`,w;try{w=await ro(g,{contextRepoCloneUrl:h.contextRepoCloneUrl,deliveryRef:h.deliveryRef,deliverySha:h.deliverySha,baseSha:h.baseSha,commitMessage:h.commitMessage})}catch(y){return await Gn(a,n),{ok:!1,message:`fetch delivery failed in ${p.spec.mountAs}: ${Ar(y)}`}}a.push({git:g,dir:p.dir,mountAs:p.spec.mountAs,originalRef:d,branch:h.branchName,baseSha:S,deliveryCommit:w,startPoint:S})}let c=[];for(let p of a)try{if(o==="apply"){await p.git.checkout(["-B",p.branch,p.startPoint]),await p.git.raw([..._l,"cherry-pick",p.deliveryCommit]);let g=(await p.git.revparse(["HEAD"])).trim();c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha,appliedSha:g})}else await p.git.checkout(["--detach",p.startPoint]),await p.git.raw([..._l,"cherry-pick","--no-commit",p.deliveryCommit]),await p.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:p.mountAs,branch:p.branch,baseSha:p.baseSha})}catch(g){return await p.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Gn(a,n),{ok:!1,message:`apply failed in ${p.mountAs}: ${Ar(g)} (rolled back all repos)`}}let l=tr(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},Nl(t.contextDir,l);let u=c.map(p=>p.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 ${u}
|
|
603
612
|
${f}
|
|
604
|
-
or: /abort ${r} --reason "..."`}}function
|
|
613
|
+
or: /abort ${r} --reason "..."`}}function Kn(t,e){let r=tr(t);r[e]&&(delete r[e],Nl(t,r))}async function Gn(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}: ${Ar(o)} \u2014 check manually`)}}async function Ll(t,e,r){let n=tr(t.contextDir)[e];if(n){for(let i of n.repos){let s=_r(t.root,i.mountAs);if(!Hn(_r(s,".git")))continue;let a=Fn(s),c=t.spec.repos.find(u=>u.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(u){r.warn(`rollback failed in ${i.mountAs}: ${Ar(u)} \u2014 check manually`)}}Kn(t.contextDir,e)}}async function Lg(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Ar(t){return t instanceof Error?t.message.trim():String(t)}var Oo=Wl(Gg(),".codepipe","history"),Dl=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],ql=500,Bl=40;async function Yl(){let t=me();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(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)),pr(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=tr(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
|
|
605
614
|
\u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
|
|
606
|
-
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=
|
|
607
|
-
`))}async function
|
|
608
|
-
`)}`:" (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}
|
|
609
|
-
`),t.unread+=1,
|
|
610
|
-
bye.`),setTimeout(()=>process.exit(0),150))}function
|
|
615
|
+
finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=rr.createInterface({input:process.stdin,output:process.stdout,completer:Hg,history:lh(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ls(s=>vt(i,s)),i.daemon=bo({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>vt(i,s),warn:s=>vt(i,s)},onEvent:s=>oh(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),qn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Kg(i,a)){Hl(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,qn(i),n.prompt()}),n.on("close",()=>{Hl(i)})}function Hg(t){let e=Dl.filter(r=>r.startsWith(t));return[e.length?e:Dl,t]}async function Kg(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Wg(),!1;case"/status":return await qg(t),!1;case"/tasks":return await Yg(t,o),!1;case"/task":return await Vg(t,o),!1;case"/sync":return await zg(t),!1;case"/logs":return nh(t,o),!1;case"/monitor":return ih(t),!1;case"/apply":return await Ml(t,o,"apply"),!1;case"/unstash":return await Ml(t,o,"unstash"),!1;case"/applied":return await Jg(t,o),!1;case"/abort":return await Xg(t,o),!1;case"/approve":return await Gl(t,o,"approve"),!1;case"/merge":return await Gl(t,o,"merge"),!1;case"/login":return Zg(t,o),!1;case"/secret":return eh(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Wg(){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(`
|
|
616
|
+
`))}async function qg(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=Kl(Wl(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Yg(t,e){let r=sh(e,"--phase");try{let o=await ga(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){Nr(o)}}async function Vg(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await ha(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){Nr(o)}}async function zg(t){let e=await Ir(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 Ml(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await Ul(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Jg(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=tr(t.ws.contextDir)[r],i=ah(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),u,f;if(l>0?(u=c.slice(0,l),f=c.slice(l+1)):(f=c,u=n?.repos.length===1?Qg(t,n.repos[0].mountAs):s.length===1?s[0]:""),!u){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let p=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!p){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:u,url:f,number:Number(p[1])})}try{let c=await wa(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Kn(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Nr(c)}}async function Gl(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await ka(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){Nr(n)}}async function Xg(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=ch(e,"--reason")||"local apply aborted";await Ll(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await ba(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){Nr(n)}}function Qg(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Zg(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},V(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 eh(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(`
|
|
617
|
+
`)}`:" (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}th(t.secrets,o,i),V(t.secrets),pr(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}rh(t.secrets,o),V(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function th(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 rh(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 oh(t,e){switch(e.kind){case"connected":t.connection="connecting",vt(t,"[hub] connected");break;case"registered":t.connection="registered",vt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Or(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",vt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Or(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Or(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?vt(t,`[hub] action ${e.actionType} done`):Or(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function vt(t,e){t.logBuffer.push(e),t.logBuffer.length>ql&&t.logBuffer.shift(),t.follow&&Or(t,e)}function nh(t,e){let r=e[0];if(r==="follow"||r==="on"){Wn(t,!0);return}if(r==="off"){Wn(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(ql,Number(r)||Bl)):Bl,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 ih(t){Wn(t,!t.follow)}function Wn(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Or(t,e){rr.cursorTo(process.stdout,0),rr.clearLine(process.stdout,0),process.stdout.write(e+`
|
|
618
|
+
`),t.unread+=1,qn(t),t.rl.prompt(!0)}function qn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Fl=!1;function Hl(t){Fl||(Fl=!0,uh(t.rl),t.daemon.stop(),console.log(`
|
|
619
|
+
bye.`),setTimeout(()=>process.exit(0),150))}function sh(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function ah(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 ch(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Nr(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function lh(){if(!Kl(Oo))return[];try{return Bg(Oo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function uh(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{Dg(Fg(Oo),{recursive:!0}),Mg(Oo,r.slice().reverse().join(`
|
|
611
620
|
`)+`
|
|
612
|
-
`)}catch{}}import{hostname as ch}from"node:os";import{cancel as lh,confirm as ql,intro as uh,isCancel as zl,log as tr,multiselect as ph,outro as Yl,password as dh,select as qn,text as Yn}from"@clack/prompts";function _r(t){lh(t),process.exit(1)}function rr(t){return zl(t)&&_r("aborted"),t}function Oo(t){return zl(t)&&_r("aborted"),typeof t=="string"?t:""}function Vn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Vl(t,e){try{let{secret:r}=await po(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&_r("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 fh(t,e){if(rr(await qn({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 pa(t,e);if(n.length>0)return rr(await ph({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}));tr.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){tr.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return Oo(await Yn({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 zn(t){uh("codepipe worker \u2014 set up this machine as a runner");let e=ne(t.profile);e&&(tr.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),rr(await ql({message:"re-register this worker?",initialValue:!1}))||_r("keeping the existing registration"));let r=we(t.profile)??we(),o=Oo(await Yn({message:"HUB URL",placeholder:ve,initialValue:L("HUB_URL")??r?.hubUrl??ve,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=rr(await qn({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 Vl(o,a),tr.success("account-issued registration token minted");else if(i==="login"){let p=await Jt();a=(await Xt(o,p)).cliToken,s=await Vl(o,a),tr.success("account-issued registration token minted")}else s=Oo(await dh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||_r("a registration token is required");let c=await fh(o,a),l=Oo(await Yn({message:"worker name",initialValue:ch(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=rr(await qn({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 gt({hub:o,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),tr.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!rr(await ql({message:"start the claim-loop now?",initialValue:!0}))){Yl("registered. start later with `codepipe worker`.");return}Yl("starting the claim-loop\u2026"),await Sr(t.profile?{profile:t.profile}:{})}function gh(){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 L("PROFILE")}var V=gh();ki(V);vi();var le=new mh;le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(pe).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 Wl()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await ul({configPath:t.config,skipVerify:t.skipVerify===!0}):await el({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await _i({...t,profile:V})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await tl({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});le.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Ma({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await qc({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await gl({profile:V,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await jc({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Pl({profile:V,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Jl=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Jl.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??L("HUB_URL")??we(V)?.hubUrl??ve,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Vn()){await zn({profile:V});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=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await gt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...V?{profile:V}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Jl.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ne(V)&&Vn()){await zn({profile:V});return}await Sr(V?{profile:V}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Xl=le.command("project").description("Manage CodePipe projects");Xl.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await bl({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Xl.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await $l({...t,cliProfile:V})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Jn=le.command("repo").description("Manage the project's git repositories");Jn.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Tl({profile:V,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Jn.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await Rl({profile:V,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Jn.command("list").description("List the project's repos").action(async()=>{try{await Il({profile:V})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();
|
|
621
|
+
`)}catch{}}import{hostname as ph}from"node:os";import{cancel as dh,confirm as Vl,intro as fh,isCancel as Xl,log as or,multiselect as mh,outro as zl,password as gh,select as Yn,text as Vn}from"@clack/prompts";function Ur(t){dh(t),process.exit(1)}function nr(t){return Xl(t)&&Ur("aborted"),t}function No(t){return Xl(t)&&Ur("aborted"),typeof t=="string"?t:""}function zn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Jl(t,e){try{let{secret:r}=await go(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&Ur("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function hh(t,e){if(nr(await Yn({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 da(t,e);if(n.length>0)return nr(await mh({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}));or.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){or.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return No(await Vn({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 Jn(t){fh("codepipe worker \u2014 set up this machine as a runner");let e=ie(t.profile);e&&(or.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),nr(await Vl({message:"re-register this worker?",initialValue:!1}))||Ur("keeping the existing registration"));let r=ke(t.profile)??ke(),o=No(await Vn({message:"HUB URL",placeholder:Ce,initialValue:L("HUB_URL")??r?.hubUrl??Ce,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=nr(await Yn({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 Jl(o,a),or.success("account-issued registration token minted");else if(i==="login"){let p=await Qt();a=(await Zt(o,p)).cliToken,s=await Jl(o,a),or.success("account-issued registration token minted")}else s=No(await gh({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||Ur("a registration token is required");let c=await hh(o,a),l=No(await Vn({message:"worker name",initialValue:ph(),validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=nr(await Yn({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 ht({hub:o,token:s,name:l,projects:c,...u?{llm:u}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),or.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!nr(await Vl({message:"start the claim-loop now?",initialValue:!0}))){zl("registered. start later with `codepipe worker`.");return}zl("starting the claim-loop\u2026"),await Rr(t.profile?{profile:t.profile}:{})}function wh(){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 L("PROFILE")}var X=wh();$i(X);Si();var ue=new yh;ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(fe).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 Yl()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await dl({configPath:t.config,skipVerify:t.skipVerify===!0}):await rl({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","Personal CLI token (issued during `codepipe init`)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Oi({...t,profile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ol({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Ga({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Vc({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await yl({profile:X,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Ec({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").option("--reregister","Replace the worker registration when the HUB no longer knows it (it was removed)",!1).action(async t=>{try{await Al({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Ql=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Ql.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??L("HUB_URL")??ke(X)?.hubUrl??Ce,r=t.token??L("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&zn()){await Jn({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=L("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??L("WORKER_NAME"),i=t.llm??L("WORKER_LLM");await ht({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)}});Ql.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ie(X)&&zn()){await Jn({profile:X});return}await Rr(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Zl=ue.command("project").description("Manage CodePipe projects");Zl.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await $l({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});Zl.command("move").description("Repoint an already-initialised project at another HUB (no full init wizard)").requiredOption("--hub <url>","Destination HUB base URL").option("--from-profile <id>","Source profile to move (defaults to --profile / the cwd workspace)").option("--to-profile <id>","Destination profile to write (defaults to the source profile \u2014 in place)").option("--project <id>","Destination project id (defaults to the source project id)").option("--account <email>","Destination account email (defaults to the source account, else prompts)").option("--yes","Skip the confirmation prompt",!1).action(async t=>{try{await vl({...t,cliProfile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Xn=ue.command("repo").description("Manage the project's git repositories");Xn.command("add").description("Add a repo to this project (a path to an existing clone, or a clone URL)").argument("[target]","Path to an already-cloned repo, or a repo clone URL").action(async t=>{try{await Il({profile:X,target:t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Xn.command("remove").description("Remove a repo from this project by its logical name").argument("<name>","Logical name of the repo (as shown by `codepipe repo list`)").option("--purge","Also delete the local clone",!1).action(async(t,e)=>{try{await jl({profile:X,name:t,purge:e.purge===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});Xn.command("list").description("List the project's repos").action(async()=>{try{await Pl({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();
|