@code-partner/codepipe 0.1.128-dev.12.g2b8ef04 → 0.1.128-dev.13.g2847d8e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +81 -81
  2. package/package.json +3 -3
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 ie="0.1.128-dev.13.g2847d8e",pe="https://hub.dev.codepipe.dev";var de=2,$c=1;function ar(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=$c&&t<=de}var be=".devpipe-context.yaml",sn=[{version:1,summary:"ADR section: adr/ scaffold (README, template, derived INDEX) + the format-version stamp itself",addedPaths:["adr/README.md","adr/0000-template.md","adr/INDEX.md",be]}];function cr(t=1){return`# CodePipe Context Repo format version.
3
3
  # Bumped by the scaffold / the format-migration PR \u2014 do not edit by hand.
4
4
  template_version: ${t}
5
- `}function 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 an(t){if(!t)return 0;let e=/^\s*template_version:\s*(\d+)\s*$/m.exec(t),r=e?parseInt(e[1]??"",10):NaN;return Number.isFinite(r)&&r>=0?r:0}function cn(t,e=sn){let r=[];for(let o of e)if(!(o.version<=t))for(let n of o.addedPaths)r.includes(n)||r.push(n);return r}function ln(t,e=sn){return e.filter(r=>r.version>t)}function lr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}var Ge=/^[a-z][a-z0-9-]{1,30}$/,xc="-codepipe-ctx";function ke(t){return`${t}${xc}`}var Nt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function rt(t){let e=t.match(/^git@([^:/]+):/);if(e)return e[1]??null;let r=t.match(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)/);if(r)return r[1]??null;let o=t.match(/^https?:\/\/(?:[^@/]+@)?([^/:]+)/);return o?o[1]??null:null}var ot="x-bitbucket-api-token-auth";function ur(t){switch(t){case Nt.gitlab:return"oauth2";case Nt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var un=20;function _(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as Lf}from"commander";import{homedir as pn}from"node:os";import{mkdirSync as vc,readFileSync as Sc,writeFileSync as Cc,existsSync as oo}from"node:fs";import{dirname as fn,join as pr,resolve as Rc}from"node:path";import{fileURLToPath as Tc}from"node:url";var dn=Rc(fn(Tc(import.meta.url)),"..");function mn(t){let e=pr(dn,".env");if(oo(e)&&process.loadEnvFile(e),t){let r=pr(dn,"profiles",t,".env");oo(r)&&process.loadEnvFile(r)}}function nt(t){let e=_("CONFIG");return e||(t?pr(pn(),".codepipe","profiles",t,"config.json"):pr(pn(),".codepipe","config.json"))}function Re(t){let e=nt(t);if(!oo(e))return null;let r=Sc(e,"utf-8");return JSON.parse(r)}function Me(t,e){let r=nt(e);vc(fn(r),{recursive:!0}),Cc(r,JSON.stringify(t,null,2)+`
6
+ `,{mode:384})}function fe(t){let e=Re(t);if(!e){let r=t?`codepipe init --profile ${t} --hub <url> --token <token> --project ${t}`:"codepipe init --hub <url> --token <token> --project <id>";console.error(t?`CLI profile '${t}' is not initialised. run \`${r}\` first.`:`CLI is not initialised. run \`${r}\` first.`),process.exit(1)}return e.projectId||(console.error(`config at ${nt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as hn}from"node:os";import{join as wn}from"node:path";import{existsSync as gn,renameSync as Ic}from"node:fs";function He(t,e,r=o=>console.error(o)){if(gn(e)||!gn(t))return!1;try{return Ic(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}function yn(){He(wn(hn(),".devpipe"),wn(hn(),".codepipe"))}import{homedir as bn}from"node:os";import{existsSync as kn,mkdirSync as $n,readFileSync as xn,writeFileSync as vn}from"node:fs";import{dirname as Sn,join as Cn}from"node:path";function dr(t,e,r){let o=H(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,Z(o),"pinned")}function Fe(t){return Cn(bn(),".codepipe","secrets",`${t}.json`)}function H(t){let e=Fe(t);return kn(e)?JSON.parse(xn(e,"utf-8")):null}function Z(t){let e=Fe(t.projectId);$n(Sn(e),{recursive:!0}),vn(e,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function fr(){return Cn(bn(),".codepipe","shared.json")}function Pc(){let t=fr();return kn(t)?JSON.parse(xn(t,"utf-8")):null}function Rn(t){let e=fr();$n(Sn(e),{recursive:!0}),vn(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function it(t){let e=H(t)?.claude?.oauthToken;return e||Pc()?.claude?.oauthToken}function Ut(t){let e=(r,o)=>{o&&!process.env[r]&&(process.env[r]=o)};e("GH_TOKEN",t.github?.token),e("BITBUCKET_EMAIL",t.bitbucket?.email),e("BITBUCKET_API_TOKEN",t.bitbucket?.apiToken),e("GITLAB_TOKEN",t.gitlab?.token),e("YOUTRACK_URL",t.youtrack?.url),e("YOUTRACK_TOKEN",t.youtrack?.token)}function st(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Tn(t){let e=t.profile??t.project;t.profile&&t.profile!==t.project&&(console.error(`--profile (${t.profile}) must equal --project (${t.project}). Profile id is the project id.`),process.exit(1));let r=Re(e);r&&!t.force&&(console.error(`already configured at ${nt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Me({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...H(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};Z(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${nt(e)}`)}import{homedir as Io}from"node:os";import{join as Ht}from"node:path";import{appendFileSync as Ec,existsSync as In,mkdirSync as jc,renameSync as Pn,statSync as Ac,unlinkSync as _c}from"node:fs";import{Writable as Oc}from"node:stream";import{join as Nc}from"node:path";var En={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},at=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&jc(e.dir,{recursive:!0}),this.currentPath=Nc(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
9
9
  `)?e:e+`
10
- `;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||!In(this.currentPath)||Ac(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;In(o)&&(r>=this.cfg.maxFiles?_c(o):Pn(o,`${this.currentPath}.${r+1}`))}Pn(this.currentPath,`${this.currentPath}.1`)}}};function mr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=Uc(process.env[`${t}_MAX_BYTES`]??String(En.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):En.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function Uc(t){let e=t.trim().match(/^(\d+)\s*([kmg]?)b?$/i);if(!e)return Number(t)||0;let r=Number(e[1]),o=(e[2]??"").toLowerCase();return o==="g"?r*1024**3:o==="m"?r*1024**2:o==="k"?r*1024:r}function gr(t){let e={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r=(o,n)=>(...i)=>{o(...i);try{t.writeLine(Lc(n,i))}catch{}};return console.log=r(e.log,"INFO"),console.warn=r(e.warn,"WARN"),console.error=r(e.error,"ERROR"),()=>{console.log=e.log,console.warn=e.warn,console.error=e.error}}function Lc(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:Dc(n)).join(" ");return`${r} ${t} ${o}`}function Dc(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as Su}from"node:path";import"ws";import{createHash as Bc}from"node:crypto";import{existsSync as Gc,readFileSync as Mc}from"node:fs";import{homedir as Hc,hostname as no}from"node:os";import{join as Fc}from"node:path";function jn(t){return Bc("sha256").update(t).digest("hex").slice(0,12)}function Kc(){let t=_("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=Fc(Hc(),".claude","credentials.json");if(!Gc(e))return;let r=JSON.parse(Mc(e,"utf-8")),o=[r.email,r.account?.email,r.user?.email];for(let n of o)if(typeof n=="string"&&n.includes("@"))return n.trim().toLowerCase()}catch{}}function An(t){let e=Kc(),r=_("ACCOUNT_ID")?.trim(),o=_("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=it(t);return n?{accountId:`acct-${jn(n)}`,label:o||no(),...e?{email:e}:{}}:{accountId:`acct-${jn(`host:${no()}`)}`,label:o||no(),...e?{email:e}:{}}}import{existsSync as Wc}from"node:fs";import{join as qc}from"node:path";import{simpleGit as Yc}from"simple-git";async function _n(t,e){if(!Wc(qc(t,".git")))return{status:"skipped"};let r=Yc(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Vc(n)}`}}let o=await r.status();if(!o.isClean())return{status:"warn",reason:"uncommitted changes \u2014 working copy left as-is"};if(o.current!==e)return{status:"warn",reason:`on '${o.current??"detached HEAD"}', not '${e}' \u2014 not fast-forwarded`};try{await r.merge(["--ff-only",`origin/${e}`])}catch{return{status:"warn",reason:`'${e}' can't fast-forward to origin (diverged) \u2014 not updated`}}return{status:"updated"}}function Vc(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as io,readFileSync as On,readdirSync as zc,watch as Jc}from"node:fs";import{join as so}from"node:path";var hr=class{constructor(e,r,o,n,i=6e4){this.contextDir=e;this.projectId=r;this.send=o;this.log=n;this.intervalMs=i}timer=null;watcher=null;debounce=null;started=!1;start(){this.started||(this.started=!0,this.report(),this.timer=setInterval(()=>this.report(),this.intervalMs),this.timer.unref?.(),this.installWatcher())}stop(){if(this.started=!1,this.timer&&clearInterval(this.timer),this.timer=null,this.debounce&&clearTimeout(this.debounce),this.debounce=null,this.watcher)try{this.watcher.close()}catch{}this.watcher=null}installWatcher(){if(io(this.contextDir))try{this.watcher=Jc(this.contextDir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>this.report(),500),this.debounce.unref?.()})}catch{this.watcher=null}}reportNow(){this.report()}report(){try{this.send(this.read())}catch(e){this.log.warn(`[config] report failed: ${e instanceof Error?e.message:String(e)}`)}}read(){return{type:"config_observation",projectId:this.projectId,projectYaml:this.readFile("project.yaml"),regimenYaml:this.readFile("regimen.yaml"),prompts:this.readPrompts()}}readFile(e){let r=so(this.contextDir,e);if(!io(r))return null;try{return On(r,"utf-8")}catch{return null}}readPrompts(){let e=so(this.contextDir,"prompts"),r={};if(!io(e))return r;let o;try{o=zc(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=On(so(e,n),"utf-8")}catch{}}return r}};import{existsSync as al,readFileSync as cl,readdirSync as ll}from"node:fs";import{join as Hn}from"node:path";import{simpleGit as ul}from"simple-git";import{existsSync as el,mkdirSync as tl,writeFileSync as Dn}from"node:fs";import{dirname as rl,isAbsolute as ol,join as Gn,normalize as fo}from"node:path";import{simpleGit as Mn}from"simple-git";import{existsSync as Te,mkdirSync as Nn,readFileSync as ao,writeFileSync as ct}from"node:fs";import{homedir as Xc}from"node:os";import{join as me}from"node:path";import{simpleGit as Qc}from"simple-git";var lt=["project.yaml","regimen.yaml"];function co(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=me(t,n);Te(s)||(ct(s,i),r.push(n))}return r}function Ke(t,e,r){let o=me(Xc(),".codepipe","profiles",t,"context-config");return Nn(o,{recursive:!0}),ct(me(o,"project.yaml"),e.projectYaml),ct(me(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Un(t,e,r){if(Te(e))for(let o of lt){let n=me(e,o),i=me(t,o);if(!(!Te(n)||Te(i)))try{ct(i,ao(n)),r.info(`[config] seeded local ${o} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${o}: ${s instanceof Error?s.message:String(s)}`)}}}var Zc=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function wr(t){let e=me(t,".gitignore"),r=Te(e)?ao(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(lt.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
11
  `)?"":`
12
- `;return fr(e,r+i+el.join(`
12
+ `;return ct(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(`
14
+ `),!0}async function Ln(t,e){try{if(!Te(me(t,".git")))return;let r=Qc(t),o=(await r.raw(["ls-files","--",...lt])).split(`
15
+ `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;wr(t),await r.raw(["rm","--cached","--quiet","--",...o]),await r.add([".gitignore"]),await r.commit("chore(context): move project config out of the Context Repo"),await po(t),e.info(`[config] migrated ${o.join(", ")} out of the Context Repo \u2014 the local copies are now the config`)}catch(r){e.warn(`[config] context-config migration failed (will retry on next start): ${r instanceof Error?r.message:String(r)}`)}}function lo(t){let e=new Map;for(let r of lt){let o=me(t,r);Te(o)&&e.set(r,ao(o))}return e}function uo(t,e){Nn(t,{recursive:!0});for(let[r,o]of e){let n=me(t,r);Te(n)||ct(n,o)}}var Bn=3,nl=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function yr(t,e,r){if(!el(Gn(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=sl(t,i.path);tl(rl(s),{recursive:!0}),i.encoding==="base64"?Dn(s,Buffer.from(i.content,"base64")):Dn(s,i.content)}let o=Mn(t);await o.add(["-A","--",".",...lt.map(i=>`:(exclude)${i}`)]),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await po(t))}async function po(t){let e=Mn(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=Bn;o++){try{await e.push();return}catch(i){r=i}await e.fetch().catch(()=>{});let n=(await e.revparse(["--abbrev-ref","HEAD"])).trim();try{await e.rebase([`origin/${n}`])}catch{let i=await il(e);if(i.length>0&&i.every(s=>nl.has(s)))await e.raw(["checkout","--theirs","--",...i]),await e.add(i),await e.raw(["-c","core.editor=true","rebase","--continue"]);else throw await e.rebase(["--abort"]).catch(()=>{}),new Error(`context push: rebase conflict in ${i.join(", ")||"unknown files"} \u2014 concurrent writers edited the same entry; resolve manually in the Context Repo`)}}throw new Error(`context push failed after ${Bn} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function il(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
16
+ `).map(r=>r.trim()).filter(Boolean)}function sl(t,e){if(ol(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=fo(Gn(t,e)),o=fo(t+"/");if(r!==fo(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var pl=/^(\d{4})-(.+)\.md$/,dl="0000-template.md";function fl(t){let e=t.split(`
17
+ `),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function ml(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
18
18
  `),a=s.findIndex(R=>R.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,u=new Set(["status","date","tasks"]),p=[],f="",l=null,d=a>=0?a+1:0;for(let R=d;R<s.length;R++){let v=(s[R]??"").trim();if(v===""){d=R+1;continue}let T=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!T)break;let j=(T[1]??"").trim().toLowerCase(),U=(T[2]??"").trim(),S=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);S&&(l=parseInt(S[1]??"",10)),j==="tasks"&&(f=U),u.has(j)||p.push(v),d=R+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,w=s.slice(d).join(`
19
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 Fn(t,e,r,o=new Date().toISOString().slice(0,10)){try{await ul(t).pull(void 0,void 0,["--rebase"])}catch{}let n=Hn(t,"adr"),i=new Map;if(al(n))for(let l of ll(n)){let d=pl.exec(l);!d||l===dl||i.set(l,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:cl(Hn(n,l),"utf-8")})}let s=Math.max(0,...[...i.values()].map(l=>l.num))+1,a=new Map,c=[],u=[];for(let l of r){if([...i.entries()].find(([,v])=>v.slug===l.slug&&v.content.includes(e))){u.push(l.slug);continue}let g=s++,w=`${String(g).padStart(4,"0")}-${l.slug}.md`,{content:k,supersedes:R}=ml(l.content,g,l.slug,e,o);if(a.set(w,k),i.set(w,{num:g,slug:l.slug,content:k}),c.push(`adr/${w}`),R!==null){let v=[...i.keys()].find(T=>T.startsWith(`${String(R).padStart(4,"0")}-`));if(v&&v!==w){let T=gl(a.get(v)??i.get(v).content,g);a.set(v,T),i.set(v,{...i.get(v),content:T})}}}if(c.length===0)return{promoted:c,skipped:u};let p=[...i.entries()].map(([l,d])=>({num:d.num,file:l,header:fl(d.content)}));a.set("INDEX.md",hl(p));let f=[...a.entries()].map(([l,d])=>({path:`adr/${l}`,content:d}));return await yr(t,f,`adr(${e}): promote ${r.map(l=>l.slug).join(", ")}`),{promoted:c,skipped:u}}import{existsSync as Kn,readFileSync as yl}from"node:fs";import{join as Wn}from"node:path";function bl(t){let e=Wn(t,be);if(!Kn(e))return 0;try{return an(yl(e,"utf-8"))}catch{return 0}}function kl(t,e,r,o=1){let n=e<o,i=n?cn(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function br(t,e){return kl(e,bl(t),r=>Kn(Wn(t,r)))}import{existsSync as Nl,mkdirSync as Ul,mkdtempSync as Ll,rmSync as Dl,writeFileSync as zn}from"node:fs";import{tmpdir as Bl}from"node:os";import{dirname as Gl,join as bo}from"node:path";import{simpleGit as ko}from"simple-git";var We=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function qn(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
27
+ `+t.slice(t.length-e)}async function ut(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function yo(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function pt(t,e,r){let o=r?`https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(r)}?pagelen=1`:"https://api.bitbucket.org/2.0/workspaces?pagelen=1",n;try{n=await fetch(o,{headers:{Authorization:"Basic "+Buffer.from(`${t}:${e}`).toString("base64")}})}catch(s){throw new Error(`cannot reach api.bitbucket.org (${s instanceof Error?s.message:String(s)})`)}if(n.ok)return t;if(n.status===410)return`${t} (Bitbucket deprecated the probe endpoint \u2014 scope check skipped)`;let i=await $l(n);throw n.status===401?new Error(`credentials rejected (401 \u2014 check the Atlassian account email / API token${i})`):n.status===403?new Error(`token not authorized \u2014 needs \`read:repository:bitbucket\` (403${i})`):n.status===404&&r?new Error(`workspace "${r}" not found or not visible to this token (404${i})`):new Error(`Bitbucket \u2192 ${n.status} ${n.statusText}${i}`)}async function $l(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function dt(t){let e;try{e=await fetch("https://gitlab.com/api/v4/user",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}})}catch(o){throw new Error(`cannot reach gitlab.com (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the GitLab PAT)");if(!e.ok)throw new Error(`GitLab \u2192 ${e.status} ${e.statusText}`);return(await e.json()).username??"ok"}async function Vn(t){try{let e=await fetch("https://gitlab.com/api/v4/personal_access_tokens/self",{headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli"}});if(!e.ok)return;let o=(await e.json()).scopes??[];return o.length>0&&!o.includes("api")?`GitLab token scopes [${o.join(", ")}] lack 'api' \u2014 CodePipe can read and push, but cannot create a Context Repo or scaffold its files`:void 0}catch{return}}var mo=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.links?.html?.href??"",number:n.id}}async findOpenPrByBranch(e,r){let o=encodeURIComponent(`state="OPEN" AND source.branch.name="${r}"`),n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests?q=${o}`,{headers:{Authorization:this.authHeader(),Accept:"application/json","User-Agent":"codepipe-cli"}});if(!n.ok)return null;let s=(await n.json()).values?.[0];return s?{url:s.links?.html?.href??"",number:s.id}:null}async getPullRequest(e,r){let o=`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/json",Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(n.status===404)throw new We(`Bitbucket PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`bitbucket GET pullrequests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();return i.state==="MERGED"?{state:"merged",merged:!0,ci:"none",mergeable:"unknown"}:i.state==="DECLINED"||i.state==="SUPERSEDED"?{state:"closed",merged:!1,ci:"none",mergeable:"unknown"}:{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){let i=o==="squash"?"squash":o==="rebase"?"fast_forward":"merge_commit",s=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/merge`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_strategy:i,close_source_branch:n})});if(!s.ok)throw new Error(`bitbucket merge PR #${r}: ${s.status} ${await s.text()}`);let a=await s.json().catch(()=>null);return a?.merge_commit?.hash?{mergedSha:a.merge_commit.hash}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/comments`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({content:{raw:o}})});if(!i.ok)throw new Error(`bitbucket comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests/${r}/decline`,{method:"POST",headers:{Authorization:this.authHeader(),"User-Agent":"codepipe-cli"}});if(!n.ok)throw new Error(`bitbucket decline PR #${r}: ${n.status} ${await n.text()}`)}},go=class{constructor(e){this.token=e}name="github";async createPullRequest(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json"},body:JSON.stringify({title:r.title,body:r.body,head:r.branchName,base:r.baseBranch})});if(!o.ok)throw new Error(`github pr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.html_url,number:n.number}}async findOpenPrByBranch(e,r){let o=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls?state=open&head=${encodeURIComponent(`${e.owner}:${r}`)}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.html_url,number:i.number}:null}async getPullRequest(e,r){let o=`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,n=await fetch(o,{method:"GET",headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(n.status===404)throw new We(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,u=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])u=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(u=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return u?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let u=(await c.json()).workflow_runs??[],p=[];for(let f of u.filter(l=>l.conclusion&&i.includes(l.conclusion))){let l=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!l.ok)continue;let d=(await l.json()).jobs??[];for(let g of d.filter(w=>w.conclusion==="failure")){let w=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!w.ok)continue;let k=await w.text();p.push(`### CI job: ${g.name}
28
28
 
29
- ${Yn(k,8e3)}`)}}return p.length===0?void 0:Yn(p.join(`
29
+ ${qn(k,8e3)}`)}}return p.length===0?void 0:qn(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()}`)}},ho=class{constructor(e){this.token=e}name="gitlab";pid(e){return encodeURIComponent(`${e.owner}/${e.repoName}`)}headers(e=!1){let r={"PRIVATE-TOKEN":this.token,"User-Agent":"codepipe-cli"};return e&&(r["Content-Type"]="application/json"),r}async createPullRequest(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({source_branch:r.branchName,target_branch:r.baseBranch,title:r.title,description:r.body})});if(!o.ok)throw new Error(`gitlab mr create: ${o.status} ${await o.text()}`);let n=await o.json();return{url:n.web_url??"",number:n.iid}}async findOpenPrByBranch(e,r){let o=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests?state=opened&source_branch=${encodeURIComponent(r)}`,{headers:this.headers()});if(!o.ok)return null;let i=(await o.json())[0];return i?{url:i.web_url??"",number:i.iid}:null}async getPullRequest(e,r){let o=`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,n=await fetch(o,{method:"GET",headers:this.headers()});if(n.status===404)throw new We(`GitLab MR not found: ${e.owner}/${e.repoName}!${r}`);if(n.status>=400)throw new Error(`gitlab GET merge_requests/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="merged")return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed"||i.state==="locked")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=xl(i.head_pipeline?.status??i.pipeline?.status),a=i.merge_status==="cannot_be_merged"||i.has_conflicts===!0?"conflict":i.merge_status==="can_be_merged"&&i.blocking_discussions_resolved!==!1?"mergeable":"unknown";return{state:"open",merged:!1,ci:s,mergeable:a}}async mergePR(e,r,o,n){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/merge`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({squash:o==="squash",should_remove_source_branch:n})});if(!i.ok)throw new Error(`gitlab merge MR !${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);return s?.merge_commit_sha?{mergedSha:s.merge_commit_sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}/notes`,{method:"POST",headers:this.headers(!0),body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`gitlab comment MR !${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://gitlab.com/api/v4/projects/${this.pid(e)}/merge_requests/${r}`,{method:"PUT",headers:this.headers(!0),body:JSON.stringify({state_event:"close"})});if(!n.ok)throw new Error(`gitlab close MR !${r}: ${n.status} ${await n.text()}`)}};function xl(t){switch(t){case"running":case"pending":case"created":case"waiting_for_resource":case"preparing":case"scheduled":return"running";case"success":return"success";case"failed":case"canceled":case"cancelled":return"failed";default:return"none"}}var wo=class{name="mock";async createPullRequest(e,r){let o=Math.floor(Math.random()*9e3)+1e3;return{url:`https://example.com/${e.owner}/${e.repoName}/pull-requests/${o}`,number:o}}async getPullRequest(e,r){return{state:"open",merged:!1,ci:"none",mergeable:"unknown"}}async mergePR(e,r,o,n){throw new Error(Yn(e,r,"merge"))}async closePR(e,r,o){throw new Error(Yn(e,r,"close"))}};function Yn(t,e,r){let o=t.host==="github"?"set GH_TOKEN or GITHUB_TOKEN in the CLI env":t.host==="bitbucket"?"set BITBUCKET_EMAIL + BITBUCKET_API_TOKEN in the CLI env":t.host==="gitlab"?"set GITLAB_TOKEN in the CLI env":`no adapter implementation for host '${t.host}'`;return`cannot ${r} PR ${t.owner}/${t.repoName}#${e}: MockGitHost is active (write operations are not allowed) \u2014 ${o}`}function $e(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new go(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new mo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new ho(e)}return new wo}function ft(t,e,r,o){return[{path:"README.md",content:Al(t,e)},{path:".gitignore",content:Tl()},{path:"CLAUDE.md",content:Pl(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:Il()},{path:"knowledge/README.md",content:El()},{path:"knowledge/build.yaml",content:jl()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:Rl()},{path:"adr/README.md",content:vl()},{path:"adr/0000-template.md",content:Sl()},{path:"adr/INDEX.md",content:Cl()},{path:be,content:cr()}]}function vl(){return`# ADR \u2014 architecture decision records
32
32
 
33
33
  Accepted architectural decisions of this project \u2014 its **framework**. The
34
34
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -56,7 +56,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
56
56
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
57
57
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
58
58
  open a PR to this repository.
59
- `}function 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 Ie(t,e,r,o){return{projectYaml:_l(t,r,o),regimenYaml:Ol(t.automationLevel,e)}}function Tl(){return`# codepipe project config is local to each member's workspace
96
96
  project.yaml
97
97
  regimen.yaml
98
98
 
99
99
  # codepipe runtime
100
100
  session.log
101
101
  apply-queue.json
102
- `}function 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}
419
+ `}function Ml(t){return`codepipe/context-migration-v${t}`}function Hl(t){let e=ln(t.templateVersion),r=[`CodePipe context format migration: **v${t.templateVersion} \u2192 v${t.currentVersion}**.`,"","Additive only \u2014 this PR creates files your context is missing and updates",`the \`${be}\` stamp. Hand-edited files are never touched.`,"","## Format changes",""];for(let o of e){r.push(`- **v${o.version}** \u2014 ${o.summary}`);for(let n of o.addedPaths)r.push(` - \`${n}\``)}return r.push("","Merge to apply. CodePipe re-checks the stamp on the next daemon start and","clears the \u201Ccontext outdated\u201D badge.","","_Opened automatically by the CodePipe CLI._"),r.join(`
420
+ `)}async function Jn(t,e,r,o){let n=ko(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=br(t,e);if(!i.outdated)return i;let s=Ml(i.currentVersion),a=r?.branch??(await n.revparse(["--abbrev-ref","HEAD"]).catch(()=>"main")).trim();try{await n.fetch().catch(()=>{}),(await n.raw(["ls-remote","--heads","origin",s]).catch(()=>"")).trim().length===0?await Fl(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(u){return o.warn(`[ctx] context migration branch failed (will retry next start): ${u instanceof Error?u.message:String(u)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let u=$e(c),p=await u.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let f=await u.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:Hl(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(u){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${u instanceof Error?u.message:String(u)}`),i}}async function Fl(t,e,r,o,n,i,s){let a=ko(t),c=Ll(bo(Bl(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let u={projectId:e,name:e,automationLevel:"assisted",repos:[]},p={host:r?.host??"github",owner:r?.owner??e,name:r?.name??`${e}-codepipe-ctx`},f=new Map(ft(u,p).map(g=>[g.path,g.content])),l=0;for(let g of o.missingPaths){if(g===be)continue;let w=f.get(g);if(w==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let k=bo(c,g);Nl(k)||(Ul(Gl(k),{recursive:!0}),zn(k,w),l++)}zn(bo(c,be),cr(o.currentVersion)),l++;let d=ko(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${l} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),Dl(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as Kl,createDecipheriv as Wl,createHash as ql,createPrivateKey as Yl,createPublicKey as $o,diffieHellman as Xn,generateKeyPairSync as Qn,hkdfSync as Zn,randomBytes as Vl}from"node:crypto";var ei=Buffer.from("devpipe-sealedbox-v1","utf-8");function ti(){let{publicKey:t,privateKey:e}=Qn("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function mt(t){let e=Buffer.from(t,"base64");return(ql("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function kr(t,e){let r=$o({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=Qn("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=Xn({privateKey:n,publicKey:r}),c=Buffer.from(Zn("sha256",a,Buffer.concat([i,s]),ei,32)),u=Vl(12),p=Kl("aes-256-gcm",c,u),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,l=Buffer.concat([p.update(f),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:u.toString("base64"),tag:d.toString("base64"),ct:l.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function ri(t,e){let r=JSON.parse(Buffer.from(e,"base64").toString("utf-8"));if(r.v!==1)throw new Error(`sealedbox: unsupported envelope version ${r.v}`);let o=Yl({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=$o({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=$o(o).export({type:"spki",format:"der"}),a=Xn({privateKey:o,publicKey:n}),c=Buffer.from(Zn("sha256",a,Buffer.concat([i,s]),ei,32)),u=Wl("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return u.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([u.update(Buffer.from(r.ct,"base64")),u.final()])}function zl(t,e){let r={};t.github?.token&&(r.github={token:t.github.token}),t.bitbucket?.apiToken&&(r.bitbucket={apiToken:t.bitbucket.apiToken}),t.gitlab?.token&&(r.gitlab={token:t.gitlab.token});let o=e??t.claude?.oauthToken;return o&&(r.claudeOauthToken=o),t.contextWrite?.token&&(r.contextWrite={token:t.contextWrite.token}),r}function oi(t,e,r,o){let n=zl(e,r);t.sandboxes.length>0&&!n.claudeOauthToken&&o.warn("[cred] no Claude OAuth token set \u2014 agent jobs will fail in the SANDBOX. Set one with `codepipe login` (per project) or `make farm-config` (shared farm token)."),t.sandboxes.length>0&&!n.contextWrite&&(n.github||n.gitlab||n.bitbucket)&&o.warn("[cred] no dedicated contextWrite token \u2014 SANDBOX pushes deliveries with the project token of the context repo's host (broader scope than necessary). Set secrets.contextWrite.token (a token scoped to the Context Repo only) to tighten. NOTE (GitHub): the push token MUST have the `workflow` scope, else delivery pushes that carry `.github/workflows/*` are rejected.");let i=JSON.stringify(n),s=[];for(let a of t.sandboxes){let c=dr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let u;try{u=kr(a.publicKey,i)}catch(p){o.warn(`[cred] failed to seal bundle for ${a.sandboxId}: ${p instanceof Error?p.message:String(p)}`);continue}s.push({type:"sandbox_bundle",projectId:t.projectId,sandboxId:a.sandboxId,sealed:u})}return s}import{existsSync as Jl,readFileSync as Xl,writeFileSync as Ql}from"node:fs";import{join as Zl}from"node:path";import{parseDocument as eu}from"yaml";var ni=64;async function ii(t,e){if(!Number.isInteger(e)||e<1||e>ni)throw new Error(`maxJobs must be an integer in [1, ${ni}], got ${e}`);let r=Zl(t,"regimen.yaml");if(!Jl(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=eu(Xl(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Ql(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as si,readFileSync as ai,writeFileSync as tu}from"node:fs";import{join as xo}from"node:path";import{parseDocument as ci}from"yaml";async function li(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=xo(t,"project.yaml");if(!si(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ci(ai(i,"utf-8"));if(e.sourceColumns!==void 0){let a=e.sourceColumns.map(c=>typeof c=="string"?c.trim():"").filter(c=>c.length>0);if(a.length===0)throw new Error("source_columns must be a non-empty list of non-empty strings");s.setIn(["youtrack","source_columns"],a)}if(e.backlogColumn!==void 0){let a=typeof e.backlogColumn=="string"?e.backlogColumn.trim():"";a?s.setIn(["youtrack","backlog_column"],a):s.deleteIn(["youtrack","backlog_column"])}if(e.assignee!==void 0){let a=typeof e.assignee=="string"?e.assignee.trim():"";a?s.setIn(["youtrack","assignee"],a):s.deleteIn(["youtrack","assignee"])}e.requireAssignee!==void 0&&s.setIn(["youtrack","require_assignee"],e.requireAssignee===!0),r.push({path:"project.yaml",content:s.toString()})}if(e.reviewStatus!==void 0||e.writes!==void 0){let i=xo(t,"regimen.yaml");if(!si(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ci(ai(i,"utf-8"));if(e.reviewStatus!==void 0){let a=e.reviewStatus.trim();a&&s.setIn(["youtrack","review_status"],a)}if(e.writes!==void 0){let a=e.writes;s.setIn(["youtrack","writes","enabled"],a.enabled===!0),s.setIn(["youtrack","writes","status_changes"],a.statusChanges===!0),s.setIn(["youtrack","writes","pr_comment"],a.prComment===!0),s.setIn(["youtrack","writes","dashboard_mirror"],a.dashboardMirror===!0)}r.push({path:"regimen.yaml",content:s.toString()})}if(r.length===0)return{files:[]};for(let i of r)tu(xo(t,i.path),i.content);return{files:r.map(i=>i.path)}}var ui=t=>console.log(t);function pi(t){ui=t}function Lt(t,e="info"){ui(t,e)}import{homedir as ru}from"node:os";import{existsSync as ou,mkdirSync as nu}from"node:fs";import{join as vo}from"node:path";import{simpleGit as di}from"simple-git";function Bt(t,e,r){let o=r??vo(ru(),".codepipe","repos");return vo(o,t,e)}async function $r(t,e,r={}){let o=Bt(t,e.name,r.baseDir),n=r.cloneUrlOverride??iu(e);if(!ou(vo(o,".git"))){nu(o,{recursive:!0});let a=di();Lt(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
421
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(`
422
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Dt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var fi=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function xr(t,e){let{contextRepoCloneUrl:r,deliveryRef:o,deliverySha:n,baseSha:i,commitMessage:s}=e;await t.raw(["fetch",r,`+refs/heads/${o}:refs/codepipe-delivery`]);let a=(await t.revparse(["refs/codepipe-delivery"])).trim();n&&a!==n&&Lt(`[git] delivery ${o} resolved ${a.slice(0,10)} (expected ${n.slice(0,10)})`);let c=(await t.raw(["rev-parse","refs/codepipe-delivery^{tree}"])).trim();if(await Dt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Dt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let u=(await t.raw([...fi,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),u}async function mi(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await Dt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await Dt(t,n)){let s=(await t.revparse([n])).trim();return await t.raw(["update-ref",o,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",o,i]).catch(()=>{}),i}async function gi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:u,defaultBranch:p,force:f}=r,l=await mi(t,i,()=>xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:u}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await Dt(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,l]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...fi,"cherry-pick",l])}catch(R){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=R instanceof Error?R.message:String(R);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
423
+ ${v.trim()}`)}}let w=(await t.revparse(["HEAD"])).trim(),k=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(k),await t.push([o,"--delete",n]).catch(()=>{}),{commit:w}}async function hi(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:u}=r,p=await mi(t,i,()=>xr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),u&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:u}}async function wi(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function iu(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}import{X509Certificate as ki}from"node:crypto";import{readFileSync as su}from"node:fs";import Pe from"node:tls";var $i=typeof Pe.getCACertificates=="function"&&typeof Pe.setDefaultCACertificates=="function",yi=!1,bi=new Map,xi=t=>console.warn(t);function au(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function vi(t=xi){if(yi)return;yi=!0;let e=_("EXTRA_CA_FILE");if(!(!e||!$i))try{let r=au(su(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Pe.setDefaultCACertificates([...Pe.getCACertificates(),...r]),t(`[tls] trusting ${r.length} extra CA cert(s) from ${e}`)}catch(r){t(`[tls] failed to load CODEPIPE_EXTRA_CA_FILE ${e}: ${r instanceof Error?r.message:String(r)}`)}}function Si(t){let e=t&&typeof t=="object"&&"cause"in t?t.cause?.code:void 0;return e==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||e==="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"||e==="UNABLE_TO_GET_ISSUER_CERT"}function cu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
424
+ `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function lu(t,e,r){return new Promise((o,n)=>{let i=Pe.connect({host:t,port:e,servername:t,rejectUnauthorized:!1},()=>{let s=i.getPeerCertificate(!0),a=new Set;for(;s?.issuerCertificate&&s.issuerCertificate!==s&&s.fingerprint256&&!a.has(s.fingerprint256);)a.add(s.fingerprint256),s=s.issuerCertificate;let c=s?.raw?new ki(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function So(t,e,r){return new Promise(o=>{let n=Pe.connect({host:t,port:e,servername:t,rejectUnauthorized:!0},()=>{n.end(),o(!0)});n.on("error",()=>o(!1)),n.setTimeout(r,()=>{n.destroy(),o(!1)})})}async function uu(t){try{let e=await fetch(t);return e.ok?new ki(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ci(t,e=443,r=xi){let o=`${t}:${e}`,n=bi.get(o);if(n)return n;let i=pu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return bi.set(o,i),i}async function pu(t,e,r){if(!$i)return!1;let o=8e3;if(await So(t,e,o))return!0;let n=await lu(t,e,o),i=Pe.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=cu(n);if(!c)break;let u=await uu(c);if(!u)break;if(s.push(u.toString()),Pe.setDefaultCACertificates([...i,...s]),await So(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(u.subject===u.issuer)break;n=u}return So(t,e,o)}function qe(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ge(t,e,r){vi();let o={Authorization:`Bearer ${t.token}`,Accept:"application/json"};r?.body&&(o["Content-Type"]="application/json");let n=t.baseUrl+e,i={...r,headers:{...o,...r?.headers??{}}};try{return await fetch(n,i)}catch(s){if(Si(s)&&await Ci(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ri=t=>new Promise(e=>setTimeout(e,t));function du(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function fu(){let t=Number(process.env.YOUTRACK_WRITE_RETRIES);return{attempts:Number.isFinite(t)&&t>=1?Math.floor(t):6,baseMs:1e3,capMs:15e3}}async function Pi(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=fu(),a=null;for(let c=1;c<=n;c++){let u=null;try{u=await ge(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(u){if(u.ok)return u;let p=await u.text();if(c<n&&du(u.status,p)){await Ri(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${u.status} ${p}`)}if(c<n){await Ri(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function gt(t){let e;try{e=await ge(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Ei(t){try{let e=await ge(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ti=new Map;async function mu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ti.get(o);if(n)return n;let i=await ge(t,`/api/issues/${encodeURIComponent(e)}?fields=customFields(name,projectCustomField(bundle(values(name,id))))`);if(!i.ok)throw new Error(`yt resolveStateId ${e}: ${i.status} ${await i.text()}`);let a=(await i.json()).customFields.find(u=>u.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(u=>u.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ti.set(o,c.id),c.id}async function ji(t,e,r){let o=await mu(t,e,r);await Pi(t,`yt updateState ${e}`,`/api/issues/${encodeURIComponent(e)}?fields=idReadable`,{method:"POST",body:JSON.stringify({customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{id:o,$type:"StateBundleElement"}}]})})}async function Ai(t,e,r){return await(await Pi(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Ii=new Map;async function gu(t,e){let r=Ii.get(e);if(r)return r;let o=await ge(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Ii.set(e,i.id),i.id}async function _i(t,e,r,o,n){let i=await gu(t,e),s=await ge(t,"/api/issues?fields=id,idReadable",{method:"POST",body:JSON.stringify({project:{id:i},summary:r,description:o,customFields:[{name:"Stage",$type:"StateIssueCustomField",value:{name:n,$type:"StateBundleElement"}}]})});if(!s.ok)throw new Error(`yt createIssue: ${s.status} ${await s.text()}`);let a=await s.json();return{id:a.id,key:a.idReadable}}async function Oi(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await ge(t,"/api/commands",{method:"POST",body:JSON.stringify({query:n,issues:[{idReadable:e}]})});if(!i.ok)throw new Error(`yt applyIssueLink (${n} on ${e}): ${i.status} ${await i.text()}`)}var Ni="attachments(id,name,url,size,mimeType)",hu="links(direction,linkType(name),issues(idReadable))",Ui=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Ni},${hu}`,wu=`id,text,created,author(login),${Ni}`;function Li(t){if(!t||t.length===0)return;let e=[];for(let r of t)!r.url||!r.name||e.push({id:r.id,name:r.name,url:r.url,...r.mimeType?{mimeType:r.mimeType}:{},...typeof r.size=="number"?{size:r.size}:{}});return e.length>0?e:void 0}async function Di(t,e){let r=e.startsWith("http")?e:t.baseUrl+e,o=await fetch(r,{headers:{Authorization:`Bearer ${t.token}`}});if(!o.ok)throw new Error(`yt downloadAttachment ${e}: ${o.status}`);return Buffer.from(await o.arrayBuffer())}async function Bi(t,e){let r=[`project: ${e.projectKey}`];if(e.columns&&e.columns.length>0){let a=e.columns.map(c=>`{${c}}`).join(", ");r.push(`Stage: ${a}`)}if(e.updatedSince){let a=new Date(e.updatedSince).toISOString().slice(0,10);r.push(`updated: ${a} .. *`)}e.assignee?r.push(`Assignee: {${e.assignee}}`):e.requireAnyAssignee&&r.push("has: Assignee");let o=r.join(" "),n=`/api/issues?query=${encodeURIComponent(o)}&fields=${Ui}&$top=200`,i=await ge(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Hi)}async function Gi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Ui}`,o=await ge(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Hi(await o.json())}async function Mi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${wu}&$top=500`,n=await ge(t,o);if(!n.ok)throw new Error(`yt listComments ${e}: ${n.status} ${await n.text()}`);return(await n.json()).filter(s=>s.created>r).map(s=>{let a={id:s.id,issueId:e,author:s.author?.login??"unknown",body:s.text??"",createdAt:new Date(s.created).toISOString()},c=Li(s.attachments);return c&&(a.attachments=c),a})}function yu(t){if(!t||t.length===0)return;let e=[];for(let r of t){if(r.direction!=="INWARD")continue;let o=r.linkType?.name==="Depend"?"depends_on":r.linkType?.name==="Subtask"?"subtask":null;if(o)for(let n of r.issues??[])n.idReadable&&e.push({type:o,targetKey:n.idReadable})}return e.length>0?e:void 0}function Hi(t){let e=t.customFields??[],r=e.find(c=>c.name==="Stage"),o=e.find(c=>c.name==="Assignee"),n=e.find(c=>c.name==="Type"),i={id:t.id,key:t.idReadable,title:t.summary,status:r?.value?.name??"Unknown",updatedAt:t.updated?new Date(t.updated).toISOString():new Date().toISOString()};t.description&&(i.description=t.description),o?.value?.login&&(i.assignee=o.value.login),n?.value?.name&&(i.issueType=n.value.name),t.tags&&t.tags.length>0&&(i.tags=t.tags.map(c=>c.name));let s=Li(t.attachments);s&&(i.attachments=s);let a=yu(t.links);return a&&(i.links=a),i}var vr=new Map;async function Co(t,e){let o=(vr.get(t)??Promise.resolve()).catch(()=>{}).then(e);vr.set(t,o);try{return await o}finally{vr.get(t)===o&&vr.delete(t)}}async function Fi(t){let{action:e,repo:r}=t,o="repoName"in e?e.repoName:"-",n="taskId"in e?e.taskId:"draftId"in e?e.draftId:e.projectId;Lt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Bt(i,r.name,t.baseDir),{commit:c}=await gi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return ee({branch:e.branchName,base:e.baseRef,baseSha:e.baseSha,commit:c,...e.force?{force:!0}:{},...typeof e.existingPrNumber=="number"?{reusedPrNumber:e.existingPrNumber}:{}})})}case"early_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Bt(i,r.name,t.baseDir),{commit:c,pushed:u}=await hi(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return ee({branch:e.branchName,commit:c,pushed:u})})}case"create_pr":{if(!r)return F("no repo spec");let i=$e(r),s=await i.createPullRequest(r,e);return ee({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return F("no repo spec");let i=$e(r),s=await i.mergePR(r,e.prNumber,e.mergeMethod,e.deleteBranch);return ee({prNumber:e.prNumber,host:i.name,...s.mergedSha?{mergedSha:s.mergedSha}:{}})}case"close_pr":{if(!r)return F("no repo spec");let i=$e(r);return await i.closePR(r,e.prNumber,e.comment),ee({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return F("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Co(`${i}/${r.name}`,async()=>{let s=await $r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Bt(i,r.name,t.baseDir),{mergedSha:c}=await wi(s,a,{branchName:e.branchName,baseBranch:e.baseBranch,mergeMethod:e.mergeMethod,deleteBranch:e.deleteBranch});return ee({branch:e.branchName,base:e.baseBranch,mergedSha:c})})}case"add_pr_comment":return ee({stub:!0});case"tracker_status":{let i=qe();return i?t.trackerIssueId?(await ji(i,t.trackerIssueId,e.newStatus),ee({issueId:t.trackerIssueId,newStatus:e.newStatus})):F("no tracker_issue_id provided"):F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=qe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return F("no tracker_issue_id provided");let s=await Ai(i,t.trackerIssueId,e.body);return ee({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=qe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return F("no projectKey in create_tracker_issue action");let{id:s,key:a}=await _i(i,e.projectKey,e.title,e.body,e.targetStatus);return ee({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=qe();if(!i)return F("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Oi(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return F(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return ee({applied:s})}case"set_parallelism":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await ii(t.contextDir,e.maxJobs);return ee({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return F("no context repo clone on this CLI");let i=await li(t.contextDir,e);return ee({files:i.files})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),ee({reported:!0})):F("no context repo clone on this CLI")}}catch(i){return F(i instanceof Error?i.message:String(i))}}function ee(t){return{status:"done",result:t}}function F(t){return{status:"failed",error:t}}import bu from"ws";function Sr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new bu(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function ht(t,e,r){return Ye(t,e,"/projects",r)}async function Ki(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Wi(t,e,r,o){return Ye(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Cr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function qi(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new A(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var Gt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function Yi(t,e){let r=await fetch(`${t}/cli/bootstrap-request`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e})});if(r.status===403){let o;try{o=(await r.json()).error}catch{}if(o==="registration_required")throw new Gt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function Vi(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new A(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function zi(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function Ji(t,e,r,o){let n=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks/${encodeURIComponent(o)}`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new A(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function Xi(t,e,r,o){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Qi(t,e,r,o,n){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function Zi(t,e,r,o,n){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function es(t,e,r,o,n){return Ye(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Rr(t,e,r,o){return Ye(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function se(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new A(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Ye(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}function wt(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function ts(t,e){let r=H(t),o=[];if(r?.youtrack?.url&&r.youtrack.token)try{await gt({baseUrl:r.youtrack.url,token:r.youtrack.token}),o.push({name:"youtrack",ok:!0})}catch(i){o.push({name:"youtrack",ok:!1,detail:wt(i)})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"});if(r?.github?.token)try{await ut(r.github.token),o.push({name:"github",ok:!0})}catch(i){o.push({name:"github",ok:!1,detail:wt(i)})}else if(r?.bitbucket?.email&&r.bitbucket.apiToken)try{await pt(r.bitbucket.email,r.bitbucket.apiToken),o.push({name:"bitbucket",ok:!0})}catch(i){o.push({name:"bitbucket",ok:!1,detail:wt(i)})}else if(r?.gitlab?.token)try{await dt(r.gitlab.token),o.push({name:"gitlab",ok:!0})}catch(i){o.push({name:"gitlab",ok:!1,detail:wt(i)})}else o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"});if(r?.github?.token){let i=r.github.token;for(let a of e?.repos??[])if(a.host==="github")try{await yo(i,a.owner,a.repoName),o.push({name:`repo:${a.name}`,ok:!0})}catch(c){o.push({name:`repo:${a.name}`,ok:!1,detail:wt(c)})}let s=e?.contextRepo;if(s?.host==="github")try{await yo(i,s.owner,s.name),o.push({name:"context-repo",ok:!0})}catch(a){o.push({name:"context-repo",ok:!1,detail:wt(a)})}}let n=it(t);if(!n)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0});else{let i=await ku(n);o.push(i==="invalid"?{name:"claude",ok:!1,detail:"Claude token rejected (401) \u2014 refresh via `claude setup-token`"}:{name:"claude",ok:!0})}return{ready:o.every(i=>i.ok),checks:o,checkedAt:Date.now()}}async function ku(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}var Tr=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}targets=new Map;lastSig=new Map;timer=null;running=!1;setTargets(e){this.targets.clear(),this.lastSig.clear();for(let r of e)this.targets.set(r.taskId,r);this.log.info(`[track] targets updated: ${this.targets.size} task(s)`)}start(){if(this.timer)return;this.log.info(`[track] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[track] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[track] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(!this.running){this.running=!0;try{for(let[e,r]of this.targets)await this.processTask(e,r)}finally{this.running=!1}}}async processTask(e,r){let o=[];for(let s of r.prs){let a=$e(s.repoSpec);try{let c=await a.getPullRequest(s.repoSpec,s.number);o.push({number:s.number,url:s.url,state:c.state,merged:c.merged,ci:c.ci,mergeable:c.mergeable})}catch(c){if(c instanceof We){this.log.warn(`[track] task=${e} pr=${s.url} not found \u2014 skipping tick for this task`);return}this.log.warn(`[track] task=${e} pr=${s.url} fetch failed: ${c instanceof Error?c.message:String(c)}`);return}}let n=o.map(s=>`${s.number}:${s.state}:${s.merged?1:0}:${s.ci}:${s.mergeable}`).join("|");if(this.lastSig.get(e)===n)return;for(let s=0;s<o.length;s++){let a=o[s];if(a.ci!=="failed")continue;let c=$e(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let u=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);u&&(a.ciFailureLog=u)}catch(u){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${u instanceof Error?u.message:String(u)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=$u(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function $u(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Ir=class{constructor(e,r,o){this.intervalMs=e;this.send=r;this.log=o}request=null;timer=null;running=!1;warnedMissingCfg=!1;shippedAttachments=new Set;setRequest(e){let r=this.request?.projectId;this.request=e,this.log.info(`[yt-sync] request updated: project=${e.projectKey} columns=[${e.sourceColumns.join(",")}] sinceMs=${e.sinceMs} offBoard=${e.offBoardIssueIds.length}`),this.timer||this.start(),r&&r!==e.projectId&&this.log.info(`[yt-sync] project switch ${r} \u2192 ${e.projectId}`)}start(){if(this.timer)return;this.log.info(`[yt-sync] poller started (interval=${this.intervalMs}ms)`);let e=()=>{this.tick().catch(r=>this.log.warn(`[yt-sync] tick crashed: ${r instanceof Error?r.message:String(r)}`))};e(),this.timer=setInterval(e,this.intervalMs)}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.log.info("[yt-sync] poller stopped"))}async tickOnce(){await this.tick()}async tick(){if(this.running||!this.request)return;let e=qe();if(!e){this.warnedMissingCfg||(this.warnedMissingCfg=!0,this.log.warn("[yt-sync] YOUTRACK_URL/YOUTRACK_TOKEN missing \u2014 poller idle. set them in cli/.env to enable YT read-sync."));return}this.warnedMissingCfg=!1,this.running=!0;try{await this.pollOnce(this.request,e)}finally{this.running=!1}}async pollOnce(e,r){let o=Date.now(),n;try{let l=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Bi(r,{projectKey:e.projectKey,columns:l,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(l){this.log.warn(`[yt-sync] listIssues failed: ${l instanceof Error?l.message:String(l)}`);return}let i=[],s=new Set;for(let l of n){s.add(l.id);let d=await rs(r,l.id,e.sinceMs,this.log);d&&i.push({issueId:l.id,comments:d})}let a=[];for(let l of e.offBoardIssueIds){if(s.has(l))continue;let d=await rs(r,l,e.sinceMs,this.log);if(d&&i.push({issueId:l,comments:d}),e.requireAssignee){let g=await vu(r,l,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),u={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(u);let p=i.reduce((l,d)=>l+d.comments.length,0),f=c.reduce((l,d)=>l+d.files.length,0);this.log.info(`[yt-sync] observation sent: issues=${n.length} comments=${p} attachments=${f} (sinceMs=${e.sinceMs})`)}async collectAttachments(e,r,o){let n=[];for(let i of e){let s=[...i.attachments??[]],a=r.find(p=>p.issueId===i.id);for(let p of a?.comments??[])s.push(...p.attachments??[]);if(s.length===0)continue;let c=[],u=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let l;try{l=await Di(o,p.url)}catch(g){this.log.warn(`[yt-sync] attachment ${p.name} (${i.id}) download failed: ${g instanceof Error?g.message:String(g)}`);continue}let d=xu(p.name);u.has(d)&&(d=`${p.id}-${d}`),u.add(d),c.push({name:d,contentBase64:l.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function xu(t){let r=(t.split(/[\\/]/).pop()??t).replace(/[^A-Za-z0-9._-]/g,"_").replace(/^\.+/,"");return r.length>0?r.slice(0,120):"attachment"}async function vu(t,e,r){try{return await Gi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function rs(t,e,r,o){try{return await Mi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Ro="npm i -g @code-partner/codepipe@latest";function Pr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ie} (protocol ${de})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&Ln(n.contextDir,r);let i=os("CLI_TRACKING_POLL_INTERVAL_SEC"),s=os("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,u=!1,p=new Set,f=l();function l(){let d=Sr(t.hubUrl,t.cliToken),g=null,w=new Tr(i,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),k=new Ir(s,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r),R=null,v=async()=>{try{let S;try{let y=await se(t.hubUrl,t.cliToken,t.projectId);S={repos:y.repos,contextRepo:y.contextRepo}}catch(y){r.warn(`[readiness] could not fetch project summary for push checks: ${y instanceof Error?y.message:String(y)}`)}let h=await ts(t.projectId,S);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let y=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${y.join(", ")}`)}}catch(S){r.warn(`[readiness] check failed: ${S instanceof Error?S.message:String(S)}`)}},T=()=>{v(),R=setInterval(()=>void v(),a),typeof R.unref=="function"&&R.unref()},j=()=>{R&&(clearInterval(R),R=null)},U=n?.contextDir?new hr(n.contextDir,t.projectId,S=>{d.readyState===d.OPEN&&d.send(JSON.stringify(S))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let S=An(t.projectId),h=_("ORIGIN")==="farm"?"farm":"local",m=_("FARM_ID"),y=t.accountEmail??S.email,$={type:"register",projectId:t.projectId,platformVersion:ie,protocolVersion:de,accountId:S.accountId,accountLabel:S.label,origin:h,inFlightActionIds:[...p],...y?{accountEmail:y}:{},...h==="farm"&&m?{farmId:m}:{}};d.send(JSON.stringify($))}),d.on("message",async S=>{let h=S.toString("utf-8");if(h==="pong"||h==="ping")return;let m;try{m=JSON.parse(h)}catch{return}if(!m||typeof m!="object")return;let y=m.type;if(y==="registered"){let b=m;if(b.ok){if(r.info(`[ws] registered for project ${b.projectId}`),o({kind:"registered",projectId:b.projectId??t.projectId}),w.start(),U?.start(),T(),n?.contextDir){let N=n.contextDir;try{let E=br(N,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(E)),E.outdated&&(r.warn(`[ctx] context format outdated: v${E.templateVersion} \u2192 v${E.currentVersion}`+(E.missingPaths.length>0?` (missing: ${E.missingPaths.join(", ")})`:"")),u||(u=!0,(async()=>{try{let M;try{M=(await se(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let le=await Jn(N,t.projectId,M,r);d.readyState===d.OPEN&&d.send(JSON.stringify(le))}catch(M){r.warn(`[ctx] context migration failed (non-fatal): ${M instanceof Error?M.message:String(M)}`)}})()))}catch(E){r.warn(`[ctx] context-format detect failed (non-fatal): ${E instanceof Error?E.message:String(E)}`)}}}else r.warn(`[ws] register rejected: ${b.reason??"unknown"}`),o({kind:"register_rejected",reason:b.reason??"unknown"}),c=!0,d.close();return}if(y==="hello"){let b=m;g=ar(b.protocolVersion);let N=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${N}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ie}, protocol ${de}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ro}`),o({kind:"incompatible",hubVersion:typeof b.platformVersion=="string"?b.platformVersion:null,hubProtocol:typeof b.protocolVersion=="number"?b.protocolVersion:null,updateCommand:Ro}));return}if(y==="tracking_targets"){w.setTargets(m.targets);return}if(y==="youtrack_sync_request"){k.setRequest(m);return}if(y==="sync_local"){await Cu(m,n,d,r);return}if(y==="context_write"){await Ru(m,n,d,r);return}if(y==="adr_promote"){await Tu(m,n,d,r);return}if(y==="sandbox_keys"){let b=H(t.projectId);if(!b){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let N=it(t.projectId),E=oi(m,b,N,r);for(let M of E)d.readyState===d.OPEN&&d.send(JSON.stringify(M));return}if(y!=="dispatch_action")return;let $=m;if(g===!1){let b=`refused: HUB protocol incompatible with CLI v${ie} (protocol ${de})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:b})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${b}`),r.warn(`[exec] update the CLI to clear this: ${Ro}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:b});return}p.add($.actionId);try{let b=await Fi({action:$.action,repo:$.repo,trackerIssueId:$.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:U?()=>U.reportNow():void 0}).catch(M=>({status:"failed",error:M instanceof Error?M.message:String(M)}));d.send(JSON.stringify({type:"action_result",actionId:$.actionId,...b}));let N=b.status!=="failed",E=!N&&"error"in b?b.error:void 0;N?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${E??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:N,...E?{error:E}:{}})}finally{p.delete($.actionId)}}),d.on("close",(S,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${S}${m?` reason=${m}`:""}`),w.stop(),k.stop(),U?.stop(),j(),m==="replaced"){c=!0,r.warn(`[ws] project ${t.projectId} was taken over by another CLI (HUB closed us as "replaced") \u2014 standing down, not reconnecting. Run exactly ONE CLI per project.`),o({kind:"replaced"});return}o({kind:"disconnected",code:S}),!c&&setTimeout(()=>{f=l()},2e3)}),d.on("error",S=>r.warn(`[ws] error: ${S.message}`)),d}return{stop(){c=!0,f.close()}}}async function Cu(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(u=>u.name===n.repoName),s=Su(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await _n(s,a).catch(u=>({status:"warn",reason:u instanceof Error?u.message:String(u)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function Ru(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[ctx] context_write ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{await yr(e.contextDir,t.files,t.message),o.info(`[ctx] context_write ${t.id}: committed ${t.files.length} file(s)`),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[ctx] context_write ${t.id} failed: ${s}`),n("failed",s)}}async function Tu(t,e,r,o){let n=(i,s)=>{if(r.readyState!==r.OPEN)return;let a={type:"context_write_result",id:t.id,status:i};s&&(a.error=s),r.send(JSON.stringify(a))};if(!e?.contextDir){o.warn(`[adr] adr_promote ${t.id} \u2014 no .codepipe clone (headless), reporting failed`),n("failed","no context repo clone on this CLI");return}try{let i=await Fn(e.contextDir,t.taskKey,t.drafts);o.info(`[adr] adr_promote ${t.id}: promoted ${i.promoted.length}, skipped ${i.skipped.length}`+(i.promoted.length>0?` (${i.promoted.join(", ")})`:"")),n("done")}catch(i){let s=i instanceof Error?i.message:String(i);o.warn(`[adr] adr_promote ${t.id} failed: ${s}`),n("failed",s)}}function os(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as us,mkdirSync as ps}from"node:fs";import{dirname as ds}from"node:path";import{simpleGit as Ve}from"simple-git";import{execFileSync as Iu}from"node:child_process";import{mkdtempSync as Pu,mkdirSync as Eu,readFileSync as ns,rmSync as ju,writeFileSync as Au}from"node:fs";import{tmpdir as _u}from"node:os";import{dirname as Ou,join as is}from"node:path";function ss(t="codepipe-context"){let e=Pu(is(_u(),"codepipe-ssh-")),r=is(e,"id_ed25519");try{return Iu("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:ns(r,"utf-8"),publicKey:ns(`${r}.pub`,"utf-8").trim()}}finally{ju(e,{recursive:!0,force:!0})}}async function as(t,e,r,o="codepipe-context"){let n=await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/keys`,{method:"POST",headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:o,key:r,read_only:!1})});if(n.ok)return;let i=await n.text();if(!(n.status===422&&/already in use/i.test(i)))throw new Error(`add deploy key failed: ${n.status} ${i}`)}function cs(t){if(/^git@[^:]+:.+/.test(t))return t;let e=t.match(/^ssh:\/\/git@([^/]+)\/(.+)$/);if(e)return`git@${e[1]}:${e[2]}`;let r=t.match(/^https:\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/);return r?`git@${r[1]}:${r[2]}`:t}function ls(t,e){Eu(Ou(t),{recursive:!0});let r=e.endsWith(`
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===Nt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Nt.bitbucket?e?.bitbucket?.apiToken?{user:ot,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function fs(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await se(e.hubUrl,e.cliToken,e.projectId)}catch(c){return n.warn(`[ctx] could not fetch project summary: ${c instanceof Error?c.message:String(c)}`),null}let s=i.contextRepo;if(!s)return n.warn("[ctx] project has no Context Repo on HUB \u2014 daemon stays headless (no config report)"),null;let a=Uu(rt(s.cloneUrl),r);if(a){let c=await Lu({ctx:s,contextDir:o,cred:a,log:n});if(c)return c;n.warn("[ctx] token clone/update failed")}if(r?.contextSsh?.privateKey){let c=await Du({ctx:s,contextDir:o,privateKey:r.contextSsh.privateKey,log:n});if(c)return c;n.warn("[ctx] SSH deploy-key clone failed")}return n.warn("[ctx] no usable context-host/contextWrite token or SSH deploy key \u2014 can't clone the Context Repo on the farm; config_observation + artifact commits disabled."),null}async function Lu(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Nu(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=u=>u.split(o.secret).join("***").split(a).join("***");try{if(us(`${r}/.git`)){let p=Ve(r);await p.remote(["set-url","origin",i]),await p.fetch("origin",s),await p.checkout(s);let f=lo(r);await p.reset(["--hard",`origin/${s}`]),uo(r,f),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else ps(ds(r),{recursive:!0}),await Ve().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);let u=Ve(r);await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local")}catch(u){return n.warn(`[ctx] Context Repo clone/update failed: ${c(u instanceof Error?u.message:String(u))}`),null}return{root:r,contextDir:r,repos:[]}}async function Du(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=ls(i,o),a=cs(e.cloneUrl),c=e.branch;try{if(us(`${r}/.git`)){let p=Ve(r);await p.addConfig("core.sshCommand",s,!1,"local"),await p.remote(["set-url","origin",a]),await p.fetch("origin",c),await p.checkout(c);let f=lo(r);await p.reset(["--hard",`origin/${c}`]),uo(r,f),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else ps(ds(r),{recursive:!0}),await Ve().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await Ve(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);let u=Ve(r);return await u.addConfig("user.email","farm@codepipe.local",!1,"local"),await u.addConfig("user.name","CodePipe Farm CLI",!1,"local"),{root:r,contextDir:r,repos:[]}}catch(u){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${u instanceof Error?u.message:String(u)}`),null}}import{existsSync as Er,readFileSync as ms,writeFileSync as Bu}from"node:fs";import{dirname as Gu,join as Ee}from"node:path";import{parse as Mu}from"yaml";var je=".codepipe",To=".devpipe";function Hu(t=process.cwd()){let e=t;for(;;){if(Er(Ee(e,je,"project.yaml")))return e;if(Er(Ee(e,To,"project.yaml")))return He(Ee(e,To),Ee(e,je))&&Ku(e),e;let r=Gu(e);if(r===e)return null;e=r}}function Fu(t){let e=Ee(t,je);return Er(e)?e:Ee(t,To)}function Ku(t){let e=Ee(t,".gitignore");if(!Er(e))return;let r=ms(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
427
+ `);o!==r&&Bu(e,o)}function Mt(t=process.cwd()){let e=Hu(t);if(!e)return null;let r=Fu(e),o=Wu(ms(Ee(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function gs(t,e=process.cwd()){try{let r=Mt(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function Wu(t){let e=Mu(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),u=String(a.name??c);if(!u||!c)continue;let p=a.host,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:u,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??u)})}return{projectId:r,name:o,repos:i}}function hs(t){return t.host==="github"?`git@github.com:${t.owner}/${t.repoName}.git`:t.host==="gitlab"?`git@gitlab.com:${t.owner}/${t.repoName}.git`:`git@bitbucket.org:${t.owner}/${t.repoName}.git`}function jr(t,e=process.env){if(!t)return!1;let r=`https://x-access-token:${t}@github.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@github.com:"),n(1,"ssh://git@github.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Ar(t,e=process.env){if(!t)return!1;let r=`https://oauth2:${t}@gitlab.com/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@gitlab.com:"),n(1,"ssh://git@gitlab.com/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function _r(t,e=process.env){if(!t)return!1;let r=`https://${ot}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}async function ws(t={profile:void 0}){let e=fe(t.profile),r=H(e.projectId);r&&Ut(r),jr(r?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Ar(r?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),_r(r?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let o=Ht(Io(),".codepipe","logs"),n=t.profile?`cli-daemon-${t.profile}`:"cli-daemon",i=mr("CLI_LOG",n,o);if(i.enabled){let f=new at(i);gr(f),console.log(`[log] file logging \u2192 ${f.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let s=null,a=gs(e.projectId);if(a&&(s={root:a.root,contextDir:a.contextDir,repos:a.spec.repos},console.log(`[ctx] workspace found at ${a.root} \u2014 using its Context Repo clone`)),!s){let f=Ht(Io(),".codepipe",t.profile?Ht("profiles",t.profile,"context"):"context");if(s=await fs({cfg:e,secrets:r,contextDir:f,log:{info:l=>console.log(l),warn:l=>console.warn(l)}}),s?.contextDir){let l=Ht(Io(),".codepipe",t.profile?Ht("profiles",t.profile,"context-config"):"context-config");Un(s.contextDir,l,{info:d=>console.log(d),warn:d=>console.warn(d)})}}let c=Pr(e,{...s?{workspace:s}:{},onEvent:f=>{f.kind==="replaced"&&(console.error(`[daemon] project ${e.projectId} is now served by another CLI \u2014 exiting. Run exactly one CLI per project.`),process.exit(0))}}),u=!1;function p(f){u||(u=!0,console.log(`
428
+ [${f}] shutting down`),c.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),await new Promise(()=>{})}import{hostname as Qu}from"node:os";import{spawnSync as qu}from"node:child_process";function Yu(){try{return qu("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function ys(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:Yu(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as yt}from"node:os";import{mkdirSync as Vu,readFileSync as bs,writeFileSync as zu,existsSync as Po}from"node:fs";import{dirname as Ju,join as Ae}from"node:path";Po(".env")&&process.loadEnvFile(".env");function _e(t){let e=_("SANDBOX_CONFIG");if(e)return e;let r=Ae(yt(),".codepipe","worker");return t?Ae(r,"profiles",t,"config.json"):Ae(r,"config.json")}function ks(){return Ae(yt(),".devpipe-sandbox","config.json")}function Or(){He(Ae(yt(),".devpipe"),Ae(yt(),".codepipe")),_("SANDBOX_CONFIG")||He(Ae(yt(),".devpipe-sandbox"),Ae(yt(),".codepipe-sandbox"))}function te(t){let e=_e(t);return Po(e)?JSON.parse(bs(e,"utf-8")):!t&&!_("SANDBOX_CONFIG")&&Po(ks())?JSON.parse(bs(ks(),"utf-8")):null}function $s(t,e){let r=_e(e);Vu(Ju(r),{recursive:!0}),zu(r,JSON.stringify(t,null,2)+`
429
+ `,{mode:384})}import Xu from"ws";var bt=class{hubUrl;token;constructor(e,r){this.hubUrl=e,this.token=r}async register(e){let r=await fetch(`${this.hubUrl}/sandbox/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`register failed: ${r.status} ${await r.text()}`);return await r.json()}async claim(e){if(!this.token)throw new Error("no sandbox token");let r={method:"POST",headers:{Authorization:`Bearer ${this.token}`}};return e&&(r.signal=e),fetch(`${this.hubUrl}/jobs/claim`,r)}async submitResult(e){if(!this.token)throw new Error("no sandbox token");let r=await fetch(`${this.hubUrl}/jobs/result`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(e)});if(!r.ok)throw new Error(`submitResult failed: ${r.status} ${await r.text()}`)}async heartbeat(e,r){if(!this.token)throw new Error("no sandbox token");let o={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e})};r&&(o.signal=r);let n=await fetch(`${this.hubUrl}/jobs/heartbeat`,o);if(n.status===410)return"claim_lost";if(!n.ok)throw new Error(`heartbeat failed: ${n.status} ${await n.text()}`);return"ok"}async releaseJob(e,r,o){if(!this.token)throw new Error("no sandbox token");let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({jobId:e,reason:r})};o&&(n.signal=o);let i=await fetch(`${this.hubUrl}/jobs/release`,n);if(!i.ok&&i.status!==409&&i.status!==404)throw new Error(`release failed: ${i.status} ${await i.text()}`)}openControlSocket(){if(!this.token)throw new Error("no sandbox token");let e=this.hubUrl.replace(/^http/,"ws")+`/sandbox/connect?token=${encodeURIComponent(this.token)}`;return new Xu(e)}};async function ze(t){Or();let e=te(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${_e(t.profile)}.`),process.exit(1));let r=t.name??Qu(),o=ys({projects:t.projects??[],llm:t.llm??null}),n=new bt(t.hub.replace(/\/$/,"")),i=ti(),s=mt(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});$s({hubUrl:t.hub.replace(/\/$/,""),sandboxId:a,token:c,name:r,llm:t.llm??null,sealPublicKey:i.publicKey,sealPrivateKey:i.privateKey},t.profile),console.log(`registered as ${a} (${r}) at ${t.hub}`),console.log(`config saved to ${_e(t.profile)}`),console.log(""),console.log(" cred-channel key fingerprint (confirm this on the CLI \u2014 pin-on-register):"),console.log(` ${s}`),console.log("")}import{mkdirSync as Dp,readFileSync as ta,readdirSync as Bp,writeFileSync as Gp}from"node:fs";import{dirname as Mp,join as Kr,resolve as Hp}from"node:path";import{spawn as Zu}from"node:child_process";import{existsSync as ep}from"node:fs";var kt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Nr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},tp=5e3,Ft=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Nr;let r=["-p",e.prompt,"--output-format","stream-json","--verbose","--dangerously-skip-permissions"];e.model&&e.model.trim().length>0&&r.push("--model",e.model.trim());for(let g of e.addDirs??[])r.push("--add-dir",g);let o=[],n=[],i=null,s={input:0,output:0,cacheRead:0,cacheCreate:0},a=0,c="",u=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let w=ip(g.rate_limit_info);w&&(!u||w.utilization>u.utilization)&&(u=w);return}if(g.type==="assistant"){let w=g.message;typeof w?.model=="string"&&(c=w.model);let k=w?.usage;k&&(a+=1,s.input+=re(k.input_tokens),s.output+=re(k.output_tokens),s.cacheRead+=re(k.cache_read_input_tokens),s.cacheCreate+=re(k.cache_creation_input_tokens))}}},f=e.role,l=e.onActivity,d=g=>{if(l)for(let w of ap(g,e.workspaceDir))try{l(w)}catch{}};return l?.({ts:Date.now(),kind:"start",text:`${f} job started`}),console.log(`[claude] spawn ${this.binary} role=${f}`+(e.model?` model=${e.model}`:"")+` cwd=${e.workspaceDir}`+(e.addDirs?.length?` add-dir=${e.addDirs.length}`:"")),new Promise((g,w)=>{let k=Zu(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});k.stdout.setEncoding("utf-8"),k.stderr.setEncoding("utf-8");let R=!1,v=null,T=()=>{R=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),k.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),k.kill("SIGKILL")},tp)};e.signal?.addEventListener("abort",T,{once:!0});let j=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",T)},U="";k.stdout.on("data",S=>{o.push(S),U+=S;let h;for(;(h=U.indexOf(`
430
+ `))!==-1;){let m=U.slice(0,h).trim();if(U=U.slice(h+1),m){let y=xs(m);p(y),y&&d(y)}}}),k.stderr.on("data",S=>{o.push(S),n.push(S);for(let h of S.split(`
431
+ `)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),k.on("error",S=>{j(),w(S)}),k.on("close",S=>{if(j(),R){w(new Nr);return}if(U.trim()){let m=xs(U.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(S!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,y=typeof i?.subtype=="string"?i.subtype:void 0,$=typeof i?.result=="string"?i.result:void 0;w(new kt(rp(S,i,n.join("")),{code:S,apiErrorStatus:m,subtype:y,resultText:$,retryAfterMs:op(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:sp(i,s,a,c),...u?{rateLimit:u}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&ep(o))}};function xs(t){let e;try{e=JSON.parse(t)}catch{return console.log(`[claude] ${t.slice(0,200)}`),null}let r=e.type;if(r==="system"){let o=e.subtype??"";return console.log(`[claude] system ${o}`),e}if(r==="assistant"){let o=e.message;for(let n of o?.content??[]){let i=n.type;if(i==="text"){let s=String(n.text??"").trim();s&&console.log(`[claude] text: ${Oe(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=np(s,a);console.log(`[claude] tool_use ${s}${c?` ${c}`:""}`)}}return e}if(r==="user"){let o=e.message;for(let n of o?.content??[])if(n.type==="tool_result")if(n.is_error===!0){let i=Ss(n.content);console.log(`[claude] tool_result (error)${i?`: ${Oe(i,200)}`:""}`)}else console.log("[claude] tool_result");return e}if(r==="result"){let o=e.subtype??"",n=e.num_turns,i=e.total_cost_usd;return console.log(`[claude] result ${o} turns=${n} cost=$${i}`),e}return console.log(`[claude] ${String(r)} ${Oe(JSON.stringify(e),200)}`),e}function rp(t,e,r){let o=t===0?["claude reported an error"]:[`claude exited with code ${t}`];if(e){let n=typeof e.result=="string"?e.result.trim():"",i=e.api_error_status,s=e.subtype;n?o.push(Oe(n,500)):typeof s=="string"&&s!=="success"&&o.push(s),typeof i=="number"&&o.push(`(api_status=${i})`)}return o.length===1&&r.trim()&&o.push(Oe(r.trim().split(`
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 Ss(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function np(t,e){if(!e)return"";if(t==="Write"||t==="Edit"||t==="Read"){let r=e.file_path??e.path;if(typeof r=="string")return`path=${r}`}if(t==="Bash"){let r=e.command;if(typeof r=="string")return`cmd=${Oe(r,80)}`}return""}function Oe(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ip(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=re(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:re(e.resetsAt),rateLimitType:typeof e.rateLimitType=="string"?e.rateLimitType:"",utilization:o,isUsingOverage:e.isUsingOverage===!0};return typeof e.surpassedThreshold=="number"&&(n.surpassedThreshold=e.surpassedThreshold),n}function sp(t,e,r,o){let n=lr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=re(i.input_tokens),n.outputTokens=re(i.output_tokens),n.cacheReadInputTokens=re(i.cache_read_input_tokens),n.cacheCreationInputTokens=re(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=re(t?.total_cost_usd),n.numTurns=t&&re(t.num_turns)>0?re(t.num_turns):r,n.durationMs=re(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var vs=200;function ap(t,e){let r=Date.now(),o=t.type;if(o==="system"){let n=String(t.subtype??"").trim();return n?[{ts:r,kind:"system",text:n}]:[]}if(o==="assistant"){let n=t.message,i=[];for(let s of n?.content??[]){let a=s.type;if(a==="text"){let c=String(s.text??"").trim();c&&i.push({ts:r,kind:"text",text:Oe(c,vs)})}else if(a==="tool_use"){let c=String(s.name??""),u=s.input,p=u?.file_path??u?.path??u?.notebook_path,f=cp(p,e);i.push({ts:r,kind:"tool",tool:c,...f?{file:f}:{}})}}return i}if(o==="user"){let n=t.message,i=[];for(let s of n?.content??[])if(s.type==="tool_result"){let a=s.is_error===!0,c=a?Oe(Ss(s.content),vs):"";i.push({ts:r,kind:"tool_result",isError:a,...c?{text:c}:{}})}return i}if(o==="result"){let n=String(t.subtype??"").trim(),i=typeof t.num_turns=="number"?t.num_turns:void 0,s=typeof t.total_cost_usd=="number"?t.total_cost_usd:void 0;return[{ts:r,kind:"result",...n?{text:n}:{},...i!==void 0?{turns:i}:{},...s!==void 0?{costUsd:s}:{}}]}return[]}function cp(t,e){if(!(typeof t!="string"||!t))return t.startsWith(e)?t.slice(e.length).replace(/^\/+/,"")||t.split("/").pop()||void 0:t.startsWith("/")?t.split("/").pop()||void 0:t}import{mkdirSync as lp,writeFileSync as Kt}from"node:fs";import{dirname as up,join as Wt}from"node:path";function Cs(t,e,r){let o=Wt(t,e);lp(up(o),{recursive:!0}),Kt(o,r)}var qt=class{name(){return"mock"}async run(e){let r=e.metadata??{},o=r.trackerIssueKey??"TASK",n=r.taskTitle??"(unknown task)",i=r.taskDescription??"",s=[];if(e.role==="estimate"){let a=pp(o,n,i);Kt(Wt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Kt(Wt(e.workspaceDir,"SOLUTION.md"),dp(o,n,i,a)),s.push("SOLUTION.md"),Kt(Wt(e.workspaceDir,"QUESTIONS.md"),fp(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Cs(e.workspaceDir,"changes/sample.patch",mp(o,n,a)),s.push("changes/sample.patch"),Cs(e.workspaceDir,"diff-summary.md",gp(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Kt(Wt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
434
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:lr()}}};function pp(t,e,r){return`# ${t} \u2014 Estimate
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,77 @@ ${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 Rs(t){switch(t){case"mock":return new qt;case"claude-headless":return new Ft;default:return null}}function Ps(t=process.env){return{maxAttempts:Ur(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Ur(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Ur(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Ur(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var hp=new Set([429,500,502,503,529]),Ts=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,wp=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,yp=new Set(["error_max_turns"]);function bp(t){if(t instanceof kt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return wp.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&yp.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:hp.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:Ts.test(s)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:o??`exit ${t.details.code}`}}let e=t instanceof Error?t.message:String(t);return Ts.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var Is=/(not logged in|invalid api key|invalid x-api-key|authentication[ _]error|unauthorized|oauth token (?:expired|revoked|invalid)|token (?:expired|revoked)|please run .{0,20}login|run `?claude\b.{0,20}(?:login|setup-token))/i;function Es(t){if(t instanceof kt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&Is.test(o)}let e=t instanceof Error?t.message:String(t);return Is.test(e)}function kp(t,e,r){if(typeof r=="number"&&r>0)return Math.min(r,e.maxDelayMs);let o=e.baseDelayMs*2**(t-1),n=Math.min(o,e.maxDelayMs);return Math.round(n/2+Math.random()*(n/2))}async function js(t,e,r){let o=r.sleep??(s=>new Promise(a=>setTimeout(a,s))),n=Date.now()+r.policy.totalBudgetMs,i="";for(let s=1;;s++)try{return await t.run(e)}catch(a){i=a instanceof Error?a.message:String(a);let c=bp(a),u=s>=r.policy.maxAttempts;if(!c.retryable||u||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=kp(s,r.policy,c.retryAfterMs);if(Date.now()+p>n)throw new Error(`agent failed after ${s} attempts (retry budget exhausted): ${i}`);console.warn(`[job] ${r.jobId} agent attempt ${s}/${r.policy.maxAttempts} failed (retryable: ${c.reason}) \u2014 cleaning workspace, backoff ${p}ms`),await r.onBeforeRetry(),await o(p)}}function Ur(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as $p,rmSync as xp,writeFileSync as As}from"node:fs";import{tmpdir as vp}from"node:os";import{join as Eo}from"node:path";function Lr(t){return`[url "https://${t}/"]
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 _s(t,e){if(t.length===0)return null;let r=$p(Eo(vp(),"devpipe-gitcreds-")),o=Eo(r,"credentials"),n=Eo(r,"gitconfig");return As(o,t.join(`
512
513
  `)+`
513
- `,{mode:384}),Ps(n,`[credential]
514
+ `,{mode:384}),As(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 jo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(Sp)),t.bitbucket?.apiToken&&(e.push(`https://${ot}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(Cp)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(Rp)),_s(e,r)}function Os(t,e){if(t.contextWrite?.token){let r=rt(e)??"github.com",o=ur(r);return _s([`https://${o}:${t.contextWrite.token}@${r}`],[Lr(r)])}return jo(t)}import{spawn as Us}from"node:child_process";import{existsSync as Dr,mkdirSync as Br,readFileSync as Tp,rmSync as Ao,symlinkSync as Ip}from"node:fs";import{homedir as Pp}from"node:os";import{dirname as Gr,join as Je}from"node:path";function Ls(){return Je(Pp(),".codepipe-sandbox","repos")}function Ns(t){let e=t instanceof Error?t.message:String(t);return/couldn't find remote ref/i.test(e)||/Remote branch .* not found/i.test(e)||/unknown revision/i.test(e)}async function Ds(t,e,r,o,n){if(Dr(Je(t,".git"))){let i=async s=>{await Y(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await Y(t,["reset","--hard",`origin/${s}`],n),await Y(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!Ns(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Dr(t)&&Ao(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0});try{return await Y(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!Ns(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Dr(t)&&Ao(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0}),await Y(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function Bs(t){await Y(t.workspacePath,["reset","--hard",t.baseSha]),await Y(t.workspacePath,["clean","-fdx"])}var Mr="CodePipe Agent",Hr="codepipe@codepartner.ee";async function Gs(t,e){let r=t.workspacePath;await Y(r,["add","-A"]);let o=(await he(r,["write-tree"])).trim(),n=(await he(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Mr,GIT_AUTHOR_EMAIL:Hr,GIT_COMMITTER_NAME:Mr,GIT_COMMITTER_EMAIL:Hr};return(await he(r,["commit-tree",o,"-m",e],i)).trim()}async function Ms(t,e,r,o,n){try{await Y(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw rt(o)==="github.com"&&/without `?workflow`? scope|workflow.*scope/i.test(s)?new Error("delivery push rejected: the Context-Repo push token needs the `workflow` scope (the delivery includes .github/workflows/*). Set secrets.contextWrite.token to a fine-grained PAT on the Context Repo with Contents: write + Workflows: write (or add `workflow` to the project token).\n"+s):i}}async function Hs(t,e){return he(t.workspacePath,["diff","--binary",t.baseSha,e])}async function Fs(t,e,r,o,n){await Y(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await Y(t.workspacePath,["checkout","--force",r])}async function _o(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Mr,GIT_AUTHOR_EMAIL:Hr,GIT_COMMITTER_NAME:Mr,GIT_COMMITTER_EMAIL:Hr};(await he(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await Y(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(u=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(u)}`)}),await Y(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await Y(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(u){s=u instanceof Error?u.message:String(u)}let a=(await he(o,["diff","--name-only","--diff-filter=U"])).split(`
517
+ `).map(u=>u.trim()).filter(u=>u.length>0),c=await he(o,["rev-parse","-q","--verify","MERGE_HEAD"]).then(()=>!0).catch(()=>!1);if(s&&!c&&a.length===0)throw new Error(`resolve-conflict: merge of ${e} into ${t.ref} failed: ${s}`);return a}function Y(t,e,r){return new Promise((o,n)=>{let i=Us("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",n),i.on("close",a=>{if(a===0)return o();n(new Error(`git ${e[0]} failed (exit ${a}):
518
+ ${s.join("").trim()||"(no stderr)"}`))})})}function he(t,e,r){return new Promise((o,n)=>{let i=Us("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",n),i.on("close",c=>{if(c===0)return o(s.join(""));n(new Error(`git ${e[0]} failed (exit ${c}):
519
+ ${a.join("").trim()||"(no stderr)"}`))})})}function Ks(t,e){Dr(t)&&Ao(t,{recursive:!0,force:!0}),Br(Gr(t),{recursive:!0}),Ip(e,t,"dir")}async function Ws(t,e,r){await Y(t,["worktree","prune"]).catch(()=>{}),Br(Gr(r),{recursive:!0}),await Y(t,["worktree","add","--detach",r,`origin/${e}`])}async function qs(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=Je(Ls(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await Ds(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let u=(await he(a,["rev-parse","HEAD"])).trim(),p=Je(t,"code",s.name);o==="direct"?(Ks(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${u.slice(0,10)}`)):(await Ws(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${u.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:u})}return i}async function Ys(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=Je(Ls(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await Ds(i,r.cloneUrl,r.ref,void 0,n)}catch(c){throw new Error(`failed to materialize context repo (${r.cloneUrl}): `+(c instanceof Error?c.message:String(c)))}let s=Je(t,"context");o==="direct"?(Ks(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await Ws(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await he(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function Vs(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await Y(r,["add","-A",...o]).catch(()=>{});let n;try{n=await he(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
520
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=Tp(Je(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as Ep}from"node:fs";import{join as jp}from"node:path";var Oo=8*1024,$t=class extends Error{},Yt="meta/build-result.json";function zs(t){let e=jp(t,Yt),r;try{r=Ep(e,"utf-8")}catch{throw new $t(`BUILD produced no ${Yt} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new $t(`${Yt} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new $t(`${Yt} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new $t(`${Yt}: "ok" must be a boolean`);let i=n.ok,a=(Array.isArray(n.steps)?n.steps:[]).flatMap(p=>{if(!p||typeof p!="object")return[];let f=p,l=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(l===null||d===null)return[];let g={name:l,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?Ap(n.logTail):"",u={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)u.failedStep=n.failedStep;else if(!i){let p=a.find(f=>f.exitCode!==0);p&&(u.failedStep=p.name)}return u}function Ap(t){let e=Buffer.from(t,"utf-8");return e.length<=Oo?t:`\u2026 [${e.length-Oo} bytes elided] \u2026
521
+ `+e.subarray(e.length-Oo).toString("utf-8")}import{lstatSync as _p,mkdtempSync as Op,readFileSync as Np,readdirSync as Xs,rmSync as Js}from"node:fs";import{tmpdir as Up}from"node:os";import{join as Fr,relative as Lp}from"node:path";var Qs=new Set(["code","context"]);function Zs(t){let e=Op(Fr(Up(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Js(e,{recursive:!0,force:!0}),listFiles:()=>ea(e,e),readFile:r=>Np(Fr(e,r),"utf-8"),clean:()=>{for(let r of Xs(e))Qs.has(r)||Js(Fr(e,r),{recursive:!0,force:!0})}}}function ea(t,e){let r=[];for(let o of Xs(e)){let n=Fr(e,o),i=_p(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Qs.has(o))continue;r.push(...ea(t,n))}else r.push(Lp(t,n))}return r}var Wr=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Fp=new Set(["implement","resolve-conflict"]);function Kp(t){let e=Buffer.from(t,"utf-8");if(e.length<=Wr)return t;let r=Math.floor(Wr/4),o=Wr-r,n=e.subarray(0,r).toString("utf-8"),i=e.subarray(e.length-o).toString("utf-8"),s=e.length-r-o;return`${n}
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 Vt(t={}){Or();let e=te(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=mr("SANDBOX_LOG","sandbox",Hp("./logs"));if(o.enabled){let h=new at(o);gr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${ie} (protocol ${de})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Rs(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=Ps();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new bt(e.hubUrl,e.token),a=!1,c=new AbortController,u=null,p=null,f=!1,l=null,d=null,g=!1,w=()=>{let h=s.openControlSocket();return l=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ie,protocolVersion:de};h.send(JSON.stringify(m))}),h.on("message",m=>{let y=m.toString("utf-8"),$=null;try{let b=JSON.parse(y);b&&typeof b=="object"&&($=b)}catch{}if($&&$.type==="hello"){let b=$;d=ar(b.protocolVersion);let N=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${b.platformVersion} (protocol ${b.protocolVersion}) \u2014 ${N}`),d&&(g=!1);return}if($&&$.type==="pause_job"){let b=typeof $.jobId=="string"?$.jobId:"";b&&b===u?(console.warn(`[ws] pause_job ${b} \u2014 aborting agent`),f=!0,p?.abort()):console.log(`[ws] pause_job ${b} \u2014 not the active job, ignoring`),b&&h.send(JSON.stringify({type:"job_paused",jobId:b}));return}console.log(`[ws] ${y}`)}),h.on("close",(m,y)=>{console.log(`[ws] closed code=${m} reason=${y?.toString()||""}`),l===h&&(l=null),!a&&setTimeout(w,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},k=w(),R=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ie}, protocol ${de}) \u2014 not claiming jobs until versions align.`),g=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await s.claim(c.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 sandbox token rejected. exiting."),a=!0;break}if(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3));continue}let m=await h.json();await v(s,m)}catch(h){if(c.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(y=>setTimeout(y,5e3))}}};async function v(h,m){u=m.jobId,p=new AbortController,f=!1;let y=!1,$=null,b=null,N=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),E=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(y=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(L){let ue=L instanceof Error?L.message:String(L);console.warn(`[job] ${m.jobId} heartbeat error: ${ue}`)}};E();let M=setInterval(()=>{E()},N),le=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(j(m.prompt," \u2502 "));let we=[],C=null,ne=400,ve=25,De=500,At=()=>{if(C&&(clearTimeout(C),C=null),we.length===0)return;let L=we.splice(0,we.length),ue=l;if(!ue||ue.readyState!==ue.OPEN)return;let Se={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:L};try{ue.send(JSON.stringify(Se))}catch{}},et=L=>{we.push(L),we.length>De&&we.shift(),we.length>=ve?At():C||(C=setTimeout(At,ne))},z=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Qr=new Set,Zr=null;try{if(!n){y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:le,finishedAt:new Date().toISOString()});return}let L=Zs(m.jobId);console.log(`[job] ${m.jobId} workspace=${L.dir}`);let ue=T(m,r);$=ue.gitCreds,b=ue.contextGitCreds;let Se=$?.env,Qo=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,Ce=[],sr=null,eo=null;try{let I="worktree";Ce=await qs(L.dir,m.projectId,m.projectRepos,I,Se);let P=await Ys(L.dir,m.projectId,m.contextRepo,I,Se);eo=P,sr=P?.workspacePath??null}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} materialize failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let Zo=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let I=m.contextRepo?.cloneUrl;if(!I||!Se)throw new Error(I?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let P of m.deliveries){let G=Ce.find(oe=>oe.name===P.name);G&&(await Fs(G,P.deliveryRef,P.deliverySha,I,Se),console.log(`[job] ${m.jobId} ${G.name}: checked out delivery ${P.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await Zo()}catch(I){let P=I instanceof Error?I.message:String(I);console.warn(`[job] ${m.jobId} delivery checkout failed: ${P}`),y||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${P}`},startedAt:le,finishedAt:new Date().toISOString()}),L.dispose();return}let en=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},tn="";if(m.role==="resolve-conflict")try{let I=[];for(let P of Ce){let G=en[P.name];if(!G)continue;let oe=await _o(P,G,Se);console.log(`[job] ${m.jobId} ${P.name}: merged ${G} into ${P.ref} \u2014 ${oe.length} conflicted file(s)`),oe.length>0?I.push(`- **${P.name}**:`,...oe.map(tt=>` - \`${tt}\``)):I.push(`- **${P.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}tn=`
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:le,finishedAt:new Date().toISOString()}),L.dispose();return}let yc=U(m.prompt,Ce,sr)+tn,to=[...Ce.map(I=>I.workspacePath),...sr?[sr]:[]];to.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${to.join(", ")}`),z&&(Zr=setInterval(()=>{let P=l;if(!P||P.readyState!==P.OPEN)return;let G;try{G=Bp(Kr(L.dir,"drafts")).filter(oe=>oe.endsWith(".json")).sort()}catch{return}for(let oe of G){if(Qr.has(oe))continue;if(Qr.size>=un)break;let tt;try{let Q=JSON.parse(ta(Kr(L.dir,"drafts",oe),"utf-8")),O=typeof Q.localRef=="string"?Q.localRef:"",q=typeof Q.title=="string"?Q.title:"",Be=typeof Q.body=="string"?Q.body:"";if(!O||!q)continue;tt={localRef:O,title:q,body:Be,...Q.isEpic===!0?{isEpic:!0}:{},...Array.isArray(Q.links)?{links:Q.links}:{}}}catch{continue}Qr.add(oe);let _t={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:z,child:tt};try{P.send(JSON.stringify(_t))}catch{}}},1500));try{let I=await js(n,{workspaceDir:L.dir,role:m.role,prompt:yc,addDirs:to,metadata:m.metadata??{},...m.model?{model:m.model}:{},...Qo?{env:Qo}:{},signal:p.signal,onActivity:et},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{L.clean();for(let O of Ce)try{await Bs(O);let q=en[O.name];m.role==="resolve-conflict"&&q&&await _o(O,q,Se)}catch(q){let Be=q instanceof Error?q.message:String(q);console.warn(`[job] ${m.jobId} worktree reset failed (${O.name}): ${Be}`)}try{await Zo()}catch(O){let q=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${q}`)}},aborted:()=>y||f}),P=[];if(Fp.has(m.role)&&Ce.length>0){let O=m.metadata??{},q=typeof O.commitMessage=="string"?O.commitMessage:`${m.taskId}: changes`,Be=m.contextRepo?.cloneUrl,rn=b?.env;if(!Be||!rn)throw new Error("delivery requested but "+(Be?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let bc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let ye of Ce){let Ot=await Gs(ye,q);if(!Ot){console.log(`[job] ${m.jobId} ${ye.name}: no changes \u2014 no delivery`);continue}let ro=`codepipe/deliveries/${bc}/${m.jobId}/${ye.name}`;await Ms(ye,Ot,ro,Be,rn),P.push({name:ye.name,deliveryRef:ro,deliverySha:Ot,baseSha:ye.baseSha}),console.log(`[job] ${m.jobId} ${ye.name}: delivered ${Ot.slice(0,10)} \u2192 ${ro}`);let on=await Hs(ye,Ot);if(on.trim().length>0){let kc=Kr("display",`${ye.name}.diff`),nn=Kr(L.dir,kc);Dp(Mp(nn),{recursive:!0}),Gp(nn,on)}}}if(m.role==="resolve-conflict"&&P.length===0)throw new Error("resolve-conflict produced no delivery \u2014 nothing changed, so the PR would not update. The conflict was not actually resolved. Check the agent's diff-summary.md, and confirm this SANDBOX runs a build with resolve-conflict support (the conflict merge must have run).");let G;m.role==="build"&&(G=zs(L.dir),console.log(`[job] ${m.jobId} build verdict: ok=${G.ok}`+(G.failedStep?` failedStep=${G.failedStep}`:"")));let oe=I.artifactPaths.length>0?I.artifactPaths:L.listFiles(),tt=Array.from(new Set(oe)),_t;if(eo)try{let O=await Vs(eo,m.role==="index"?["adr/SOURCES.md"]:[]);O.length>0&&(_t=O,console.log(`[job] ${m.jobId} captured ${O.length} knowledge file(s) for Context Repo`))}catch(O){let q=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${q}`)}let Q={jobId:m.jobId,status:"succeeded",artifacts:tt.map(O=>({path:O,contentBase64:ta(`${L.dir}/${O}`).toString("base64")})),..._t?{contextWrites:_t}:{},...P.length>0?{deliveries:P}:{},log:Kp(I.log),startedAt:le,finishedAt:new Date().toISOString(),usage:I.usage,...I.rateLimit?{rateLimit:I.rateLimit}:{},...G?{build:G}:{}};if(y||f)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${f?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(Q),console.log(`[job] ${m.jobId} done \u2014 uploaded ${Q.artifacts.length} artifact(s):`);for(let O of Q.artifacts){let q=Buffer.from(O.contentBase64,"base64").length;console.log(` \xB7 ${O.path} (${q} bytes)`)}Q.artifacts.length===0&&console.warn(`[job] ${m.jobId} produced 0 artifacts \u2014 workspace was empty after runner exit. Task will likely get stuck downstream.`)}}catch(I){let P=I instanceof Error?I.message:String(I);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(y)console.warn(`[job] ${m.jobId} failed after claim lost (${P}) \u2014 skipping result upload`);else{let G=Es(I);console.warn(G?`[job] ${m.jobId} failed: ${P} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${P}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:P},startedAt:le,finishedAt:new Date().toISOString(),...G?{authError:!0}:{}})}}finally{L.dispose()}}finally{clearInterval(M),Zr&&clearInterval(Zr),At(),u=null,p=null,$?.cleanup(),b?.cleanup()}}function T(h,m){if(!h.credBundle)return{gitCreds:null,contextGitCreds:null};if(!m)return console.warn(`[job] ${h.jobId} has a credBundle but this sandbox has no private key \u2014 ignoring`),{gitCreds:null,contextGitCreds:null};let y;try{y=JSON.parse(ri(m,h.credBundle).toString("utf-8"))}catch(E){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${E instanceof Error?E.message:String(E)}`),{gitCreds:null,contextGitCreds:null}}let $=jo(y);$&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let b=Os(y,h.contextRepo.cloneUrl),N={gitCreds:$,contextGitCreds:b};return y.claudeOauthToken&&(N.claudeOauthToken=y.claudeOauthToken),N}function j(h,m){return h.split(`
531
532
  `).map(y=>m+y).join(`
532
533
  `)}function U(h,m,y){let $=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,y??"")}let S=h=>{if(a)return;a=!0,console.log(`
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:
534
+ [${h}] shutting down`),c.abort();let m=new AbortController,y=setTimeout(()=>m.abort(),3e3);(async()=>{let $=u;if($)try{await s.releaseJob($,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${$}`)}catch(b){let N=b instanceof Error?b.message:String(b);console.warn(`[${h}] release failed: ${N} (sweeper will reclaim)`)}clearTimeout(y),k.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>S("SIGINT")),process.on("SIGTERM",()=>S("SIGTERM")),await R()}async function ra(t={profile:void 0}){let e=fe(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Sr(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let u={type:"register",projectId:e.projectId};r.send(JSON.stringify(u))}),r.on("message",u=>{let p=u.toString("utf-8");if(s.push(`msg:${p}`),p!=="pong")try{let f=JSON.parse(p);f.type==="registered"?(a=!!f.ok,clearTimeout(c),r.send("ping")):f.type}catch{}}),r.on("error",u=>s.push(`error:${u.message}`)),r.on("close",(u,p)=>{s.push(`close:${u}:${p?.toString()||""}`),clearTimeout(c),i({ok:a,events:s})}),setTimeout(()=>r.close(),1500)});for(let i of o.events)console.log(` ${i}`);o.ok||(console.error("hello failed"),process.exit(1)),console.log("ok \u2014 HUB reachable, CLI auth + project binding works.");try{let i=await se(e.hubUrl,e.cliToken,e.projectId);if(i.duplicateIntake){let s=i.duplicateIntake;console.warn(`warning: project \xAB${s.withProjectId}\xBB watches the same YouTrack columns (${s.columns.join(", ")}) and at least one of the two has no assignee filter \u2014 both will grab the same issues. Enable require_assignee + assignee on both.`)}}catch{}let n=te(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{existsSync as Ct,mkdirSync as Sa,readFileSync as Ca,readdirSync as $d,writeFileSync as Ra}from"node:fs";import{join as Xe,resolve as Ta}from"node:path";import{setTimeout as xd}from"node:timers/promises";import{cancel as vd,confirm as Rt,intro as Ia,isCancel as Mo,log as x,outro as Bo,password as Jt,select as Qe,spinner as Pa,text as K}from"@clack/prompts";import{simpleGit as Vr}from"simple-git";async function vt(t,e,r){return e.host==="github"?qp(t,e,r):e.host==="gitlab"?Zp(t,e,r):td(t,e,r)}async function oa(t,e,r={}){let o=r.explain??!0,n=`${t.owner}/${t.name} not found on ${t.host}`;try{if(t.host==="github")return e.githubToken?(await Ue(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await na(e.githubToken,t):n}:{found:"unknown",detail:"no GitHub token \u2014 existence not checked"};if(t.host==="gitlab"){if(!e.gitlabToken)return{found:"unknown",detail:"no GitLab token \u2014 existence not checked"};let s=encodeURIComponent(`${t.owner}/${t.name}`);return(await Ne(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await ia(e.gitlabToken,t):n}}return e.bitbucket?(await xt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await sa(e.bitbucket,t):n}:{found:"unknown",detail:"no Bitbucket credentials \u2014 existence not checked"}}catch(i){return{found:"unknown",detail:i instanceof Error?i.message:String(i)}}}async function na(t,e){let r=!1;try{r=(await Ue(t,"GET",`/users/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitHub repo ${e.owner}/${e.name} does not exist, or the token cannot see it \u2014 check the name; a fine-grained PAT must be scoped to this repo (and approved in the org)`:`GitHub owner "${e.owner}" not found \u2014 check the org/user spelling`}async function ia(t,e){let r=!1;try{r=(await Ne(t,"GET",`/namespaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`GitLab project ${e.owner}/${e.name} does not exist (the namespace "${e.owner}" is visible to the token) \u2014 check the project name, or the token has no access to this specific project`:`GitLab namespace "${e.owner}" is not visible to this token \u2014 check the group/username spelling; a private group answers 404 until the token's owner is a member`}async function sa(t,e){let r=!1;try{r=(await xt(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var Wp="https://api.github.com";async function Ue(t,e,r,o){let n={method:e,headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}};o!==void 0&&(n.body=JSON.stringify(o),n.headers["Content-Type"]="application/json");let i=await fetch(Wp+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?a.message:s;throw new Error(`GitHub ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function qp(t,e,r){let o=r.githubToken;if(!o)throw new Error("GitHub PAT required to provision a github-hosted Context Repo \u2014 set GH_TOKEN / GITHUB_TOKEN or provide it during `codepipe init`");let n=await Yp(o,e,r),i=await zp(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=ft(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Jp(o,n.owner,n.name,a.path,i)||await Xp(o,n.owner,n.name,a.path,a.content,`chore(codepipe): scaffold ${a.path}`,i);return{host:"github",owner:n.owner,name:n.name,cloneUrl:n.sshUrl,branch:i}}async function Yp(t,e,r){let o=await Ue(t,"GET",`/repos/${e.owner}/${encodeURIComponent(e.name)}`);if(o.status===200&&o.data)return r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),{owner:o.data.owner.login,name:o.data.name,sshUrl:o.data.ssh_url};if(r.mode==="attach")throw new Error(`attach: ${await na(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Vp(t,e.owner),i=n?`/orgs/${e.owner}/repos`:"/user/repos";r.log.info(`creating Context Repo ${e.owner}/${e.name} (${n?"org":"user"})`);let s=await Ue(t,"POST",i,{name:e.name,private:!0,auto_init:!0,description:`CodePipe Context Repo for project ${e.name}`});if(!s.data)throw new Error("GitHub createRepo: empty response");return{owner:s.data.owner.login,name:s.data.name,sshUrl:s.data.ssh_url}}async function Vp(t,e){let{status:r,data:o}=await Ue(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function zp(t,e,r){let{data:o}=await Ue(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Jp(t,e,r,o,n){let{status:i,data:s}=await Ue(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Xp(t,e,r,o,n,i,s,a){let c={message:i,content:Buffer.from(n,"utf-8").toString("base64"),branch:s};a&&(c.sha=a),await Ue(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Qp="https://gitlab.com/api/v4";async function Ne(t,e,r,o){let n={method:e,headers:{"PRIVATE-TOKEN":t,"User-Agent":"codepipe-cli",...o!==void 0?{"Content-Type":"application/json"}:{}}};o!==void 0&&(n.body=JSON.stringify(o));let i=await fetch(Qp+r,n),s=await i.text(),a=s?JSON.parse(s):null;if(i.status>=400&&i.status!==404){let c=typeof a=="object"&&a&&"message"in a?JSON.stringify(a.message):s;throw new Error(`GitLab ${e} ${r} \u2192 ${i.status} ${c}`)}return{status:i.status,data:a}}async function Zp(t,e,r){let o=r.gitlabToken;if(!o)throw new Error("GitLab PAT required to provision a gitlab-hosted Context Repo \u2014 set GITLAB_TOKEN or provide it during `codepipe init`");let n=encodeURIComponent(`${e.owner}/${e.name}`),i,s=await Ne(o,"GET",`/projects/${n}`);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await ia(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ne(o,"GET","/user"),l={name:e.name,path:e.name,visibility:"private",initialize_with_readme:!0,description:`CodePipe Context Repo for project ${e.name}`};if(f.data?.username!==e.owner){let g=await Ne(o,"GET",`/namespaces/${encodeURIComponent(e.owner)}`);if(g.status===404||!g.data)throw new Error(`GitLab namespace "${e.owner}" not found (or the token cannot see it) \u2014 use your username or a group the token can create projects in`);l.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await Ne(o,"POST","/projects",l);if(!d.data)throw new Error("GitLab create project: empty response");i=d.data}let a=i.default_branch??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ft(t,e,r.youtrackWrites,r.trackerUrl),u=new Set;for(let f=1;;f++){let d=(await Ne(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)u.add(g.path);if(d.length<100)break}let p=c.filter(f=>!u.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Ne(o,"POST",`/projects/${i.id}/repository/commits`,{branch:a,commit_message:"chore(codepipe): scaffold context repo files",actions:p}):r.log.info("nothing to scaffold \u2014 all files already present"),{host:"gitlab",owner:e.owner,name:i.path,cloneUrl:i.ssh_url_to_repo,branch:a}}var ed="https://api.bitbucket.org/2.0";async function xt(t,e,r,o){let n={method:e,headers:{Authorization:"Basic "+Buffer.from(`${t.email}:${t.apiToken}`).toString("base64"),"User-Agent":"codepipe-cli"}};o?.json!==void 0?(n.body=JSON.stringify(o.json),n.headers["Content-Type"]="application/json"):o?.form&&(n.body=o.form);let i=await fetch(ed+r,n),s=await i.text(),a=null;try{a=s?JSON.parse(s):null}catch{}if(i.status>=400&&i.status!==404)throw new Error(`Bitbucket ${e} ${r} \u2192 ${i.status} ${s}`);return{status:i.status,data:a}}async function td(t,e,r){let o=r.bitbucket;if(!o)throw new Error("Bitbucket account email + API token required to provision a bitbucket-hosted Context Repo \u2014 provide them during `codepipe init`");let n=`/repositories/${e.owner}/${encodeURIComponent(e.name)}`,i,s=await xt(o,"GET",n);if(s.status===200&&s.data)r.log.info(`Context Repo ${e.owner}/${e.name} already exists \u2014 reusing`),i=s.data;else{if(r.mode==="attach")throw new Error(`attach: ${await sa(o,e)} (attach joins an existing Context Repo and never creates one)`);r.log.info(`creating Context Repo ${e.owner}/${e.name} (bitbucket)`);let f=await xt(o,"POST",n,{json:{scm:"git",is_private:!0,description:`CodePipe Context Repo for project ${e.name}`}});if(f.status===404||!f.data?.slug)throw new Error(`Bitbucket cannot create ${e.owner}/${e.name} \u2014 workspace "${e.owner}" not found or the API token lacks repository-admin access to it`);i=f.data}let a=i.mainbranch?.name??"main";r.log.info(`scaffolding Context Repo files \u2192 ${e.owner}/${e.name}@${a}`);let c=ft(t,e,r.youtrackWrites,r.trackerUrl),u=[];for(let f of c)(await xt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&u.push(f);if(u.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of u)f.set(d.path,d.content);if((await xt(o,"POST",`${n}/src`,{form:f})).status===404)throw new Error(`Bitbucket src commit to ${e.owner}/${e.name} \u2192 404 \u2014 the repo is not reachable with this credential (check workspace/name and API-token scopes)`)}else r.log.info("nothing to scaffold \u2014 all files already present");let p=i.links?.clone?.find(f=>f.name==="ssh")?.href;return{host:"bitbucket",owner:e.owner,name:i.slug??e.name,cloneUrl:p??`git@bitbucket.org:${e.owner}/${e.name}.git`,branch:a}}var rd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function xe(t){let e=t.trim();if(!e)return null;let r,o;if(e.includes("://")){let a;try{a=new URL(e)}catch{return null}r=a.hostname.toLowerCase(),o=a.pathname}else{let a=/^(?:[\w.-]+@)?([\w.-]+):(.+)$/.exec(e);if(!a)return null;r=a[1].toLowerCase(),o=a[2]}let n=rd[r];if(!n)return null;let i=o.replace(/^\/+/,"").replace(/\/+$/,"").split("/").filter(Boolean);if(i.length<2)return null;let s=i[i.length-1].replace(/\.git$/,"");return s?{host:n,owner:i.slice(0,-1).join("/"),repoName:s}:null}import{createHash as od}from"node:crypto";import{existsSync as aa,mkdirSync as nd,readFileSync as ca,readdirSync as id,rmSync as qr,writeFileSync as sd}from"node:fs";import{homedir as ad}from"node:os";import{dirname as cd,join as No}from"node:path";var ld=24*60*60*1e3;function la(){return No(ad(),".codepipe","init-drafts")}function Uo(t){let e=od("sha256").update(t).digest("hex").slice(0,16);return No(la(),`${e}.json`)}function ua(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=ld)}function pa(t){let e=Uo(t);if(!aa(e))return null;try{let r=JSON.parse(ca(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:ua(r.savedAt)?(qr(e,{force:!0}),null):r}catch{return null}}function Lo(t){qr(Uo(t),{force:!0})}function da(){let t=la();if(aa(t))for(let e of id(t)){let r=No(t,e);try{let o=JSON.parse(ca(r,"utf-8"));ua(o.savedAt)&&qr(r,{force:!0})}catch{qr(r,{force:!0})}}}var St=class{constructor(e,r){this.cwd=e;this.answers=r?.answers?{...r.answers}:{}}answers;get(e){return this.answers[e]}set(e,r){this.answers[e]=r,this.persist()}delete(e){delete this.answers[e],this.persist()}async ask(e,r){if(e in this.answers)return this.answers[e];let o=await r();return this.set(e,o),o}clear(){Lo(this.cwd)}persist(){let e=Uo(this.cwd);nd(cd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};sd(e,JSON.stringify(r,null,2)+`
535
+ `,{mode:384})}};function fa(t){return t?{message:"An index already exists. Re-index the project?",proceedValue:"yes",reindex:!0,options:[{value:"no",label:"No, keep the existing one"},{value:"yes",label:"Yes, re-index"}],initialValue:"no"}:{message:"Index the project repositories? (recommended on first run)",proceedValue:"yes",reindex:!1,options:[{value:"yes",label:"Yes"},{value:"skip",label:"Skip"}],initialValue:"yes"}}async function ma(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{homedir as ud}from"node:os";import{existsSync as pd,mkdirSync as dd,readFileSync as fd,writeFileSync as md}from"node:fs";import{dirname as gd,join as hd}from"node:path";function Do(){return _("FARM_PINS")??hd(ud(),".codepipe","farm-pins.json")}function ga(){let t=Do();if(!pd(t))return{};try{return JSON.parse(fd(t,"utf-8"))}catch{return{}}}function wd(t){let e=Do();dd(gd(e),{recursive:!0}),md(e,JSON.stringify(t,null,2)+`
536
+ `,{mode:384})}function yd(t){return ga()[t]}function ha(t,e){let r=ga();r[t]=e,wd(r)}function wa(t,e){let r=mt(e),o=yd(t);if(o&&o!==r)throw new Error(`farm ${t} key fingerprint changed (pinned ${o}, now ${r}) \u2014 refusing to seal. If the farm was re-registered intentionally, remove its entry from ${Do()}.`);return r}import{existsSync as ya}from"node:fs";import{join as ba}from"node:path";import{simpleGit as ka}from"simple-git";var bd={info:t=>console.log(t),warn:t=>console.warn(t)};async function zt(t,e,r={}){let o=r.log??bd,n=[];for(let i of e){let s=ba(t,i.mountAs),a=hs(i);if(!ya(s)){if(r.dryRun){o.info(`would clone ${a} \u2192 ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"cloned",detail:"(dry-run)"});continue}try{o.info(`cloning ${a} \u2192 ${i.mountAs}/`),await ka().clone(a,s),n.push({mountAs:i.mountAs,status:"cloned"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`clone failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}continue}if(!ya(ba(s,".git"))){o.warn(`${i.mountAs}/ exists but is not a git repo \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-not-git"});continue}let c=ka(s),u="";try{u=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{u=""}if(!kd(u,a)){o.warn(`${i.mountAs}/ origin (${u||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:u});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(p){let f=p instanceof Error?p.message:String(p);o.warn(`fetch failed for ${i.mountAs}: ${f}`),n.push({mountAs:i.mountAs,status:"error",detail:f})}}return n}function kd(t,e){return $a(t)===$a(e)}function $a(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function xa(t={}){let e=Mt();e||(console.error("no .codepipe/ workspace found in this directory or any parent. run `codepipe init` first."),process.exit(1)),console.log(`codepipe sync \u2014 project ${e.spec.projectId} (${e.spec.repos.length} repos)`);let r=await zt(e.root,e.spec.repos,{dryRun:t.dryRun===!0});for(let o of r)console.log(` ${o.mountAs}: ${o.status}${o.detail?` \u2014 ${o.detail}`:""}`)}var va=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function B(t){vd(t),process.exit(1)}function ae(t){return Mo(t)&&B("aborted"),t}function D(t){return Mo(t)&&B("aborted"),typeof t=="string"?t:""}async function Ea(t={}){Ia("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();da();let r=pa(e),o,n=!1;r&&Object.keys(r.answers).length>0?ae(await Rt({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(x.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new St(e,r),n=!0):(Lo(e),o=new St(e)):o=new St(e);let i=t.force===!0?null:await Cd(e),s=await o.ask("target",async()=>ae(await Qe({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?x.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):n&&o.get("contextRepo")!==void 0||Aa(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:pe,initialValue:_("HUB_URL")??pe,validate:C=>C.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),u=await o.ask("email",()=>_a()),p=await o.ask("cliToken",()=>zr(c,u)),f=null;s==="farm"&&(f=await Sd(c,p));let l=a?Td(a.parsed.repoName):"",d=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:l||"acme",...l?{initialValue:l}:{},validate:C=>Ge.test(C.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),g=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:C=>C.trim().length>0?void 0:"required"})).trim()),w=await o.ask("automationLevel",async()=>ae(await Qe({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"}))),k=await o.ask("youtrack",()=>Ga()),R=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:C=>C.trim().length>0?void 0:"required"})).trim()),v=await o.ask("youtrackWrites",async()=>ae(await Rt({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),T=o.get("tokens")??{},j=()=>o.set("tokens",T),U=await o.ask("repos",()=>Ed(T,u,a,{onCred:j,initial:o.get("reposPartial")??[],onProgress:C=>o.set("reposPartial",C)}));o.delete("reposPartial");let S=await jd(await o.ask("contextRepo",()=>La(d,U,T,u)),d,U,T,u,j,C=>o.set("contextRepo",C)),{spec:h,mode:m}=S;x.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let y=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...k.login?{initialValue:k.login}:{},validate:C=>C.trim().length>0?void 0:"required"})).trim()),$={projectId:d,name:g,automationLevel:w,repos:U,youtrackProjectKey:R,ownerEmail:u};x.step(`${m==="attach"?"attaching to":"provisioning"} Context Repo ${h.owner}/${h.name} (${h.host})\u2026`);let b;try{b=await vt($,h,{...Da(T),youtrackWrites:v,trackerUrl:k.url,mode:m,log:{info:C=>x.message(C),warn:C=>x.warn(C)}})}catch(C){B(`Context Repo provisioning failed: ${C instanceof Error?C.message:String(C)}`)}$.contextRepo=b,x.success(`Context Repo ready: ${b.owner}/${b.name}@${b.branch}`),x.step(`registering project on ${c}\u2026`);let N;try{N=await ht(c,p,$)}catch(C){if(C instanceof A&&C.status===409){x.warn(`project ${d} already exists on HUB \u2014 reusing it`);try{N=await se(c,p,d)}catch(ne){throw ne instanceof A&&B(`HUB \u2192 ${ne.status} ${ne.message}`),ne}}else if(C instanceof A&&C.status===401)o.delete("cliToken"),B("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(C instanceof A)B(`HUB \u2192 ${C.status} ${C.message}`);else throw C}let E=N.contextRepo??b;x.success(`project ${N.projectId} ready (${N.provisioningStatus})`);let M=await Ud(E),le={url:k.url,token:k.token};if(s==="farm"){let C=f,ne={...T,...M?{contextWrite:M}:{},youtrack:le},ve=T.github?.token;if(E.host==="github"&&ve)try{let z=ss(`devpipe-${d}`);await as(E,ve,z.publicKey,`devpipe-${d}`),ne.contextSsh={privateKey:z.privateKey},x.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(z){x.warn(`could not set up Context Repo SSH deploy key (${z instanceof Error?z.message:String(z)}); the farm will fall back to the token path.`)}let De={projectId:d,config:{hubUrl:c,cliToken:p,projectId:d},secrets:ne,contextRepo:E,projectConfig:Ie($,v,k.url,y||void 0)},At=kr(C.farm.publicKey,JSON.stringify(De));x.step(`handing project ${d} to farm ${C.farm.name}\u2026`);let et;try{et=await Wi(c,p,C.farm.farmId,{projectId:d,sealedBundle:At})}catch(z){throw z instanceof A&&B(z.status===409?`farm ${C.farm.name} is offline \u2014 start it and re-run.`:z.status===504?`farm ${C.farm.name} did not respond in time.`:`HUB \u2192 ${z.status} ${z.message}`),z}et.ok||B(`farm rejected provisioning: ${et.error??"unknown error"}`),await Go(c,p,d,E,ve),o.clear(),Bo(`done. project ${d} is now hosted on farm ${C.farm.name} (daemon ${et.daemonStatus}). Watch it on the dashboard \u2192 Status.`);return}Ba(T),await Oa(e,E.cloneUrl,E.branch),Ua(e),a&&await Pd(e);{let C=Xe(e,je);wr(C);let ne=Ie($,v,k.url,y||void 0),ve=co(C,ne);ve.length>0&&x.success(`local project config \u2192 .codepipe/{${ve.join(", ")}}`),Ke(d,ne,{info:De=>x.message(De),warn:De=>x.warn(De)})}await Na(e,N.repos);let we={hubUrl:c,cliToken:p,projectId:d,...T,...M?{contextWrite:M}:{},youtrack:le};Z(we),Me({hubUrl:c,cliToken:p,projectId:d,accountEmail:u},d),x.success(`secrets \u2192 ${Fe(d)}`),await Go(c,p,d,E,T.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),Bo(`done. next: \`codepipe\` (interactive) or \`codepipe --profile ${d} daemon\`.`)}async function Go(t,e,r,o,n){let i=await ma(o,n),s=fa(i),a=await Qe({message:s.message,options:s.options,initialValue:s.initialValue});if(!(Mo(a)||a!==s.proceedValue))try{let{jobId:c}=await Rr(t,e,r,{reindex:s.reindex});x.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){x.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Sd(t,e){let r;try{r=await Ki(t,e)}catch(c){throw c instanceof A&&B(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&B("no farms registered on this HUB. Register one first: on the farm host run `codepipe-farm register --hub <url> --token <HUB_FARM_REG_TOKEN>` and `codepipe-farm start`.");let n=ae(await Qe({message:"target farm",options:o.map(c=>({value:c.farmId,label:`${c.name}${c.online?"":" (offline)"} \u2014 ${c.keyFingerprint??"no fingerprint"}`}))})),i=o.find(c=>c.farmId===n),s;try{s=wa(i.farmId,i.publicKey)}catch(c){B(c instanceof Error?c.message:String(c))}return ae(await Rt({message:`confirm farm ${i.name} cred-channel fingerprint:
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}))||B("farm fingerprint not confirmed \u2014 aborting."),ha(i.farmId,s),{farm:i,fingerprint:s}}async function ja(t){Ia(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();Aa(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:_("HUB_URL")??pe,validate:p=>p.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await _a(),n=await zr(r,o);x.step(`fetching project ${t.projectId} from HUB\u2026`);let i;try{i=await se(r,n,t.projectId)}catch(p){throw p instanceof A&&B(`HUB \u2192 ${p.status} ${p.message}`),p}i.contextRepo||B(`project ${t.projectId} has no Context Repo on HUB`);let s=await Ga(),a={},c=new Set(i.repos.map(p=>p.host));c.add(i.contextRepo.host);for(let p of c)await Yr(p,a,p===i.contextRepo.host?i.contextRepo.owner:i.repos.find(f=>f.host===p)?.owner,o);Ba(a),await Oa(e,i.contextRepo.cloneUrl,i.contextRepo.branch),Ua(e);{let p=Xe(e,je);wr(p);let f={projectId:t.projectId,name:i.name,automationLevel:i.automationLevel,repos:i.repos,...i.youtrackProjectKey?{youtrackProjectKey:i.youtrackProjectKey}:{}},l=Ie(f,!0,s.url),d=co(p,l);d.length>0&&x.success(`local project config \u2192 .codepipe/{${d.join(", ")}} (defaults \u2014 review and adjust)`),Ke(t.projectId,l,{info:g=>x.message(g),warn:g=>x.warn(g)})}await Na(e,i.repos);let u={hubUrl:r,cliToken:n,projectId:t.projectId,...a,youtrack:{url:s.url,token:s.token}};Z(u),Me({hubUrl:r,cliToken:n,projectId:t.projectId},t.projectId),x.success(`secrets \u2192 ${Fe(t.projectId)}`),await Go(r,n,t.projectId,i.contextRepo,a.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Bo("done.")}function Aa(t,e){if(!Ct(t)){Sa(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=$d(t).filter(n=>!r.has(n));o.length!==0&&(e||B(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function Cd(t){if(!Ct(Xe(t,".git")))return null;try{let r=(await Vr(t).remote(["get-url","origin"])||"").toString().trim(),o=r?xe(r):null;return o?{parsed:o,defaultBranch:await Rd(t)}:null}catch{return null}}async function Rd(t){let e=Vr(t);try{let o=(await e.raw(["symbolic-ref","--short","refs/remotes/origin/HEAD"])).trim().replace(/^origin\//,"");if(o)return o}catch{}try{let r=(await e.raw(["symbolic-ref","--short","HEAD"])).trim();if(r)return r}catch{}return"main"}function Td(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ge.test(e)?e:""}function Id(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function Pd(t){let e=Xe(t,".gitignore"),r=Ct(e)?Ca(e,"utf-8"):"";if(Id(r))return;if(!ae(await Rt({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){x.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
539
539
  `)?"":`
540
- `;Ca(e,r+n+`
540
+ `;Ra(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
+ `),x.success(`.codepipe/ added to ${Ta(e)}`)}async function _a(){let t="";try{t=(await Vr().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Email (admin email of this HUB)",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function zr(t,e){x.step(`sending magic link to ${e}`);let r;try{r=await Yi(t,e)}catch(n){throw n instanceof Gt&&B(`${e} is not authorized on this HUB yet.
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}x.message(`click the link in your inbox to confirm. polling\u2026 (request ${r.requestId})`);let o=Date.now();for(;Date.now()-o<15*6e4;){let n=await Vi(t,r.requestId);if(n.status==="confirmed"&&n.cliToken)return x.success("confirmed"),n.cliToken;n.status==="rejected"&&B("HUB rejected this email \u2014 not the admin"),n.status==="expired"&&B("link expired \u2014 re-run init"),await xd(2e3)}B("bootstrap timed out after 15 minutes")}async function Oa(t,e,r){let o=Xe(t,je);if(Ct(Xe(o,".git"))){x.message(`${o} already cloned \u2014 skipping`);return}Ct(o)&&B(`${o} exists but is not a git repo \u2014 remove it and re-run`),Sa(o,{recursive:!0}),x.step(`cloning Context Repo \u2192 ${o}`);try{await Vr().clone(e,o,["--branch",r]),x.success(`cloned ${e}`)}catch(n){B(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function Na(t,e){if(e.length===0)return;x.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await zt(t,r,{log:{info:n=>x.message(n),warn:n=>x.warn(n)}});for(let n of o)x.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function Ua(t){let e=Xe(t,je,".gitignore"),r="";if(Ct(e)&&(r=Ca(e,"utf-8")),va.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
547
547
  `)||r.length===0?"":`
548
- `,i=xa.join(`
548
+ `,i=va.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
+ `;Ra(e,r+n+(r?`
551
+ `:"")+i),x.message(`appended runtime entries to ${Ta(e)}`)}async function Ed(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;x.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await Yr(s.host,t,s.owner,e),i?.();let c=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:s.repoName,initialValue:s.repoName,validate:p=>p.trim().length>0?void 0:"required"})).trim(),u=D(await K({message:"default branch",placeholder:a,initialValue:a,validate:p=>p.trim().length>0?void 0:"required"})).trim();n.push({name:c,host:s.host,owner:s.owner,repoName:s.repoName,defaultBranch:u,mountAs:"."}),o.onProgress?.(n)}for(;ae(await Rt({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=D(await K({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:d=>!d||!d.trim()||xe(d)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!a)continue;let c=xe(a);x.message(`${c.host}: ${c.owner}/${c.repoName}`),await Yr(c.host,t,c.owner,e),i?.();let u=D(await K({message:"repo logical name (used inside Context Repo paths)",placeholder:c.repoName,initialValue:c.repoName,validate:d=>d.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"default branch (optional)",placeholder:"main"})).trim(),f=D(await K({message:"local folder name (sibling of .codepipe/, optional)",placeholder:u})).trim(),l={name:u,host:c.host,owner:c.owner,repoName:c.repoName};p&&(l.defaultBranch=p),f&&f!==u&&(l.mountAs=f),n.push(l),o.onProgress?.(n)}return n}async function La(t,e,r,o){x.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let n=ae(await Qe({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&x.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=D(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:ke(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!xe(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),u=xe(c);a=u?{host:u.host,owner:u.owner,name:u.repoName}:{host:i,owner:s,name:c}}else{let c=await Ad(),u=D(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=D(await K({message:"Context Repo name",placeholder:ke(t),initialValue:ke(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:u,name:p}}return{spec:a,mode:n}}function Da(t){return{githubToken:t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:t.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:t.bitbucket??st()}}async function jd(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:u}=a;await Yr(c.host,o,c.owner,n),i?.();let p=Pa();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await oa(c,Da(o),{explain:u==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${u==="create"?" \u2014 existing repo will be reused":""}`),a;if(f.found==="unknown")return p.stop(`could not check ${c.owner}/${c.name} (${f.detail}) \u2014 continuing`,1),a;if(u==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let l=ae(await Qe({message:"the Context Repo to attach to is not reachable \u2014 what now?",options:[{value:"retry",label:"enter a different name / URL"},{value:"create",label:"create it instead \u2014 start a new context at this location"},{value:"abort",label:"abort init"}],initialValue:"retry"}));if(l==="abort"&&B("aborted"),l==="create")return a={spec:c,mode:"create"},s(a),a;a=await La(e,r,o,n),s(a)}}async function Ad(){return ae(await Qe({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function Xt(t,e){let r=Pa();r.start(`verifying ${t}\u2026`);try{let o=await e();return r.stop(`${t} OK \u2014 ${o}`),!0}catch(o){return r.stop(`${t} failed \u2014 ${o instanceof Error?o.message:String(o)}`,1),!1}}function Ba(t){jr(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Ar(t.gitlab?.token??process.env.GITLAB_TOKEN),_r(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function Yr(t,e,r,o){if(!e[t])if(t==="github"){let n=await _d(r);n?e.github=n:x.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await Od(r,o);n?e.bitbucket=n:x.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let n=await Nd();n?e.gitlab=n:x.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function _d(t){for(;;){let e=D(await Jt({message:`GitHub PAT \u2014 blank to skip
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",()=>ut(e,t?{owner:t}:void 0)))return{token:e};x.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function Od(t,e){for(x.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
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 Jt({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){x.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await Xt("Bitbucket",()=>pt(r,o,t)))return{email:r,apiToken:o};x.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function Nd(){for(;;){let t=D(await Jt({message:`GitLab PAT \u2014 blank to skip
562
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await Xt("GitLab",()=>dt(t))){let e=await Vn(t);return e&&x.warn(e),{token:t}}x.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function Ud(t){if(ae(await Rt({message:`Issue a separate context-write token (scoped to the Context Repo only)?
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
565
  your trusted network.`,initialValue:!1})))for(t.host==="github"?x.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
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(`
568
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=D(await Jt({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await Xt("contextWrite",()=>Ld(r,t)))return{token:r};x.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function Ld(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch(`https://api.github.com/repos/${e.owner}/${e.name}`,{headers:r})}catch(i){throw new Error(`cannot reach api.github.com (${i instanceof Error?i.message:String(i)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the PAT)");if(o.status===404)throw new Error(`token cannot see ${e.owner}/${e.name} (404) \u2014 scope the fine-grained PAT to that repo and approve it in the org, or use a classic PAT with 'repo'`);if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let n=await o.json();if(n.permissions&&n.permissions.push===!1)throw new Error(`token has no write access to ${e.owner}/${e.name} \u2014 needs Contents: write`);return n.full_name??`${e.owner}/${e.name}`}async function Ga(){for(;;){let t=D(await K({message:"YouTrack URL (YOUTRACK_URL)",placeholder:"https://your.youtrack.cloud",validate:r=>{let o=r.trim();if(!o)return"required";if(!o.startsWith("http"))return"must start with http(s)://"}})).trim().replace(/\/$/,""),e=D(await Jt({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await Xt("YouTrack",()=>gt({baseUrl:t,token:e}))){let r=await Ei({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}x.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as Dd}from"node:fs";function W(t){throw new Error(t)}function V(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function Qt(t,e){if(t==null)return;typeof t!="string"&&W(`config: '${e}' must be a string`);let r=t.trim();return r.length>0?r:void 0}function Bd(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=V(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=V(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=V(i.id,"project.id");Ge.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=V(i.name,"project.name"),c=V(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let u=i.repos;Array.isArray(u)||W("config: 'project.repos' must be an array");let p=u.map((v,T)=>{(!v||typeof v!="object")&&W(`config: project.repos[${T}] must be an object`);let j=v,U=V(j.host,`project.repos[${T}].host`);U!=="github"&&U!=="bitbucket"&&U!=="gitlab"&&W(`config: project.repos[${T}].host must be 'github', 'bitbucket' or 'gitlab'`);let S={name:V(j.name,`project.repos[${T}].name`),host:U,owner:V(j.owner,`project.repos[${T}].owner`),repoName:V(j.repoName,`project.repos[${T}].repoName`)},h=Qt(j.defaultBranch,`project.repos[${T}].defaultBranch`);h&&(S.defaultBranch=h);let m=Qt(j.mountAs,`project.repos[${T}].mountAs`);return m&&(S.mountAs=m),S}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let l=f,d=Qt(l.host,"project.contextRepo.host")??"github";d!=="github"&&d!=="bitbucket"&&d!=="gitlab"&&W("config: 'project.contextRepo.host' must be 'github', 'bitbucket' or 'gitlab'");let g={host:d,owner:V(l.owner,"project.contextRepo.owner"),name:Qt(l.name,"project.contextRepo.name")??ke(s)},w={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},k=Qt(i.youtrackProjectKey,"project.youtrackProjectKey");k&&(w.project.youtrackProjectKey=k),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),w.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),w.project.youtrackWrites=i.youtrackWrites);let R=e.secrets;if(R!==void 0){(typeof R!="object"||R===null)&&W("config: 'secrets' must be an object");let v=R,T={};if(v.github){let j=v.github;T.github={token:V(j.token,"secrets.github.token")}}if(v.bitbucket){let j=v.bitbucket;T.bitbucket={email:V(j.email,"secrets.bitbucket.email"),apiToken:V(j.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let j=v.gitlab;T.gitlab={token:V(j.token,"secrets.gitlab.token")}}if(v.youtrack){let j=v.youtrack;T.youtrack={url:V(j.url,"secrets.youtrack.url").replace(/\/$/,""),token:V(j.token,"secrets.youtrack.token")}}if(v.contextWrite){let j=v.contextWrite;T.contextWrite={token:V(j.token,"secrets.contextWrite.token")}}w.secrets=T}return w}async function Gd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function Md(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await ut(e.github.token,r.host==="github"?{owner:r.owner}:void 0);console.log(` GitHub OK \u2014 ${o}`)}if(e.bitbucket){let r=t.project.contextRepo.host==="bitbucket"?t.project.contextRepo.owner:t.project.repos.find(n=>n.host==="bitbucket")?.owner,o=await pt(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await dt(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await gt({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function Ma(t){let e=!t.configPath||t.configPath==="-"?await Gd():Dd(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(l){W(`config: invalid JSON \u2014 ${l instanceof Error?l.message:String(l)}`)}let o=Bd(r),{hubUrl:n,cliToken:i,project:s}=o;console.log(`codepipe init --headless \u2192 ${n} (project=${s.id})`),t.skipVerify||(console.log("verifying credentials\u2026"),await Md(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,u;try{u=await vt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??st(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:l=>console.log(` ${l}`),warn:l=>console.warn(` ${l}`)}})}catch(l){W(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`)}a.contextRepo=u,console.log(`Context Repo ready: ${u.owner}/${u.name}@${u.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await ht(n,i,a)}catch(l){if(l instanceof A&&l.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await se(n,i,s.id);else if(l instanceof A)W(`HUB \u2192 ${l.status} ${l.message}`);else throw l}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(Z(f),Me({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Fe(s.id)}`),Ke(s.id,Ie(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:l=>console.log(l),warn:l=>console.warn(l)}),s.index)try{let{jobId:l}=await Rr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${l}); runs once a SANDBOX claims it.`)}catch(l){console.warn(`could not enqueue index job: ${l instanceof Error?l.message:String(l)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as Ha,intro as Fa,isCancel as Ka,log as Ho,outro as Hd,password as Wa}from"@clack/prompts";async function Fd(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function qa(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await Fd(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){Fa("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Wa({message:"Claude OAuth token"});Ka(i)&&(Ha("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Rn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${fr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=fe(t.profile);if(!e){Fa(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),Ho.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await Wa({message:"Claude OAuth token"});Ka(i)&&(Ha("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=H(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},Z(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(Ho.success("Claude OAuth token saved."),Hd("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as Kd,confirm as Wd,intro as qd,isCancel as Ya,log as J,outro as Yd,select as Va,text as Le}from"@clack/prompts";function za(t){Kd(t),process.exit(1)}function Tt(t){return Ya(t)&&za("aborted"),t}function Zt(t){return Ya(t)&&za("aborted"),typeof t=="string"?t:""}async function Vd(t,e){let r=Tt(await Va({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:e[0]?.host??"github"})),o=e.find(s=>s.host===r)?.owner??e[0]?.owner??"",n=Zt(await Le({message:"Context Repo owner (org / group / workspace / user)",placeholder:o||"your-org",initialValue:o,validate:s=>s.trim().length>0?void 0:"required"})).trim(),i=Zt(await Le({message:"Context Repo name",placeholder:ke(t),initialValue:ke(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function Ja(t={profile:void 0}){let e=fe(t.profile);qd(`codepipe project add \u2192 ${e.hubUrl}`);let r=Tt(await Le({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:l=>Ge.test(l.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Tt(await Le({message:"project name (human-readable)",placeholder:"CodePartner",validate:l=>l.trim().length>0?void 0:"required"})).trim(),n=Tt(await Va({message:"automation level",options:[{value:"assisted",label:"assisted \u2014 every gate via manual Run on the dashboard"},{value:"full",label:"full \u2014 gates auto-approve, runs end-to-end"}],initialValue:"assisted"})),i=Tt(await Le({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Tt(await Wd({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let l=Zt(await Le({message:a.length===0?"project repo clone URL \u2014 blank if none":"next repo clone URL \u2014 blank to finish",placeholder:"git@bitbucket.org:acme/api.git",validate:R=>!R||!R.trim()||xe(R)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!l)break;let d=xe(l);J.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=Zt(await Le({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:R=>R.trim().length>0?void 0:"required"})).trim(),w=Zt(await Le({message:"default branch (optional)",placeholder:"main"})).trim(),k={name:g,host:d.host,owner:d.owner,repoName:d.repoName};w&&(k.defaultBranch=w),a.push(k)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let u=await Vd(r,a),p=H(e.projectId);J.info(`provisioning Context Repo ${u.owner}/${u.name} (${u.host})\u2026`);let f;try{f=await vt(c,u,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??st(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:l=>J.message(l),warn:l=>J.warn(l)}})}catch(l){J.error(`Context Repo provisioning failed: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}c.contextRepo=f,J.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let l=await ht(e.hubUrl,e.cliToken,c);J.success(`project "${l.projectId}" \u2014 ${l.provisioningStatus}`),Ke(r,Ie(c,s,p?.youtrack?.url),{info:d=>J.message(d),warn:d=>J.warn(d)}),l.contextRepo&&(J.message(` context repo: ${l.contextRepo.owner}/${l.contextRepo.name} (${l.contextRepo.cloneUrl})`),J.message(` branch: ${l.contextRepo.branch}`)),l.provisioningError&&J.error(` error: ${l.provisioningError}`),Yd("done")}catch(l){l instanceof A?(J.error(`HUB \u2192 ${l.status} ${l.message}`),l.payload&&typeof l.payload=="object"&&J.message(JSON.stringify(l.payload,null,2))):J.error(l instanceof Error?l.message:String(l)),process.exit(1)}}import{spawn as zd}from"node:child_process";import{hostname as Jd}from"node:os";async function Xd(t,e){let r=te(e.profile);if(r){if(r.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${r.sandboxId} (${r.name})`);return}throw new Error(`worker config ${_e(e.profile)} points at a different HUB (${r.hubUrl}). Re-register it explicitly: codepipe worker register --hub ${t.hubUrl} --token \u2026 --force`)}console.log("[up] no worker registration \u2014 requesting an account-issued token from HUB");let o;try{({secret:o}=await Cr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(n){throw n instanceof A&&n.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):n instanceof A&&n.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):n}await ze({hub:t.hubUrl,token:o,name:e.name??`${Jd()}-up`,llm:e.llm??"claude-headless",projects:e.projects??[],...e.profile?{profile:e.profile}:{}})}function Qd(t,e){let r=te(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=mt(r.sealPublicKey);if(!H(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=dr(t,r.sandboxId,o);if(n==="mismatch")throw new Error(`pinned fingerprint for ${r.sandboxId} differs from the local worker key (${o}). The registration was replaced \u2014 remove the stale pin from the project secrets to accept the new key.`);console.log(`[up] worker key ${n==="pinned"?"auto-pinned":"already pinned"} for ${t} (${o})`)}async function Xa(t){let e=fe(t.profile);await Xd(e,t),Qd(e.projectId,t.profile);let r=process.argv[1];if(!r)throw new Error("cannot resolve the codepipe entry script for child processes");let o=(l,d)=>{let g=w=>k=>{for(let R of k.toString("utf-8").split(`
569
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}
570
+ `)};l.stdout?.on("data",g(process.stdout)),l.stderr?.on("data",g(process.stderr))},n=(l,d)=>{let g=zd(process.execPath,[r,...d],{stdio:["ignore","pipe","pipe"],env:process.env});return o(g,l),g};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let i=n("[cli]",[...t.profile?["--profile",t.profile]:[],"daemon"]),s=n("[worker]",[...t.profile?["--profile",t.profile]:[],"worker","start"]),a=[{name:"daemon",child:i},{name:"worker",child:s}],c=!1,u=l=>{if(!c){c=!0,console.log(`
571
+ [up] ${l} \u2014 stopping both roles`);for(let{child:d}of a)d.exitCode===null&&d.kill(l);setTimeout(()=>{for(let{name:d,child:g}of a)g.exitCode===null&&(console.warn(`[up] ${d} did not stop \u2014 SIGKILL`),g.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM"));let p=a.map(({name:l,child:d})=>new Promise(g=>{d.on("exit",(w,k)=>g({name:l,code:w??(k?1:0)}))})),f=await Promise.race(p);c||(console.log(`[up] ${f.name} exited (code ${f.code}) \u2014 stopping the other role`),u("SIGTERM")),await Promise.all(p),process.exit(f.code)}import{existsSync as lc,mkdirSync as of,readFileSync as nf,writeFileSync as sf}from"node:fs";import{homedir as af}from"node:os";import{dirname as cf,join as uc}from"node:path";import*as Pt from"node:readline";import{existsSync as Wo,readFileSync as Zd,writeFileSync as ef}from"node:fs";import{join as tr}from"node:path";import{simpleGit as Ko}from"simple-git";var Qa=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],tf="apply-queue.json";function Za(t){return tr(t,tf)}function It(t){let e=Za(t);if(!Wo(e))return{};try{return JSON.parse(Zd(e,"utf-8"))}catch{return{}}}function ec(t,e){ef(Za(t),JSON.stringify(e,null,2)+`
572
+ `)}async function tc(t,e,r,o,n){let i;try{i=await Xi(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(l){return{ok:!1,message:`claim failed: ${l instanceof Error?l.message:String(l)}`}}let s=[];for(let l of i.repos){let d=t.spec.repos.find(R=>R.name===l.repoName);if(!d)return{ok:!1,message:`repo "${l.repoName}" not in project.yaml \u2014 run /sync`};let g=tr(t.root,d.mountAs);if(!Wo(tr(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await Ko(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:l,spec:d,dir:g})}let a=[];for(let l of s){let d=Ko(l.dir),g=await rf(d),w=l.claimRepo;try{await d.fetch()}catch(v){return await Fo(a,n),{ok:!1,message:`fetch failed in ${l.spec.mountAs}: ${er(v)}`}}let k=`origin/${w.baseRef}`,R;try{R=await xr(d,{contextRepoCloneUrl:w.contextRepoCloneUrl,deliveryRef:w.deliveryRef,deliverySha:w.deliverySha,baseSha:w.baseSha,commitMessage:w.commitMessage})}catch(v){return await Fo(a,n),{ok:!1,message:`fetch delivery failed in ${l.spec.mountAs}: ${er(v)}`}}a.push({git:d,dir:l.dir,mountAs:l.spec.mountAs,originalRef:g,branch:w.branchName,baseSha:k,deliveryCommit:R,startPoint:k})}let c=[];for(let l of a)try{if(o==="apply"){await l.git.checkout(["-B",l.branch,l.startPoint]),await l.git.raw([...Qa,"cherry-pick",l.deliveryCommit]);let d=(await l.git.revparse(["HEAD"])).trim();c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha,appliedSha:d})}else await l.git.checkout(["--detach",l.startPoint]),await l.git.raw([...Qa,"cherry-pick","--no-commit",l.deliveryCommit]),await l.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:l.mountAs,branch:l.branch,baseSha:l.baseSha})}catch(d){return await l.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await Fo(a,n),{ok:!1,message:`apply failed in ${l.mountAs}: ${er(d)} (rolled back all repos)`}}let u=It(t.contextDir);u[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},ec(t.contextDir,u);let p=c.map(l=>l.mountAs).join(", "),f=o==="apply"?`review, push branch '${i.repos[0]?.branchName}', then: /applied ${r} --pr <url>`:`review with 'git diff', commit & push yourself, then: /applied ${r} --pr <url>`;return{ok:!0,message:`${o==="apply"?"applied":"unstashed"} ${r} in ${p}
573
573
  ${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(`
574
+ or: /abort ${r} --reason "..."`}}function qo(t,e){let r=It(t);r[e]&&(delete r[e],ec(t,r))}async function Fo(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(o){e.warn(`rollback failed in ${r.mountAs}: ${er(o)} \u2014 check manually`)}}async function rc(t,e,r){let n=It(t.contextDir)[e];if(n){for(let i of n.repos){let s=tr(t.root,i.mountAs);if(!Wo(tr(s,".git")))continue;let a=Ko(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),u=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",u]),await a.reset(["--hard",u]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${er(p)} \u2014 check manually`)}}qo(t.contextDir,e)}}async function rf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function er(t){return t instanceof Error?t.message.trim():String(t)}var Jr=uc(af(),".codepipe","history"),oc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],pc=500,nc=40;async function dc(){let t=Mt();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=H(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Ut(e),console.log(`connected to ${e.hubUrl} as project ${t.spec.projectId}`),console.log("type /help to list commands. Ctrl+D or /quit to exit.");let r=It(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
575
575
  \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(`
576
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Pt.createInterface({input:process.stdin,output:process.stdout,completer:lf,history:Pf(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};pi(s=>Ze(i,s)),i.daemon=Pr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>Ze(i,s),warn:s=>Ze(i,s)},onEvent:s=>vf(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),Vo(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await uf(i,a)){cc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,Vo(i),n.prompt()}),n.on("close",()=>{cc(i)})}function lf(t){let e=oc.filter(r=>r.startsWith(t));return[e.length?e:oc,t]}async function uf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return pf(),!1;case"/status":return await df(t),!1;case"/tasks":return await ff(t,o),!1;case"/task":return await mf(t,o),!1;case"/sync":return await gf(t),!1;case"/logs":return Sf(t,o),!1;case"/monitor":return Cf(t),!1;case"/apply":return await ic(t,o,"apply"),!1;case"/unstash":return await ic(t,o,"unstash"),!1;case"/applied":return await hf(t,o),!1;case"/abort":return await wf(t,o),!1;case"/approve":return await sc(t,o,"approve"),!1;case"/merge":return await sc(t,o,"merge"),!1;case"/login":return bf(t,o),!1;case"/secret":return kf(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function pf(){console.log(["/help show this list","/status connection, project, Context Repo branch, siblings","/tasks [--phase P] list tasks (optionally filtered by phase)","/task <key> task detail (phase + artifacts)","/sync clone/fetch project repos per project.yaml","/logs [n|follow|clear] tail last n daemon logs / toggle live / clear buffer","/monitor toggle live daemon log streaming (alias /logs follow)","/apply <key> apply task patch on a new branch + commit (local mode)","/unstash <key> apply task patch uncommitted on base commit","/applied <key> --pr U mark applied; --pr repo=URL for multi-repo","/abort <key> --reason roll back local apply, send task back to agent","/approve <key> merge the task's PR(s) (TRACKING, PR mode)","/merge <key> direct-merge the branch to main (TRACKING, no-PR mode)","/login <token> set the Claude OAuth token (not stored in history)","/secret set <k> <v> set a secret (not stored in history)","/secret list list secret keys (no values)","/secret unset <k> remove a secret","/quit stop the daemon and exit"].join(`
577
+ `))}async function df(t){let e=t.connection==="registered"?"registered":t.connection==="rejected"?"rejected":t.connection==="offline"?"offline (reconnecting)":"connecting";console.log(` hub: ${t.secrets.hubUrl} (${e})`),console.log(` project: ${t.ws.spec.projectId}`),console.log(` workspace: ${t.ws.root}`);for(let r of t.ws.spec.repos){let o=lc(uc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function ff(t,e){let r=Rf(e,"--phase");try{let o=await zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId),n=r?o.filter(i=>i.phase.toLowerCase()===r.toLowerCase()):o;if(n.length===0){console.log(" (no tasks)");return}for(let i of n)console.log(` ${i.key.padEnd(10)} ${i.phase.padEnd(16)} ${i.title}`)}catch(o){or(o)}}async function mf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await Ji(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r);if(console.log(` ${r}: ${o.task.phase} \u2014 ${o.task.title}`),o.artifacts.length>0){console.log(" artifacts:");for(let n of o.artifacts)console.log(` ${n.path}`)}}catch(o){or(o)}}async function gf(t){let e=await zt(t.ws.root,t.ws.spec.repos);for(let r of e)console.log(` ${r.mountAs}: ${r.status}${r.detail?` \u2014 ${r.detail}`:""}`)}async function ic(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await tc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function hf(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=It(t.ws.contextDir)[r],i=Tf(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let u=c.indexOf("="),p,f;if(u>0?(p=c.slice(0,u),f=c.slice(u+1)):(f=c,p=n?.repos.length===1?yf(t,n.repos[0].mountAs):s.length===1?s[0]:""),!p){console.log(` multi-repo task \u2014 use --pr <repoName>=<url> for ${f}`);return}let l=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!l){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(l[1])})}try{let c=await Qi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);qo(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){or(c)}}async function sc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await es(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){or(n)}}async function wf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=If(e,"--reason")||"local apply aborted";await rc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await Zi(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){or(n)}}function yf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function bf(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},Z(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function kf(t,e){let[r,o,...n]=e;if(r==="list"){let i=[];t.secrets.github&&i.push("github.token"),t.secrets.bitbucket&&i.push("bitbucket.email","bitbucket.apiToken"),t.secrets.youtrack&&i.push("youtrack.url","youtrack.token"),console.log(i.length?` ${i.join(`
578
+ `)}`:" (none)");return}if(r==="set"){let i=n.join(" ");if(!o||!i){console.log("usage: /secret set <key> <value> (keys: GH_TOKEN, YOUTRACK_URL, YOUTRACK_TOKEN, BITBUCKET_EMAIL, BITBUCKET_API_TOKEN)");return}$f(t.secrets,o,i),Z(t.secrets),Ut(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}xf(t.secrets,o),Z(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function $f(t,e,r){switch(e){case"GH_TOKEN":t.github={token:r};break;case"YOUTRACK_URL":t.youtrack={url:r,token:t.youtrack?.token??""};break;case"YOUTRACK_TOKEN":t.youtrack={url:t.youtrack?.url??"",token:r};break;case"BITBUCKET_EMAIL":t.bitbucket={email:r,apiToken:t.bitbucket?.apiToken??""};break;case"BITBUCKET_API_TOKEN":t.bitbucket={email:t.bitbucket?.email??"",apiToken:r};break;default:console.log(`unknown secret key: ${e}`)}}function xf(t,e){e.startsWith("GH")||e==="github"?delete t.github:e.toUpperCase().startsWith("YOUTRACK")||e==="youtrack"?delete t.youtrack:(e.toUpperCase().startsWith("BITBUCKET")||e==="bitbucket")&&delete t.bitbucket}function vf(t,e){switch(e.kind){case"connected":t.connection="connecting",Ze(t,"[hub] connected");break;case"registered":t.connection="registered",Ze(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",rr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",Ze(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",rr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":rr(t,`[hub] HUB v${e.hubVersion??"?"} (protocol ${e.hubProtocol??"?"}) is incompatible with this CLI \u2014 WriteActions are refused. Update: ${e.updateCommand}`);break;case"action":e.ok?Ze(t,`[hub] action ${e.actionType} done`):rr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function Ze(t,e){t.logBuffer.push(e),t.logBuffer.length>pc&&t.logBuffer.shift(),t.follow&&rr(t,e)}function Sf(t,e){let r=e[0];if(r==="follow"||r==="on"){Yo(t,!0);return}if(r==="off"){Yo(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(pc,Number(r)||nc)):nc,n=t.logBuffer.slice(-o);if(n.length===0){console.log(" (no daemon logs buffered yet)");return}for(let i of n)console.log(` ${i}`);console.log(` \u2014 ${n.length} line(s); /monitor for live stream`)}function Cf(t){Yo(t,!t.follow)}function Yo(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function rr(t,e){Pt.cursorTo(process.stdout,0),Pt.clearLine(process.stdout,0),process.stdout.write(e+`
579
+ `),t.unread+=1,Vo(t),t.rl.prompt(!0)}function Vo(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var ac=!1;function cc(t){ac||(ac=!0,Ef(t.rl),t.daemon.stop(),console.log(`
580
+ bye.`),setTimeout(()=>process.exit(0),150))}function Rf(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function Tf(t,e){let r=[];for(let o=0;o<t.length;o++)t[o]===e&&t[o+1]&&r.push(t[o+1]);return r}function If(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function or(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function Pf(){if(!lc(Jr))return[];try{return nf(Jr,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function Ef(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{of(cf(Jr),{recursive:!0}),sf(Jr,r.slice().reverse().join(`
581
581
  `)+`
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();
582
+ `)}catch{}}import{hostname as jf}from"node:os";import{cancel as Af,confirm as fc,intro as _f,isCancel as hc,log as Et,multiselect as Of,outro as mc,password as Nf,select as zo,text as Xr}from"@clack/prompts";function ir(t){Af(t),process.exit(1)}function jt(t){return hc(t)&&ir("aborted"),t}function nr(t){return hc(t)&&ir("aborted"),typeof t=="string"?t:""}function Jo(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function gc(t,e){try{let{secret:r}=await Cr(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&ir("this HUB has no account-issued sandbox registration \u2014 issue a registration token in the dashboard (Status \u2192 SANDBOX) and re-run with it"),r}}async function Uf(t,e){if(jt(await zo({message:"which projects should this worker serve?",options:[{value:"all",label:"all my projects (recommended \u2014 new projects included automatically)"},{value:"selected",label:"only selected projects"}],initialValue:"all"}))==="all")return[];if(e)try{let n=await qi(t,e);if(n.length>0)return jt(await Of({message:"pick the projects (space to toggle, enter to confirm)",options:n.map(i=>({value:i.id,label:`${i.id} \u2014 ${i.name}`})),required:!0}));Et.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){Et.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return nr(await Xr({message:"project ids (comma or space separated)",placeholder:"acme, beta",validate:n=>n.trim().length>0?void 0:"required"})).split(/[\s,]+/).filter(Boolean)}async function Xo(t){_f("codepipe worker \u2014 set up this machine as a runner");let e=te(t.profile);e&&(Et.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),jt(await fc({message:"re-register this worker?",initialValue:!1}))||ir("keeping the existing registration"));let r=Re(t.profile)??Re(),o=nr(await Xr({message:"HUB URL",placeholder:pe,initialValue:_("HUB_URL")??r?.hubUrl??pe,validate:l=>l.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=jt(await zo({message:"how to authorize the registration?",options:[...n?[{value:"local",label:"this machine's CLI account (recommended \u2014 no token hand-off)"}]:[],{value:"login",label:"log in by email (magic-link, like codepipe init)"},{value:"paste",label:"paste a registration token from the dashboard"}],initialValue:n?"local":"login"})),s,a=null;if(i==="local")a=r.cliToken,s=await gc(o,a),Et.success("account-issued registration token minted");else if(i==="login"){let l=nr(await Xr({message:"Email (your HUB account)",validate:d=>d.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase();a=await zr(o,l),s=await gc(o,a),Et.success("account-issued registration token minted")}else s=nr(await Nf({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||ir("a registration token is required");let c=await Uf(o,a),u=nr(await Xr({message:"worker name",initialValue:jf(),validate:l=>l.trim().length>0?void 0:"required"})).trim(),p=jt(await zo({message:"agent backend",options:[{value:"claude-headless",label:"claude-headless \u2014 Claude Code on PATH (the real thing)"},{value:"mock",label:"mock \u2014 deterministic stub (development)"},{value:"",label:"none \u2014 this worker will not claim agent jobs"}],initialValue:"claude-headless"}));if(await ze({hub:o,token:s,name:u,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Et.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!jt(await fc({message:"start the claim-loop now?",initialValue:!0}))){mc("registered. start later with `codepipe worker`.");return}mc("starting the claim-loop\u2026"),await Vt(t.profile?{profile:t.profile}:{})}function Df(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return _("PROFILE")}var X=Df();mn(X);yn();var ce=new Lf;ce.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ie).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await dc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await Ma({configPath:t.config,skipVerify:t.skipVerify===!0}):await Ea({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Tn({...t,profile:X})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await ja({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ce.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await ws({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await xa({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await qa({profile:X,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ce.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await ra({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await Xa({profile:X,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var wc=ce.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");wc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??_("HUB_URL")??Re(X)?.hubUrl??pe,r=t.token??_("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&Jo()){await Xo({profile:X});return}console.error("missing --token (or CODEPIPE_WORKER_REG_TOKEN); run `codepipe worker register` with no flags on a terminal for the wizard"),process.exit(1)}let o=_("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??_("WORKER_NAME"),i=t.llm??_("WORKER_LLM");await ze({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...X?{profile:X}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});wc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!te(X)&&Jo()){await Xo({profile:X});return}await Vt(X?{profile:X}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var Bf=ce.command("project").description("Manage CodePipe projects");Bf.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await Ja({profile:X})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ce.parseAsync();