@code-partner/codepipe 0.1.128-dev.12.g2b8ef04 → 0.1.128-dev.14.g0964444

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.
Files changed (2) hide show
  1. package/dist/index.js +87 -86
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,34 +1,34 @@
1
1
  #!/usr/bin/env node
2
- var ie="0.1.128-dev.12.g2b8ef04",pe="https://hub.dev.codepipe.dev";var de=2,xc=1;function or(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=xc&&t<=de}var ye=".devpipe-context.yaml",an=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",ye]}];function nr(t=1){return`# CodePipe Context Repo format version.
2
+ var se="0.1.128-dev.14.g0964444",de="https://hub.dev.codepipe.dev";var fe=2,xc=1;function ar(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=xc&&t<=fe}var ke=".devpipe-context.yaml",an=[{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",ke]}];function cr(t=1){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function cn(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 ln(t,e=an){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 un(t,e=an){return e.filter(r=>r.version>t)}function ir(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Le=/^[a-z][a-z0-9-]{1,30}$/,vc="-codepipe-ctx";function be(t){return`${t}${vc}`}var At={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function Ze(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 et="x-bitbucket-api-token-auth";function sr(t){switch(t){case At.gitlab:return"oauth2";case At.bitbucket:return"x-token-auth";default:return"x-access-token"}}var pn=20;function _(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Hf}from"commander";import{homedir as dn}from"node:os";import{mkdirSync as Sc,readFileSync as Cc,writeFileSync as Rc,existsSync as ro}from"node:fs";import{dirname as mn,join as ar,resolve as Tc}from"node:path";import{fileURLToPath as Ic}from"node:url";var fn=Tc(mn(Ic(import.meta.url)),"..");function gn(t){let e=ar(fn,".env");if(ro(e)&&process.loadEnvFile(e),t){let r=ar(fn,"profiles",t,".env");ro(r)&&process.loadEnvFile(r)}}function tt(t){let e=_("CONFIG");return e||(t?ar(dn(),".codepipe","profiles",t,"config.json"):ar(dn(),".codepipe","config.json"))}function Se(t){let e=tt(t);if(!ro(e))return null;let r=Cc(e,"utf-8");return JSON.parse(r)}function De(t,e){let r=tt(e);Sc(mn(r),{recursive:!0}),Rc(r,JSON.stringify(t,null,2)+`
6
- `,{mode:384})}function fe(t){let e=Se(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${tt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as wn}from"node:os";import{join as yn}from"node:path";import{existsSync as hn,renameSync as Pc}from"node:fs";function Be(t,e,r=o=>console.error(o)){if(hn(e)||!hn(t))return!1;try{return Pc(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}function bn(){Be(yn(wn(),".devpipe"),yn(wn(),".codepipe"))}import{homedir as kn}from"node:os";import{existsSync as $n,mkdirSync as xn,readFileSync as vn,writeFileSync as Sn}from"node:fs";import{dirname as Cn,join as Rn}from"node:path";function cr(t,e,r){let o=H(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,Q(o),"pinned")}function Ge(t){return Rn(kn(),".codepipe","secrets",`${t}.json`)}function H(t){let e=Ge(t);return $n(e)?JSON.parse(vn(e,"utf-8")):null}function Q(t){let e=Ge(t.projectId);xn(Cn(e),{recursive:!0}),Sn(e,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function lr(){return Rn(kn(),".codepipe","shared.json")}function Ec(){let t=lr();return $n(t)?JSON.parse(vn(t,"utf-8")):null}function Tn(t){let e=lr();xn(Cn(e),{recursive:!0}),Sn(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function rt(t){let e=H(t)?.claude?.oauthToken;return e||Ec()?.claude?.oauthToken}function _t(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 ot(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function In(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Se(e);r&&!t.force&&(console.error(`already configured at ${tt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");De({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};Q(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${tt(e)}`)}import{homedir as Ro}from"node:os";import{join as Dt}from"node:path";import{appendFileSync as jc,existsSync as Pn,mkdirSync as Ac,renameSync as En,statSync as _c,unlinkSync as Oc}from"node:fs";import{Writable as Nc}from"node:stream";import{join as Uc}from"node:path";var jn={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},nt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&Ac(e.dir,{recursive:!0}),this.currentPath=Uc(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
5
+ `}function cn(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 ln(t,e=an){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 un(t,e=an){return e.filter(r=>r.version>t)}function lr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var He=/^[a-z][a-z0-9-]{1,30}$/,vc="-codepipe-ctx";function $e(t){return`${t}${vc}`}var Ut={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function ot(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 nt="x-bitbucket-api-token-auth";function ur(t){switch(t){case Ut.gitlab:return"oauth2";case Ut.bitbucket:return"x-token-auth";default:return"x-access-token"}}var pn=20;function _(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Df}from"commander";import{homedir as dn}from"node:os";import{mkdirSync as Sc,readFileSync as Cc,writeFileSync as Rc,existsSync as oo}from"node:fs";import{dirname as mn,join as pr,resolve as Tc}from"node:path";import{fileURLToPath as Ic}from"node:url";var fn=Tc(mn(Ic(import.meta.url)),"..");function gn(t){let e=pr(fn,".env");if(oo(e)&&process.loadEnvFile(e),t){let r=pr(fn,"profiles",t,".env");oo(r)&&process.loadEnvFile(r)}}function it(t){let e=_("CONFIG");return e||(t?pr(dn(),".codepipe","profiles",t,"config.json"):pr(dn(),".codepipe","config.json"))}function Te(t){let e=it(t);if(!oo(e))return null;let r=Cc(e,"utf-8");return JSON.parse(r)}function Fe(t,e){let r=it(e);Sc(mn(r),{recursive:!0}),Rc(r,JSON.stringify(t,null,2)+`
6
+ `,{mode:384})}function me(t){let e=Te(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${it(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as wn}from"node:os";import{join as yn}from"node:path";import{existsSync as hn,renameSync as Pc}from"node:fs";function Ke(t,e,r=o=>console.error(o)){if(hn(e)||!hn(t))return!1;try{return Pc(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}function bn(){Ke(yn(wn(),".devpipe"),yn(wn(),".codepipe"))}import{homedir as kn}from"node:os";import{existsSync as $n,mkdirSync as xn,readFileSync as vn,writeFileSync as Sn}from"node:fs";import{dirname as Cn,join as Rn}from"node:path";function dr(t,e,r){let o=H(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,Z(o),"pinned")}function We(t){return Rn(kn(),".codepipe","secrets",`${t}.json`)}function H(t){let e=We(t);return $n(e)?JSON.parse(vn(e,"utf-8")):null}function Z(t){let e=We(t.projectId);xn(Cn(e),{recursive:!0}),Sn(e,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function fr(){return Rn(kn(),".codepipe","shared.json")}function no(){let t=fr();return $n(t)?JSON.parse(vn(t,"utf-8")):null}function Tn(t){let e=fr();xn(Cn(e),{recursive:!0}),Sn(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function st(t){let e=H(t)?.claude?.oauthToken;return e||no()?.claude?.oauthToken}function Lt(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 at(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function In(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Te(e);r&&!t.force&&(console.error(`already configured at ${it(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Fe({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};Z(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${it(e)}`)}import{homedir as Po}from"node:os";import{join as Ft}from"node:path";import{appendFileSync as Ec,existsSync as Pn,mkdirSync as jc,renameSync as En,statSync as Ac,unlinkSync as _c}from"node:fs";import{Writable as Oc}from"node:stream";import{join as Nc}from"node:path";var jn={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},ct=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&jc(e.dir,{recursive:!0}),this.currentPath=Nc(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
9
9
  `)?e:e+`
10
- `;jc(this.currentPath,r,"utf-8")}asWritable(){return new Nc({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||!Pn(this.currentPath)||_c(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Pn(o)&&(r>=this.cfg.maxFiles?Oc(o):En(o,`${this.currentPath}.${r+1}`))}En(this.currentPath,`${this.currentPath}.1`)}}};function ur(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Lc(process.env[`${t}_MAX_BYTES`]??String(jn.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):jn.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Lc(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 pr(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(Dc(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 Dc(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Bc(n)).join(" ");return`${r} ${t} ${o}`}function Bc(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Cu}from"node:path";import"ws";import{createHash as Gc}from"node:crypto";import{existsSync as Mc,readFileSync as Hc}from"node:fs";import{homedir as Fc,hostname as oo}from"node:os";import{join as Kc}from"node:path";function An(t){return Gc("sha256").update(t).digest("hex").slice(0,12)}function Wc(){let t=_("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Kc(Fc(),".claude","credentials.json");if(!Mc(e))return;let r=JSON.parse(Hc(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 _n(t){let e=Wc(),r=_("ACCOUNT_ID")?.trim(),o=_("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=rt(t);return n?{accountId:`acct-${An(n)}`,label:o||oo(),...e?{email:e}:{}}:{accountId:`acct-${An(`host:${oo()}`)}`,label:o||oo(),...e?{email:e}:{}}}import{existsSync as Yc}from"node:fs";import{join as qc}from"node:path";import{simpleGit as Vc}from"simple-git";async function On(t,e){if(!Yc(qc(t,".git")))return{status:"skipped"};let r=Vc(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${zc(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 zc(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as no,readFileSync as Nn,readdirSync as Jc,watch as Xc}from"node:fs";import{join as io}from"node:path";var dr=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(no(this.contextDir))try{this.watcher=Xc(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=io(this.contextDir,e);if(!no(r))return null;try{return Nn(r,"utf-8")}catch{return null}}readPrompts(){let e=io(this.contextDir,"prompts"),r={};if(!no(e))return r;let o;try{o=Jc(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Nn(io(e,n),"utf-8")}catch{}}return r}};import{existsSync as cl,readFileSync as ll,readdirSync as ul}from"node:fs";import{join as Hn}from"node:path";import{simpleGit as pl}from"simple-git";import{existsSync as tl,mkdirSync as rl,writeFileSync as Dn}from"node:fs";import{dirname as ol,isAbsolute as nl,join as Gn,normalize as po}from"node:path";import{simpleGit as Mn}from"simple-git";import{existsSync as Ce,mkdirSync as Qc,readFileSync as so,writeFileSync as fr}from"node:fs";import{join as Me}from"node:path";import{simpleGit as Zc}from"simple-git";var it=["project.yaml","regimen.yaml"];function ao(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=Me(t,n);Ce(s)||(fr(s,i),r.push(n))}return r}function Un(t,e,r){if(Ce(e))for(let o of it){let n=Me(e,o),i=Me(t,o);if(!(!Ce(n)||Ce(i)))try{fr(i,so(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 el=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function mr(t){let e=Me(t,".gitignore"),r=Ce(e)?so(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(it.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
10
+ `;Ec(this.currentPath,r,"utf-8")}asWritable(){return new Oc({write:(e,r,o)=>{try{let n=typeof e=="string"?e:e.toString("utf-8");for(let i of n.split(/\r?\n/))i&&this.writeLine(i);o()}catch(n){o(n)}}})}rotateIfNeeded(){if(!(this.cfg.maxBytes<=0||!Pn(this.currentPath)||Ac(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Pn(o)&&(r>=this.cfg.maxFiles?_c(o):En(o,`${this.currentPath}.${r+1}`))}En(this.currentPath,`${this.currentPath}.1`)}}};function mr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Uc(process.env[`${t}_MAX_BYTES`]??String(jn.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):jn.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Uc(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),o=(e[2]??"").toLowerCase();return o==="g"?r*1024**3:o==="m"?r*1024**2:o==="k"?r*1024:r}function gr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(o,n)=>(...i)=>{o(...i);try{t.writeLine(Lc(n,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Lc(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Dc(n)).join(" ");return`${r} ${t} ${o}`}function Dc(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Su}from"node:path";import"ws";import{createHash as Bc}from"node:crypto";import{existsSync as Gc,readFileSync as Mc}from"node:fs";import{homedir as Hc,hostname as io}from"node:os";import{join as Fc}from"node:path";function An(t){return Bc("sha256").update(t).digest("hex").slice(0,12)}function Kc(){let t=_("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Fc(Hc(),".claude","credentials.json");if(!Gc(e))return;let r=JSON.parse(Mc(e,"utf-8")),o=[r.email,r.account?.email,r.user?.email];for(let n of o)if(typeof n=="string"&&n.includes("@"))return n.trim().toLowerCase()}catch{}}function _n(t){let e=Kc(),r=_("ACCOUNT_ID")?.trim(),o=_("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=st(t);return n?{accountId:`acct-${An(n)}`,label:o||io(),...e?{email:e}:{}}:{accountId:`acct-${An(`host:${io()}`)}`,label:o||io(),...e?{email:e}:{}}}import{existsSync as Wc}from"node:fs";import{join as qc}from"node:path";import{simpleGit as Yc}from"simple-git";async function On(t,e){if(!Wc(qc(t,".git")))return{status:"skipped"};let r=Yc(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Vc(n)}`}}let o=await r.status();if(!o.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(o.current!==e)return{status:"warn",reason:`on '${o.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function Vc(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as so,readFileSync as Nn,readdirSync as zc,watch as Jc}from"node:fs";import{join as ao}from"node:path";var hr=class{constructor(e,r,o,n,i=6e4){this.contextDir=e;this.projectId=r;this.send=o;this.log=n;this.intervalMs=i}timer=null;watcher=null;debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(so(this.contextDir))try{this.watcher=Jc(this.contextDir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()})}catch{this.watcher=null}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts()}}readFile(e){let r=ao(this.contextDir,e);if(!so(r))return null;try{return Nn(r,"utf-8")}catch{return null}}readPrompts(){let e=ao(this.contextDir,"prompts"),r={};if(!so(e))return r;let o;try{o=zc(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=Nn(ao(e,n),"utf-8")}catch{}}return r}};import{existsSync as al,readFileSync as cl,readdirSync as ll}from"node:fs";import{join as Fn}from"node:path";import{simpleGit as ul}from"simple-git";import{existsSync as el,mkdirSync as tl,writeFileSync as Bn}from"node:fs";import{dirname as rl,isAbsolute as ol,join as Mn,normalize as mo}from"node:path";import{simpleGit as Hn}from"simple-git";import{existsSync as Ie,mkdirSync as Un,readFileSync as co,writeFileSync as lt}from"node:fs";import{homedir as Xc}from"node:os";import{join as ge}from"node:path";import{simpleGit as Qc}from"simple-git";var ut=["project.yaml","regimen.yaml"];function lo(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=ge(t,n);Ie(s)||(lt(s,i),r.push(n))}return r}function qe(t,e,r){let o=ge(Xc(),".codepipe","profiles",t,"context-config");return Un(o,{recursive:!0}),lt(ge(o,"project.yaml"),e.projectYaml),lt(ge(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Ln(t,e,r){if(Ie(e))for(let o of ut){let n=ge(e,o),i=ge(t,o);if(!(!Ie(n)||Ie(i)))try{lt(i,co(n)),r.info(`[config] seeded local ${o} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${o}: ${s instanceof Error?s.message:String(s)}`)}}}var Zc=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function wr(t){let e=ge(t,".gitignore"),r=Ie(e)?co(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(ut.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
11
  `)?"":`
12
- `;return fr(e,r+i+el.join(`
12
+ `;return lt(e,r+i+Zc.join(`
13
13
  `)+`
14
- `),!0}async function Ln(t,e){try{if(!Ce(Me(t,".git")))return;let r=Zc(t),o=(await r.raw(["ls-files","--",...it])).split(`
15
- `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;mr(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 uo(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 co(t){let e=new Map;for(let r of it){let o=Me(t,r);Ce(o)&&e.set(r,so(o))}return e}function lo(t,e){Qc(t,{recursive:!0});for(let[r,o]of e){let n=Me(t,r);Ce(n)||fr(n,o)}}var Bn=3,il=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function gr(t,e,r){if(!tl(Gn(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=al(t,i.path);rl(ol(s),{recursive:!0}),i.encoding==="base64"?Dn(s,Buffer.from(i.content,"base64")):Dn(s,i.content)}let o=Mn(t);await o.add(["-A","--",".",...it.map(i=>`:(exclude)${i}`)]),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await uo(t))}async function uo(t){let e=Mn(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Bn;o++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let n=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${n}`])}catch{let i=await sl(e);if(i.length>0&&i.every(s=>il.has(s)))await e.raw(["checkout","--theirs","--",...i]),await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"]);else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${Bn} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function sl(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
16
- `).map(r=>r.trim()).filter(Boolean)}function al(t,e){if(nl(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=po(Gn(t,e)),o=po(t+"/");if(r!==po(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var dl=/^(\d{4})-(.+)\.md$/,fl="0000-template.md";function ml(t){let e=t.split(`
17
- `),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function gl(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
18
- `),a=s.findIndex(R=>R.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,u=new Set(["status","date","tasks"]),p=[],f="",l=null,d=a>=0?a+1:0;for(let R=d;R<s.length;R++){let v=(s[R]??"").trim();if(v===""){d=R+1;continue}let T=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!T)break;let j=(T[1]??"").trim().toLowerCase(),U=(T[2]??"").trim(),S=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);S&&(l=parseInt(S[1]??"",10)),j==="tasks"&&(f=U),u.has(j)||p.push(v),d=R+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,w=s.slice(d).join(`
14
+ `),!0}async function Dn(t,e){try{if(!Ie(ge(t,".git")))return;let r=Qc(t),o=(await r.raw(["ls-files","--",...ut])).split(`
15
+ `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;wr(t),await r.raw(["rm","--cached","--quiet","--",...o]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await fo(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 uo(t){let e=new Map;for(let r of ut){let o=ge(t,r);Ie(o)&&e.set(r,co(o))}return e}function po(t,e){Un(t,{recursive:!0});for(let[r,o]of e){let n=ge(t,r);Ie(n)||lt(n,o)}}var Gn=3,nl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function yr(t,e,r){if(!el(Mn(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=sl(t,i.path);tl(rl(s),{recursive:!0}),i.encoding==="base64"?Bn(s,Buffer.from(i.content,"base64")):Bn(s,i.content)}let o=Hn(t);await o.add(["-A","--",".",...ut.map(i=>`:(exclude)${i}`)]),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await fo(t))}async function fo(t){let e=Hn(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Gn;o++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let n=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${n}`])}catch{let i=await il(e);if(i.length>0&&i.every(s=>nl.has(s)))await e.raw(["checkout","--theirs","--",...i]),await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"]);else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${Gn} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function il(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
16
+ `).map(r=>r.trim()).filter(Boolean)}function sl(t,e){if(ol(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=mo(Mn(t,e)),o=mo(t+"/");if(r!==mo(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var pl=/^(\d{4})-(.+)\.md$/,dl="0000-template.md";function fl(t){let e=t.split(`
17
+ `),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function ml(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
18
+ `),a=s.findIndex(C=>C.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,u=new Set(["status","date","tasks"]),p=[],f="",l=null,d=a>=0?a+1:0;for(let C=d;C<s.length;C++){let v=(s[C]??"").trim();if(v===""){d=C+1;continue}let T=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!T)break;let E=(T[1]??"").trim().toLowerCase(),U=(T[2]??"").trim(),S=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);S&&(l=parseInt(S[1]??"",10)),E==="tasks"&&(f=U),u.has(E)||p.push(v),d=C+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,w=s.slice(d).join(`
19
19
  `).replace(/^\n+/,""),k=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${g}`,...p,"",w].join(`
20
20
  `);return{content:k.endsWith(`
21
21
  `)?k:k+`
22
- `,supersedes:l}}function hl(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
22
+ `,supersedes:l}}function gl(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
23
23
 
24
- - **Status:** superseded by ADR-${r}`):o}function wl(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(`
24
+ - **Status:** superseded by ADR-${r}`):o}function hl(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
25
25
  `)+`
26
- `}async function Fn(t,e,r,o=new Date().toISOString().slice(0,10)){try{await pl(t).pull(void 0,void 0,["--rebase"])}catch{}let n=Hn(t,"adr"),i=new Map;if(cl(n))for(let l of ul(n)){let d=dl.exec(l);!d||l===fl||i.set(l,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:ll(Hn(n,l),"utf-8")})}let s=Math.max(0,...[...i.values()].map(l=>l.num))+1,a=new Map,c=[],u=[];for(let l of r){if([...i.entries()].find(([,v])=>v.slug===l.slug&&v.content.includes(e))){u.push(l.slug);continue}let g=s++,w=`${String(g).padStart(4,"0")}-${l.slug}.md`,{content:k,supersedes:R}=gl(l.content,g,l.slug,e,o);if(a.set(w,k),i.set(w,{num:g,slug:l.slug,content:k}),c.push(`adr/${w}`),R!==null){let v=[...i.keys()].find(T=>T.startsWith(`${String(R).padStart(4,"0")}-`));if(v&&v!==w){let T=hl(a.get(v)??i.get(v).content,g);a.set(v,T),i.set(v,{...i.get(v),content:T})}}}if(c.length===0)return{promoted:c,skipped:u};let p=[...i.entries()].map(([l,d])=>({num:d.num,file:l,header:ml(d.content)}));a.set("INDEX.md",wl(p));let f=[...a.entries()].map(([l,d])=>({path:`adr/${l}`,content:d}));return await gr(t,f,`adr(${e}): promote ${r.map(l=>l.slug).join(", ")}`),{promoted:c,skipped:u}}import{existsSync as Kn,readFileSync as bl}from"node:fs";import{join as Wn}from"node:path";function kl(t){let e=Wn(t,ye);if(!Kn(e))return 0;try{return cn(bl(e,"utf-8"))}catch{return 0}}function $l(t,e,r,o=1){let n=e<o,i=n?ln(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function hr(t,e){return $l(e,kl(t),r=>Kn(Wn(t,r)))}import{existsSync as Ul,mkdirSync as Ll,mkdtempSync as Dl,rmSync as Bl,writeFileSync as zn}from"node:fs";import{tmpdir as Gl}from"node:os";import{dirname as Ml,join as yo}from"node:path";import{simpleGit as bo}from"simple-git";var He=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Yn(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
27
- `+t.slice(t.length-e)}async function st(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 wo(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 at(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 xl(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 xl(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ct(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Vn(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let o=(await e.json()).scopes??[];return o.length>0&&!o.includes("api")?`GitLab token scopes [${o.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var fo=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 He(`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()}`)}},mo=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 He(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,u=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])u=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(u=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return u?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let u=(await c.json()).workflow_runs??[],p=[];for(let f of u.filter(l=>l.conclusion&&i.includes(l.conclusion))){let l=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!l.ok)continue;let d=(await l.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let k=await w.text();p.push(`### CI job: ${g.name}
26
+ `}async function Kn(t,e,r,o=new Date().toISOString().slice(0,10)){try{await ul(t).pull(void 0,void 0,["--rebase"])}catch{}let n=Fn(t,"adr"),i=new Map;if(al(n))for(let l of ll(n)){let d=pl.exec(l);!d||l===dl||i.set(l,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:cl(Fn(n,l),"utf-8")})}let s=Math.max(0,...[...i.values()].map(l=>l.num))+1,a=new Map,c=[],u=[];for(let l of r){if([...i.entries()].find(([,v])=>v.slug===l.slug&&v.content.includes(e))){u.push(l.slug);continue}let g=s++,w=`${String(g).padStart(4,"0")}-${l.slug}.md`,{content:k,supersedes:C}=ml(l.content,g,l.slug,e,o);if(a.set(w,k),i.set(w,{num:g,slug:l.slug,content:k}),c.push(`adr/${w}`),C!==null){let v=[...i.keys()].find(T=>T.startsWith(`${String(C).padStart(4,"0")}-`));if(v&&v!==w){let T=gl(a.get(v)??i.get(v).content,g);a.set(v,T),i.set(v,{...i.get(v),content:T})}}}if(c.length===0)return{promoted:c,skipped:u};let p=[...i.entries()].map(([l,d])=>({num:d.num,file:l,header:fl(d.content)}));a.set("INDEX.md",hl(p));let f=[...a.entries()].map(([l,d])=>({path:`adr/${l}`,content:d}));return await yr(t,f,`adr(${e}): promote ${r.map(l=>l.slug).join(", ")}`),{promoted:c,skipped:u}}import{existsSync as Wn,readFileSync as yl}from"node:fs";import{join as qn}from"node:path";function bl(t){let e=qn(t,ke);if(!Wn(e))return 0;try{return cn(yl(e,"utf-8"))}catch{return 0}}function kl(t,e,r,o=1){let n=e<o,i=n?ln(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function br(t,e){return kl(e,bl(t),r=>Wn(qn(t,r)))}import{existsSync as Nl,mkdirSync as Ul,mkdtempSync as Ll,rmSync as Dl,writeFileSync as Jn}from"node:fs";import{tmpdir as Bl}from"node:os";import{dirname as Gl,join as ko}from"node:path";import{simpleGit as $o}from"simple-git";var Ye=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function Yn(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
27
+ `+t.slice(t.length-e)}async function pt(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 bo(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 dt(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await $l(n);throw n.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):n.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):n.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${n.status} ${n.statusText}${i}`)}async function $l(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function ft(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 zn(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 go=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 Ye(`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()}`)}},ho=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 Ye(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,u=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])u=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(u=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return u?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let u=(await c.json()).workflow_runs??[],p=[];for(let f of u.filter(l=>l.conclusion&&i.includes(l.conclusion))){let l=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!l.ok)continue;let d=(await l.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let k=await w.text();p.push(`### CI job: ${g.name}
28
28
 
29
29
  ${Yn(k,8e3)}`)}}return p.length===0?void 0:Yn(p.join(`
30
30
 
31
- `),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let u=(await a.json()).head?.ref;u&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${u}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},go=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 He(`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=vl(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function vl(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 ho=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(qn(e,r,"merge"))}async closePR(e,r,o){throw new Error(qn(e,r,"close"))}};function qn(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 ke(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new mo(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new fo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new go(e)}return new ho}function lt(t,e,r,o){return[{path:"README.md",content:_l(t,e)},{path:".gitignore",content:Il()},{path:"CLAUDE.md",content:El(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Pl()},{path:"knowledge/README.md",content:jl()},{path:"knowledge/build.yaml",content:Al()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Tl()},{path:"adr/README.md",content:Sl()},{path:"adr/0000-template.md",content:Cl()},{path:"adr/INDEX.md",content:Rl()},{path:ye,content:nr()}]}function Sl(){return`# ADR \u2014 architecture decision records
31
+ `),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let u=(await a.json()).head?.ref;u&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${u}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},wo=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 Ye(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(n.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=xl(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function xl(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}var yo=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(Vn(e,r,"merge"))}async closePR(e,r,o){throw new Error(Vn(e,r,"close"))}};function Vn(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 xe(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new ho(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new go(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new wo(e)}return new yo}function mt(t,e,r,o){return[{path:"README.md",content:Al(t,e)},{path:".gitignore",content:Tl()},{path:"CLAUDE.md",content:Pl(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Il()},{path:"knowledge/README.md",content:El()},{path:"knowledge/build.yaml",content:jl()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Rl()},{path:"adr/README.md",content:vl()},{path:"adr/0000-template.md",content:Sl()},{path:"adr/INDEX.md",content:Cl()},{path:ke,content:cr()}]}function vl(){return`# ADR \u2014 architecture decision records
32
32
 
33
33
  Accepted architectural decisions of this project \u2014 its **framework**. The
34
34
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -56,7 +56,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
56
56
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
57
57
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
58
58
  open a PR to this repository.
59
- `}function Cl(){return`# ADR-NNNN: <title>
59
+ `}function Sl(){return`# ADR-NNNN: <title>
60
60
 
61
61
  - **Status:** accepted | superseded by ADR-NNNN
62
62
  - **Date:** YYYY-MM-DD
@@ -78,12 +78,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
78
78
  ## Alternatives considered
79
79
 
80
80
  - **<alternative>** \u2014 why it was rejected.
81
- `}function Rl(){return`# ADR index
81
+ `}function Cl(){return`# ADR index
82
82
 
83
83
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
84
84
 
85
85
  (no accepted ADRs yet)
86
- `}function Tl(){return`# Audit
86
+ `}function Rl(){return`# Audit
87
87
 
88
88
  Pipeline event logs. Naming is per-writer: each codepipe
89
89
  project appends only to its own file \u2014
@@ -92,14 +92,14 @@ project appends only to its own file \u2014
92
92
 
93
93
  \u2014 so several team members' CLIs never contend on one file. Do not create a
94
94
  shared aggregate here.
95
- `}function Re(t,e,r,o){return{projectYaml:Ol(t,r,o),regimenYaml:Nl(t.automationLevel,e)}}function Il(){return`# codepipe project config is local to each member's workspace
95
+ `}function Pe(t,e,r,o){return{projectYaml:_l(t,r,o),regimenYaml:Ol(t.automationLevel,e)}}function Tl(){return`# codepipe project config is local to each member's workspace
96
96
  project.yaml
97
97
  regimen.yaml
98
98
 
99
99
  # codepipe runtime
100
100
  session.log
101
101
  apply-queue.json
102
- `}function Pl(){return`# Index prompt
102
+ `}function Il(){return`# Index prompt
103
103
 
104
104
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
105
105
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -156,7 +156,7 @@ current working directory; write nothing else under the Context Repo.
156
156
  Keep both durable and skimmable \u2014 they are read at the start of every future
157
157
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
158
158
  empty or unavailable, say so briefly rather than inventing content.
159
- `}function El(t){return`# Project context for the CodePipe agent
159
+ `}function Pl(t){return`# Project context for the CodePipe agent
160
160
 
161
161
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
162
162
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -184,7 +184,7 @@ project's architectural invariants: read them at the start of a task and treat
184
184
  them as binding. New or changed decisions do **not** go here directly \u2014 during
185
185
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
186
186
  only after the analysis is approved.
187
- `}function jl(){return`# Knowledge
187
+ `}function El(){return`# Knowledge
188
188
 
189
189
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
190
190
  **memory** across tasks. Architectural decisions, domain rules,
@@ -201,7 +201,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
201
201
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
202
202
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
203
203
  any merge conflict in it as noise (either side converges on the next run).
204
- `}function Al(){return`# BUILD phase config. Discovered & maintained by the agent.
204
+ `}function jl(){return`# BUILD phase config. Discovered & maintained by the agent.
205
205
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
206
206
  # Success = every step exits 0. Credentials are NOT available inside the container.
207
207
  #
@@ -217,7 +217,7 @@ any merge conflict in it as noise (either side converges on the next run).
217
217
  # - name: test
218
218
  # run: npm test
219
219
  # timeout_sec: 600 # per-step timeout (optional, default 600)
220
- `}function _l(t,e){return`# ${e.name}
220
+ `}function Al(t,e){return`# ${e.name}
221
221
 
222
222
  Context Repo for the **${t.name}** project (CodePipe).
223
223
 
@@ -243,7 +243,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
243
243
  pipeline \u2014 don't edit them by hand.
244
244
 
245
245
  Automation level: **${t.automationLevel}**.
246
- `}function Ol(t,e,r){let o=e?`
246
+ `}function _l(t,e,r){let o=e?`
247
247
  tracker_url: ${e}`:`
248
248
  # tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
249
249
  assignee: ${r}`:`require_assignee: false
@@ -301,7 +301,7 @@ branch:
301
301
 
302
302
  repos:
303
303
  ${s}
304
- `}function Nl(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
304
+ `}function Ol(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
305
305
  automation:
306
306
  level: ${t}
307
307
 
@@ -416,21 +416,22 @@ parallelism:
416
416
  # # the previous task's branch (auto-merge without reworking the
417
417
  # # tail of the chain).
418
418
  # mode: parallel
419
- `}function Hl(t){return`codepipe/context-migration-v${t}`}function Fl(t){let e=un(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${ye}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
420
- `)}async function Jn(t,e,r,o){let n=bo(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=hr(t,e);if(!i.outdated)return i;let s=Hl(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 Kl(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(u){return o.warn(`[ctx] context migration branch failed (will retry next start): ${u instanceof Error?u.message:String(u)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let u=ke(c),p=await u.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let f=await u.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Fl(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(u){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${u instanceof Error?u.message:String(u)}`),i}}async function Kl(t,e,r,o,n,i,s){let a=bo(t),c=Dl(yo(Gl(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let u={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(lt(u,p).map(g=>[g.path,g.content])),l=0;for(let g of o.missingPaths){if(g===ye)continue;let w=f.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=yo(c,g);Ul(k)||(Ll(Ml(k),{recursive:!0}),zn(k,w),l++)}zn(yo(c,ye),nr(o.currentVersion)),l++;let d=bo(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${l} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Bl(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as Wl,createDecipheriv as Yl,createHash as ql,createPrivateKey as Vl,createPublicKey as ko,diffieHellman as Xn,generateKeyPairSync as Qn,hkdfSync as Zn,randomBytes as zl}from"node:crypto";var ei=Buffer.from("devpipe-sealedbox-v1","utf-8");function ti(){let{publicKey:t,privateKey:e}=Qn("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ut(t){let e=Buffer.from(t,"base64");return(ql("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function wr(t,e){let r=ko({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=Qn("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Xn({privateKey:n,publicKey:r}),c=Buffer.from(Zn("sha256",a,Buffer.concat([i,s]),ei,32)),u=zl(12),p=Wl("aes-256-gcm",c,u),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,l=Buffer.concat([p.update(f),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:u.toString("base64"),tag:d.toString("base64"),ct:l.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function ri(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let o=Vl({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=ko({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=ko(o).export({type:"spki",format:"der"}),a=Xn({privateKey:o,publicKey:n}),c=Buffer.from(Zn("sha256",a,Buffer.concat([i,s]),ei,32)),u=Yl("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return u.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([u.update(Buffer.from(r.ct,"base64")),u.final()])}function Jl(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let o=e??t.claude?.oauthToken;return o&&(r.claudeOauthToken=o),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function oi(t,e,r,o){let n=Jl(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=cr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let u;try{u=wr(a.publicKey,i)}catch(p){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:u})}return s}import{existsSync as Xl,readFileSync as Ql,writeFileSync as Zl}from"node:fs";import{join as eu}from"node:path";import{parseDocument as tu}from"yaml";var ni=64;async function ii(t,e){if(!Number.isInteger(e)||e<1||e>ni)throw new Error(`maxJobs must be an integer in [1, ${ni}], got ${e}`);let r=eu(t,"regimen.yaml");if(!Xl(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=tu(Ql(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Zl(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as si,readFileSync as ai,writeFileSync as ru}from"node:fs";import{join as $o}from"node:path";import{parseDocument as ci}from"yaml";async function li(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=$o(t,"project.yaml");if(!si(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ci(ai(i,"utf-8"));if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=$o(t,"regimen.yaml");if(!si(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ci(ai(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)ru($o(t,i.path),i.content);return{files:r.map(i=>i.path)}}var ui=t=>console.log(t);function pi(t){ui=t}function Ot(t,e="info"){ui(t,e)}import{homedir as ou}from"node:os";import{existsSync as nu,mkdirSync as iu}from"node:fs";import{join as xo}from"node:path";import{simpleGit as di}from"simple-git";function Ut(t,e,r){let o=r??xo(ou(),".codepipe","repos");return xo(o,t,e)}async function yr(t,e,r={}){let o=Ut(t,e.name,r.baseDir),n=r.cloneUrlOverride??su(e);if(!nu(xo(o,".git"))){iu(o,{recursive:!0});let a=di();Ot(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
421
- ${u.trim()}`)}}let i=di(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
422
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Nt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var fi=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function br(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&&Ot(`[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 Nt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Nt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let u=(await t.raw([...fi,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),u}async function mi(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await Nt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await Nt(t,n)){let s=(await t.revparse([n])).trim();return await t.raw(["update-ref",o,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",o,i]).catch(()=>{}),i}async function gi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:u,defaultBranch:p,force:f}=r,l=await mi(t,i,()=>br(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:u}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await Nt(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,l]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...fi,"cherry-pick",l])}catch(R){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=R instanceof Error?R.message:String(R);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
423
- ${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),k=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(k),await t.push([o,"--delete",n]).catch(()=>{}),{commit:w}}async function hi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:u}=r,p=await mi(t,i,()=>br(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),u&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:u}}async function wi(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function su(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{X509Certificate as ki}from"node:crypto";import{readFileSync as au}from"node:fs";import Te from"node:tls";var $i=typeof Te.getCACertificates=="function"&&typeof Te.setDefaultCACertificates=="function",yi=!1,bi=new Map,xi=t=>console.warn(t);function cu(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function vi(t=xi){if(yi)return;yi=!0;let e=_("EXTRA_CA_FILE");if(!(!e||!$i))try{let r=cu(au(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Te.setDefaultCACertificates([...Te.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function Si(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function lu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
424
- `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function uu(t,e,r){return new Promise((o,n)=>{let i=Te.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new ki(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function vo(t,e,r){return new Promise(o=>{let n=Te.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 pu(t){try{let e=await fetch(t);return e.ok?new ki(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ci(t,e=443,r=xi){let o=`${t}:${e}`,n=bi.get(o);if(n)return n;let i=du(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return bi.set(o,i),i}async function du(t,e,r){if(!$i)return!1;let o=8e3;if(await vo(t,e,o))return!0;let n=await uu(t,e,o),i=Te.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=lu(n);if(!c)break;let u=await pu(c);if(!u)break;if(s.push(u.toString()),Te.setDefaultCACertificates([...i,...s]),await vo(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(u.subject===u.issuer)break;n=u}return vo(t,e,o)}function Fe(){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){vi();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let n=t.baseUrl+e,i={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(n,i)}catch(s){if(Si(s)&&await Ci(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ri=t=>new Promise(e=>setTimeout(e,t));function fu(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function mu(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function Pi(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=mu(),a=null;for(let c=1;c<=n;c++){let u=null;try{u=await me(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(u){if(u.ok)return u;let p=await u.text();if(c<n&&fu(u.status,p)){await Ri(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${u.status} ${p}`)}if(c<n){await Ri(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function pt(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 Ei(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 Ti=new Map;async function gu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ti.get(o);if(n)return n;let i=await me(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let a=(await i.json()).customFields.find(u=>u.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(u=>u.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ti.set(o,c.id),c.id}async function ji(t,e,r){let o=await gu(t,e,r);await Pi(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Ai(t,e,r){return await(await Pi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ii=new Map;async function hu(t,e){let r=Ii.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 Ii.set(e,i.id),i.id}async function _i(t,e,r,o,n){let i=await hu(t,e),s=await me(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function Oi(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await 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 Ni="attachments(id,name,url,size,mimeType)",wu="links(direction,linkType(name),issues(idReadable))",Ui=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ni},${wu}`,yu=`id,text,created,author(login),${Ni}`;function Li(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Di(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Bi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),n=`/api/issues?query=${encodeURIComponent(o)}&fields=${Ui}&$top=200`,i=await me(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Hi)}async function Gi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Ui}`,o=await me(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Hi(await o.json())}async function Mi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${yu}&$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=Li(s.attachments);return c&&(a.attachments=c),a})}function bu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Hi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),n=e.find(c=>c.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),n?.value?.name&&(i.issueType=n.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=Li(t.attachments);s&&(i.attachments=s);let a=bu(t.links);return a&&(i.links=a),i}var kr=new Map;async function So(t,e){let o=(kr.get(t)??Promise.resolve()).catch(()=>{}).then(e);kr.set(t,o);try{return await o}finally{kr.get(t)===o&&kr.delete(t)}}async function Fi(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",n="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Ot(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return So(`${i}/${r.name}`,async()=>{let s=await yr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ut(i,r.name,t.baseDir),{commit:c}=await gi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return Z({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return So(`${i}/${r.name}`,async()=>{let s=await yr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ut(i,r.name,t.baseDir),{commit:c,pushed:u}=await hi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:u})})}case"create_pr":{if(!r)return F("no repo spec");let i=ke(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=ke(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return Z({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=ke(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return So(`${i}/${r.name}`,async()=>{let s=await yr(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Ut(i,r.name,t.baseDir),{mergedSha:c}=await wi(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return Z({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return Z({stub:!0});case"tracker_status":{let i=Fe();return i?t.trackerIssueId?(await ji(i,t.trackerIssueId,e.newStatus),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Fe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await Ai(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Fe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await _i(i,e.projectKey,e.title,e.body,e.targetStatus);return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Fe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Oi(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await ii(t.contextDir,e.maxJobs);return Z({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await li(t.contextDir,e);return Z({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import ku from"ws";function $r(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new ku(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function dt(t,e,r){return Ke(t,e,"/projects",r)}async function Ki(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Wi(t,e,r,o){return Ke(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function xr(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 Yi(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 Lt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function qi(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 Lt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Vi(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function zi(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function Ji(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function Xi(t,e,r,o){return Ke(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Qi(t,e,r,o,n){return Ke(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function Zi(t,e,r,o,n){return Ke(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function es(t,e,r,o,n){return Ke(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function vr(t,e,r,o){return Ke(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function se(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Ke(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}function ft(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function ts(t,e){let r=H(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await pt({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(i){o.push({name:"youtrack",ok:!1,detail:ft(i)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await st(r.github.token),o.push({name:"github",ok:!0})}catch(i){o.push({name:"github",ok:!1,detail:ft(i)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await at(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(i){o.push({name:"bitbucket",ok:!1,detail:ft(i)})}else if(r?.gitlab?.token)try{await ct(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(i){o.push({name:"gitlab",ok:!1,detail:ft(i)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let i=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await wo(i,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:ft(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await wo(i,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:ft(a)})}}let n=rt(t);if(!n)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let i=await $u(n);o.push(i==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(i=>i.ok),checks:o,checkedAt:Date.now()}}async function $u(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var Sr=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=ke(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 He){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=ke(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let u=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);u&&(a.ciFailureLog=u)}catch(u){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${u instanceof Error?u.message:String(u)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=xu(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function xu(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Cr=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=Fe();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),n;try{let l=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Bi(r,{projectKey:e.projectKey,columns:l,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(l){this.log.warn(`[yt-sync] listIssues failed: ${l instanceof Error?l.message:String(l)}`);return}let i=[],s=new Set;for(let l of n){s.add(l.id);let d=await rs(r,l.id,e.sinceMs,this.log);d&&i.push({issueId:l.id,comments:d})}let a=[];for(let l of e.offBoardIssueIds){if(s.has(l))continue;let d=await rs(r,l,e.sinceMs,this.log);if(d&&i.push({issueId:l,comments:d}),e.requireAssignee){let g=await Su(r,l,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),u={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(u);let p=i.reduce((l,d)=>l+d.comments.length,0),f=c.reduce((l,d)=>l+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${p} attachments=${f} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let n=[];for(let i of e){let s=[...i.attachments??[]],a=r.find(p=>p.issueId===i.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],u=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let l;try{l=await Di(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${i.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=vu(p.name);u.has(d)&&(d=`${p.id}-${d}`),u.add(d),c.push({name:d,contentBase64:l.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function vu(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 Su(t,e,r){try{return await Gi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function rs(t,e,r,o){try{return await Mi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Co="npm i -g @code-partner/codepipe@latest";function Rr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ie} (protocol ${de})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Ln(n.contextDir,r);let i=os("CLI_TRACKING_POLL_INTERVAL_SEC"),s=os("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,u=!1,p=new Set,f=l();function l(){let d=$r(t.hubUrl,t.cliToken),g=null,w=new Sr(i,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),k=new Cr(s,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),R=null,v=async()=>{try{let S;try{let y=await se(t.hubUrl,t.cliToken,t.projectId);S={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await ts(t.projectId,S);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},T=()=>{v(),R=setInterval(()=>void v(),a),typeof R.unref=="function"&&R.unref()},j=()=>{R&&(clearInterval(R),R=null)},U=n?.contextDir?new dr(n.contextDir,t.projectId,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let S=_n(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",m=_("FARM_ID"),y=t.accountEmail??S.email,$={type:"register",projectId:t.projectId,platformVersion:ie,protocolVersion:de,accountId:S.accountId,accountLabel:S.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&m?{farmId:m}:{}};d.send(JSON.stringify($))}),d.on("message",async S=>{let h=S.toString("utf-8");if(h==="pong"||h==="ping")return;let m;try{m=JSON.parse(h)}catch{return}if(!m||typeof m!="object")return;let y=m.type;if(y==="registered"){let b=m;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),o({kind:"registered",projectId:b.projectId??t.projectId}),w.start(),U?.start(),T(),n?.contextDir){let N=n.contextDir;try{let E=hr(N,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(E)),E.outdated&&(r.warn(`[ctx] context format outdated: v${E.templateVersion} \u2192 v${E.currentVersion}`+(E.missingPaths.length>0?` (missing: ${E.missingPaths.join(", ")})`:"")),u||(u=!0,(async()=>{try{let M;try{M=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let le=await Jn(N,t.projectId,M,r);d.readyState===d.OPEN&&d.send(JSON.stringify(le))}catch(M){r.warn(`[ctx] context migration failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}})()))}catch(E){r.warn(`[ctx] context-format detect failed (non-fatal): ${E instanceof Error?E.message:String(E)}`)}}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),o({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let b=m;g=or(b.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${N}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ie}, protocol ${de}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Co}`),o({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:Co}));return}if(y==="tracking_targets"){w.setTargets(m.targets);return}if(y==="youtrack_sync_request"){k.setRequest(m);return}if(y==="sync_local"){await Ru(m,n,d,r);return}if(y==="context_write"){await Tu(m,n,d,r);return}if(y==="adr_promote"){await Iu(m,n,d,r);return}if(y==="sandbox_keys"){let b=H(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let N=rt(t.projectId),E=oi(m,b,N,r);for(let M of E)d.readyState===d.OPEN&&d.send(JSON.stringify(M));return}if(y!=="dispatch_action")return;let $=m;if(g===!1){let b=`refused: HUB protocol incompatible with CLI v${ie} (protocol ${de})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:b})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${Co}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:b});return}p.add($.actionId);try{let b=await Fi({action:$.action,repo:$.repo,trackerIssueId:$.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0}).catch(M=>({status:"failed",error:M instanceof Error?M.message:String(M)}));d.send(JSON.stringify({type:"action_result",actionId:$.actionId,...b}));let N=b.status!=="failed",E=!N&&"error"in b?b.error:void 0;N?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${E??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:N,...E?{error:E}:{}})}finally{p.delete($.actionId)}}),d.on("close",(S,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${m?` reason=${m}`:""}`),w.stop(),k.stop(),U?.stop(),j(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:S}),!c&&setTimeout(()=>{f=l()},2e3)}),d.on("error",S=>r.warn(`[ws] error: ${S.message}`)),d}return{stop(){c=!0,f.close()}}}async function Ru(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(u=>u.name===n.repoName),s=Cu(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await On(s,a).catch(u=>({status:"warn",reason:u instanceof Error?u.message:String(u)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Tu(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await gr(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 Iu(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Fn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function os(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as us,mkdirSync as ps}from"node:fs";import{dirname as ds}from"node:path";import{simpleGit as We}from"simple-git";import{execFileSync as Pu}from"node:child_process";import{mkdtempSync as Eu,mkdirSync as ju,readFileSync as ns,rmSync as Au,writeFileSync as _u}from"node:fs";import{tmpdir as Ou}from"node:os";import{dirname as Nu,join as is}from"node:path";function ss(t="codepipe-context"){let e=Eu(is(Ou(),"codepipe-ssh-")),r=is(e,"id_ed25519");try{return Pu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ns(r,"utf-8"),publicKey:ns(`${r}.pub`,"utf-8").trim()}}finally{Au(e,{recursive:!0,force:!0})}}async function as(t,e,r,o="codepipe-context"){let n=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:o,key:r,read_only:!1})});if(n.ok)return;let i=await n.text();if(!(n.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${n.status} ${i}`)}function cs(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function ls(t,e){ju(Nu(t),{recursive:!0});let r=e.endsWith(`
419
+ `}function Ml(t){return`codepipe/context-migration-v${t}`}function Hl(t){let e=un(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 \`${ke}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
420
+ `)}async function Xn(t,e,r,o){let n=$o(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=br(t,e);if(!i.outdated)return i;let s=Ml(i.currentVersion),a=r?.branch??(await n.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await n.fetch().catch(()=>{}),(await n.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Fl(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(u){return o.warn(`[ctx] context migration branch failed (will retry next start): ${u instanceof Error?u.message:String(u)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let u=xe(c),p=await u.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let f=await u.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Hl(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(u){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${u instanceof Error?u.message:String(u)}`),i}}async function Fl(t,e,r,o,n,i,s){let a=$o(t),c=Ll(ko(Bl(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let u={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(mt(u,p).map(g=>[g.path,g.content])),l=0;for(let g of o.missingPaths){if(g===ke)continue;let w=f.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=ko(c,g);Nl(k)||(Ul(Gl(k),{recursive:!0}),Jn(k,w),l++)}Jn(ko(c,ke),cr(o.currentVersion)),l++;let d=$o(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${l} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Dl(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as Kl,createDecipheriv as Wl,createHash as ql,createPrivateKey as Yl,createPublicKey as xo,diffieHellman as Qn,generateKeyPairSync as Zn,hkdfSync as ei,randomBytes as Vl}from"node:crypto";var ti=Buffer.from("devpipe-sealedbox-v1","utf-8");function ri(){let{publicKey:t,privateKey:e}=Zn("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function gt(t){let e=Buffer.from(t,"base64");return(ql("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function kr(t,e){let r=xo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=Zn("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Qn({privateKey:n,publicKey:r}),c=Buffer.from(ei("sha256",a,Buffer.concat([i,s]),ti,32)),u=Vl(12),p=Kl("aes-256-gcm",c,u),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,l=Buffer.concat([p.update(f),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:u.toString("base64"),tag:d.toString("base64"),ct:l.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function oi(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let o=Yl({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=xo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=xo(o).export({type:"spki",format:"der"}),a=Qn({privateKey:o,publicKey:n}),c=Buffer.from(ei("sha256",a,Buffer.concat([i,s]),ti,32)),u=Wl("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return u.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([u.update(Buffer.from(r.ct,"base64")),u.final()])}function zl(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let o=e??t.claude?.oauthToken;return o&&(r.claudeOauthToken=o),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function ni(t,e,r,o){let n=zl(e,r);t.sandboxes.length>0&&!n.claudeOauthToken&&o.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!n.contextWrite&&(n.github||n.gitlab||n.bitbucket)&&o.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(n),s=[];for(let a of t.sandboxes){let c=dr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let u;try{u=kr(a.publicKey,i)}catch(p){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:u})}return s}import{existsSync as Jl,readFileSync as Xl,writeFileSync as Ql}from"node:fs";import{join as Zl}from"node:path";import{parseDocument as eu}from"yaml";var ii=64;async function si(t,e){if(!Number.isInteger(e)||e<1||e>ii)throw new Error(`maxJobs must be an integer in [1, ${ii}], got ${e}`);let r=Zl(t,"regimen.yaml");if(!Jl(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=eu(Xl(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Ql(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as ai,readFileSync as ci,writeFileSync as tu}from"node:fs";import{join as vo}from"node:path";import{parseDocument as li}from"yaml";async function ui(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=vo(t,"project.yaml");if(!ai(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=li(ci(i,"utf-8"));if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=vo(t,"regimen.yaml");if(!ai(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=li(ci(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)tu(vo(t,i.path),i.content);return{files:r.map(i=>i.path)}}var pi=t=>console.log(t);function di(t){pi=t}function Dt(t,e="info"){pi(t,e)}import{homedir as ru}from"node:os";import{existsSync as ou,mkdirSync as nu}from"node:fs";import{join as So}from"node:path";import{simpleGit as fi}from"simple-git";function Gt(t,e,r){let o=r??So(ru(),".codepipe","repos");return So(o,t,e)}async function $r(t,e,r={}){let o=Gt(t,e.name,r.baseDir),n=r.cloneUrlOverride??iu(e);if(!ou(So(o,".git"))){nu(o,{recursive:!0});let a=fi();Dt(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
421
+ ${u.trim()}`)}}let i=fi(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
422
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Bt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var mi=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function xr(t,e){let{contextRepoCloneUrl:r,deliveryRef:o,deliverySha:n,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${o}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();n&&a!==n&&Dt(`[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 Bt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Bt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let u=(await t.raw([...mi,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),u}async function gi(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await Bt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await Bt(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 hi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:u,defaultBranch:p,force:f}=r,l=await gi(t,i,()=>xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:u}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await Bt(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,l]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...mi,"cherry-pick",l])}catch(C){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=C instanceof Error?C.message:String(C);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
423
+ ${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),k=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(k),await t.push([o,"--delete",n]).catch(()=>{}),{commit:w}}async function wi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:u}=r,p=await gi(t,i,()=>xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),u&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:u}}async function yi(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function iu(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{X509Certificate as $i}from"node:crypto";import{readFileSync as su}from"node:fs";import Ee from"node:tls";var xi=typeof Ee.getCACertificates=="function"&&typeof Ee.setDefaultCACertificates=="function",bi=!1,ki=new Map,vi=t=>console.warn(t);function au(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Si(t=vi){if(bi)return;bi=!0;let e=_("EXTRA_CA_FILE");if(!(!e||!xi))try{let r=au(su(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Ee.setDefaultCACertificates([...Ee.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 Ci(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function cu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
424
+ `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function lu(t,e,r){return new Promise((o,n)=>{let i=Ee.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 $i(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Co(t,e,r){return new Promise(o=>{let n=Ee.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function uu(t){try{let e=await fetch(t);return e.ok?new $i(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ri(t,e=443,r=vi){let o=`${t}:${e}`,n=ki.get(o);if(n)return n;let i=pu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return ki.set(o,i),i}async function pu(t,e,r){if(!xi)return!1;let o=8e3;if(await Co(t,e,o))return!0;let n=await lu(t,e,o),i=Ee.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=cu(n);if(!c)break;let u=await uu(c);if(!u)break;if(s.push(u.toString()),Ee.setDefaultCACertificates([...i,...s]),await Co(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(u.subject===u.issuer)break;n=u}return Co(t,e,o)}function Ve(){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){Si();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(Ci(s)&&await Ri(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ti=t=>new Promise(e=>setTimeout(e,t));function du(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fu(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function Ei(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=fu(),a=null;for(let c=1;c<=n;c++){let u=null;try{u=await he(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(u){if(u.ok)return u;let p=await u.text();if(c<n&&du(u.status,p)){await Ti(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${u.status} ${p}`)}if(c<n){await Ti(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function ht(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 ji(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 Ii=new Map;async function mu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ii.get(o);if(n)return n;let i=await he(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let a=(await i.json()).customFields.find(u=>u.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(u=>u.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ii.set(o,c.id),c.id}async function Ai(t,e,r){let o=await mu(t,e,r);await Ei(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function _i(t,e,r){return await(await Ei(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Pi=new Map;async function gu(t,e){let r=Pi.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 Pi.set(e,i.id),i.id}async function Oi(t,e,r,o,n){let i=await gu(t,e),s=await he(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function Ni(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 Ui="attachments(id,name,url,size,mimeType)",hu="links(direction,linkType(name),issues(idReadable))",Li=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ui},${hu}`,wu=`id,text,created,author(login),${Ui}`;function Di(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 Bi(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 Gi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),n=`/api/issues?query=${encodeURIComponent(o)}&fields=${Li}&$top=200`,i=await he(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Fi)}async function Mi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Li}`,o=await he(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Fi(await o.json())}async function Hi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${wu}&$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=Di(s.attachments);return c&&(a.attachments=c),a})}function yu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Fi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),n=e.find(c=>c.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),n?.value?.name&&(i.issueType=n.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=Di(t.attachments);s&&(i.attachments=s);let a=yu(t.links);return a&&(i.links=a),i}var vr=new Map;async function Ro(t,e){let o=(vr.get(t)??Promise.resolve()).catch(()=>{}).then(e);vr.set(t,o);try{return await o}finally{vr.get(t)===o&&vr.delete(t)}}async function Ki(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;Dt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ro(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Gt(i,r.name,t.baseDir),{commit:c}=await hi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return ee({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ro(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Gt(i,r.name,t.baseDir),{commit:c,pushed:u}=await wi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:u})})}case"create_pr":{if(!r)return F("no repo spec");let i=xe(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=xe(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=xe(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Ro(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Gt(i,r.name,t.baseDir),{mergedSha:c}=await yi(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return ee({stub:!0});case"tracker_status":{let i=Ve();return i?t.trackerIssueId?(await Ai(i,t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=Ve();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await _i(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=Ve();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Oi(i,e.projectKey,e.title,e.body,e.targetStatus);return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=Ve();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Ni(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await si(t.contextDir,e.maxJobs);return ee({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await ui(t.contextDir,e);return ee({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import bu from"ws";function Sr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new bu(r)}var j=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function wt(t,e,r){return ze(t,e,"/projects",r)}async function Wi(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new j(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function qi(t,e,r,o){return ze(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Cr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new j(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function Yi(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new j(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Mt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Vi(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 Mt(e)}if(!r.ok)throw new j(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function zi(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new j(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function Ji(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new j(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function Xi(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 j(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function Qi(t,e,r,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Zi(t,e,r,o,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function es(t,e,r,o,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function ts(t,e,r,o,n){return ze(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Rr(t,e,r,o){return ze(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function ae(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new j(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function ze(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 j(n.status,s,a)}return s}function yt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function rs(t,e){let r=H(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await ht({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(i){o.push({name:"youtrack",ok:!1,detail:yt(i)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await pt(r.github.token),o.push({name:"github",ok:!0})}catch(i){o.push({name:"github",ok:!1,detail:yt(i)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await dt(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(i){o.push({name:"bitbucket",ok:!1,detail:yt(i)})}else if(r?.gitlab?.token)try{await ft(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(i){o.push({name:"gitlab",ok:!1,detail:yt(i)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let i=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await bo(i,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:yt(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await bo(i,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:yt(a)})}}let n=st(t);if(!n)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let i=await ku(n);o.push(i==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(i=>i.ok),checks:o,checkedAt:Date.now()}}async function ku(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var Tr=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let o=[];for(let s of r.prs){let a=xe(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 Ye){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=xe(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let u=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);u&&(a.ciFailureLog=u)}catch(u){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${u instanceof Error?u.message:String(u)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=$u(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function $u(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Ir=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=Ve();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),n;try{let l=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Gi(r,{projectKey:e.projectKey,columns:l,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(l){this.log.warn(`[yt-sync] listIssues failed: ${l instanceof Error?l.message:String(l)}`);return}let i=[],s=new Set;for(let l of n){s.add(l.id);let d=await os(r,l.id,e.sinceMs,this.log);d&&i.push({issueId:l.id,comments:d})}let a=[];for(let l of e.offBoardIssueIds){if(s.has(l))continue;let d=await os(r,l,e.sinceMs,this.log);if(d&&i.push({issueId:l,comments:d}),e.requireAssignee){let g=await vu(r,l,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),u={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(u);let p=i.reduce((l,d)=>l+d.comments.length,0),f=c.reduce((l,d)=>l+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${p} attachments=${f} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let n=[];for(let i of e){let s=[...i.attachments??[]],a=r.find(p=>p.issueId===i.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],u=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let l;try{l=await Bi(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${i.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=xu(p.name);u.has(d)&&(d=`${p.id}-${d}`),u.add(d),c.push({name:d,contentBase64:l.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function xu(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function vu(t,e,r){try{return await Mi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function os(t,e,r,o){try{return await Hi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var To="npm i -g @code-partner/codepipe@latest";function Pr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${se} (protocol ${fe})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Dn(n.contextDir,r);let i=ns("CLI_TRACKING_POLL_INTERVAL_SEC"),s=ns("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,u=!1,p=new Set,f=l();function l(){let d=Sr(t.hubUrl,t.cliToken),g=null,w=new Tr(i,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),k=new Ir(s,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),C=null,v=async()=>{try{let S;try{let y=await ae(t.hubUrl,t.cliToken,t.projectId);S={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await rs(t.projectId,S);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter(x=>!x.ok).map(x=>`${x.name}(${x.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},T=()=>{v(),C=setInterval(()=>void v(),a),typeof C.unref=="function"&&C.unref()},E=()=>{C&&(clearInterval(C),C=null)},U=n?.contextDir?new hr(n.contextDir,t.projectId,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let S=_n(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",m=_("FARM_ID"),y=t.accountEmail??S.email,x={type:"register",projectId:t.projectId,platformVersion:se,protocolVersion:fe,accountId:S.accountId,accountLabel:S.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&m?{farmId:m}:{}};d.send(JSON.stringify(x))}),d.on("message",async S=>{let h=S.toString("utf-8");if(h==="pong"||h==="ping")return;let m;try{m=JSON.parse(h)}catch{return}if(!m||typeof m!="object")return;let y=m.type;if(y==="registered"){let $=m;if($.ok){if(r.info(`[ws] registered for project ${$.projectId}`),o({kind:"registered",projectId:$.projectId??t.projectId}),w.start(),U?.start(),T(),n?.contextDir){let N=n.contextDir;try{let A=br(N,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(A)),A.outdated&&(r.warn(`[ctx] context format outdated: v${A.templateVersion} \u2192 v${A.currentVersion}`+(A.missingPaths.length>0?` (missing: ${A.missingPaths.join(", ")})`:"")),u||(u=!0,(async()=>{try{let B;try{B=(await ae(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let oe=await Xn(N,t.projectId,B,r);d.readyState===d.OPEN&&d.send(JSON.stringify(oe))}catch(B){r.warn(`[ctx] context migration failed (non-fatal): ${B instanceof Error?B.message:String(B)}`)}})()))}catch(A){r.warn(`[ctx] context-format detect failed (non-fatal): ${A instanceof Error?A.message:String(A)}`)}}}else r.warn(`[ws] register rejected: ${$.reason??"unknown"}`),o({kind:"register_rejected",reason:$.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let $=m;g=ar($.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${N}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${se}, protocol ${fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${To}`),o({kind:"incompatible",hubVersion:typeof $.platformVersion=="string"?$.platformVersion:null,hubProtocol:typeof $.protocolVersion=="number"?$.protocolVersion:null,updateCommand:To}));return}if(y==="tracking_targets"){w.setTargets(m.targets);return}if(y==="youtrack_sync_request"){k.setRequest(m);return}if(y==="sync_local"){await Cu(m,n,d,r);return}if(y==="context_write"){await Ru(m,n,d,r);return}if(y==="adr_promote"){await Tu(m,n,d,r);return}if(y==="sandbox_keys"){let $=H(t.projectId);if(!$){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let N=st(t.projectId),A=ni(m,$,N,r);for(let B of A)d.readyState===d.OPEN&&d.send(JSON.stringify(B));return}if(y!=="dispatch_action")return;let x=m;if(g===!1){let $=`refused: HUB protocol incompatible with CLI v${se} (protocol ${fe})`;d.send(JSON.stringify({type:"action_result",actionId:x.actionId,status:"failed",error:$})),r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 REFUSED: ${$}`),r.warn(`[exec] update the CLI to clear this: ${To}`),o({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:!1,error:$});return}p.add(x.actionId);try{let $=await Ki({action:x.action,repo:x.repo,trackerIssueId:x.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0}).catch(B=>({status:"failed",error:B instanceof Error?B.message:String(B)}));d.send(JSON.stringify({type:"action_result",actionId:x.actionId,...$}));let N=$.status!=="failed",A=!N&&"error"in $?$.error:void 0;N?r.info(`[exec] ${x.actionId} (${x.action.type}) \u2192 done`):r.warn(`[exec] ${x.actionId} (${x.action.type}) \u2192 FAILED: ${A??"?"}`),o({kind:"action",actionId:x.actionId,actionType:x.action.type,ok:N,...A?{error:A}:{}})}finally{p.delete(x.actionId)}}),d.on("close",(S,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${m?` reason=${m}`:""}`),w.stop(),k.stop(),U?.stop(),E(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:S}),!c&&setTimeout(()=>{f=l()},2e3)}),d.on("error",S=>r.warn(`[ws] error: ${S.message}`)),d}return{stop(){c=!0,f.close()}}}async function Cu(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(u=>u.name===n.repoName),s=Su(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await On(s,a).catch(u=>({status:"warn",reason:u instanceof Error?u.message:String(u)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Ru(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await yr(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Tu(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Kn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function ns(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as ps,mkdirSync as ds}from"node:fs";import{dirname as fs}from"node:path";import{simpleGit as Je}from"simple-git";import{execFileSync as Iu}from"node:child_process";import{mkdtempSync as Pu,mkdirSync as Eu,readFileSync as is,rmSync as ju,writeFileSync as Au}from"node:fs";import{tmpdir as _u}from"node:os";import{dirname as Ou,join as ss}from"node:path";function as(t="codepipe-context"){let e=Pu(ss(_u(),"codepipe-ssh-")),r=ss(e,"id_ed25519");try{return Iu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:is(r,"utf-8"),publicKey:is(`${r}.pub`,"utf-8").trim()}}finally{ju(e,{recursive:!0,force:!0})}}async function cs(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 ls(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 us(t,e){Eu(Ou(t),{recursive:!0});let r=e.endsWith(`
425
425
  `)?e:e+`
426
- `;return _u(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Uu(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 Lu(t,e){return e?.contextWrite?.token?{user:sr(t),secret:e.contextWrite.token}:t===At.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===At.bitbucket?e?.bitbucket?.apiToken?{user:et,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function fs(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){return n.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return n.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Lu(Ze(s.cloneUrl),r);if(a){let c=await Du({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 Bu({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 Du(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Uu(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=u=>u.split(o.secret).join("***").split(a).join("***");try{if(us(`${r}/.git`)){let p=We(r);await p.remote(["set-url","origin",i]),await p.fetch("origin",s),await p.checkout(s);let f=co(r);await p.reset(["--hard",`origin/${s}`]),lo(r,f),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ps(ds(r),{recursive:!0}),await We().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);let u=We(r);await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local")}catch(u){return n.warn(`[ctx] Context Repo clone/update failed: ${c(u instanceof Error?u.message:String(u))}`),null}return{root:r,contextDir:r,repos:[]}}async function Bu(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=ls(i,o),a=cs(e.cloneUrl),c=e.branch;try{if(us(`${r}/.git`)){let p=We(r);await p.addConfig("core.sshCommand",s,!1,"local"),await p.remote(["set-url","origin",a]),await p.fetch("origin",c),await p.checkout(c);let f=co(r);await p.reset(["--hard",`origin/${c}`]),lo(r,f),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ps(ds(r),{recursive:!0}),await We().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await We(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);let u=We(r);return await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local"),{root:r,contextDir:r,repos:[]}}catch(u){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${u instanceof Error?u.message:String(u)}`),null}}function Tr(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 Ir(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 Pr(t,e=process.env){if(!t)return!1;let r=`https://${et}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}async function ms(t={profile:void 0}){let e=fe(t.profile),r=H(e.projectId);r&&_t(r),Tr(r?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ir(r?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Pr(r?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Dt(Ro(),".codepipe","logs"),n=t.profile?`cli-daemon-${t.profile}`:"cli-daemon",i=ur("CLI_LOG",n,o);if(i.enabled){let f=new nt(i);pr(f),console.log(`[log] file logging \u2192 ${f.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let s=Dt(Ro(),".codepipe",t.profile?Dt("profiles",t.profile,"context"):"context"),a=await fs({cfg:e,secrets:r,contextDir:s,log:{info:f=>console.log(f),warn:f=>console.warn(f)}});if(a?.contextDir){let f=Dt(Ro(),".codepipe",t.profile?Dt("profiles",t.profile,"context-config"):"context-config");Un(a.contextDir,f,{info:l=>console.log(l),warn:l=>console.warn(l)})}let c=Rr(e,{...a?{workspace:a}:{},onEvent:f=>{f.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function p(f){u||(u=!0,console.log(`
427
- [${f}] shutting down`),c.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}import{hostname as Yu}from"node:os";import{spawnSync as Gu}from"node:child_process";function Mu(){try{return Gu("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function gs(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Mu(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as mt}from"node:os";import{mkdirSync as Hu,readFileSync as hs,writeFileSync as Fu,existsSync as To}from"node:fs";import{dirname as Ku,join as Ie}from"node:path";To(".env")&&process.loadEnvFile(".env");function Pe(t){let e=_("SANDBOX_CONFIG");if(e)return e;let r=Ie(mt(),".codepipe","worker");return t?Ie(r,"profiles",t,"config.json"):Ie(r,"config.json")}function ws(){return Ie(mt(),".devpipe-sandbox","config.json")}function Er(){Be(Ie(mt(),".devpipe"),Ie(mt(),".codepipe")),_("SANDBOX_CONFIG")||Be(Ie(mt(),".devpipe-sandbox"),Ie(mt(),".codepipe-sandbox"))}function ee(t){let e=Pe(t);return To(e)?JSON.parse(hs(e,"utf-8")):!t&&!_("SANDBOX_CONFIG")&&To(ws())?JSON.parse(hs(ws(),"utf-8")):null}function ys(t,e){let r=Pe(e);Hu(Ku(r),{recursive:!0}),Fu(r,JSON.stringify(t,null,2)+`
428
- `,{mode:384})}import Wu from"ws";var gt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Wu(e)}};async function Ye(t){Er();let e=ee(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Pe(t.profile)}.`),process.exit(1));let r=t.name??Yu(),o=gs({projects:t.projects??[],llm:t.llm??null}),n=new gt(t.hub.replace(/\/$/,"")),i=ti(),s=ut(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});ys({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${Pe(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Ap,readFileSync as Qs,readdirSync as _p,writeFileSync as Op}from"node:fs";import{dirname as Np,join as Gr,resolve as Up}from"node:path";import{spawn as qu}from"node:child_process";import{existsSync as Vu}from"node:fs";var ht=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},jr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},zu=5e3,Bt=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new jr;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let g of e.addDirs??[])r.push("--add-dir",g);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",u=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let w=Zu(g.rate_limit_info);w&&(!u||w.utilization>u.utilization)&&(u=w);return}if(g.type==="assistant"){let w=g.message;typeof w?.model=="string"&&(c=w.model);let k=w?.usage;k&&(a+=1,s.input+=te(k.input_tokens),s.output+=te(k.output_tokens),s.cacheRead+=te(k.cache_read_input_tokens),s.cacheCreate+=te(k.cache_creation_input_tokens))}}},f=e.role,l=e.onActivity,d=g=>{if(l)for(let w of tp(g,e.workspaceDir))try{l(w)}catch{}};return l?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let k=qu(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let R=!1,v=null,T=()=>{R=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),k.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},zu)};e.signal?.addEventListener("abort",T,{once:!0});let j=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",T)},U="";k.stdout.on("data",S=>{o.push(S),U+=S;let h;for(;(h=U.indexOf(`
429
- `))!==-1;){let m=U.slice(0,h).trim();if(U=U.slice(h+1),m){let y=bs(m);p(y),y&&d(y)}}}),k.stderr.on("data",S=>{o.push(S),n.push(S);for(let h of S.split(`
430
- `)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),k.on("error",S=>{j(),w(S)}),k.on("close",S=>{if(j(),R){w(new jr);return}if(U.trim()){let m=bs(U.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(S!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,y=typeof i?.subtype=="string"?i.subtype:void 0,$=typeof i?.result=="string"?i.result:void 0;w(new ht(Ju(S,i,n.join("")),{code:S,apiErrorStatus:m,subtype:y,resultText:$,retryAfterMs:Xu(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:ep(i,s,a,c),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&Vu(o))}};function bs(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: ${Ee(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=Qu(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=$s(n.content);console.log(`[claude] tool_result (error)${i?`: ${Ee(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)} ${Ee(JSON.stringify(e),200)}`),e}function Ju(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(Ee(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(Ee(r.trim().split(`
426
+ `;return Au(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Nu(t,e,r="x-access-token"){let o=`${encodeURIComponent(r)}:${encodeURIComponent(e)}`,n=t.match(/^git@([^:]+):(.+)$/);if(n)return`https://${o}@${n[1]}/${n[2]}`;let i=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(i)return`https://${o}@${i[1]}/${i[2]}`;let s=t.match(/^https:\/\/(?:[^@/]+@)?(.+)$/);return s?`https://${o}@${s[1]}`:t}function Uu(t,e){return e?.contextWrite?.token?{user:ur(t),secret:e.contextWrite.token}:t===Ut.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Ut.bitbucket?e?.bitbucket?.apiToken?{user:nt,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function ms(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await ae(e.hubUrl,e.cliToken,e.projectId)}catch(c){return n.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return n.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Uu(ot(s.cloneUrl),r);if(a){let c=await Lu({ctx:s,contextDir:o,cred:a,log:n});if(c)return c;n.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Du({ctx:s,contextDir:o,privateKey:r.contextSsh.privateKey,log:n});if(c)return c;n.warn("[ctx] SSH deploy-key clone failed")}return n.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function Lu(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Nu(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=u=>u.split(o.secret).join("***").split(a).join("***");try{if(ps(`${r}/.git`)){let p=Je(r);await p.remote(["set-url","origin",i]),await p.fetch("origin",s),await p.checkout(s);let f=uo(r);await p.reset(["--hard",`origin/${s}`]),po(r,f),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ds(fs(r),{recursive:!0}),await Je().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);let u=Je(r);await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local")}catch(u){return n.warn(`[ctx] Context Repo clone/update failed: ${c(u instanceof Error?u.message:String(u))}`),null}return{root:r,contextDir:r,repos:[]}}async function Du(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=us(i,o),a=ls(e.cloneUrl),c=e.branch;try{if(ps(`${r}/.git`)){let p=Je(r);await p.addConfig("core.sshCommand",s,!1,"local"),await p.remote(["set-url","origin",a]),await p.fetch("origin",c),await p.checkout(c);let f=uo(r);await p.reset(["--hard",`origin/${c}`]),po(r,f),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ds(fs(r),{recursive:!0}),await Je().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Je(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);let u=Je(r);return await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local"),{root:r,contextDir:r,repos:[]}}catch(u){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${u instanceof Error?u.message:String(u)}`),null}}import{existsSync as Er,readFileSync as gs,writeFileSync as Bu}from"node:fs";import{dirname as Gu,join as je}from"node:path";import{parse as Mu}from"yaml";var Ae=".codepipe",Io=".devpipe";function Hu(t=process.cwd()){let e=t;for(;;){if(Er(je(e,Ae,"project.yaml")))return e;if(Er(je(e,Io,"project.yaml")))return Ke(je(e,Io),je(e,Ae))&&Ku(e),e;let r=Gu(e);if(r===e)return null;e=r}}function Fu(t){let e=je(t,Ae);return Er(e)?e:je(t,Io)}function Ku(t){let e=je(t,".gitignore");if(!Er(e))return;let r=gs(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
427
+ `);o!==r&&Bu(e,o)}function Ht(t=process.cwd()){let e=Hu(t);if(!e)return null;let r=Fu(e),o=Wu(gs(je(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function hs(t,e=process.cwd()){try{let r=Ht(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Wu(t){let e=Mu(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),u=String(a.name??c);if(!u||!c)continue;let p=a.host,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:u,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??u)})}return{projectId:r,name:o,repos:i}}function ws(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function jr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@github.com:"),n(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Ar(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@gitlab.com:"),n(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function _r(t,e=process.env){if(!t)return!1;let r=`https://${nt}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}async function ys(t={profile:void 0}){let e=me(t.profile),r=H(e.projectId);r&&Lt(r),jr(r?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ar(r?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),_r(r?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Ft(Po(),".codepipe","logs"),n=t.profile?`cli-daemon-${t.profile}`:"cli-daemon",i=mr("CLI_LOG",n,o);if(i.enabled){let f=new ct(i);gr(f),console.log(`[log] file logging \u2192 ${f.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let s=null,a=hs(e.projectId);if(a&&(s={root:a.root,contextDir:a.contextDir,repos:a.spec.repos},console.log(`[ctx] workspace found at ${a.root} \u2014 using its Context Repo clone`)),!s){let f=Ft(Po(),".codepipe",t.profile?Ft("profiles",t.profile,"context"):"context");if(s=await ms({cfg:e,secrets:r,contextDir:f,log:{info:l=>console.log(l),warn:l=>console.warn(l)}}),s?.contextDir){let l=Ft(Po(),".codepipe",t.profile?Ft("profiles",t.profile,"context-config"):"context-config");Ln(s.contextDir,l,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let c=Pr(e,{...s?{workspace:s}:{},onEvent:f=>{f.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function p(f){u||(u=!0,console.log(`
428
+ [${f}] shutting down`),c.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}import{hostname as Qu}from"node:os";import{spawnSync as qu}from"node:child_process";function Yu(){try{return qu("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function bs(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Yu(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as bt}from"node:os";import{mkdirSync as Vu,readFileSync as ks,writeFileSync as zu,existsSync as Eo}from"node:fs";import{dirname as Ju,join as _e}from"node:path";Eo(".env")&&process.loadEnvFile(".env");function Oe(t){let e=_("SANDBOX_CONFIG");if(e)return e;let r=_e(bt(),".codepipe","worker");return t?_e(r,"profiles",t,"config.json"):_e(r,"config.json")}function $s(){return _e(bt(),".devpipe-sandbox","config.json")}function Or(){Ke(_e(bt(),".devpipe"),_e(bt(),".codepipe")),_("SANDBOX_CONFIG")||Ke(_e(bt(),".devpipe-sandbox"),_e(bt(),".codepipe-sandbox"))}function te(t){let e=Oe(t);return Eo(e)?JSON.parse(ks(e,"utf-8")):!t&&!_("SANDBOX_CONFIG")&&Eo($s())?JSON.parse(ks($s(),"utf-8")):null}function xs(t,e){let r=Oe(e);Vu(Ju(r),{recursive:!0}),zu(r,JSON.stringify(t,null,2)+`
429
+ `,{mode:384})}import Xu from"ws";var kt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Xu(e)}};async function Xe(t){Or();let e=te(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Oe(t.profile)}.`),process.exit(1));let r=t.name??Qu(),o=bs({projects:t.projects??[],llm:t.llm??null}),n=new kt(t.hub.replace(/\/$/,"")),i=ri(),s=gt(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});xs({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 ${Oe(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Dp,readFileSync as ra,readdirSync as Bp,writeFileSync as Gp}from"node:fs";import{dirname as Mp,join as Kr,resolve as Hp}from"node:path";import{spawn as Zu}from"node:child_process";import{existsSync as ep}from"node:fs";var $t=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Nr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},tp=5e3,Kt=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Nr;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let g of e.addDirs??[])r.push("--add-dir",g);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",u=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let w=ip(g.rate_limit_info);w&&(!u||w.utilization>u.utilization)&&(u=w);return}if(g.type==="assistant"){let w=g.message;typeof w?.model=="string"&&(c=w.model);let k=w?.usage;k&&(a+=1,s.input+=re(k.input_tokens),s.output+=re(k.output_tokens),s.cacheRead+=re(k.cache_read_input_tokens),s.cacheCreate+=re(k.cache_creation_input_tokens))}}},f=e.role,l=e.onActivity,d=g=>{if(l)for(let w of ap(g,e.workspaceDir))try{l(w)}catch{}};return l?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let k=Zu(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let C=!1,v=null,T=()=>{C=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),k.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},tp)};e.signal?.addEventListener("abort",T,{once:!0});let E=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",T)},U="";k.stdout.on("data",S=>{o.push(S),U+=S;let h;for(;(h=U.indexOf(`
430
+ `))!==-1;){let m=U.slice(0,h).trim();if(U=U.slice(h+1),m){let y=vs(m);p(y),y&&d(y)}}}),k.stderr.on("data",S=>{o.push(S),n.push(S);for(let h of S.split(`
431
+ `)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),k.on("error",S=>{E(),w(S)}),k.on("close",S=>{if(E(),C){w(new Nr);return}if(U.trim()){let m=vs(U.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(S!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,y=typeof i?.subtype=="string"?i.subtype:void 0,x=typeof i?.result=="string"?i.result:void 0;w(new $t(rp(S,i,n.join("")),{code:S,apiErrorStatus:m,subtype:y,resultText:x,retryAfterMs:op(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:sp(i,s,a,c),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&ep(o))}};function vs(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: ${Ne(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=np(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=Cs(n.content);console.log(`[claude] tool_result (error)${i?`: ${Ne(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)} ${Ne(JSON.stringify(e),200)}`),e}function rp(t,e,r){let o=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let n=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;n?o.push(Ne(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(Ne(r.trim().split(`
431
432
  `).slice(-5).join(`
432
- `),500)),o.join(" \u2014 ")}function Xu(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 $s(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Qu(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=${Ee(r,80)}`}return""}function Ee(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function te(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Zu(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=te(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:te(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 ep(t,e,r,o){let n=ir(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=te(i.input_tokens),n.outputTokens=te(i.output_tokens),n.cacheReadInputTokens=te(i.cache_read_input_tokens),n.cacheCreationInputTokens=te(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=te(t?.total_cost_usd),n.numTurns=t&&te(t.num_turns)>0?te(t.num_turns):r,n.durationMs=te(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var ks=200;function tp(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:Ee(c,ks)})}else if(a==="tool_use"){let c=String(s.name??""),u=s.input,p=u?.file_path??u?.path??u?.notebook_path,f=rp(p,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Ee($s(s.content),ks):"";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 rp(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 op,writeFileSync as Gt}from"node:fs";import{dirname as np,join as Mt}from"node:path";function xs(t,e,r){let o=Mt(t,e);op(np(o),{recursive:!0}),Gt(o,r)}var Ht=class{name(){return"mock"}async run(e){let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=ip(o,n,i);Gt(Mt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Gt(Mt(e.workspaceDir,"SOLUTION.md"),sp(o,n,i,a)),s.push("SOLUTION.md"),Gt(Mt(e.workspaceDir,"QUESTIONS.md"),ap(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;xs(e.workspaceDir,"changes/sample.patch",cp(o,n,a)),s.push("changes/sample.patch"),xs(e.workspaceDir,"diff-summary.md",lp(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Gt(Mt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
433
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:ir()}}};function ip(t,e,r){return`# ${t} \u2014 Estimate
433
+ `),500)),o.join(" \u2014 ")}function op(t){if(!t)return;let e=t.retry_after;if(typeof e=="number"&&e>0)return Math.round(e*1e3);let r=typeof t.result=="string"?t.result:"",o=/retry[\s-]*after[:\s]*(\d+)|reset[s]?\s+in[:\s]*(\d+)/i.exec(r),n=o?Number(o[1]??o[2]):NaN;return Number.isFinite(n)&&n>0?n*1e3:void 0}function Cs(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function np(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Ne(r,80)}`}return""}function Ne(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ip(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=re(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:re(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:o,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(n.surpassedThreshold=e.surpassedThreshold),n}function sp(t,e,r,o){let n=lr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=re(i.input_tokens),n.outputTokens=re(i.output_tokens),n.cacheReadInputTokens=re(i.cache_read_input_tokens),n.cacheCreationInputTokens=re(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=re(t?.total_cost_usd),n.numTurns=t&&re(t.num_turns)>0?re(t.num_turns):r,n.durationMs=re(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Ss=200;function ap(t,e){let r=Date.now(),o=t.type;if(o==="system"){let n=String(t.subtype??"").trim();return n?[{ts:r,kind:"system",text:n}]:[]}if(o==="assistant"){let n=t.message,i=[];for(let s of n?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:Ne(c,Ss)})}else if(a==="tool_use"){let c=String(s.name??""),u=s.input,p=u?.file_path??u?.path??u?.notebook_path,f=cp(p,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Ne(Cs(s.content),Ss):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(o==="result"){let n=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...n?{text:n}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function cp(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}import{mkdirSync as lp,writeFileSync as Wt}from"node:fs";import{dirname as up,join as qt}from"node:path";function Rs(t,e,r){let o=qt(t,e);lp(up(o),{recursive:!0}),Wt(o,r)}var Yt=class{name(){return"mock"}async run(e){let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=pp(o,n,i);Wt(qt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Wt(qt(e.workspaceDir,"SOLUTION.md"),dp(o,n,i,a)),s.push("SOLUTION.md"),Wt(qt(e.workspaceDir,"QUESTIONS.md"),fp(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Rs(e.workspaceDir,"changes/sample.patch",mp(o,n,a)),s.push("changes/sample.patch"),Rs(e.workspaceDir,"diff-summary.md",gp(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Wt(qt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
434
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:lr()}}};function pp(t,e,r){return`# ${t} \u2014 Estimate
434
435
 
435
436
  **Title:** ${e}
436
437
 
@@ -451,7 +452,7 @@ production-grade estimates.)
451
452
  ${r.split(`
452
453
  `).slice(0,8).join(`
453
454
  `).trim()||"(empty)"}
454
- `}function sp(t,e,r,o){let n=o?`
455
+ `}function dp(t,e,r,o){let n=o?`
455
456
  ## Reviewer rework instruction
456
457
 
457
458
  > ${o.split(`
@@ -480,10 +481,10 @@ TBD (mock runner does not yet inspect project code).
480
481
  ${r.split(`
481
482
  `).slice(0,8).join(`
482
483
  `).trim()||"(empty)"}
483
- `}function ap(t){return`# ${t} \u2014 Open questions
484
+ `}function fp(t){return`# ${t} \u2014 Open questions
484
485
 
485
486
  (none \u2014 mock runner did not surface ambiguities.)
486
- `}function cp(t,e,r){let o=r?` (rework: ${r.split(`
487
+ `}function mp(t,e,r){let o=r?` (rework: ${r.split(`
487
488
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
488
489
  index 0000000..1111111 100644
489
490
  --- a/CHANGELOG.md
@@ -494,7 +495,7 @@ index 0000000..1111111 100644
494
495
  +- mock-runner placeholder change for slice 5 testing.
495
496
  +
496
497
  # Changelog
497
- `}function lp(t,e,r){return`# ${t} \u2014 Diff summary
498
+ `}function gp(t,e,r){return`# ${t} \u2014 Diff summary
498
499
 
499
500
  **Title:** ${e}
500
501
  ${r?`
@@ -505,78 +506,78 @@ ${r?`
505
506
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
506
507
 
507
508
  (Mock-runner output. Replace with claude-headless for production patches.)
508
- `}function vs(t){switch(t){case"mock":return new Ht;case"claude-headless":return new Bt;default:return null}}function Rs(t=process.env){return{maxAttempts:Ar(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ar(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ar(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ar(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var up=new Set([429,500,502,503,529]),Ss=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,pp=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,dp=new Set(["error_max_turns"]);function fp(t){if(t instanceof ht){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return pp.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&dp.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:up.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Ss.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 Ss.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Cs=/(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 Ts(t){if(t instanceof ht){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Cs.test(o)}let e=t instanceof Error?t.message:String(t);return Cs.test(e)}function mp(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 Is(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=fp(a),u=s>=r.policy.maxAttempts;if(!c.retryable||u||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=mp(s,r.policy,c.retryAfterMs);if(Date.now()+p>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await o(p)}}function Ar(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as gp,rmSync as hp,writeFileSync as Ps}from"node:fs";import{tmpdir as wp}from"node:os";import{join as Io}from"node:path";function _r(t){return`[url "https://${t}/"]
509
+ `}function Ts(t){switch(t){case"mock":return new Yt;case"claude-headless":return new Kt;default:return null}}function Es(t=process.env){return{maxAttempts:Ur(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ur(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ur(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ur(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var hp=new Set([429,500,502,503,529]),Is=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,wp=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,yp=new Set(["error_max_turns"]);function bp(t){if(t instanceof $t){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return wp.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&yp.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:hp.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Is.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 Is.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Ps=/(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 js(t){if(t instanceof $t){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Ps.test(o)}let e=t instanceof Error?t.message:String(t);return Ps.test(e)}function kp(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let o=e.baseDelayMs*2**(t-1),n=Math.min(o,e.maxDelayMs);return Math.round(n/2+Math.random()*(n/2))}async function As(t,e,r){let o=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),n=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=bp(a),u=s>=r.policy.maxAttempts;if(!c.retryable||u||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=kp(s,r.policy,c.retryAfterMs);if(Date.now()+p>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await o(p)}}function Ur(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as $p,rmSync as xp,writeFileSync as _s}from"node:fs";import{tmpdir as vp}from"node:os";import{join as jo}from"node:path";function Lr(t){return`[url "https://${t}/"]
509
510
  insteadOf = git@${t}:
510
511
  insteadOf = ssh://git@${t}/
511
- `}var yp=_r("github.com"),bp=_r("bitbucket.org"),kp=_r("gitlab.com");function Es(t,e){if(t.length===0)return null;let r=gp(Io(wp(),"devpipe-gitcreds-")),o=Io(r,"credentials"),n=Io(r,"gitconfig");return Ps(o,t.join(`
512
+ `}var Sp=Lr("github.com"),Cp=Lr("bitbucket.org"),Rp=Lr("gitlab.com");function Os(t,e){if(t.length===0)return null;let r=$p(jo(vp(),"devpipe-gitcreds-")),o=jo(r,"credentials"),n=jo(r,"gitconfig");return _s(o,t.join(`
512
513
  `)+`
513
- `,{mode:384}),Ps(n,`[credential]
514
+ `,{mode:384}),_s(n,`[credential]
514
515
  helper = store --file=${o}
515
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{hp(r,{recursive:!0,force:!0})}catch{}}}}function Po(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(yp)),t.bitbucket?.apiToken&&(e.push(`https://${et}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(bp)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(kp)),Es(e,r)}function js(t,e){if(t.contextWrite?.token){let r=Ze(e)??"github.com",o=sr(r);return Es([`https://${o}:${t.contextWrite.token}@${r}`],[_r(r)])}return Po(t)}import{spawn as _s}from"node:child_process";import{existsSync as Or,mkdirSync as Nr,readFileSync as $p,rmSync as Eo,symlinkSync as xp}from"node:fs";import{homedir as vp}from"node:os";import{dirname as Ur,join as qe}from"node:path";function Os(){return qe(vp(),".codepipe-sandbox","repos")}function As(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 Ns(t,e,r,o,n){if(Or(qe(t,".git"))){let i=async s=>{await q(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await q(t,["reset","--hard",`origin/${s}`],n),await q(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!As(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Or(t)&&Eo(t,{recursive:!0,force:!0}),Nr(Ur(t),{recursive:!0});try{return await q(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!As(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Or(t)&&Eo(t,{recursive:!0,force:!0}),Nr(Ur(t),{recursive:!0}),await q(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function Us(t){await q(t.workspacePath,["reset","--hard",t.baseSha]),await q(t.workspacePath,["clean","-fdx"])}var Lr="CodePipe Agent",Dr="codepipe@codepartner.ee";async function Ls(t,e){let r=t.workspacePath;await q(r,["add","-A"]);let o=(await ge(r,["write-tree"])).trim(),n=(await ge(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Lr,GIT_AUTHOR_EMAIL:Dr,GIT_COMMITTER_NAME:Lr,GIT_COMMITTER_EMAIL:Dr};return(await ge(r,["commit-tree",o,"-m",e],i)).trim()}async function Ds(t,e,r,o,n){try{await q(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw Ze(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 Bs(t,e){return ge(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Gs(t,e,r,o,n){await q(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await q(t.workspacePath,["checkout","--force",r])}async function jo(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Lr,GIT_AUTHOR_EMAIL:Dr,GIT_COMMITTER_NAME:Lr,GIT_COMMITTER_EMAIL:Dr};(await ge(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await q(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(u=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(u)}`)}),await q(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await q(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(u){s=u instanceof Error?u.message:String(u)}let a=(await ge(o,["diff","--name-only","--diff-filter=U"])).split(`
516
- `).map(u=>u.trim()).filter(u=>u.length>0),c=await ge(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 q(t,e,r){return new Promise((o,n)=>{let i=_s("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}):
517
- ${s.join("").trim()||"(no stderr)"}`))})})}function ge(t,e,r){return new Promise((o,n)=>{let i=_s("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}):
518
- ${a.join("").trim()||"(no stderr)"}`))})})}function Ms(t,e){Or(t)&&Eo(t,{recursive:!0,force:!0}),Nr(Ur(t),{recursive:!0}),xp(e,t,"dir")}async function Hs(t,e,r){await q(t,["worktree","prune"]).catch(()=>{}),Nr(Ur(r),{recursive:!0}),await q(t,["worktree","add","--detach",r,`origin/${e}`])}async function Fs(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=qe(Os(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Ns(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let u=(await ge(a,["rev-parse","HEAD"])).trim(),p=qe(t,"code",s.name);o==="direct"?(Ms(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${u.slice(0,10)}`)):(await Hs(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${u.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:u})}return i}async function Ks(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=qe(Os(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Ns(i,r.cloneUrl,r.ref,void 0,n)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=qe(t,"context");o==="direct"?(Ms(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await Hs(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await ge(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function Ws(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await q(r,["add","-A",...o]).catch(()=>{});let n;try{n=await ge(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
519
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=$p(qe(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Sp}from"node:fs";import{join as Cp}from"node:path";var Ao=8*1024,wt=class extends Error{},Ft="meta/build-result.json";function Ys(t){let e=Cp(t,Ft),r;try{r=Sp(e,"utf-8")}catch{throw new wt(`BUILD produced no ${Ft} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new wt(`${Ft} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new wt(`${Ft} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new wt(`${Ft}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let f=p,l=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(l===null||d===null)return[];let g={name:l,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?Rp(n.logTail):"",u={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)u.failedStep=n.failedStep;else if(!i){let p=a.find(f=>f.exitCode!==0);p&&(u.failedStep=p.name)}return u}function Rp(t){let e=Buffer.from(t,"utf-8");return e.length<=Ao?t:`\u2026 [${e.length-Ao} bytes elided] \u2026
520
- `+e.subarray(e.length-Ao).toString("utf-8")}import{lstatSync as Tp,mkdtempSync as Ip,readFileSync as Pp,readdirSync as Vs,rmSync as qs}from"node:fs";import{tmpdir as Ep}from"node:os";import{join as Br,relative as jp}from"node:path";var zs=new Set(["code","context"]);function Js(t){let e=Ip(Br(Ep(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>qs(e,{recursive:!0,force:!0}),listFiles:()=>Xs(e,e),readFile:r=>Pp(Br(e,r),"utf-8"),clean:()=>{for(let r of Vs(e))zs.has(r)||qs(Br(e,r),{recursive:!0,force:!0})}}}function Xs(t,e){let r=[];for(let o of Vs(e)){let n=Br(e,o),i=Tp(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&zs.has(o))continue;r.push(...Xs(t,n))}else r.push(jp(t,n))}return r}var Mr=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Lp=new Set(["implement","resolve-conflict"]);function Dp(t){let e=Buffer.from(t,"utf-8");if(e.length<=Mr)return t;let r=Math.floor(Mr/4),o=Mr-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}
516
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{xp(r,{recursive:!0,force:!0})}catch{}}}}function Ao(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Sp)),t.bitbucket?.apiToken&&(e.push(`https://${nt}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Cp)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Rp)),Os(e,r)}function Ns(t,e){if(t.contextWrite?.token){let r=ot(e)??"github.com",o=ur(r);return Os([`https://${o}:${t.contextWrite.token}@${r}`],[Lr(r)])}return Ao(t)}import{spawn as Ls}from"node:child_process";import{existsSync as Dr,mkdirSync as Br,readFileSync as Tp,rmSync as _o,symlinkSync as Ip}from"node:fs";import{homedir as Pp}from"node:os";import{dirname as Gr,join as Qe}from"node:path";function Ds(){return Qe(Pp(),".codepipe-sandbox","repos")}function Us(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 Bs(t,e,r,o,n){if(Dr(Qe(t,".git"))){let i=async s=>{await V(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await V(t,["reset","--hard",`origin/${s}`],n),await V(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!Us(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Dr(t)&&_o(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0});try{return await V(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!Us(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Dr(t)&&_o(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0}),await V(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function Gs(t){await V(t.workspacePath,["reset","--hard",t.baseSha]),await V(t.workspacePath,["clean","-fdx"])}var Mr="CodePipe Agent",Hr="codepipe@codepartner.ee";async function Ms(t,e){let r=t.workspacePath;await V(r,["add","-A"]);let o=(await we(r,["write-tree"])).trim(),n=(await we(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Mr,GIT_AUTHOR_EMAIL:Hr,GIT_COMMITTER_NAME:Mr,GIT_COMMITTER_EMAIL:Hr};return(await we(r,["commit-tree",o,"-m",e],i)).trim()}async function Hs(t,e,r,o,n){try{await V(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw ot(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 Fs(t,e){return we(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Ks(t,e,r,o,n){await V(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await V(t.workspacePath,["checkout","--force",r])}async function Oo(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Mr,GIT_AUTHOR_EMAIL:Hr,GIT_COMMITTER_NAME:Mr,GIT_COMMITTER_EMAIL:Hr};(await we(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await V(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(u=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(u)}`)}),await V(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await V(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(u){s=u instanceof Error?u.message:String(u)}let a=(await we(o,["diff","--name-only","--diff-filter=U"])).split(`
517
+ `).map(u=>u.trim()).filter(u=>u.length>0),c=await we(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 V(t,e,r){return new Promise((o,n)=>{let i=Ls("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",n),i.on("close",a=>{if(a===0)return o();n(new Error(`git ${e[0]} failed (exit ${a}):
518
+ ${s.join("").trim()||"(no stderr)"}`))})})}function we(t,e,r){return new Promise((o,n)=>{let i=Ls("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",n),i.on("close",c=>{if(c===0)return o(s.join(""));n(new Error(`git ${e[0]} failed (exit ${c}):
519
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Ws(t,e){Dr(t)&&_o(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0}),Ip(e,t,"dir")}async function qs(t,e,r){await V(t,["worktree","prune"]).catch(()=>{}),Br(Gr(r),{recursive:!0}),await V(t,["worktree","add","--detach",r,`origin/${e}`])}async function Ys(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=Qe(Ds(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Bs(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let u=(await we(a,["rev-parse","HEAD"])).trim(),p=Qe(t,"code",s.name);o==="direct"?(Ws(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${u.slice(0,10)}`)):(await qs(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${u.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:u})}return i}async function Vs(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=Qe(Ds(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Bs(i,r.cloneUrl,r.ref,void 0,n)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=Qe(t,"context");o==="direct"?(Ws(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await qs(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await we(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function zs(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await V(r,["add","-A",...o]).catch(()=>{});let n;try{n=await we(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
520
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Tp(Qe(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Ep}from"node:fs";import{join as jp}from"node:path";var No=8*1024,xt=class extends Error{},Vt="meta/build-result.json";function Js(t){let e=jp(t,Vt),r;try{r=Ep(e,"utf-8")}catch{throw new xt(`BUILD produced no ${Vt} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new xt(`${Vt} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new xt(`${Vt} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new xt(`${Vt}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let f=p,l=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(l===null||d===null)return[];let g={name:l,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?Ap(n.logTail):"",u={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)u.failedStep=n.failedStep;else if(!i){let p=a.find(f=>f.exitCode!==0);p&&(u.failedStep=p.name)}return u}function Ap(t){let e=Buffer.from(t,"utf-8");return e.length<=No?t:`\u2026 [${e.length-No} bytes elided] \u2026
521
+ `+e.subarray(e.length-No).toString("utf-8")}import{lstatSync as _p,mkdtempSync as Op,readFileSync as Np,readdirSync as Qs,rmSync as Xs}from"node:fs";import{tmpdir as Up}from"node:os";import{join as Fr,relative as Lp}from"node:path";var Zs=new Set(["code","context"]);function ea(t){let e=Op(Fr(Up(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Xs(e,{recursive:!0,force:!0}),listFiles:()=>ta(e,e),readFile:r=>Np(Fr(e,r),"utf-8"),clean:()=>{for(let r of Qs(e))Zs.has(r)||Xs(Fr(e,r),{recursive:!0,force:!0})}}}function ta(t,e){let r=[];for(let o of Qs(e)){let n=Fr(e,o),i=_p(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Zs.has(o))continue;r.push(...ta(t,n))}else r.push(Lp(t,n))}return r}var Wr=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Fp=new Set(["implement","resolve-conflict"]);function Kp(t){let e=Buffer.from(t,"utf-8");if(e.length<=Wr)return t;let r=Math.floor(Wr/4),o=Wr-r,n=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-o).toString("utf-8"),s=e.length-r-o;return`${n}
521
522
 
522
- \u2026 [${s} bytes elided \u2014 log capped at ${Mr} bytes for upload] \u2026
523
+ \u2026 [${s} bytes elided \u2014 log capped at ${Wr} bytes for upload] \u2026
523
524
 
524
- ${i}`}async function Kt(t={}){Er();let e=ee(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=ur("SANDBOX_LOG","sandbox",Up("./logs"));if(o.enabled){let h=new nt(o);pr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${ie} (protocol ${de})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=vs(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Rs();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new gt(e.hubUrl,e.token),a=!1,c=new AbortController,u=null,p=null,f=!1,l=null,d=null,g=!1,w=()=>{let h=s.openControlSocket();return l=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ie,protocolVersion:de};h.send(JSON.stringify(m))}),h.on("message",m=>{let y=m.toString("utf-8"),$=null;try{let b=JSON.parse(y);b&&typeof b=="object"&&($=b)}catch{}if($&&$.type==="hello"){let b=$;d=or(b.protocolVersion);let N=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${N}`),d&&(g=!1);return}if($&&$.type==="pause_job"){let b=typeof $.jobId=="string"?$.jobId:"";b&&b===u?(console.warn(`[ws] pause_job ${b} \u2014 aborting agent`),f=!0,p?.abort()):console.log(`[ws] pause_job ${b} \u2014 not the active job, ignoring`),b&&h.send(JSON.stringify({type:"job_paused",jobId:b}));return}console.log(`[ws] ${y}`)}),h.on("close",(m,y)=>{console.log(`[ws] closed code=${m} reason=${y?.toString()||""}`),l===h&&(l=null),!a&&setTimeout(w,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},k=w(),R=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ie}, protocol ${de}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await s.claim(c.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 sandbox token rejected. exiting."),a=!0;break}if(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3));continue}let m=await h.json();await v(s,m)}catch(h){if(c.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3))}}};async function v(h,m){u=m.jobId,p=new AbortController,f=!1;let y=!1,$=null,b=null,N=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),E=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(y=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let ue=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} heartbeat error: ${ue}`)}};E();let M=setInterval(()=>{E()},N),le=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(j(m.prompt," \u2502 "));let he=[],C=null,ne=400,It=25,Jr=500,Pt=()=>{if(C&&(clearTimeout(C),C=null),he.length===0)return;let L=he.splice(0,he.length),ue=l;if(!ue||ue.readyState!==ue.OPEN)return;let xe={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:L};try{ue.send(JSON.stringify(xe))}catch{}},Xe=L=>{he.push(L),he.length>Jr&&he.shift(),he.length>=It?Pt():C||(C=setTimeout(Pt,ne))},z=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Xr=new Set,Qr=null;try{if(!n){y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:le,finishedAt:new Date().toISOString()});return}let L=Js(m.jobId);console.log(`[job] ${m.jobId} workspace=${L.dir}`);let ue=T(m,r);$=ue.gitCreds,b=ue.contextGitCreds;let xe=$?.env,Zo=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,ve=[],rr=null,Zr=null;try{let I="worktree";ve=await Fs(L.dir,m.projectId,m.projectRepos,I,xe);let P=await Ks(L.dir,m.projectId,m.contextRepo,I,xe);Zr=P,rr=P?.workspacePath??null}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} materialize failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let en=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let I=m.contextRepo?.cloneUrl;if(!I||!xe)throw new Error(I?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let P of m.deliveries){let G=ve.find(oe=>oe.name===P.name);G&&(await Gs(G,P.deliveryRef,P.deliverySha,I,xe),console.log(`[job] ${m.jobId} ${G.name}: checked out delivery ${P.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await en()}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} delivery checkout failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let tn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},rn="";if(m.role==="resolve-conflict")try{let I=[];for(let P of ve){let G=tn[P.name];if(!G)continue;let oe=await jo(P,G,xe);console.log(`[job] ${m.jobId} ${P.name}: merged ${G} into ${P.ref} \u2014 ${oe.length} conflicted file(s)`),oe.length>0?I.push(`- **${P.name}**:`,...oe.map(Qe=>` - \`${Qe}\``)):I.push(`- **${P.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}rn=`
525
+ ${i}`}async function zt(t={}){Or();let e=te(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=mr("SANDBOX_LOG","sandbox",Hp("./logs"));if(o.enabled){let h=new ct(o);gr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${se} (protocol ${fe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Ts(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Es();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new kt(e.hubUrl,e.token),a=!1,c=new AbortController,u=null,p=null,f=!1,l=null,d=null,g=!1,w=()=>{let h=s.openControlSocket();return l=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:se,protocolVersion:fe};h.send(JSON.stringify(m))}),h.on("message",m=>{let y=m.toString("utf-8"),x=null;try{let $=JSON.parse(y);$&&typeof $=="object"&&(x=$)}catch{}if(x&&x.type==="hello"){let $=x;d=ar($.protocolVersion);let N=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${N}`),d&&(g=!1);return}if(x&&x.type==="pause_job"){let $=typeof x.jobId=="string"?x.jobId:"";$&&$===u?(console.warn(`[ws] pause_job ${$} \u2014 aborting agent`),f=!0,p?.abort()):console.log(`[ws] pause_job ${$} \u2014 not the active job, ignoring`),$&&h.send(JSON.stringify({type:"job_paused",jobId:$}));return}console.log(`[ws] ${y}`)}),h.on("close",(m,y)=>{console.log(`[ws] closed code=${m} reason=${y?.toString()||""}`),l===h&&(l=null),!a&&setTimeout(w,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},k=w(),C=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${se}, protocol ${fe}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await s.claim(c.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 sandbox token rejected. exiting."),a=!0;break}if(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3));continue}let m=await h.json();await v(s,m)}catch(h){if(c.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3))}}};async function v(h,m){u=m.jobId,p=new AbortController,f=!1;let y=!1,x=null,$=null,N=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),A=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(y=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let ue=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} heartbeat error: ${ue}`)}};A();let B=setInterval(()=>{A()},N),oe=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(E(m.prompt," \u2502 "));let pe=[],Be=null,R=400,ie=25,Se=500,ye=()=>{if(Be&&(clearTimeout(Be),Be=null),pe.length===0)return;let L=pe.splice(0,pe.length),ue=l;if(!ue||ue.readyState!==ue.OPEN)return;let Ce={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:L};try{ue.send(JSON.stringify(Ce))}catch{}},Qr=L=>{pe.push(L),pe.length>Se&&pe.shift(),pe.length>=ie?ye():Be||(Be=setTimeout(ye,R))},Ge=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,q=new Set,Zr=null;try{if(!n){y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:oe,finishedAt:new Date().toISOString()});return}let L=ea(m.jobId);console.log(`[job] ${m.jobId} workspace=${L.dir}`);let ue=T(m,r);x=ue.gitCreds,$=ue.contextGitCreds;let Ce=x?.env,Zo=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,Re=[],sr=null,eo=null;try{let I="worktree";Re=await Ys(L.dir,m.projectId,m.projectRepos,I,Ce);let P=await Vs(L.dir,m.projectId,m.contextRepo,I,Ce);eo=P,sr=P?.workspacePath??null}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} materialize failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${P}`},startedAt:oe,finishedAt:new Date().toISOString()}),L.dispose();return}let en=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let I=m.contextRepo?.cloneUrl;if(!I||!Ce)throw new Error(I?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let P of m.deliveries){let M=Re.find(ne=>ne.name===P.name);M&&(await Ks(M,P.deliveryRef,P.deliverySha,I,Ce),console.log(`[job] ${m.jobId} ${M.name}: checked out delivery ${P.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await en()}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} delivery checkout failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${P}`},startedAt:oe,finishedAt:new Date().toISOString()}),L.dispose();return}let tn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},rn="";if(m.role==="resolve-conflict")try{let I=[];for(let P of Re){let M=tn[P.name];if(!M)continue;let ne=await Oo(P,M,Ce);console.log(`[job] ${m.jobId} ${P.name}: merged ${M} into ${P.ref} \u2014 ${ne.length} conflicted file(s)`),ne.length>0?I.push(`- **${P.name}**:`,...ne.map(rt=>` - \`${rt}\``)):I.push(`- **${P.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}rn=`
525
526
 
526
527
  ## Conflicts to resolve
527
528
 
528
529
  `+(I.length>0?I.join(`
529
530
  `):"(no task branches to merge)")+`
530
- `}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} conflict merge failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let bc=U(m.prompt,ve,rr)+rn,eo=[...ve.map(I=>I.workspacePath),...rr?[rr]:[]];eo.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${eo.join(", ")}`),z&&(Qr=setInterval(()=>{let P=l;if(!P||P.readyState!==P.OPEN)return;let G;try{G=_p(Gr(L.dir,"drafts")).filter(oe=>oe.endsWith(".json")).sort()}catch{return}for(let oe of G){if(Xr.has(oe))continue;if(Xr.size>=pn)break;let Qe;try{let X=JSON.parse(Qs(Gr(L.dir,"drafts",oe),"utf-8")),O=typeof X.localRef=="string"?X.localRef:"",Y=typeof X.title=="string"?X.title:"",Ue=typeof X.body=="string"?X.body:"";if(!O||!Y)continue;Qe={localRef:O,title:Y,body:Ue,...X.isEpic===!0?{isEpic:!0}:{},...Array.isArray(X.links)?{links:X.links}:{}}}catch{continue}Xr.add(oe);let Et={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:z,child:Qe};try{P.send(JSON.stringify(Et))}catch{}}},1500));try{let I=await Is(n,{workspaceDir:L.dir,role:m.role,prompt:bc,addDirs:eo,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Zo?{env:Zo}:{},signal:p.signal,onActivity:Xe},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{L.clean();for(let O of ve)try{await Us(O);let Y=tn[O.name];m.role==="resolve-conflict"&&Y&&await jo(O,Y,xe)}catch(Y){let Ue=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${m.jobId} worktree reset failed (${O.name}): ${Ue}`)}try{await en()}catch(O){let Y=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${Y}`)}},aborted:()=>y||f}),P=[];if(Lp.has(m.role)&&ve.length>0){let O=m.metadata??{},Y=typeof O.commitMessage=="string"?O.commitMessage:`${m.taskId}: changes`,Ue=m.contextRepo?.cloneUrl,on=b?.env;if(!Ue||!on)throw new Error("delivery requested but "+(Ue?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let kc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let we of ve){let jt=await Ls(we,Y);if(!jt){console.log(`[job] ${m.jobId} ${we.name}: no changes \u2014 no delivery`);continue}let to=`codepipe/deliveries/${kc}/${m.jobId}/${we.name}`;await Ds(we,jt,to,Ue,on),P.push({name:we.name,deliveryRef:to,deliverySha:jt,baseSha:we.baseSha}),console.log(`[job] ${m.jobId} ${we.name}: delivered ${jt.slice(0,10)} \u2192 ${to}`);let nn=await Bs(we,jt);if(nn.trim().length>0){let $c=Gr("display",`${we.name}.diff`),sn=Gr(L.dir,$c);Ap(Np(sn),{recursive:!0}),Op(sn,nn)}}}if(m.role==="resolve-conflict"&&P.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let G;m.role==="build"&&(G=Ys(L.dir),console.log(`[job] ${m.jobId} build verdict: ok=${G.ok}`+(G.failedStep?` failedStep=${G.failedStep}`:"")));let oe=I.artifactPaths.length>0?I.artifactPaths:L.listFiles(),Qe=Array.from(new Set(oe)),Et;if(Zr)try{let O=await Ws(Zr,m.role==="index"?["adr/SOURCES.md"]:[]);O.length>0&&(Et=O,console.log(`[job] ${m.jobId} captured ${O.length} knowledge file(s) for Context Repo`))}catch(O){let Y=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${Y}`)}let X={jobId:m.jobId,status:"succeeded",artifacts:Qe.map(O=>({path:O,contentBase64:Qs(`${L.dir}/${O}`).toString("base64")})),...Et?{contextWrites:Et}:{},...P.length>0?{deliveries:P}:{},log:Dp(I.log),startedAt:le,finishedAt:new Date().toISOString(),usage:I.usage,...I.rateLimit?{rateLimit:I.rateLimit}:{},...G?{build:G}:{}};if(y||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(X),console.log(`[job] ${m.jobId} done \u2014 uploaded ${X.artifacts.length} artifact(s):`);for(let O of X.artifacts){let Y=Buffer.from(O.contentBase64,"base64").length;console.log(` \xB7 ${O.path} (${Y} bytes)`)}X.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(I){let P=I instanceof Error?I.message:String(I);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(y)console.warn(`[job] ${m.jobId} failed after claim lost (${P}) \u2014 skipping result upload`);else{let G=Ts(I);console.warn(G?`[job] ${m.jobId} failed: ${P} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${P}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:P},startedAt:le,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(M),Qr&&clearInterval(Qr),Pt(),u=null,p=null,$?.cleanup(),b?.cleanup()}}function T(h,m){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let y;try{y=JSON.parse(ri(m,h.credBundle).toString("utf-8"))}catch(E){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${E instanceof Error?E.message:String(E)}`),{gitCreds:null,contextGitCreds:null}}let $=Po(y);$&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let b=js(y,h.contextRepo.cloneUrl),N={gitCreds:$,contextGitCreds:b};return y.claudeOauthToken&&(N.claudeOauthToken=y.claudeOauthToken),N}function j(h,m){return h.split(`
531
+ `}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} conflict merge failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${P}`},startedAt:oe,finishedAt:new Date().toISOString()}),L.dispose();return}let bc=U(m.prompt,Re,sr)+rn,to=[...Re.map(I=>I.workspacePath),...sr?[sr]:[]];to.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${to.join(", ")}`),Ge&&(Zr=setInterval(()=>{let P=l;if(!P||P.readyState!==P.OPEN)return;let M;try{M=Bp(Kr(L.dir,"drafts")).filter(ne=>ne.endsWith(".json")).sort()}catch{return}for(let ne of M){if(q.has(ne))continue;if(q.size>=pn)break;let rt;try{let Q=JSON.parse(ra(Kr(L.dir,"drafts",ne),"utf-8")),O=typeof Q.localRef=="string"?Q.localRef:"",Y=typeof Q.title=="string"?Q.title:"",Me=typeof Q.body=="string"?Q.body:"";if(!O||!Y)continue;rt={localRef:O,title:Y,body:Me,...Q.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Q.links)?{links:Q.links}:{}}}catch{continue}q.add(ne);let Ot={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:Ge,child:rt};try{P.send(JSON.stringify(Ot))}catch{}}},1500));try{let I=await As(n,{workspaceDir:L.dir,role:m.role,prompt:bc,addDirs:to,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Zo?{env:Zo}:{},signal:p.signal,onActivity:Qr},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{L.clean();for(let O of Re)try{await Gs(O);let Y=tn[O.name];m.role==="resolve-conflict"&&Y&&await Oo(O,Y,Ce)}catch(Y){let Me=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${m.jobId} worktree reset failed (${O.name}): ${Me}`)}try{await en()}catch(O){let Y=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${Y}`)}},aborted:()=>y||f}),P=[];if(Fp.has(m.role)&&Re.length>0){let O=m.metadata??{},Y=typeof O.commitMessage=="string"?O.commitMessage:`${m.taskId}: changes`,Me=m.contextRepo?.cloneUrl,on=$?.env;if(!Me||!on)throw new Error("delivery requested but "+(Me?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let kc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let be of Re){let Nt=await Ms(be,Y);if(!Nt){console.log(`[job] ${m.jobId} ${be.name}: no changes \u2014 no delivery`);continue}let ro=`codepipe/deliveries/${kc}/${m.jobId}/${be.name}`;await Hs(be,Nt,ro,Me,on),P.push({name:be.name,deliveryRef:ro,deliverySha:Nt,baseSha:be.baseSha}),console.log(`[job] ${m.jobId} ${be.name}: delivered ${Nt.slice(0,10)} \u2192 ${ro}`);let nn=await Fs(be,Nt);if(nn.trim().length>0){let $c=Kr("display",`${be.name}.diff`),sn=Kr(L.dir,$c);Dp(Mp(sn),{recursive:!0}),Gp(sn,nn)}}}if(m.role==="resolve-conflict"&&P.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let M;m.role==="build"&&(M=Js(L.dir),console.log(`[job] ${m.jobId} build verdict: ok=${M.ok}`+(M.failedStep?` failedStep=${M.failedStep}`:"")));let ne=I.artifactPaths.length>0?I.artifactPaths:L.listFiles(),rt=Array.from(new Set(ne)),Ot;if(eo)try{let O=await zs(eo,m.role==="index"?["adr/SOURCES.md"]:[]);O.length>0&&(Ot=O,console.log(`[job] ${m.jobId} captured ${O.length} knowledge file(s) for Context Repo`))}catch(O){let Y=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${Y}`)}let Q={jobId:m.jobId,status:"succeeded",artifacts:rt.map(O=>({path:O,contentBase64:ra(`${L.dir}/${O}`).toString("base64")})),...Ot?{contextWrites:Ot}:{},...P.length>0?{deliveries:P}:{},log:Kp(I.log),startedAt:oe,finishedAt:new Date().toISOString(),usage:I.usage,...I.rateLimit?{rateLimit:I.rateLimit}:{},...M?{build:M}:{}};if(y||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(Q),console.log(`[job] ${m.jobId} done \u2014 uploaded ${Q.artifacts.length} artifact(s):`);for(let O of Q.artifacts){let Y=Buffer.from(O.contentBase64,"base64").length;console.log(` \xB7 ${O.path} (${Y} bytes)`)}Q.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(I){let P=I instanceof Error?I.message:String(I);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(y)console.warn(`[job] ${m.jobId} failed after claim lost (${P}) \u2014 skipping result upload`);else{let M=js(I);console.warn(M?`[job] ${m.jobId} failed: ${P} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${P}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:P},startedAt:oe,finishedAt:new Date().toISOString(),...M?{authError:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(B),Zr&&clearInterval(Zr),ye(),u=null,p=null,x?.cleanup(),$?.cleanup()}}function T(h,m){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let y;try{y=JSON.parse(oi(m,h.credBundle).toString("utf-8"))}catch(A){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${A instanceof Error?A.message:String(A)}`),{gitCreds:null,contextGitCreds:null}}let x=Ao(y);x&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let $=Ns(y,h.contextRepo.cloneUrl),N={gitCreds:x,contextGitCreds:$};return y.claudeOauthToken&&(N.claudeOauthToken=y.claudeOauthToken),N}function E(h,m){return h.split(`
531
532
  `).map(y=>m+y).join(`
532
- `)}function U(h,m,y){let $=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,y??"")}let S=h=>{if(a)return;a=!0,console.log(`
533
- [${h}] shutting down`),c.abort();let m=new AbortController,y=setTimeout(()=>m.abort(),3e3);(async()=>{let $=u;if($)try{await s.releaseJob($,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${$}`)}catch(b){let N=b instanceof Error?b.message:String(b);console.warn(`[${h}] release failed: ${N} (sweeper will reclaim)`)}clearTimeout(y),k.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>S("SIGINT")),process.on("SIGTERM",()=>S("SIGTERM")),await R()}async function Zs(t={profile:void 0}){let e=fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=$r(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let u={type:"register",projectId:e.projectId};r.send(JSON.stringify(u))}),r.on("message",u=>{let p=u.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",u=>s.push(`error:${u.message}`)),r.on("close",(u,p)=>{s.push(`close:${u}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=ee(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as $t,mkdirSync as va,readFileSync as Sa,readdirSync as xd,writeFileSync as Ca}from"node:fs";import{join as Ve,resolve as Ra}from"node:path";import{setTimeout as vd}from"node:timers/promises";import{cancel as Sd,confirm as xt,intro as Ta,isCancel as Go,log as x,outro as Do,password as Yt,select as ze,spinner as Ia,text as K}from"@clack/prompts";import{simpleGit as Yr}from"simple-git";async function bt(t,e,r){return e.host==="github"?Gp(t,e,r):e.host==="gitlab"?qp(t,e,r):zp(t,e,r)}async function ea(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 Ae(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await ta(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 je(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await ra(e.gitlabToken,t):n}}return e.bitbucket?(await yt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await oa(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 ta(t,e){let r=!1;try{r=(await Ae(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 ra(t,e){let r=!1;try{r=(await je(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 oa(t,e){let r=!1;try{r=(await yt(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 Bp="https://api.github.com";async function Ae(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(Bp+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 Gp(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 Mp(o,e,r),i=await Fp(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=lt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Kp(o,n.owner,n.name,a.path,i)||await Wp(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 Mp(t,e,r){let o=await Ae(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 ta(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Hp(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 Ae(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 Hp(t,e){let{status:r,data:o}=await Ae(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function Fp(t,e,r){let{data:o}=await Ae(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Kp(t,e,r,o,n){let{status:i,data:s}=await Ae(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Wp(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 Ae(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Yp="https://gitlab.com/api/v4";async function je(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(Yp+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 qp(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 je(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 ra(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await je(o,"GET","/user"),l={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let g=await je(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);l.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await je(o,"POST","/projects",l);if(!d.data)throw new Error("GitLab create project: empty response");i=d.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=lt(t,e,r.youtrackWrites,r.trackerUrl),u=new Set;for(let f=1;;f++){let d=(await je(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)u.add(g.path);if(d.length<100)break}let p=c.filter(f=>!u.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await je(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var Vp="https://api.bitbucket.org/2.0";async function yt(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(Vp+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 zp(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 yt(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 oa(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 yt(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=lt(t,e,r.youtrackWrites,r.trackerUrl),u=[];for(let f of c)(await yt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&u.push(f);if(u.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of u)f.set(d.path,d.content);if((await yt(o,"POST",`${n}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var Jp={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function $e(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=Jp[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 Xp}from"node:crypto";import{existsSync as na,mkdirSync as Qp,readFileSync as ia,readdirSync as Zp,rmSync as Hr,writeFileSync as ed}from"node:fs";import{homedir as td}from"node:os";import{dirname as rd,join as _o}from"node:path";var od=24*60*60*1e3;function sa(){return _o(td(),".codepipe","init-drafts")}function Oo(t){let e=Xp("sha256").update(t).digest("hex").slice(0,16);return _o(sa(),`${e}.json`)}function aa(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=od)}function ca(t){let e=Oo(t);if(!na(e))return null;try{let r=JSON.parse(ia(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:aa(r.savedAt)?(Hr(e,{force:!0}),null):r}catch{return null}}function No(t){Hr(Oo(t),{force:!0})}function la(){let t=sa();if(na(t))for(let e of Zp(t)){let r=_o(t,e);try{let o=JSON.parse(ia(r,"utf-8"));aa(o.savedAt)&&Hr(r,{force:!0})}catch{Hr(r,{force:!0})}}}var kt=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(){No(this.cwd)}persist(){let e=Oo(this.cwd);Qp(rd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};ed(e,JSON.stringify(r,null,2)+`
534
- `,{mode:384})}};function ua(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 pa(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{homedir as nd}from"node:os";import{existsSync as id,mkdirSync as sd,readFileSync as ad,writeFileSync as cd}from"node:fs";import{dirname as ld,join as ud}from"node:path";function Uo(){return _("FARM_PINS")??ud(nd(),".codepipe","farm-pins.json")}function da(){let t=Uo();if(!id(t))return{};try{return JSON.parse(ad(t,"utf-8"))}catch{return{}}}function pd(t){let e=Uo();sd(ld(e),{recursive:!0}),cd(e,JSON.stringify(t,null,2)+`
535
- `,{mode:384})}function dd(t){return da()[t]}function fa(t,e){let r=da();r[t]=e,pd(r)}function ma(t,e){let r=ut(e),o=dd(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 ${Uo()}.`);return r}import{existsSync as wa}from"node:fs";import{join as ya}from"node:path";import{simpleGit as ba}from"simple-git";import{existsSync as Fr,readFileSync as ga,writeFileSync as fd}from"node:fs";import{dirname as md,join as _e}from"node:path";import{parse as gd}from"yaml";var Oe=".codepipe",Lo=".devpipe";function hd(t=process.cwd()){let e=t;for(;;){if(Fr(_e(e,Oe,"project.yaml")))return e;if(Fr(_e(e,Lo,"project.yaml")))return Be(_e(e,Lo),_e(e,Oe))&&yd(e),e;let r=md(e);if(r===e)return null;e=r}}function wd(t){let e=_e(t,Oe);return Fr(e)?e:_e(t,Lo)}function yd(t){let e=_e(t,".gitignore");if(!Fr(e))return;let r=ga(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(`
536
- `);o!==r&&fd(e,o)}function Kr(t=process.cwd()){let e=hd(t);if(!e)return null;let r=wd(e),o=bd(ga(_e(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function bd(t){let e=gd(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),u=String(a.name??c);if(!u||!c)continue;let p=a.host,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:u,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??u)})}return{projectId:r,name:o,repos:i}}function ha(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 kd={info:t=>console.log(t),warn:t=>console.warn(t)};async function Wt(t,e,r={}){let o=r.log??kd,n=[];for(let i of e){let s=ya(t,i.mountAs),a=ha(i);if(!wa(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 ba().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!wa(ya(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=ba(s),u="";try{u=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{u=""}if(!$d(u,a)){o.warn(`${i.mountAs}/ origin (${u||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:u});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function $d(t,e){return ka(t)===ka(e)}function ka(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function $a(t={}){let e=Kr();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 Wt(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 xa=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function B(t){Sd(t),process.exit(1)}function ae(t){return Go(t)&&B("aborted"),t}function D(t){return Go(t)&&B("aborted"),typeof t=="string"?t:""}async function Pa(t={}){Ta("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();la();let r=ca(e),o,n=!1;r&&Object.keys(r.answers).length>0?ae(await xt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(x.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new kt(e,r),n=!0):(No(e),o=new kt(e)):o=new kt(e);let i=t.force===!0?null:await Rd(e),s=await o.ask("target",async()=>ae(await ze({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?x.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):n&&o.get("contextRepo")!==void 0||ja(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:pe,initialValue:_("HUB_URL")??pe,validate:C=>C.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),u=await o.ask("email",()=>Aa()),p=await o.ask("cliToken",()=>qr(c,u)),f=null;s==="farm"&&(f=await Cd(c,p));let l=a?Id(a.parsed.repoName):"",d=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:l||"acme",...l?{initialValue:l}:{},validate:C=>Le.test(C.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:C=>C.trim().length>0?void 0:"required"})).trim()),w=await o.ask("automationLevel",async()=>ae(await ze({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await o.ask("youtrack",()=>Ba()),R=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:C=>C.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ae(await xt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},j=()=>o.set("tokens",T),U=await o.ask("repos",()=>jd(T,u,a,{onCred:j,initial:o.get("reposPartial")??[],onProgress:C=>o.set("reposPartial",C)}));o.delete("reposPartial");let S=await Ad(await o.ask("contextRepo",()=>Ua(d,U,T,u)),d,U,T,u,j,C=>o.set("contextRepo",C)),{spec:h,mode:m}=S;x.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let y=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:C=>C.trim().length>0?void 0:"required"})).trim()),$={projectId:d,name:g,automationLevel:w,repos:U,youtrackProjectKey:R,ownerEmail:u};x.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let b;try{b=await bt($,h,{...La(T),youtrackWrites:v,trackerUrl:k.url,mode:m,log:{info:C=>x.message(C),warn:C=>x.warn(C)}})}catch(C){B(`Context Repo provisioning failed: ${C instanceof Error?C.message:String(C)}`)}$.contextRepo=b,x.success(`Context Repo ready: ${b.owner}/${b.name}@${b.branch}`),x.step(`registering project on ${c}\u2026`);let N;try{N=await dt(c,p,$)}catch(C){if(C instanceof A&&C.status===409){x.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{N=await se(c,p,d)}catch(ne){throw ne instanceof A&&B(`HUB \u2192 ${ne.status} ${ne.message}`),ne}}else if(C instanceof A&&C.status===401)o.delete("cliToken"),B("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(C instanceof A)B(`HUB \u2192 ${C.status} ${C.message}`);else throw C}let E=N.contextRepo??b;x.success(`project ${N.projectId} ready (${N.provisioningStatus})`);let M=await Ld(E),le={url:k.url,token:k.token};if(s==="farm"){let C=f,ne={...T,...M?{contextWrite:M}:{},youtrack:le},It=T.github?.token;if(E.host==="github"&&It)try{let z=ss(`devpipe-${d}`);await as(E,It,z.publicKey,`devpipe-${d}`),ne.contextSsh={privateKey:z.privateKey},x.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(z){x.warn(`could not set up Context Repo SSH deploy key (${z instanceof Error?z.message:String(z)}); the farm will fall back to the token path.`)}let Jr={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:ne,contextRepo:E,projectConfig:Re($,v,k.url,y||void 0)},Pt=wr(C.farm.publicKey,JSON.stringify(Jr));x.step(`handing project ${d} to farm ${C.farm.name}\u2026`);let Xe;try{Xe=await Wi(c,p,C.farm.farmId,{projectId:d,sealedBundle:Pt})}catch(z){throw z instanceof A&&B(z.status===409?`farm ${C.farm.name} is offline \u2014 start it and re-run.`:z.status===504?`farm ${C.farm.name} did not respond in time.`:`HUB \u2192 ${z.status} ${z.message}`),z}Xe.ok||B(`farm rejected provisioning: ${Xe.error??"unknown error"}`),await Bo(c,p,d,E,It),o.clear(),Do(`done. project ${d} is now hosted on farm ${C.farm.name} (daemon ${Xe.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Da(T),await _a(e,E.cloneUrl,E.branch),Na(e),a&&await Ed(e);{let C=Ve(e,Oe);mr(C);let ne=ao(C,Re($,v,k.url,y||void 0));ne.length>0&&x.success(`local project config \u2192 .codepipe/{${ne.join(", ")}}`)}await Oa(e,N.repos);let he={hubUrl:c,cliToken:p,projectId:d,...T,...M?{contextWrite:M}:{},youtrack:le};Q(he),De({hubUrl:c,cliToken:p,projectId:d,accountEmail:u},d),x.success(`secrets \u2192 ${Ge(d)}`),await Bo(c,p,d,E,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Do(`done. next: \`codepipe\` (interactive) or \`codepipe --profile ${d} daemon\`.`)}async function Bo(t,e,r,o,n){let i=await pa(o,n),s=ua(i),a=await ze({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Go(a)||a!==s.proceedValue))try{let{jobId:c}=await vr(t,e,r,{reindex:s.reindex});x.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){x.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Cd(t,e){let r;try{r=await Ki(t,e)}catch(c){throw c instanceof A&&B(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&B("no farms registered on this HUB. Register one first: on the farm host run `codepipe-farm register --hub <url> --token <HUB_FARM_REG_TOKEN>` and `codepipe-farm start`.");let n=ae(await ze({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=ma(i.farmId,i.publicKey)}catch(c){B(c instanceof Error?c.message:String(c))}return ae(await xt({message:`confirm farm ${i.name} cred-channel fingerprint:
533
+ `)}function U(h,m,y){let x=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,x).replace(/\{\{codeRoot\}\}/g,x?x.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,y??"")}let S=h=>{if(a)return;a=!0,console.log(`
534
+ [${h}] shutting down`),c.abort();let m=new AbortController,y=setTimeout(()=>m.abort(),3e3);(async()=>{let x=u;if(x)try{await s.releaseJob(x,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${x}`)}catch($){let N=$ instanceof Error?$.message:String($);console.warn(`[${h}] release failed: ${N} (sweeper will reclaim)`)}clearTimeout(y),k.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>S("SIGINT")),process.on("SIGTERM",()=>S("SIGTERM")),await C()}async function oa(t={profile:void 0}){let e=me(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Sr(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let u={type:"register",projectId:e.projectId};r.send(JSON.stringify(u))}),r.on("message",u=>{let p=u.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",u=>s.push(`error:${u.message}`)),r.on("close",(u,p)=>{s.push(`close:${u}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await ae(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=te(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as Rt,mkdirSync as Ca,readFileSync as Ra,readdirSync as $d,writeFileSync as Ta}from"node:fs";import{join as Ze,resolve as Ia}from"node:path";import{setTimeout as xd}from"node:timers/promises";import{cancel as vd,confirm as Tt,intro as Pa,isCancel as Ho,log as b,outro as Go,password as It,select as et,spinner as Ea,text as K}from"@clack/prompts";import{simpleGit as Vr}from"simple-git";async function St(t,e,r){return e.host==="github"?qp(t,e,r):e.host==="gitlab"?Zp(t,e,r):td(t,e,r)}async function na(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 Le(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await ia(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 Ue(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await sa(e.gitlabToken,t):n}}return e.bitbucket?(await vt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await aa(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 ia(t,e){let r=!1;try{r=(await Le(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 sa(t,e){let r=!1;try{r=(await Ue(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 aa(t,e){let r=!1;try{r=(await vt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var Wp="https://api.github.com";async function Le(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(Wp+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function qp(t,e,r){let o=r.githubToken;if(!o)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let n=await Yp(o,e,r),i=await zp(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=mt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Jp(o,n.owner,n.name,a.path,i)||await Xp(o,n.owner,n.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:n.owner,name:n.name,cloneUrl:n.sshUrl,branch:i}}async function Yp(t,e,r){let o=await Le(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 ia(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Vp(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await Le(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Vp(t,e){let{status:r,data:o}=await Le(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function zp(t,e,r){let{data:o}=await Le(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Jp(t,e,r,o,n){let{status:i,data:s}=await Le(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Xp(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Le(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Qp="https://gitlab.com/api/v4";async function Ue(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(Qp+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Zp(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ue(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 sa(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ue(o,"GET","/user"),l={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let g=await Ue(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);l.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await Ue(o,"POST","/projects",l);if(!d.data)throw new Error("GitLab create project: empty response");i=d.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=mt(t,e,r.youtrackWrites,r.trackerUrl),u=new Set;for(let f=1;;f++){let d=(await Ue(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)u.add(g.path);if(d.length<100)break}let p=c.filter(f=>!u.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Ue(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var ed="https://api.bitbucket.org/2.0";async function vt(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(ed+r,n),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function td(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await vt(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 aa(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 vt(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=mt(t,e,r.youtrackWrites,r.trackerUrl),u=[];for(let f of c)(await vt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&u.push(f);if(u.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of u)f.set(d.path,d.content);if((await vt(o,"POST",`${n}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function ve(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=rd[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as od}from"node:crypto";import{existsSync as ca,mkdirSync as nd,readFileSync as la,readdirSync as id,rmSync as qr,writeFileSync as sd}from"node:fs";import{homedir as ad}from"node:os";import{dirname as cd,join as Uo}from"node:path";var ld=24*60*60*1e3;function ua(){return Uo(ad(),".codepipe","init-drafts")}function Lo(t){let e=od("sha256").update(t).digest("hex").slice(0,16);return Uo(ua(),`${e}.json`)}function pa(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=ld)}function da(t){let e=Lo(t);if(!ca(e))return null;try{let r=JSON.parse(la(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:pa(r.savedAt)?(qr(e,{force:!0}),null):r}catch{return null}}function Do(t){qr(Lo(t),{force:!0})}function fa(){let t=ua();if(ca(t))for(let e of id(t)){let r=Uo(t,e);try{let o=JSON.parse(la(r,"utf-8"));pa(o.savedAt)&&qr(r,{force:!0})}catch{qr(r,{force:!0})}}}var Ct=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(){Do(this.cwd)}persist(){let e=Lo(this.cwd);nd(cd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sd(e,JSON.stringify(r,null,2)+`
535
+ `,{mode:384})}};function ma(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 ga(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{homedir as ud}from"node:os";import{existsSync as pd,mkdirSync as dd,readFileSync as fd,writeFileSync as md}from"node:fs";import{dirname as gd,join as hd}from"node:path";function Bo(){return _("FARM_PINS")??hd(ud(),".codepipe","farm-pins.json")}function ha(){let t=Bo();if(!pd(t))return{};try{return JSON.parse(fd(t,"utf-8"))}catch{return{}}}function wd(t){let e=Bo();dd(gd(e),{recursive:!0}),md(e,JSON.stringify(t,null,2)+`
536
+ `,{mode:384})}function yd(t){return ha()[t]}function wa(t,e){let r=ha();r[t]=e,wd(r)}function ya(t,e){let r=gt(e),o=yd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Bo()}.`);return r}import{existsSync as ba}from"node:fs";import{join as ka}from"node:path";import{simpleGit as $a}from"simple-git";var bd={info:t=>console.log(t),warn:t=>console.warn(t)};async function Jt(t,e,r={}){let o=r.log??bd,n=[];for(let i of e){let s=ka(t,i.mountAs),a=ws(i);if(!ba(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 $a().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!ba(ka(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=$a(s),u="";try{u=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{u=""}if(!kd(u,a)){o.warn(`${i.mountAs}/ origin (${u||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:u});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function kd(t,e){return xa(t)===xa(e)}function xa(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function va(t={}){let e=Ht();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 Jt(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 Sa=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function G(t){vd(t),process.exit(1)}function ce(t){return Ho(t)&&G("aborted"),t}function D(t){return Ho(t)&&G("aborted"),typeof t=="string"?t:""}async function ja(t={}){Pa("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();fa();let r=da(e),o,n=!1;r&&Object.keys(r.answers).length>0?ce(await Tt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(b.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new Ct(e,r),n=!0):(Do(e),o=new Ct(e)):o=new Ct(e);let i=t.force===!0?null:await Cd(e),s=await o.ask("target",async()=>ce(await et({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?b.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):n&&o.get("contextRepo")!==void 0||_a(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:de,initialValue:_("HUB_URL")??de,validate:R=>R.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),u=await o.ask("email",()=>Oa()),p=await o.ask("cliToken",()=>zr(c,u)),f=null;s==="farm"&&(f=await Sd(c,p));let l=a?Td(a.parsed.repoName):"",d=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:l||"acme",...l?{initialValue:l}:{},validate:R=>He.test(R.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),w=await o.ask("automationLevel",async()=>ce(await et({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await o.ask("youtrack",()=>Ma()),C=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:R=>R.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ce(await Tt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},E=()=>o.set("tokens",T),U=await o.ask("repos",()=>Ed(T,u,a,{onCred:E,initial:o.get("reposPartial")??[],onProgress:R=>o.set("reposPartial",R)}));o.delete("reposPartial");let S=await jd(await o.ask("contextRepo",()=>Da(d,U,T,u)),d,U,T,u,E,R=>o.set("contextRepo",R)),{spec:h,mode:m}=S;b.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let y=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:R=>R.trim().length>0?void 0:"required"})).trim()),x=await o.ask("claudeToken",()=>Dd(s==="farm")),$={projectId:d,name:g,automationLevel:w,repos:U,youtrackProjectKey:C,ownerEmail:u};b.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let N;try{N=await St($,h,{...Ba(T),youtrackWrites:v,trackerUrl:k.url,mode:m,log:{info:R=>b.message(R),warn:R=>b.warn(R)}})}catch(R){G(`Context Repo provisioning failed: ${R instanceof Error?R.message:String(R)}`)}$.contextRepo=N,b.success(`Context Repo ready: ${N.owner}/${N.name}@${N.branch}`),b.step(`registering project on ${c}\u2026`);let A;try{A=await wt(c,p,$)}catch(R){if(R instanceof j&&R.status===409){b.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{A=await ae(c,p,d)}catch(ie){throw ie instanceof j&&G(`HUB \u2192 ${ie.status} ${ie.message}`),ie}}else if(R instanceof j&&R.status===401)o.delete("cliToken"),G("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(R instanceof j)G(`HUB \u2192 ${R.status} ${R.message}`);else throw R}let B=A.contextRepo??N;b.success(`project ${A.projectId} ready (${A.provisioningStatus})`);let oe=await Ud(B),pe={url:k.url,token:k.token};if(s==="farm"){let R=f,ie={...T,...oe?{contextWrite:oe}:{},...x?{claude:{oauthToken:x}}:{},youtrack:pe},Se=T.github?.token;if(B.host==="github"&&Se)try{let q=as(`devpipe-${d}`);await cs(B,Se,q.publicKey,`devpipe-${d}`),ie.contextSsh={privateKey:q.privateKey},b.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(q){b.warn(`could not set up Context Repo SSH deploy key (${q instanceof Error?q.message:String(q)}); the farm will fall back to the token path.`)}let ye={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:ie,contextRepo:B,projectConfig:Pe($,v,k.url,y||void 0)},Qr=kr(R.farm.publicKey,JSON.stringify(ye));b.step(`handing project ${d} to farm ${R.farm.name}\u2026`);let Ge;try{Ge=await qi(c,p,R.farm.farmId,{projectId:d,sealedBundle:Qr})}catch(q){throw q instanceof j&&G(q.status===409?`farm ${R.farm.name} is offline \u2014 start it and re-run.`:q.status===504?`farm ${R.farm.name} did not respond in time.`:`HUB \u2192 ${q.status} ${q.message}`),q}Ge.ok||G(`farm rejected provisioning: ${Ge.error??"unknown error"}`),await Mo(c,p,d,B,Se),o.clear(),Go(`done. project ${d} is now hosted on farm ${R.farm.name} (daemon ${Ge.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Ga(T),await Na(e,B.cloneUrl,B.branch),La(e),a&&await Pd(e);{let R=Ze(e,Ae);wr(R);let ie=Pe($,v,k.url,y||void 0),Se=lo(R,ie);Se.length>0&&b.success(`local project config \u2192 .codepipe/{${Se.join(", ")}}`),qe(d,ie,{info:ye=>b.message(ye),warn:ye=>b.warn(ye)})}await Ua(e,A.repos);let Be={hubUrl:c,cliToken:p,projectId:d,...T,...oe?{contextWrite:oe}:{},...x?{claude:{oauthToken:x}}:{},youtrack:pe};Z(Be),Fe({hubUrl:c,cliToken:p,projectId:d,accountEmail:u},d),b.success(`secrets \u2192 ${We(d)}`),await Mo(c,p,d,B,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Go(`done. next: \`codepipe\` (interactive) or \`codepipe --profile ${d} daemon\`.`)}async function Mo(t,e,r,o,n){let i=await ga(o,n),s=ma(i),a=await et({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Ho(a)||a!==s.proceedValue))try{let{jobId:c}=await Rr(t,e,r,{reindex:s.reindex});b.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){b.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Sd(t,e){let r;try{r=await Wi(t,e)}catch(c){throw c instanceof j&&G(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&G("no farms registered on this HUB. Register one first: on the farm host run `codepipe-farm register --hub <url> --token <HUB_FARM_REG_TOKEN>` and `codepipe-farm start`.");let n=ce(await et({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=ya(i.farmId,i.publicKey)}catch(c){G(c instanceof Error?c.message:String(c))}return ce(await Tt({message:`confirm farm ${i.name} cred-channel fingerprint:
537
537
  ${s}
538
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||B("farm fingerprint not confirmed \u2014 aborting."),fa(i.farmId,s),{farm:i,fingerprint:s}}async function Ea(t){Ta(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();ja(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:_("HUB_URL")??pe,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await Aa(),n=await qr(r,o);x.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await se(r,n,t.projectId)}catch(p){throw p instanceof A&&B(`HUB \u2192 ${p.status} ${p.message}`),p}i.contextRepo||B(`project ${t.projectId} has no Context Repo on HUB`);let s=await Ba(),a={},c=new Set(i.repos.map(p=>p.host));c.add(i.contextRepo.host);for(let p of c)await Wr(p,a,p===i.contextRepo.host?i.contextRepo.owner:i.repos.find(f=>f.host===p)?.owner,o);Da(a),await _a(e,i.contextRepo.cloneUrl,i.contextRepo.branch),Na(e);{let p=Ve(e,Oe);mr(p);let f={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{}},l=ao(p,Re(f,!0,s.url));l.length>0&&x.success(`local project config \u2192 .codepipe/{${l.join(", ")}} (defaults \u2014 review and adjust)`)}await Oa(e,i.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...a,youtrack:{url:s.url,token:s.token}};Q(u),De({hubUrl:r,cliToken:n,projectId:t.projectId},t.projectId),x.success(`secrets \u2192 ${Ge(t.projectId)}`),await Bo(r,n,t.projectId,i.contextRepo,a.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Do("done.")}function ja(t,e){if(!$t(t)){va(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=xd(t).filter(n=>!r.has(n));o.length!==0&&(e||B(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Rd(t){if(!$t(Ve(t,".git")))return null;try{let r=(await Yr(t).remote(["get-url","origin"])||"").toString().trim(),o=r?$e(r):null;return o?{parsed:o,defaultBranch:await Td(t)}:null}catch{return null}}async function Td(t){let e=Yr(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 Id(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Le.test(e)?e:""}function Pd(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Ed(t){let e=Ve(t,".gitignore"),r=$t(e)?Sa(e,"utf-8"):"";if(Pd(r))return;if(!ae(await xt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){x.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
538
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||G("farm fingerprint not confirmed \u2014 aborting."),wa(i.farmId,s),{farm:i,fingerprint:s}}async function Aa(t){Pa(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();_a(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:_("HUB_URL")??de,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await Oa(),n=await zr(r,o);b.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await ae(r,n,t.projectId)}catch(p){throw p instanceof j&&G(`HUB \u2192 ${p.status} ${p.message}`),p}i.contextRepo||G(`project ${t.projectId} has no Context Repo on HUB`);let s=await Ma(),a={},c=new Set(i.repos.map(p=>p.host));c.add(i.contextRepo.host);for(let p of c)await Yr(p,a,p===i.contextRepo.host?i.contextRepo.owner:i.repos.find(f=>f.host===p)?.owner,o);Ga(a),await Na(e,i.contextRepo.cloneUrl,i.contextRepo.branch),La(e);{let p=Ze(e,Ae);wr(p);let f={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{}},l=Pe(f,!0,s.url),d=lo(p,l);d.length>0&&b.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),qe(t.projectId,l,{info:g=>b.message(g),warn:g=>b.warn(g)})}await Ua(e,i.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...a,youtrack:{url:s.url,token:s.token}};Z(u),Fe({hubUrl:r,cliToken:n,projectId:t.projectId},t.projectId),b.success(`secrets \u2192 ${We(t.projectId)}`),await Mo(r,n,t.projectId,i.contextRepo,a.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Go("done.")}function _a(t,e){if(!Rt(t)){Ca(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=$d(t).filter(n=>!r.has(n));o.length!==0&&(e||G(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Cd(t){if(!Rt(Ze(t,".git")))return null;try{let r=(await Vr(t).remote(["get-url","origin"])||"").toString().trim(),o=r?ve(r):null;return o?{parsed:o,defaultBranch:await Rd(t)}:null}catch{return null}}async function Rd(t){let e=Vr(t);try{let o=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(o)return o}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function Td(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return He.test(e)?e:""}function Id(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Pd(t){let e=Ze(t,".gitignore"),r=Rt(e)?Ra(e,"utf-8"):"";if(Id(r))return;if(!ce(await Tt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){b.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
539
539
  `)?"":`
540
- `;Ca(e,r+n+`
540
+ `;Ta(e,r+n+`
541
541
  # codepipe workspace (added by \`codepipe init\`)
542
542
  .codepipe/
543
- `),x.success(`.codepipe/ added to ${Ra(e)}`)}async function Aa(){let t="";try{t=(await Yr().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Email (admin email of this HUB)",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function qr(t,e){x.step(`sending magic link to ${e}`);let r;try{r=await qi(t,e)}catch(n){throw n instanceof Lt&&B(`${e} is not authorized on this HUB yet.
543
+ `),b.success(`.codepipe/ added to ${Ia(e)}`)}async function Oa(){let t="";try{t=(await Vr().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Email (admin email of this HUB)",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function zr(t,e){b.step(`sending magic link to ${e}`);let r;try{r=await Vi(t,e)}catch(n){throw n instanceof Mt&&G(`${e} is not authorized on this HUB yet.
544
544
  Sign up at ${t} (registration form on the login screen),
545
545
  wait for the operator to approve it by email, then re-run
546
- \`codepipe init\` with the same email.`),n}x.message(`click the link in your inbox to confirm. polling\u2026 (request ${r.requestId})`);let o=Date.now();for(;Date.now()-o<15*6e4;){let n=await Vi(t,r.requestId);if(n.status==="confirmed"&&n.cliToken)return x.success("confirmed"),n.cliToken;n.status==="rejected"&&B("HUB rejected this email \u2014 not the admin"),n.status==="expired"&&B("link expired \u2014 re-run init"),await vd(2e3)}B("bootstrap timed out after 15 minutes")}async function _a(t,e,r){let o=Ve(t,Oe);if($t(Ve(o,".git"))){x.message(`${o} already cloned \u2014 skipping`);return}$t(o)&&B(`${o} exists but is not a git repo \u2014 remove it and re-run`),va(o,{recursive:!0}),x.step(`cloning Context Repo \u2192 ${o}`);try{await Yr().clone(e,o,["--branch",r]),x.success(`cloned ${e}`)}catch(n){B(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Oa(t,e){if(e.length===0)return;x.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await Wt(t,r,{log:{info:n=>x.message(n),warn:n=>x.warn(n)}});for(let n of o)x.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function Na(t){let e=Ve(t,Oe,".gitignore"),r="";if($t(e)&&(r=Sa(e,"utf-8")),xa.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
546
+ \`codepipe init\` with the same email.`),n}b.message(`click the link in your inbox to confirm. polling\u2026 (request ${r.requestId})`);let o=Date.now();for(;Date.now()-o<15*6e4;){let n=await zi(t,r.requestId);if(n.status==="confirmed"&&n.cliToken)return b.success("confirmed"),n.cliToken;n.status==="rejected"&&G("HUB rejected this email \u2014 not the admin"),n.status==="expired"&&G("link expired \u2014 re-run init"),await xd(2e3)}G("bootstrap timed out after 15 minutes")}async function Na(t,e,r){let o=Ze(t,Ae);if(Rt(Ze(o,".git"))){b.message(`${o} already cloned \u2014 skipping`);return}Rt(o)&&G(`${o} exists but is not a git repo \u2014 remove it and re-run`),Ca(o,{recursive:!0}),b.step(`cloning Context Repo \u2192 ${o}`);try{await Vr().clone(e,o,["--branch",r]),b.success(`cloned ${e}`)}catch(n){G(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Ua(t,e){if(e.length===0)return;b.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 Jt(t,r,{log:{info:n=>b.message(n),warn:n=>b.warn(n)}});for(let n of o)b.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function La(t){let e=Ze(t,Ae,".gitignore"),r="";if(Rt(e)&&(r=Ra(e,"utf-8")),Sa.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
547
547
  `)||r.length===0?"":`
548
- `,i=xa.join(`
548
+ `,i=Sa.join(`
549
549
  `)+`
550
- `;Ca(e,r+n+(r?`
551
- `:"")+i),x.message(`appended runtime entries to ${Ra(e)}`)}async function jd(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;x.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Wr(s.host,t,s.owner,e),i?.();let c=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=D(await K({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:u,mountAs:"."}),o.onProgress?.(n)}for(;ae(await xt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=D(await K({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:d=>!d||!d.trim()||$e(d)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=$e(a);x.message(`${c.host}: ${c.owner}/${c.repoName}`),await Wr(c.host,t,c.owner,e),i?.();let u=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"default branch (optional)",placeholder:"main"})).trim(),f=D(await K({message:"local folder name (sibling of .codepipe/, optional)",placeholder:u})).trim(),l={name:u,host:c.host,owner:c.owner,repoName:c.repoName};p&&(l.defaultBranch=p),f&&f!==u&&(l.mountAs=f),n.push(l),o.onProgress?.(n)}return n}async function Ua(t,e,r,o){x.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let n=ae(await ze({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&x.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=D(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:be(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!$e(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=$e(c);a=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:i,owner:s,name:c}}else{let c=await _d(),u=D(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"Context Repo name",placeholder:be(t),initialValue:be(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:u,name:p}}return{spec:a,mode:n}}function La(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??ot()}}async function Ad(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:u}=a;await Wr(c.host,o,c.owner,n),i?.();let p=Ia();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await ea(c,La(o),{explain:u==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(u==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let l=ae(await ze({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(l==="abort"&&B("aborted"),l==="create")return a={spec:c,mode:"create"},s(a),a;a=await Ua(e,r,o,n),s(a)}}async function _d(){return ae(await ze({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function qt(t,e){let r=Ia();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 Da(t){Tr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ir(t.gitlab?.token??process.env.GITLAB_TOKEN),Pr(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Wr(t,e,r,o){if(!e[t])if(t==="github"){let n=await Od(r);n?e.github=n:x.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Nd(r,o);n?e.bitbucket=n:x.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let n=await Ud();n?e.gitlab=n:x.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function Od(t){for(;;){let e=D(await Yt({message:`GitHub PAT \u2014 blank to skip
550
+ `;Ta(e,r+n+(r?`
551
+ `:"")+i),b.message(`appended runtime entries to ${Ia(e)}`)}async function Ed(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;b.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Yr(s.host,t,s.owner,e),i?.();let c=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=D(await K({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:u,mountAs:"."}),o.onProgress?.(n)}for(;ce(await Tt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=D(await K({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:d=>!d||!d.trim()||ve(d)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=ve(a);b.message(`${c.host}: ${c.owner}/${c.repoName}`),await Yr(c.host,t,c.owner,e),i?.();let u=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"default branch (optional)",placeholder:"main"})).trim(),f=D(await K({message:"local folder name (sibling of .codepipe/, optional)",placeholder:u})).trim(),l={name:u,host:c.host,owner:c.owner,repoName:c.repoName};p&&(l.defaultBranch=p),f&&f!==u&&(l.mountAs=f),n.push(l),o.onProgress?.(n)}return n}async function Da(t,e,r,o){b.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=ce(await et({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"&&b.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=D(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:$e(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!ve(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=ve(c);a=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:i,owner:s,name:c}}else{let c=await Ad(),u=D(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"Context Repo name",placeholder:$e(t),initialValue:$e(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:u,name:p}}return{spec:a,mode:n}}function Ba(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??at()}}async function jd(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:u}=a;await Yr(c.host,o,c.owner,n),i?.();let p=Ea();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await na(c,Ba(o),{explain:u==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(u==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let l=ce(await et({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(l==="abort"&&G("aborted"),l==="create")return a={spec:c,mode:"create"},s(a),a;a=await Da(e,r,o,n),s(a)}}async function Ad(){return ce(await et({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Xt(t,e){let r=Ea();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 Ga(t){jr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ar(t.gitlab?.token??process.env.GITLAB_TOKEN),_r(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Yr(t,e,r,o){if(!e[t])if(t==="github"){let n=await _d(r);n?e.github=n:b.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Od(r,o);n?e.bitbucket=n:b.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let n=await Nd();n?e.gitlab=n:b.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function _d(t){for(;;){let e=D(await It({message:`GitHub PAT \u2014 blank to skip
552
552
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
553
553
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
554
554
  if org: approve token in org Settings \u2192 Personal access tokens.
555
555
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
556
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await qt("GitHub",()=>st(e,t?{owner:t}:void 0)))return{token:e};x.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Nd(t,e){for(x.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
556
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await Xt("GitHub",()=>pt(e,t?{owner:t}:void 0)))return{token:e};b.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Od(t,e){for(b.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
557
557
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
558
558
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
559
559
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
560
560
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
561
- The token is shown ONCE \u2014 copy it right away.`);;){let r=D(await K({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:n=>!n||!n.trim()||n.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let o=D(await Yt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){x.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await qt("Bitbucket",()=>at(r,o,t)))return{email:r,apiToken:o};x.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Ud(){for(;;){let t=D(await Yt({message:`GitLab PAT \u2014 blank to skip
562
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await qt("GitLab",()=>ct(t))){let e=await Vn(t);return e&&x.warn(e),{token:t}}x.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ld(t){if(ae(await xt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
561
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=D(await K({message:"Atlassian account email (BITBUCKET_EMAIL) \u2014 clear to skip",initialValue:e??"",validate:n=>!n||!n.trim()||n.includes("@")?void 0:"must be an email"})).trim();if(!r)return;let o=D(await It({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){b.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Xt("Bitbucket",()=>dt(r,o,t)))return{email:r,apiToken:o};b.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Nd(){for(;;){let t=D(await It({message:`GitLab PAT \u2014 blank to skip
562
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Xt("GitLab",()=>ft(t))){let e=await zn(t);return e&&b.warn(e),{token:t}}b.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ud(t){if(ce(await Tt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
563
563
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
564
564
  credential. A scoped token hardens setups where the SANDBOX runs outside
565
- your trusted network.`,initialValue:!1})))for(t.host==="github"?x.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
565
+ your trusted network.`,initialValue:!1})))for(t.host==="github"?b.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
566
566
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
567
- required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):x.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
568
- (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=D(await Yt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await qt("contextWrite",()=>Dd(r,t)))return{token:r};x.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Dd(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 Ba(){for(;;){let t=D(await K({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=D(await Yt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await qt("YouTrack",()=>pt({baseUrl:t,token:e}))){let r=await Ei({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}x.warn("re-enter the YouTrack URL / token.")}}import{mkdirSync as Bd,readFileSync as Gd,writeFileSync as Ga}from"node:fs";import{homedir as Md}from"node:os";import{join as Mo}from"node:path";function W(t){throw new Error(t)}function V(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function Vt(t,e){if(t==null)return;typeof t!="string"&&W(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Hd(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=V(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=V(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=V(i.id,"project.id");Le.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=V(i.name,"project.name"),c=V(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let u=i.repos;Array.isArray(u)||W("config: 'project.repos' must be an array");let p=u.map((v,T)=>{(!v||typeof v!="object")&&W(`config: project.repos[${T}] must be an object`);let j=v,U=V(j.host,`project.repos[${T}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${T}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:V(j.name,`project.repos[${T}].name`),host:U,owner:V(j.owner,`project.repos[${T}].owner`),repoName:V(j.repoName,`project.repos[${T}].repoName`)},h=Vt(j.defaultBranch,`project.repos[${T}].defaultBranch`);h&&(S.defaultBranch=h);let m=Vt(j.mountAs,`project.repos[${T}].mountAs`);return m&&(S.mountAs=m),S}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let l=f,d=Vt(l.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&W("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:V(l.owner,"project.contextRepo.owner"),name:Vt(l.name,"project.contextRepo.name")??be(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},k=Vt(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(w.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let R=e.secrets;if(R!==void 0){(typeof R!="object"||R===null)&&W("config: 'secrets' must be an object");let v=R,T={};if(v.github){let j=v.github;T.github={token:V(j.token,"secrets.github.token")}}if(v.bitbucket){let j=v.bitbucket;T.bitbucket={email:V(j.email,"secrets.bitbucket.email"),apiToken:V(j.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let j=v.gitlab;T.gitlab={token:V(j.token,"secrets.gitlab.token")}}if(v.youtrack){let j=v.youtrack;T.youtrack={url:V(j.url,"secrets.youtrack.url").replace(/\/$/,""),token:V(j.token,"secrets.youtrack.token")}}if(v.contextWrite){let j=v.contextWrite;T.contextWrite={token:V(j.token,"secrets.contextWrite.token")}}w.secrets=T}return w}async function Fd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Kd(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await st(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 at(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await ct(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await pt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ma(t){let e=!t.configPath||t.configPath==="-"?await Fd():Gd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(l){W(`config: invalid JSON \u2014 ${l instanceof Error?l.message:String(l)}`)}let o=Hd(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 Kd(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,u;try{u=await bt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??ot(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:l=>console.log(` ${l}`),warn:l=>console.warn(` ${l}`)}})}catch(l){W(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`)}a.contextRepo=u,console.log(`Context Repo ready: ${u.owner}/${u.name}@${u.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await dt(n,i,a)}catch(l){if(l instanceof A&&l.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await se(n,i,s.id);else if(l instanceof A)W(`HUB \u2192 ${l.status} ${l.message}`);else throw l}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};Q(f),De({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ge(s.id)}`);{let l=Mo(Md(),".codepipe","profiles",s.id,"context-config");Bd(l,{recursive:!0});let d=Re(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url);Ga(Mo(l,"project.yaml"),d.projectYaml),Ga(Mo(l,"regimen.yaml"),d.regimenYaml),console.log(`local project config staged \u2192 ${l}`)}if(s.index)try{let{jobId:l}=await vr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${l}); runs once a SANDBOX claims it.`)}catch(l){console.warn(`could not enqueue index job: ${l instanceof Error?l.message:String(l)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Ha,intro as Fa,isCancel as Ka,log as Ho,outro as Wd,password as Wa}from"@clack/prompts";async function Yd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ya(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Yd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fa("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Wa({message:"Claude OAuth token"});Ka(i)&&(Ha("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Tn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${lr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=fe(t.profile);if(!e){Fa(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Wa({message:"Claude OAuth token"});Ka(i)&&(Ha("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},Q(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ho.success("Claude OAuth token saved."),Wd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as qd,confirm as Vd,intro as zd,isCancel as Va,log as re,outro as Jd,select as za,text as Ne}from"@clack/prompts";import{mkdirSync as Xd,writeFileSync as qa}from"node:fs";import{homedir as Qd}from"node:os";import{join as Fo}from"node:path";function Ja(t){qd(t),process.exit(1)}function vt(t){return Va(t)&&Ja("aborted"),t}function zt(t){return Va(t)&&Ja("aborted"),typeof t=="string"?t:""}async function Zd(t,e){let r=vt(await za({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=zt(await Ne({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=zt(await Ne({message:"Context Repo name",placeholder:be(t),initialValue:be(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function Xa(t={profile:void 0}){let e=fe(t.profile);zd(`codepipe project add \u2192 ${e.hubUrl}`);let r=vt(await Ne({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:l=>Le.test(l.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=vt(await Ne({message:"project name (human-readable)",placeholder:"CodePartner",validate:l=>l.trim().length>0?void 0:"required"})).trim(),n=vt(await za({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=vt(await Ne({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=vt(await Vd({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let l=zt(await Ne({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:R=>!R||!R.trim()||$e(R)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!l)break;let d=$e(l);re.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=zt(await Ne({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:R=>R.trim().length>0?void 0:"required"})).trim(),w=zt(await Ne({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(k.defaultBranch=w),a.push(k)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let u=await Zd(r,a),p=H(e.projectId);re.info(`provisioning Context Repo ${u.owner}/${u.name} (${u.host})\u2026`);let f;try{f=await bt(c,u,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??ot(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:l=>re.message(l),warn:l=>re.warn(l)}})}catch(l){re.error(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}c.contextRepo=f,re.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let l=await dt(e.hubUrl,e.cliToken,c);re.success(`project "${l.projectId}" \u2014 ${l.provisioningStatus}`);{let d=Fo(Qd(),".codepipe","profiles",r,"context-config");Xd(d,{recursive:!0});let g=Re(c,s,p?.youtrack?.url);qa(Fo(d,"project.yaml"),g.projectYaml),qa(Fo(d,"regimen.yaml"),g.regimenYaml),re.message(`local project config staged \u2192 ${d}`)}l.contextRepo&&(re.message(` context repo: ${l.contextRepo.owner}/${l.contextRepo.name} (${l.contextRepo.cloneUrl})`),re.message(` branch: ${l.contextRepo.branch}`)),l.provisioningError&&re.error(` error: ${l.provisioningError}`),Jd("done")}catch(l){l instanceof A?(re.error(`HUB \u2192 ${l.status} ${l.message}`),l.payload&&typeof l.payload=="object"&&re.message(JSON.stringify(l.payload,null,2))):re.error(l instanceof Error?l.message:String(l)),process.exit(1)}}import{spawn as ef}from"node:child_process";import{hostname as tf}from"node:os";async function rf(t,e){let r=ee(e.profile);if(r){if(r.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${r.sandboxId} (${r.name})`);return}throw new Error(`worker config ${Pe(e.profile)} points at a different HUB (${r.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await xr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(n){throw n instanceof A&&n.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):n instanceof A&&n.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):n}await Ye({hub:t.hubUrl,token:o,name:e.name??`${tf()}-up`,llm:e.llm??"claude-headless",projects:e.projects??[],...e.profile?{profile:e.profile}:{}})}function of(t,e){let r=ee(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=ut(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=cr(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 Qa(t){let e=fe(t.profile);await rf(e,t),of(e.projectId,t.profile);let r=process.argv[1];if(!r)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(l,d)=>{let g=w=>k=>{for(let R of k.toString("utf-8").split(`
569
- `))R.length>0&&w.write(`${d} ${R}
570
- `)};l.stdout?.on("data",g(process.stdout)),l.stderr?.on("data",g(process.stderr))},n=(l,d)=>{let g=ef(process.execPath,[r,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,l),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let i=n("[cli]",[...t.profile?["--profile",t.profile]:[],"daemon"]),s=n("[worker]",[...t.profile?["--profile",t.profile]:[],"worker","start"]),a=[{name:"daemon",child:i},{name:"worker",child:s}],c=!1,u=l=>{if(!c){c=!0,console.log(`
571
- [up] ${l} \u2014 stopping both roles`);for(let{child:d}of a)d.exitCode===null&&d.kill(l);setTimeout(()=>{for(let{name:d,child:g}of a)g.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=a.map(({name:l,child:d})=>new Promise(g=>{d.on("exit",(w,k)=>g({name:l,code:w??(k?1:0)}))})),f=await Promise.race(p);c||(console.log(`[up] ${f.name} exited (code ${f.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(f.code)}import{existsSync as uc,mkdirSync as lf,readFileSync as uf,writeFileSync as pf}from"node:fs";import{homedir as df}from"node:os";import{dirname as ff,join as pc}from"node:path";import*as Ct from"node:readline";import{existsSync as Yo,readFileSync as nf,writeFileSync as sf}from"node:fs";import{join as Xt}from"node:path";import{simpleGit as Wo}from"simple-git";var Za=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],af="apply-queue.json";function ec(t){return Xt(t,af)}function St(t){let e=ec(t);if(!Yo(e))return{};try{return JSON.parse(nf(e,"utf-8"))}catch{return{}}}function tc(t,e){sf(ec(t),JSON.stringify(e,null,2)+`
572
- `)}async function rc(t,e,r,o,n){let i;try{i=await Xi(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(l){return{ok:!1,message:`claim failed: ${l instanceof Error?l.message:String(l)}`}}let s=[];for(let l of i.repos){let d=t.spec.repos.find(R=>R.name===l.repoName);if(!d)return{ok:!1,message:`repo "${l.repoName}" not in project.yaml \u2014 run /sync`};let g=Xt(t.root,d.mountAs);if(!Yo(Xt(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Wo(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:l,spec:d,dir:g})}let a=[];for(let l of s){let d=Wo(l.dir),g=await cf(d),w=l.claimRepo;try{await d.fetch()}catch(v){return await Ko(a,n),{ok:!1,message:`fetch failed in ${l.spec.mountAs}: ${Jt(v)}`}}let k=`origin/${w.baseRef}`,R;try{R=await br(d,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(v){return await Ko(a,n),{ok:!1,message:`fetch delivery failed in ${l.spec.mountAs}: ${Jt(v)}`}}a.push({git:d,dir:l.dir,mountAs:l.spec.mountAs,originalRef:g,branch:w.branchName,baseSha:k,deliveryCommit:R,startPoint:k})}let c=[];for(let l of a)try{if(o==="apply"){await l.git.checkout(["-B",l.branch,l.startPoint]),await l.git.raw([...Za,"cherry-pick",l.deliveryCommit]);let d=(await l.git.revparse(["HEAD"])).trim();c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha,appliedSha:d})}else await l.git.checkout(["--detach",l.startPoint]),await l.git.raw([...Za,"cherry-pick","--no-commit",l.deliveryCommit]),await l.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha})}catch(d){return await l.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Ko(a,n),{ok:!1,message:`apply failed in ${l.mountAs}: ${Jt(d)} (rolled back all repos)`}}let u=St(t.contextDir);u[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},tc(t.contextDir,u);let p=c.map(l=>l.mountAs).join(", "),f=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${p}
567
+ required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):b.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
568
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=D(await It({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Xt("contextWrite",()=>Ld(r,t)))return{token:r};b.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ld(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(o.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let n=await o.json();if(n.permissions&&n.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return n.full_name??`${e.owner}/${e.name}`}async function Dd(t){if(no()?.claude?.oauthToken&&!t)return b.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`)."),"";b.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?`
569
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=D(await It({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||b.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(b.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function Ma(){for(;;){let t=D(await K({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=D(await It({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Xt("YouTrack",()=>ht({baseUrl:t,token:e}))){let r=await ji({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Bd}from"node:fs";function W(t){throw new Error(t)}function z(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function Qt(t,e){if(t==null)return;typeof t!="string"&&W(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Gd(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=z(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=z(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=z(i.id,"project.id");He.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=z(i.name,"project.name"),c=z(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let u=i.repos;Array.isArray(u)||W("config: 'project.repos' must be an array");let p=u.map((v,T)=>{(!v||typeof v!="object")&&W(`config: project.repos[${T}] must be an object`);let E=v,U=z(E.host,`project.repos[${T}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${T}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:z(E.name,`project.repos[${T}].name`),host:U,owner:z(E.owner,`project.repos[${T}].owner`),repoName:z(E.repoName,`project.repos[${T}].repoName`)},h=Qt(E.defaultBranch,`project.repos[${T}].defaultBranch`);h&&(S.defaultBranch=h);let m=Qt(E.mountAs,`project.repos[${T}].mountAs`);return m&&(S.mountAs=m),S}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let l=f,d=Qt(l.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&W("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:z(l.owner,"project.contextRepo.owner"),name:Qt(l.name,"project.contextRepo.name")??$e(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},k=Qt(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(w.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let C=e.secrets;if(C!==void 0){(typeof C!="object"||C===null)&&W("config: 'secrets' must be an object");let v=C,T={};if(v.github){let E=v.github;T.github={token:z(E.token,"secrets.github.token")}}if(v.bitbucket){let E=v.bitbucket;T.bitbucket={email:z(E.email,"secrets.bitbucket.email"),apiToken:z(E.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let E=v.gitlab;T.gitlab={token:z(E.token,"secrets.gitlab.token")}}if(v.youtrack){let E=v.youtrack;T.youtrack={url:z(E.url,"secrets.youtrack.url").replace(/\/$/,""),token:z(E.token,"secrets.youtrack.token")}}if(v.contextWrite){let E=v.contextWrite;T.contextWrite={token:z(E.token,"secrets.contextWrite.token")}}w.secrets=T}return w}async function Md(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Hd(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await pt(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 dt(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await ft(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await ht({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ha(t){let e=!t.configPath||t.configPath==="-"?await Md():Bd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(l){W(`config: invalid JSON \u2014 ${l instanceof Error?l.message:String(l)}`)}let o=Gd(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 Hd(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,u;try{u=await St(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??at(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:l=>console.log(` ${l}`),warn:l=>console.warn(` ${l}`)}})}catch(l){W(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`)}a.contextRepo=u,console.log(`Context Repo ready: ${u.owner}/${u.name}@${u.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await wt(n,i,a)}catch(l){if(l instanceof j&&l.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await ae(n,i,s.id);else if(l instanceof j)W(`HUB \u2192 ${l.status} ${l.message}`);else throw l}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(Z(f),Fe({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${We(s.id)}`),qe(s.id,Pe(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:l=>console.log(l),warn:l=>console.warn(l)}),s.index)try{let{jobId:l}=await Rr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${l}); runs once a SANDBOX claims it.`)}catch(l){console.warn(`could not enqueue index job: ${l instanceof Error?l.message:String(l)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Fa,intro as Ka,isCancel as Wa,log as Fo,outro as Fd,password as qa}from"@clack/prompts";async function Kd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function Ya(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Kd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Ka("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Fo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await qa({message:"Claude OAuth token"});Wa(i)&&(Fa("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Tn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${fr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=me(t.profile);if(!e){Ka(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Fo.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await qa({message:"Claude OAuth token"});Wa(i)&&(Fa("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},Z(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Fo.success("Claude OAuth token saved."),Fd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Wd,confirm as qd,intro as Yd,isCancel as Va,log as J,outro as Vd,select as za,text as De}from"@clack/prompts";function Ja(t){Wd(t),process.exit(1)}function Pt(t){return Va(t)&&Ja("aborted"),t}function Zt(t){return Va(t)&&Ja("aborted"),typeof t=="string"?t:""}async function zd(t,e){let r=Pt(await za({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=Zt(await De({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Zt(await De({message:"Context Repo name",placeholder:$e(t),initialValue:$e(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function Xa(t={profile:void 0}){let e=me(t.profile);Yd(`codepipe project add \u2192 ${e.hubUrl}`);let r=Pt(await De({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:l=>He.test(l.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Pt(await De({message:"project name (human-readable)",placeholder:"CodePartner",validate:l=>l.trim().length>0?void 0:"required"})).trim(),n=Pt(await za({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=Pt(await De({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Pt(await qd({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let l=Zt(await De({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:C=>!C||!C.trim()||ve(C)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!l)break;let d=ve(l);J.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=Zt(await De({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:C=>C.trim().length>0?void 0:"required"})).trim(),w=Zt(await De({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(k.defaultBranch=w),a.push(k)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let u=await zd(r,a),p=H(e.projectId);J.info(`provisioning Context Repo ${u.owner}/${u.name} (${u.host})\u2026`);let f;try{f=await St(c,u,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??at(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:l=>J.message(l),warn:l=>J.warn(l)}})}catch(l){J.error(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}c.contextRepo=f,J.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let l=await wt(e.hubUrl,e.cliToken,c);J.success(`project "${l.projectId}" \u2014 ${l.provisioningStatus}`),qe(r,Pe(c,s,p?.youtrack?.url),{info:d=>J.message(d),warn:d=>J.warn(d)}),l.contextRepo&&(J.message(` context repo: ${l.contextRepo.owner}/${l.contextRepo.name} (${l.contextRepo.cloneUrl})`),J.message(` branch: ${l.contextRepo.branch}`)),l.provisioningError&&J.error(` error: ${l.provisioningError}`),Vd("done")}catch(l){l instanceof j?(J.error(`HUB \u2192 ${l.status} ${l.message}`),l.payload&&typeof l.payload=="object"&&J.message(JSON.stringify(l.payload,null,2))):J.error(l instanceof Error?l.message:String(l)),process.exit(1)}}import{spawn as Jd}from"node:child_process";import{hostname as Xd}from"node:os";async function Qd(t,e){let r=te(e.profile);if(r){if(r.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${r.sandboxId} (${r.name})`);return}throw new Error(`worker config ${Oe(e.profile)} points at a different HUB (${r.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await Cr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(n){throw n instanceof j&&n.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):n instanceof j&&n.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):n}await Xe({hub:t.hubUrl,token:o,name:e.name??`${Xd()}-up`,llm:e.llm??"claude-headless",projects:e.projects??[],...e.profile?{profile:e.profile}:{}})}function Zd(t,e){let r=te(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=gt(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=dr(t,r.sandboxId,o);if(n==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${n==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function Qa(t){let e=me(t.profile);await Qd(e,t),Zd(e.projectId,t.profile);let r=process.argv[1];if(!r)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(l,d)=>{let g=w=>k=>{for(let C of k.toString("utf-8").split(`
570
+ `))C.length>0&&w.write(`${d} ${C}
571
+ `)};l.stdout?.on("data",g(process.stdout)),l.stderr?.on("data",g(process.stderr))},n=(l,d)=>{let g=Jd(process.execPath,[r,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,l),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let i=n("[cli]",[...t.profile?["--profile",t.profile]:[],"daemon"]),s=n("[worker]",[...t.profile?["--profile",t.profile]:[],"worker","start"]),a=[{name:"daemon",child:i},{name:"worker",child:s}],c=!1,u=l=>{if(!c){c=!0,console.log(`
572
+ [up] ${l} \u2014 stopping both roles`);for(let{child:d}of a)d.exitCode===null&&d.kill(l);setTimeout(()=>{for(let{name:d,child:g}of a)g.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=a.map(({name:l,child:d})=>new Promise(g=>{d.on("exit",(w,k)=>g({name:l,code:w??(k?1:0)}))})),f=await Promise.race(p);c||(console.log(`[up] ${f.name} exited (code ${f.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(f.code)}import{existsSync as uc,mkdirSync as nf,readFileSync as sf,writeFileSync as af}from"node:fs";import{homedir as cf}from"node:os";import{dirname as lf,join as pc}from"node:path";import*as jt from"node:readline";import{existsSync as qo,readFileSync as ef,writeFileSync as tf}from"node:fs";import{join as tr}from"node:path";import{simpleGit as Wo}from"simple-git";var Za=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],rf="apply-queue.json";function ec(t){return tr(t,rf)}function Et(t){let e=ec(t);if(!qo(e))return{};try{return JSON.parse(ef(e,"utf-8"))}catch{return{}}}function tc(t,e){tf(ec(t),JSON.stringify(e,null,2)+`
573
+ `)}async function rc(t,e,r,o,n){let i;try{i=await Qi(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(l){return{ok:!1,message:`claim failed: ${l instanceof Error?l.message:String(l)}`}}let s=[];for(let l of i.repos){let d=t.spec.repos.find(C=>C.name===l.repoName);if(!d)return{ok:!1,message:`repo "${l.repoName}" not in project.yaml \u2014 run /sync`};let g=tr(t.root,d.mountAs);if(!qo(tr(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Wo(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:l,spec:d,dir:g})}let a=[];for(let l of s){let d=Wo(l.dir),g=await of(d),w=l.claimRepo;try{await d.fetch()}catch(v){return await Ko(a,n),{ok:!1,message:`fetch failed in ${l.spec.mountAs}: ${er(v)}`}}let k=`origin/${w.baseRef}`,C;try{C=await xr(d,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(v){return await Ko(a,n),{ok:!1,message:`fetch delivery failed in ${l.spec.mountAs}: ${er(v)}`}}a.push({git:d,dir:l.dir,mountAs:l.spec.mountAs,originalRef:g,branch:w.branchName,baseSha:k,deliveryCommit:C,startPoint:k})}let c=[];for(let l of a)try{if(o==="apply"){await l.git.checkout(["-B",l.branch,l.startPoint]),await l.git.raw([...Za,"cherry-pick",l.deliveryCommit]);let d=(await l.git.revparse(["HEAD"])).trim();c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha,appliedSha:d})}else await l.git.checkout(["--detach",l.startPoint]),await l.git.raw([...Za,"cherry-pick","--no-commit",l.deliveryCommit]),await l.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha})}catch(d){return await l.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Ko(a,n),{ok:!1,message:`apply failed in ${l.mountAs}: ${er(d)} (rolled back all repos)`}}let u=Et(t.contextDir);u[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},tc(t.contextDir,u);let p=c.map(l=>l.mountAs).join(", "),f=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${p}
573
574
  ${f}
574
- or: /abort ${r} --reason "..."`}}function qo(t,e){let r=St(t);r[e]&&(delete r[e],tc(t,r))}async function Ko(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}: ${Jt(o)} \u2014 check manually`)}}async function oc(t,e,r){let n=St(t.contextDir)[e];if(n){for(let i of n.repos){let s=Xt(t.root,i.mountAs);if(!Yo(Xt(s,".git")))continue;let a=Wo(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),u=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",u]),await a.reset(["--hard",u]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${Jt(p)} \u2014 check manually`)}}qo(t.contextDir,e)}}async function cf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function Jt(t){return t instanceof Error?t.message.trim():String(t)}var Vr=pc(df(),".codepipe","history"),nc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],dc=500,ic=40;async function fc(){let t=Kr();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=H(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),_t(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=St(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
575
+ or: /abort ${r} --reason "..."`}}function Yo(t,e){let r=Et(t);r[e]&&(delete r[e],tc(t,r))}async function Ko(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(o){e.warn(`rollback failed in ${r.mountAs}: ${er(o)} \u2014 check manually`)}}async function oc(t,e,r){let n=Et(t.contextDir)[e];if(n){for(let i of n.repos){let s=tr(t.root,i.mountAs);if(!qo(tr(s,".git")))continue;let a=Wo(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),u=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",u]),await a.reset(["--hard",u]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${er(p)} \u2014 check manually`)}}Yo(t.contextDir,e)}}async function of(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function er(t){return t instanceof Error?t.message.trim():String(t)}var Jr=pc(cf(),".codepipe","history"),nc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],dc=500,ic=40;async function fc(){let t=Ht();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=H(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Lt(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=Et(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
575
576
  \u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
576
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Ct.createInterface({input:process.stdin,output:process.stdout,completer:mf,history:Of(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};pi(s=>Je(i,s)),i.daemon=Rr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Je(i,s),warn:s=>Je(i,s)},onEvent:s=>If(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),zo(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await gf(i,a)){lc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,zo(i),n.prompt()}),n.on("close",()=>{lc(i)})}function mf(t){let e=nc.filter(r=>r.startsWith(t));return[e.length?e:nc,t]}async function gf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return hf(),!1;case"/status":return await wf(t),!1;case"/tasks":return await yf(t,o),!1;case"/task":return await bf(t,o),!1;case"/sync":return await kf(t),!1;case"/logs":return Pf(t,o),!1;case"/monitor":return Ef(t),!1;case"/apply":return await sc(t,o,"apply"),!1;case"/unstash":return await sc(t,o,"unstash"),!1;case"/applied":return await $f(t,o),!1;case"/abort":return await xf(t,o),!1;case"/approve":return await ac(t,o,"approve"),!1;case"/merge":return await ac(t,o,"merge"),!1;case"/login":return Sf(t,o),!1;case"/secret":return Cf(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function hf(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
577
- `))}async function wf(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=uc(pc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function yf(t,e){let r=jf(e,"--phase");try{let o=await zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),n=r?o.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):o;if(n.length===0){console.log(" (no tasks)");return}for(let i of n)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(o){Zt(o)}}async function bf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await Ji(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${o.task.phase} \u2014 ${o.task.title}`),o.artifacts.length>0){console.log(" artifacts:");for(let n of o.artifacts)console.log(` ${n.path}`)}}catch(o){Zt(o)}}async function kf(t){let e=await Wt(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 sc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await rc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function $f(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=St(t.ws.contextDir)[r],i=Af(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let u=c.indexOf("="),p,f;if(u>0?(p=c.slice(0,u),f=c.slice(u+1)):(f=c,p=n?.repos.length===1?vf(t,n.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let l=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!l){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(l[1])})}try{let c=await Qi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);qo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){Zt(c)}}async function ac(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await es(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){Zt(n)}}async function xf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=_f(e,"--reason")||"local apply aborted";await oc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await Zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){Zt(n)}}function vf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Sf(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},Q(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 Cf(t,e){let[r,o,...n]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
578
- `)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}Rf(t.secrets,o,i),Q(t.secrets),_t(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}Tf(t.secrets,o),Q(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function Rf(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 Tf(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 If(t,e){switch(e.kind){case"connected":t.connection="connecting",Je(t,"[hub] connected");break;case"registered":t.connection="registered",Je(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",Qt(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Je(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",Qt(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":Qt(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?Je(t,`[hub] action ${e.actionType} done`):Qt(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Je(t,e){t.logBuffer.push(e),t.logBuffer.length>dc&&t.logBuffer.shift(),t.follow&&Qt(t,e)}function Pf(t,e){let r=e[0];if(r==="follow"||r==="on"){Vo(t,!0);return}if(r==="off"){Vo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(dc,Number(r)||ic)):ic,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 Ef(t){Vo(t,!t.follow)}function Vo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function Qt(t,e){Ct.cursorTo(process.stdout,0),Ct.clearLine(process.stdout,0),process.stdout.write(e+`
579
- `),t.unread+=1,zo(t),t.rl.prompt(!0)}function zo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var cc=!1;function lc(t){cc||(cc=!0,Nf(t.rl),t.daemon.stop(),console.log(`
580
- bye.`),setTimeout(()=>process.exit(0),150))}function jf(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Af(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 _f(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function Zt(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Of(){if(!uc(Vr))return[];try{return uf(Vr,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Nf(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{lf(ff(Vr),{recursive:!0}),pf(Vr,r.slice().reverse().join(`
577
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=jt.createInterface({input:process.stdin,output:process.stdout,completer:uf,history:Ef(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};di(s=>tt(i,s)),i.daemon=Pr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>tt(i,s),warn:s=>tt(i,s)},onEvent:s=>Sf(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),zo(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await pf(i,a)){lc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,zo(i),n.prompt()}),n.on("close",()=>{lc(i)})}function uf(t){let e=nc.filter(r=>r.startsWith(t));return[e.length?e:nc,t]}async function pf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return df(),!1;case"/status":return await ff(t),!1;case"/tasks":return await mf(t,o),!1;case"/task":return await gf(t,o),!1;case"/sync":return await hf(t),!1;case"/logs":return Cf(t,o),!1;case"/monitor":return Rf(t),!1;case"/apply":return await sc(t,o,"apply"),!1;case"/unstash":return await sc(t,o,"unstash"),!1;case"/applied":return await wf(t,o),!1;case"/abort":return await yf(t,o),!1;case"/approve":return await ac(t,o,"approve"),!1;case"/merge":return await ac(t,o,"merge"),!1;case"/login":return kf(t,o),!1;case"/secret":return $f(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function df(){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(`
578
+ `))}async function ff(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=uc(pc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function mf(t,e){let r=Tf(e,"--phase");try{let o=await Ji(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),n=r?o.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):o;if(n.length===0){console.log(" (no tasks)");return}for(let i of n)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(o){or(o)}}async function gf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await Xi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${o.task.phase} \u2014 ${o.task.title}`),o.artifacts.length>0){console.log(" artifacts:");for(let n of o.artifacts)console.log(` ${n.path}`)}}catch(o){or(o)}}async function hf(t){let e=await Jt(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 sc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await rc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function wf(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=Et(t.ws.contextDir)[r],i=If(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let u=c.indexOf("="),p,f;if(u>0?(p=c.slice(0,u),f=c.slice(u+1)):(f=c,p=n?.repos.length===1?bf(t,n.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let l=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!l){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(l[1])})}try{let c=await Zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);Yo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){or(c)}}async function ac(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await ts(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){or(n)}}async function yf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=Pf(e,"--reason")||"local apply aborted";await oc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await es(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){or(n)}}function bf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function kf(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},Z(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function $f(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(`
579
+ `)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}xf(t.secrets,o,i),Z(t.secrets),Lt(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}vf(t.secrets,o),Z(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function xf(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 vf(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 Sf(t,e){switch(e.kind){case"connected":t.connection="connecting",tt(t,"[hub] connected");break;case"registered":t.connection="registered",tt(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",rr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",tt(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",rr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":rr(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?tt(t,`[hub] action ${e.actionType} done`):rr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function tt(t,e){t.logBuffer.push(e),t.logBuffer.length>dc&&t.logBuffer.shift(),t.follow&&rr(t,e)}function Cf(t,e){let r=e[0];if(r==="follow"||r==="on"){Vo(t,!0);return}if(r==="off"){Vo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(dc,Number(r)||ic)):ic,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 Rf(t){Vo(t,!t.follow)}function Vo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function rr(t,e){jt.cursorTo(process.stdout,0),jt.clearLine(process.stdout,0),process.stdout.write(e+`
580
+ `),t.unread+=1,zo(t),t.rl.prompt(!0)}function zo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var cc=!1;function lc(t){cc||(cc=!0,jf(t.rl),t.daemon.stop(),console.log(`
581
+ bye.`),setTimeout(()=>process.exit(0),150))}function Tf(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function If(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 Pf(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function or(t){t instanceof j?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Ef(){if(!uc(Jr))return[];try{return sf(Jr,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function jf(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{nf(lf(Jr),{recursive:!0}),af(Jr,r.slice().reverse().join(`
581
582
  `)+`
582
- `)}catch{}}import{hostname as Uf}from"node:os";import{cancel as Lf,confirm as mc,intro as Df,isCancel as wc,log as Rt,multiselect as Bf,outro as gc,password as Gf,select as Jo,text as zr}from"@clack/prompts";function tr(t){Lf(t),process.exit(1)}function Tt(t){return wc(t)&&tr("aborted"),t}function er(t){return wc(t)&&tr("aborted"),typeof t=="string"?t:""}function Xo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function hc(t,e){try{let{secret:r}=await xr(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&tr("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Mf(t,e){if(Tt(await Jo({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 Yi(t,e);if(n.length>0)return Tt(await Bf({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}));Rt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){Rt.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return er(await zr({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 Qo(t){Df("codepipe worker \u2014 set up this machine as a runner");let e=ee(t.profile);e&&(Rt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Tt(await mc({message:"re-register this worker?",initialValue:!1}))||tr("keeping the existing registration"));let r=Se(t.profile)??Se(),o=er(await zr({message:"HUB URL",placeholder:pe,initialValue:_("HUB_URL")??r?.hubUrl??pe,validate:l=>l.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=Tt(await Jo({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 hc(o,a),Rt.success("account-issued registration token minted");else if(i==="login"){let l=er(await zr({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await qr(o,l),s=await hc(o,a),Rt.success("account-issued registration token minted")}else s=er(await Gf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||tr("a registration token is required");let c=await Mf(o,a),u=er(await zr({message:"worker name",initialValue:Uf(),validate:l=>l.trim().length>0?void 0:"required"})).trim(),p=Tt(await Jo({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 Ye({hub:o,token:s,name:u,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Rt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Tt(await mc({message:"start the claim-loop now?",initialValue:!0}))){gc("registered. start later with `codepipe worker`.");return}gc("starting the claim-loop\u2026"),await Kt(t.profile?{profile:t.profile}:{})}function Ff(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var J=Ff();gn(J);bn();var ce=new Hf;ce.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ie).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await fc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Ma({configPath:t.config,skipVerify:t.skipVerify===!0}):await Pa({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await In({...t,profile:J})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await Ea({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ce.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ms({profile:J})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await $a({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await Ya({profile:J,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Zs({profile:J})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await Qa({profile:J,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var yc=ce.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");yc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??Se(J)?.hubUrl??pe,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Xo()){await Qo({profile:J});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??_("WORKER_NAME"),i=t.llm??_("WORKER_LLM");await Ye({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...J?{profile:J}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});yc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!ee(J)&&Xo()){await Qo({profile:J});return}await Kt(J?{profile:J}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Kf=ce.command("project").description("Manage CodePipe projects");Kf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Xa({profile:J})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.parseAsync();
583
+ `)}catch{}}import{hostname as Af}from"node:os";import{cancel as _f,confirm as mc,intro as Of,isCancel as wc,log as At,multiselect as Nf,outro as gc,password as Uf,select as Jo,text as Xr}from"@clack/prompts";function ir(t){_f(t),process.exit(1)}function _t(t){return wc(t)&&ir("aborted"),t}function nr(t){return wc(t)&&ir("aborted"),typeof t=="string"?t:""}function Xo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function hc(t,e){try{let{secret:r}=await Cr(t,e);return r}catch(r){throw r instanceof j&&r.status===404&&ir("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Lf(t,e){if(_t(await Jo({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 Yi(t,e);if(n.length>0)return _t(await Nf({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}));At.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){At.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return nr(await Xr({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:n=>n.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Qo(t){Of("codepipe worker \u2014 set up this machine as a runner");let e=te(t.profile);e&&(At.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),_t(await mc({message:"re-register this worker?",initialValue:!1}))||ir("keeping the existing registration"));let r=Te(t.profile)??Te(),o=nr(await Xr({message:"HUB URL",placeholder:de,initialValue:_("HUB_URL")??r?.hubUrl??de,validate:l=>l.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=_t(await Jo({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 hc(o,a),At.success("account-issued registration token minted");else if(i==="login"){let l=nr(await Xr({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await zr(o,l),s=await hc(o,a),At.success("account-issued registration token minted")}else s=nr(await Uf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ir("a registration token is required");let c=await Lf(o,a),u=nr(await Xr({message:"worker name",initialValue:Af(),validate:l=>l.trim().length>0?void 0:"required"})).trim(),p=_t(await Jo({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 Xe({hub:o,token:s,name:u,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),At.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!_t(await mc({message:"start the claim-loop now?",initialValue:!0}))){gc("registered. start later with `codepipe worker`.");return}gc("starting the claim-loop\u2026"),await zt(t.profile?{profile:t.profile}:{})}function Bf(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var X=Bf();gn(X);bn();var le=new Df;le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(se).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 fc()}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 Ha({configPath:t.config,skipVerify:t.skipVerify===!0}):await ja({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await In({...t,profile:X})}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 Aa({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 ys({profile:X})}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 va({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 Ya({profile:X,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 oa({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await Qa({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var yc=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");yc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??Te(X)?.hubUrl??de,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Xo()){await Qo({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??_("WORKER_NAME"),i=t.llm??_("WORKER_LLM");await Xe({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)}});yc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!te(X)&&Xo()){await Qo({profile:X});return}await zt(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Gf=le.command("project").description("Manage CodePipe projects");Gf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Xa({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();