@code-partner/codepipe 0.1.133 → 0.1.134-dev.40.g6022991

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 +94 -94
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
1
  #!/usr/bin/env node
2
- var ce="0.1.133",me="https://hub.codepipe.dev";var ge=2,Wc=1;function mr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Wc&&t<=ge}var ve=".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",ve]}];function gr(t=1){return`# CodePipe Context Repo format version.
2
+ var ae="0.1.134-dev.40.g6022991",de="https://hub.dev.codepipe.dev";var fe=2,Yc=1;function hr(t){return typeof t!="number"||!Number.isFinite(t)?!1:t>=Yc&&t<=fe}var ve=".devpipe-context.yaml",Tn=[{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",ve]}];function yr(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 Tn(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 Rn(t,e=Sn){return e.filter(r=>r.version>t)}function hr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}function In(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}var ze=/^[a-z][a-z0-9-]{1,30}$/,qc="-codepipe-ctx";function Se(t){return`${t}${qc}`}var Gt={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function ut(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 Je="x-bitbucket-api-token-auth";function yr(t){switch(t){case Gt.gitlab:return"oauth2";case Gt.bitbucket:return"x-token-auth";default:return"x-access-token"}}var Pn=20;function N(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as mm}from"commander";import{homedir as Nn}from"node:os";import{mkdirSync as rl,readFileSync as ol,writeFileSync as nl,existsSync as wo}from"node:fs";import{dirname as Un,join as kr,resolve as il}from"node:path";import{fileURLToPath as sl}from"node:url";import{existsSync as wr,readFileSync as En,readdirSync as Vc,writeFileSync as zc}from"node:fs";import{dirname as Jc,join as Ae}from"node:path";import{parse as Xc}from"yaml";import{existsSync as jn,renameSync as Yc}from"node:fs";function Xe(t,e,r=o=>console.error(o)){if(jn(e)||!jn(t))return!1;try{return Yc(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}var he=".codepipe",yo=".devpipe";function Qc(t=process.cwd()){let e=t;for(;;){if(wr(Ae(e,he,"project.yaml")))return e;if(wr(Ae(e,yo,"project.yaml")))return Xe(Ae(e,yo),Ae(e,he))&&el(e),e;let r=Jc(e);if(r===e)return null;e=r}}function Zc(t){let e=Ae(t,he);return wr(e)?e:Ae(t,yo)}function el(t){let e=Ae(t,".gitignore");if(!wr(e))return;let r=En(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
6
- `);o!==r&&zc(e,o)}function Qe(t=process.cwd()){let e=Qc(t);if(!e)return null;let r=Zc(e),o=tl(En(Ae(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function An(t,e,r){return Vc(t).filter(n=>n!==".DS_Store").length===0?!0:e?r.some(n=>n.host===e.host&&n.owner===e.owner&&n.repoName===e.repoName):!1}function br(t,e=process.cwd()){try{let r=Qe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function tl(t){let e=Xc(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let p=a.host,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:o,repos:i}}function _n(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 On=il(Un(sl(import.meta.url)),"..");function Ln(t){let e=kr(On,".env");if(wo(e)&&process.loadEnvFile(e),t){let r=kr(On,"profiles",t,".env");wo(r)&&process.loadEnvFile(r)}}function pt(t){let e=N("CONFIG");return e||(t?kr(Nn(),".codepipe","profiles",t,"config.json"):kr(Nn(),".codepipe","config.json"))}function Ce(t){let e=pt(t);if(!wo(e))return null;let r=ol(e,"utf-8");return JSON.parse(r)}function Ze(t,e){let r=pt(e);rl(Un(r),{recursive:!0}),nl(r,JSON.stringify(t,null,2)+`
7
- `,{mode:384})}function $r(t){if(t)return{cfg:_e(t),profile:t};let e;try{e=Qe()?.spec.projectId||void 0}catch{}if(e){let r=Ce(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:_e(void 0),profile:void 0}}function _e(t){let e=Ce(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 ${pt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Bn}from"node:os";import{join as Dn}from"node:path";function Gn(){Xe(Dn(Bn(),".devpipe"),Dn(Bn(),".codepipe"))}import{homedir as Mn}from"node:os";import{existsSync as Fn,mkdirSync as Hn,readFileSync as Kn,writeFileSync as Wn}from"node:fs";import{dirname as qn,join as Yn}from"node:path";function xr(t,e,r){let o=U(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,z(o),"pinned")}function et(t){return Yn(Mn(),".codepipe","secrets",`${t}.json`)}function U(t){let e=et(t);return Fn(e)?JSON.parse(Kn(e,"utf-8")):null}function z(t){let e=et(t.projectId);Hn(qn(e),{recursive:!0}),Wn(e,JSON.stringify(t,null,2)+`
8
- `,{mode:384})}function vr(){return Yn(Mn(),".codepipe","shared.json")}function bo(){let t=vr();return Fn(t)?JSON.parse(Kn(t,"utf-8")):null}function Vn(t){let e=vr();Hn(qn(e),{recursive:!0}),Wn(e,JSON.stringify(t,null,2)+`
9
- `,{mode:384})}function dt(t){let e=U(t)?.claude?.oauthToken;return e||bo()?.claude?.oauthToken}function Mt(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 ft(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function zn(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=Ce(e);r&&!t.force&&(console.error(`already configured at ${pt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Ze({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...U(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};z(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${pt(e)}`)}import{homedir as Ko}from"node:os";import{join as Jt}from"node:path";import{appendFileSync as al,existsSync as Jn,mkdirSync as cl,renameSync as Xn,statSync as ll,unlinkSync as ul}from"node:fs";import{Writable as pl}from"node:stream";import{join as dl}from"node:path";var Qn={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},mt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&cl(e.dir,{recursive:!0}),this.currentPath=dl(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 Rn(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 In(t,e=Tn){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 Pn(t,e=Tn){return e.filter(r=>r.version>t)}function wr(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,totalCostUsd:0,model:"",numTurns:0,durationMs:0}}function jn(t){return!(!t||t.length>250||!/^[A-Za-z0-9._/-]+$/.test(t)||/^[-/.]/.test(t)||/[/.]$/.test(t)||t.endsWith(".lock")||t.includes("..")||t.includes("//")||t.includes("/."))}var Ve=/^[a-z][a-z0-9-]{1,30}$/,Vc="-codepipe-ctx";function Se(t){return`${t}${Vc}`}var Ft={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"};function pt(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 ze="x-bitbucket-api-token-auth";function br(t){switch(t){case Ft.gitlab:return"oauth2";case Ft.bitbucket:return"x-token-auth";default:return"x-access-token"}}var En=20;function O(t){return process.env[`CODEPIPE_${t}`]??process.env[`DEVPIPE_${t}`]}import{Command as hm}from"commander";import{homedir as Un}from"node:os";import{mkdirSync as nl,readFileSync as il,writeFileSync as sl,existsSync as ko}from"node:fs";import{dirname as Bn,join as xr,resolve as al}from"node:path";import{fileURLToPath as cl}from"node:url";import{existsSync as kr,readFileSync as _n,readdirSync as Jc,writeFileSync as Xc}from"node:fs";import{dirname as Qc,join as Ee}from"node:path";import{parse as Zc}from"yaml";import{existsSync as An,renameSync as zc}from"node:fs";function Je(t,e,r=o=>console.error(o)){if(An(e)||!An(t))return!1;try{return zc(t,e),r(`migrated ${t} \u2192 ${e} (DevPipe \u2192 CodePipe)`),!0}catch(o){return r(`failed to migrate ${t} \u2192 ${e}: ${o instanceof Error?o.message:String(o)} \u2014 continuing with the legacy path untouched`),!1}}var me=".codepipe",bo=".devpipe";function el(t=process.cwd()){let e=t;for(;;){if(kr(Ee(e,me,"project.yaml")))return e;if(kr(Ee(e,bo,"project.yaml")))return Je(Ee(e,bo),Ee(e,me))&&rl(e),e;let r=Qc(e);if(r===e)return null;e=r}}function tl(t){let e=Ee(t,me);return kr(e)?e:Ee(t,bo)}function rl(t){let e=Ee(t,".gitignore");if(!kr(e))return;let r=_n(e,"utf-8"),o=r.split(/\r?\n/).map(n=>{let i=n.trim();return i===".devpipe"||i===".devpipe/"||i==="/.devpipe"||i==="/.devpipe/"?n.replace(".devpipe",".codepipe"):n}).join(`
6
+ `);o!==r&&Xc(e,o)}function Xe(t=process.cwd()){let e=el(t);if(!e)return null;let r=tl(e),o=ol(_n(Ee(r,"project.yaml"),"utf-8"));return{root:e,contextDir:r,spec:o}}function Nn(t,e,r){return Jc(t).filter(n=>n!==".DS_Store").length===0?!0:e?r.some(n=>n.host===e.host&&n.owner===e.owner&&n.repoName===e.repoName):!1}function $r(t,e=process.cwd()){try{let r=Xe(e);return r&&r.spec.projectId===t?r:null}catch{return null}}function ol(t){let e=Zc(t);if(!e||typeof e!="object")throw new Error("project.yaml is empty or malformed");let r=String(e.id??""),o=String(e.name??r),n=Array.isArray(e.repos)?e.repos:[],i=[];for(let s of n){if(!s||typeof s!="object")continue;let a=s,c=String(a.repo??a.repoName??""),l=String(a.name??c);if(!l||!c)continue;let p=a.host,f=p==="bitbucket"?"bitbucket":p==="gitlab"?"gitlab":"github";i.push({name:l,host:f,owner:String(a.owner??""),repoName:c,defaultBranch:String(a.default_branch??a.defaultBranch??"main"),mountAs:String(a.mount_as??a.mountAs??l)})}return{projectId:r,name:o,repos:i}}function On(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 Ln=al(Bn(cl(import.meta.url)),"..");function Dn(t){let e=xr(Ln,".env");if(ko(e)&&process.loadEnvFile(e),t){let r=xr(Ln,"profiles",t,".env");ko(r)&&process.loadEnvFile(r)}}function dt(t){let e=O("CONFIG");return e||(t?xr(Un(),".codepipe","profiles",t,"config.json"):xr(Un(),".codepipe","config.json"))}function Ce(t){let e=dt(t);if(!ko(e))return null;let r=il(e,"utf-8");return JSON.parse(r)}function Qe(t,e){let r=dt(e);nl(Bn(r),{recursive:!0}),sl(r,JSON.stringify(t,null,2)+`
7
+ `,{mode:384})}function vr(t){if(t)return{cfg:Ae(t),profile:t};let e;try{e=Xe()?.spec.projectId||void 0}catch{}if(e){let r=Ce(e);if(r)return console.log(`[profile] ${e} \u2014 resolved from this folder's workspace`),{cfg:r,profile:e};console.error(`this folder is the workspace of project '${e}', but that CLI profile is not initialised on this machine \u2014 run \`codepipe init\` here (or pass --profile).`),process.exit(1)}return{cfg:Ae(void 0),profile:void 0}}function Ae(t){let e=Ce(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 ${dt(t)} is missing 'projectId'. re-run init with --force.`),process.exit(1)),e}import{homedir as Gn}from"node:os";import{join as Mn}from"node:path";function Fn(){Je(Mn(Gn(),".devpipe"),Mn(Gn(),".codepipe"))}import{homedir as Hn}from"node:os";import{existsSync as Kn,mkdirSync as Wn,readFileSync as qn,writeFileSync as Yn}from"node:fs";import{dirname as Vn,join as zn}from"node:path";function Sr(t,e,r){let o=L(t);if(!o)return"mismatch";let n=o.sandboxPins??{},i=n[e];return i&&i===r?"ok":i&&i!==r?"mismatch":(n[e]=r,o.sandboxPins=n,V(o),"pinned")}function Ze(t){return zn(Hn(),".codepipe","secrets",`${t}.json`)}function L(t){let e=Ze(t);return Kn(e)?JSON.parse(qn(e,"utf-8")):null}function V(t){let e=Ze(t.projectId);Wn(Vn(e),{recursive:!0}),Yn(e,JSON.stringify(t,null,2)+`
8
+ `,{mode:384})}function Cr(){return zn(Hn(),".codepipe","shared.json")}function $o(){let t=Cr();return Kn(t)?JSON.parse(qn(t,"utf-8")):null}function Jn(t){let e=Cr();Wn(Vn(e),{recursive:!0}),Yn(e,JSON.stringify(t,null,2)+`
9
+ `,{mode:384})}function ft(t){let e=L(t)?.claude?.oauthToken;return e||$o()?.claude?.oauthToken}function Ht(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 mt(){let t=process.env.BITBUCKET_EMAIL,e=process.env.BITBUCKET_API_TOKEN;return t&&e?{email:t,apiToken:e}:void 0}async function Xn(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=Ce(e);r&&!t.force&&(console.error(`already configured at ${dt(e)} (hub=${r.hubUrl}).`),console.error("pass --force to overwrite."),process.exit(1));let o=t.hub.replace(/\/$/,"");Qe({hubUrl:o,cliToken:t.token,projectId:t.project},e);let i={...L(t.project)??{},hubUrl:o,cliToken:t.token,projectId:t.project};V(i),console.log(`configured \u2192 hub=${o}, project=${t.project}, config=${dt(e)}`)}import{homedir as qo}from"node:os";import{join as Qt}from"node:path";import{appendFileSync as ll,existsSync as Qn,mkdirSync as ul,renameSync as Zn,statSync as pl,unlinkSync as dl}from"node:fs";import{Writable as fl}from"node:stream";import{join as ml}from"node:path";var ei={enabled:!0,maxBytes:10*1024*1024,maxFiles:5},gt=class{cfg;currentPath;constructor(e){this.cfg=e,e.enabled&&ul(e.dir,{recursive:!0}),this.currentPath=ml(e.dir,`${e.basename}.log`)}get path(){return this.currentPath}writeLine(e){if(!this.cfg.enabled)return;this.rotateIfNeeded();let r=e.endsWith(`
10
10
  `)?e:e+`
11
- `;al(this.currentPath,r,"utf-8")}asWritable(){return new pl({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||!Jn(this.currentPath)||ll(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Jn(o)&&(r>=this.cfg.maxFiles?ul(o):Xn(o,`${this.currentPath}.${r+1}`))}Xn(this.currentPath,`${this.currentPath}.1`)}}};function Sr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=fl(process.env[`${t}_MAX_BYTES`]??String(Qn.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):Qn.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function fl(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 Cr(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(ml(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 ml(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:gl(n)).join(" ");return`${r} ${t} ${o}`}function gl(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as mp}from"node:path";import"ws";import{createHash as hl}from"node:crypto";import{existsSync as yl,readFileSync as wl}from"node:fs";import{homedir as bl,hostname as ko}from"node:os";import{join as kl}from"node:path";function Zn(t){return hl("sha256").update(t).digest("hex").slice(0,12)}function $l(){let t=N("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=kl(bl(),".claude","credentials.json");if(!yl(e))return;let r=JSON.parse(wl(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 ei(t){let e=$l(),r=N("ACCOUNT_ID")?.trim(),o=N("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=dt(t);return n?{accountId:`acct-${Zn(n)}`,label:o||ko(),...e?{email:e}:{}}:{accountId:`acct-${Zn(`host:${ko()}`)}`,label:o||ko(),...e?{email:e}:{}}}import{existsSync as xl}from"node:fs";import{join as vl}from"node:path";import{simpleGit as Sl}from"simple-git";async function ti(t,e){if(!xl(vl(t,".git")))return{status:"skipped"};let r=Sl(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Cl(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 Cl(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as $o,readFileSync as ri,readdirSync as Tl,watch as Rl}from"node:fs";import{join as xo}from"node:path";var Tr=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($o(this.contextDir))try{this.watcher=Rl(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=xo(this.contextDir,e);if(!$o(r))return null;try{return ri(r,"utf-8")}catch{return null}}readPrompts(){let e=xo(this.contextDir,"prompts"),r={};if(!$o(e))return r;let o;try{o=Tl(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=ri(xo(e,n),"utf-8")}catch{}}return r}};import{existsSync as Bl,readFileSync as Dl,readdirSync as Gl}from"node:fs";import{join as li}from"node:path";import{simpleGit as Ml}from"simple-git";import{existsSync as El,mkdirSync as Al,writeFileSync as ii}from"node:fs";import{dirname as _l,isAbsolute as Nl,join as ai,normalize as Ro}from"node:path";import{simpleGit as ci}from"simple-git";import{existsSync as Ne,mkdirSync as oi,readFileSync as vo,writeFileSync as gt}from"node:fs";import{homedir as Il}from"node:os";import{join as ye}from"node:path";import{simpleGit as Pl}from"simple-git";var ht=["project.yaml","regimen.yaml"];function Ft(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=ye(t,n);Ne(s)||(gt(s,i),r.push(n))}return r}function tt(t,e,r){let o=ye(Il(),".codepipe","profiles",t,"context-config");return oi(o,{recursive:!0}),gt(ye(o,"project.yaml"),e.projectYaml),gt(ye(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Rr(t,e,r){if(Ne(e))for(let o of ht){let n=ye(e,o),i=ye(t,o);if(!(!Ne(n)||Ne(i)))try{gt(i,vo(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 jl=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function yt(t){let e=ye(t,".gitignore"),r=Ne(e)?vo(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(ht.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
11
+ `;ll(this.currentPath,r,"utf-8")}asWritable(){return new fl({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||!Qn(this.currentPath)||pl(this.currentPath).size<this.cfg.maxBytes)){for(let r=this.cfg.maxFiles;r>=1;r--){let o=`${this.currentPath}.${r}`;Qn(o)&&(r>=this.cfg.maxFiles?dl(o):Zn(o,`${this.currentPath}.${r+1}`))}Zn(this.currentPath,`${this.currentPath}.1`)}}};function Tr(t,e,r){let o=(process.env[`${t}_FILE_ENABLED`]??"true").toLowerCase()!=="false",n=process.env[`${t}_DIR`]??r,i=gl(process.env[`${t}_MAX_BYTES`]??String(ei.maxBytes)),s=process.env[`${t}_MAX_FILES`],a=s?Math.max(1,Number(s)):ei.maxFiles;return{enabled:o,dir:n,basename:e,maxBytes:i,maxFiles:a}}function gl(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 Rr(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(hl(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 hl(t,e){let r=new Date().toISOString(),o=e.map(n=>typeof n=="string"?n:yl(n)).join(" ");return`${r} ${t} ${o}`}function yl(t){try{return JSON.stringify(t)}catch{return String(t)}}import{join as hp}from"node:path";import"ws";import{createHash as wl}from"node:crypto";import{existsSync as bl,readFileSync as kl}from"node:fs";import{homedir as $l,hostname as xo}from"node:os";import{join as xl}from"node:path";function ti(t){return wl("sha256").update(t).digest("hex").slice(0,12)}function vl(){let t=O("ACCOUNT_EMAIL")?.trim();if(t)return t.toLowerCase();try{let e=xl($l(),".claude","credentials.json");if(!bl(e))return;let r=JSON.parse(kl(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 ri(t){let e=vl(),r=O("ACCOUNT_ID")?.trim(),o=O("ACCOUNT_LABEL")?.trim();if(r)return{accountId:r,label:o||r,...e?{email:e}:{}};let n=ft(t);return n?{accountId:`acct-${ti(n)}`,label:o||xo(),...e?{email:e}:{}}:{accountId:`acct-${ti(`host:${xo()}`)}`,label:o||xo(),...e?{email:e}:{}}}import{existsSync as Sl}from"node:fs";import{join as Cl}from"node:path";import{simpleGit as Tl}from"simple-git";async function oi(t,e){if(!Sl(Cl(t,".git")))return{status:"skipped"};let r=Tl(t);try{await r.fetch()}catch(n){return{status:"warn",reason:`git fetch failed: ${Rl(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 Rl(t){return t instanceof Error?t.message.trim():String(t)}import{existsSync as vo,readFileSync as ni,readdirSync as Il,watch as Pl}from"node:fs";import{join as So}from"node:path";var Ir=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(vo(this.contextDir))try{this.watcher=Pl(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(!vo(r))return null;try{return ni(r,"utf-8")}catch{return null}}readPrompts(){let e=So(this.contextDir,"prompts"),r={};if(!vo(e))return r;let o;try{o=Il(e)}catch{return r}for(let n of o){if(!n.endsWith(".md"))continue;let i=n.slice(0,-3);try{r[i]=ni(So(e,n),"utf-8")}catch{}}return r}};import{existsSync as Gl,readFileSync as Ml,readdirSync as Fl}from"node:fs";import{join as pi}from"node:path";import{simpleGit as Hl}from"simple-git";import{existsSync as _l,mkdirSync as Nl,writeFileSync as ai}from"node:fs";import{dirname as Ol,isAbsolute as Ul,join as li,normalize as Po}from"node:path";import{simpleGit as ui}from"simple-git";import{existsSync as _e,mkdirSync as ii,readFileSync as Co,writeFileSync as ht}from"node:fs";import{homedir as jl}from"node:os";import{join as ge}from"node:path";import{simpleGit as El}from"simple-git";var yt=["project.yaml","regimen.yaml"];function Kt(t,e){let r=[],o=[["project.yaml",e.projectYaml],["regimen.yaml",e.regimenYaml]];for(let[n,i]of o){let s=ge(t,n);_e(s)||(ht(s,i),r.push(n))}return r}function et(t,e,r){let o=ge(jl(),".codepipe","profiles",t,"context-config");return ii(o,{recursive:!0}),ht(ge(o,"project.yaml"),e.projectYaml),ht(ge(o,"regimen.yaml"),e.regimenYaml),r.info(`local project config staged \u2192 ${o}`),o}function Pr(t,e,r){if(_e(e))for(let o of yt){let n=ge(e,o),i=ge(t,o);if(!(!_e(n)||_e(i)))try{ht(i,Co(n)),r.info(`[config] seeded local ${o} from the provisioning bundle`)}catch(s){r.warn(`[config] could not seed ${o}: ${s instanceof Error?s.message:String(s)}`)}}}var Al=["# codepipe project config is local to this workspace","project.yaml","regimen.yaml"];function wt(t){let e=ge(t,".gitignore"),r=_e(e)?Co(e,"utf-8"):"",o=new Set(r.split(/\r?\n/).map(s=>s.trim()));if(yt.filter(s=>!o.has(s)&&!o.has(`/${s}`)).length===0)return!1;let i=r.length===0||r.endsWith(`
12
12
  `)?"":`
13
- `;return gt(e,r+i+jl.join(`
13
+ `;return ht(e,r+i+Al.join(`
14
14
  `)+`
15
- `),!0}async function ni(t,e){try{if(!Ne(ye(t,".git")))return;let r=Pl(t),o=(await r.raw(["ls-files","--",...ht])).split(`
16
- `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;yt(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 To(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 So(t){let e=new Map;for(let r of ht){let o=ye(t,r);Ne(o)&&e.set(r,vo(o))}return e}function Co(t,e){oi(t,{recursive:!0});for(let[r,o]of e){let n=ye(t,r);Ne(n)||gt(n,o)}}var si=3,Ol=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function Ir(t,e,r){if(!El(ai(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Ll(t,i.path);Al(_l(s),{recursive:!0}),i.encoding==="base64"?ii(s,Buffer.from(i.content,"base64")):ii(s,i.content)}let o=ci(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...ht]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await To(t))}async function To(t){let e=ci(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=si;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 Ul(e);if(i.length>0&&i.every(s=>Ol.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 ${si} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Ul(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
- `).map(r=>r.trim()).filter(Boolean)}function Ll(t,e){if(Nl(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Ro(ai(t,e)),o=Ro(t+"/");if(r!==Ro(t)&&!r.startsWith(o))throw new Error(`context_write: path escapes context repo: ${e}`);return r}var Fl=/^(\d{4})-(.+)\.md$/,Hl="0000-template.md";function Kl(t){let e=t.split(`
18
- `),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function Wl(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
19
- `),a=s.findIndex(x=>x.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),p=[],f="",u=null,d=a>=0?a+1:0;for(let x=d;x<s.length;x++){let v=(s[x]??"").trim();if(v===""){d=x+1;continue}let A=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(v);if(!A)break;let I=(A[1]??"").trim().toLowerCase(),L=(A[2]??"").trim(),C=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(v);C&&(u=parseInt(C[1]??"",10)),I==="tasks"&&(f=L),l.has(I)||p.push(v),d=x+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,y=s.slice(d).join(`
20
- `).replace(/^\n+/,""),S=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${g}`,...p,"",y].join(`
21
- `);return{content:S.endsWith(`
22
- `)?S:S+`
23
- `,supersedes:u}}function ql(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
24
-
25
- - **Status:** superseded by ADR-${r}`):o}function Yl(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(`
15
+ `),!0}async function si(t,e){try{if(!_e(ge(t,".git")))return;let r=El(t),o=(await r.raw(["ls-files","--",...yt])).split(`
16
+ `).map(n=>n.trim()).filter(Boolean);if(o.length===0)return;wt(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 Io(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 To(t){let e=new Map;for(let r of yt){let o=ge(t,r);_e(o)&&e.set(r,Co(o))}return e}function Ro(t,e){ii(t,{recursive:!0});for(let[r,o]of e){let n=ge(t,r);_e(n)||ht(n,o)}}var ci=3,Ll=new Set(["knowledge/INDEX.md","adr/INDEX.md","adr/SOURCES.md"]);async function jr(t,e,r){if(!_l(li(t,".git")))throw new Error(`context repo clone not found at ${t}`);for(let i of e){let s=Dl(t,i.path);Nl(Ol(s),{recursive:!0}),i.encoding==="base64"?ai(s,Buffer.from(i.content,"base64")):ai(s,i.content)}let o=ui(t);await o.add(["-A","--","."]),await o.raw(["reset","-q","--",...yt]).catch(()=>{}),(await o.raw(["diff","--cached","--name-only"])).trim()&&(await o.commit(r),await Io(t))}async function Io(t){let e=ui(t,{unsafe:{allowUnsafeEditor:!0}}),r;for(let o=0;o<=ci;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 Bl(e);if(i.length>0&&i.every(s=>Ll.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 ${ci} rebase retries: ${r instanceof Error?r.message:String(r)}`)}async function Bl(t){return(await t.raw(["diff","--name-only","--diff-filter=U"]).catch(()=>"")).split(`
17
+ `).map(r=>r.trim()).filter(Boolean)}function Dl(t,e){if(Ul(e))throw new Error(`context_write: absolute path rejected: ${e}`);let r=Po(li(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 Kl=/^(\d{4})-(.+)\.md$/,Wl="0000-template.md";function ql(t){let e=t.split(`
18
+ `),r=e.find(i=>i.startsWith("# ")),o=r?r.replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim():"",n=i=>{let s=new RegExp(`^-\\s*\\*\\*${i}:\\*\\*\\s*(.*)$`,"i");for(let a of e){let c=s.exec(a.trim());if(c)return(c[1]??"").trim()}return""};return{title:o,status:n("Status"),date:n("Date")}}function Yl(t,e,r,o,n){let i=String(e).padStart(4,"0"),s=t.split(`
19
+ `),a=s.findIndex(x=>x.startsWith("# ")),c=a>=0&&(s[a]??"").replace(/^#\s*(ADR-[\w?]+\s*:\s*)?/i,"").trim()||r,l=new Set(["status","date","tasks"]),p=[],f="",u=null,d=a>=0?a+1:0;for(let x=d;x<s.length;x++){let S=(s[x]??"").trim();if(S===""){d=x+1;continue}let E=/^-\s*\*\*([\w ]+):\*\*\s*(.*)$/.exec(S);if(!E)break;let I=(E[1]??"").trim().toLowerCase(),B=(E[2]??"").trim(),C=/supersedes?\b.*?ADR-(\d{1,4})/i.exec(S);C&&(u=parseInt(C[1]??"",10)),I==="tasks"&&(f=B),l.has(I)||p.push(S),d=x+1}let g=f?f.includes(o)?f:`${f}, ${o}`:o,y=s.slice(d).join(`
20
+ `).replace(/^\n+/,""),v=[`# ADR-${i}: ${c}`,"","- **Status:** accepted",`- **Date:** ${n}`,`- **Tasks:** ${g}`,...p,"",y].join(`
21
+ `);return{content:v.endsWith(`
22
+ `)?v:v+`
23
+ `,supersedes:u}}function Vl(t,e){let r=String(e).padStart(4,"0"),o=t.replace(/^(-\s*\*\*Status:\*\*).*$/im,`$1 superseded by ADR-${r}`);return o===t?t.replace(/^(# .*)$/m,`$1
24
+
25
+ - **Status:** superseded by ADR-${r}`):o}function zl(t){let e=["# ADR index","","<!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->",""];if(t.length===0)e.push("(no accepted ADRs yet)");else for(let r of[...t].sort((o,n)=>o.num-n.num)){let o=String(r.num).padStart(4,"0"),n=[r.header.status||"accepted",r.header.date].filter(Boolean).join(", ");e.push(`- [ADR-${o} \u2014 ${r.header.title||r.file}](${r.file}) \u2014 ${n}`)}return e.join(`
26
26
  `)+`
27
- `}async function ui(t,e,r,o=new Date().toISOString().slice(0,10)){try{await Ml(t).pull(void 0,void 0,["--rebase"])}catch{}let n=li(t,"adr"),i=new Map;if(Bl(n))for(let u of Gl(n)){let d=Fl.exec(u);!d||u===Hl||i.set(u,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:Dl(li(n,u),"utf-8")})}let s=Math.max(0,...[...i.values()].map(u=>u.num))+1,a=new Map,c=[],l=[];for(let u of r){if([...i.entries()].find(([,v])=>v.slug===u.slug&&v.content.includes(e))){l.push(u.slug);continue}let g=s++,y=`${String(g).padStart(4,"0")}-${u.slug}.md`,{content:S,supersedes:x}=Wl(u.content,g,u.slug,e,o);if(a.set(y,S),i.set(y,{num:g,slug:u.slug,content:S}),c.push(`adr/${y}`),x!==null){let v=[...i.keys()].find(A=>A.startsWith(`${String(x).padStart(4,"0")}-`));if(v&&v!==y){let A=ql(a.get(v)??i.get(v).content,g);a.set(v,A),i.set(v,{...i.get(v),content:A})}}}if(c.length===0)return{promoted:c,skipped:l};let p=[...i.entries()].map(([u,d])=>({num:d.num,file:u,header:Kl(d.content)}));a.set("INDEX.md",Yl(p));let f=[...a.entries()].map(([u,d])=>({path:`adr/${u}`,content:d}));return await Ir(t,f,`adr(${e}): promote ${r.map(u=>u.slug).join(", ")}`),{promoted:c,skipped:l}}import{existsSync as pi,readFileSync as zl}from"node:fs";import{join as di}from"node:path";function Jl(t){let e=di(t,ve);if(!pi(e))return 0;try{return Cn(zl(e,"utf-8"))}catch{return 0}}function Xl(t,e,r,o=1){let n=e<o,i=n?Tn(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Pr(t,e){return Xl(e,Jl(t),r=>pi(di(t,r)))}import{existsSync as du,mkdirSync as fu,mkdtempSync as mu,rmSync as gu,writeFileSync as hi}from"node:fs";import{tmpdir as hu}from"node:os";import{dirname as yu,join as Ao}from"node:path";import{simpleGit as _o}from"simple-git";var rt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function fi(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
- `+t.slice(t.length-e)}async function Oe(t,e){let r={Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"},o;try{o=await fetch("https://api.github.com/user",{headers:r})}catch(a){throw new Error(`cannot reach api.github.com (${a instanceof Error?a.message:String(a)})`)}if(o.status===401)throw new Error("token rejected (401 \u2014 check the GitHub PAT)");if(!o.ok)throw new Error(`GitHub \u2192 ${o.status} ${o.statusText}`);let i=(await o.json()).login??"ok",s=o.headers.get("x-oauth-scopes");if(s!==null&&e&&!s.split(",").map(c=>c.trim()).includes("repo"))throw new Error(`classic PAT is missing the 'repo' scope (present: "${s||"none"}") \u2014 required to create and write to GitHub repos`);if(e){let a;try{let c=await fetch(`https://api.github.com/users/${encodeURIComponent(e.owner)}`,{headers:r});c.ok&&(a=(await c.json()).type)}catch{}if(a==="Organization"){let c=await fetch(`https://api.github.com/orgs/${encodeURIComponent(e.owner)}`,{headers:r});if(c.status===403)throw new Error(`token cannot access org "${e.owner}" (403) \u2014 for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens; for classic PATs: verify 'repo' or 'admin:org' scope`);if(c.status===404)throw new Error(`org "${e.owner}" not found or not visible to this token \u2014 check the org name; for fine-grained PATs: approve the token in org Settings \u2192 Personal access tokens`);if(!c.ok)throw new Error(`GitHub GET /orgs/${e.owner} \u2192 ${c.status} ${c.statusText}`)}}return i}async function jr(t,e,r){let o=`https://api.github.com/repos/${encodeURIComponent(e)}/${encodeURIComponent(r)}`,n;try{n=await fetch(o,{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json","User-Agent":"codepipe-cli"}})}catch(s){throw new Error(`cannot reach api.github.com (${s instanceof Error?s.message:String(s)})`)}if(n.status===401)throw new Error("token rejected (401 \u2014 expired/revoked PAT)");if(n.status===404)throw new Error(`repo ${e}/${r} not found or token has no access (404)`);if(!n.ok)throw new Error(`GitHub GET /repos/${e}/${r} \u2192 ${n.status} ${n.statusText}`);if((await n.json()).permissions?.push!==!0)throw new Error(`no push access to ${e}/${r} (read-only key or insufficient token)`)}async function Ue(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 Ql(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 Ql(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Le(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 gi(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 Io=class{constructor(e,r){this.email=e;this.apiToken=r}name="bitbucket";authHeader(){return"Basic "+Buffer.from(`${this.email}:${this.apiToken}`).toString("base64")}async createPullRequest(e,r){let o=await fetch(`https://api.bitbucket.org/2.0/repositories/${e.owner}/${e.repoName}/pullrequests`,{method:"POST",headers:{Authorization:this.authHeader(),"Content-Type":"application/json"},body:JSON.stringify({title:r.title,description:r.body,source:{branch:{name:r.branchName}},destination:{branch:{name:r.baseBranch}}})});if(!o.ok)throw new Error(`bitbucket pr create: ${o.status} ${await o.text()}`);let 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 rt(`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()}`)}},Po=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 rt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],p=[];for(let f of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!u.ok)continue;let d=(await u.json()).jobs??[];for(let g of d.filter(y=>y.conclusion==="failure")){let y=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!y.ok)continue;let S=await y.text();p.push(`### CI job: ${g.name}
27
+ `}async function di(t,e,r,o=new Date().toISOString().slice(0,10)){try{await Hl(t).pull(void 0,void 0,["--rebase"])}catch{}let n=pi(t,"adr"),i=new Map;if(Gl(n))for(let u of Fl(n)){let d=Kl.exec(u);!d||u===Wl||i.set(u,{num:parseInt(d[1]??"",10),slug:d[2]??"",content:Ml(pi(n,u),"utf-8")})}let s=Math.max(0,...[...i.values()].map(u=>u.num))+1,a=new Map,c=[],l=[];for(let u of r){if([...i.entries()].find(([,S])=>S.slug===u.slug&&S.content.includes(e))){l.push(u.slug);continue}let g=s++,y=`${String(g).padStart(4,"0")}-${u.slug}.md`,{content:v,supersedes:x}=Yl(u.content,g,u.slug,e,o);if(a.set(y,v),i.set(y,{num:g,slug:u.slug,content:v}),c.push(`adr/${y}`),x!==null){let S=[...i.keys()].find(E=>E.startsWith(`${String(x).padStart(4,"0")}-`));if(S&&S!==y){let E=Vl(a.get(S)??i.get(S).content,g);a.set(S,E),i.set(S,{...i.get(S),content:E})}}}if(c.length===0)return{promoted:c,skipped:l};let p=[...i.entries()].map(([u,d])=>({num:d.num,file:u,header:ql(d.content)}));a.set("INDEX.md",zl(p));let f=[...a.entries()].map(([u,d])=>({path:`adr/${u}`,content:d}));return await jr(t,f,`adr(${e}): promote ${r.map(u=>u.slug).join(", ")}`),{promoted:c,skipped:l}}import{existsSync as fi,readFileSync as Xl}from"node:fs";import{join as mi}from"node:path";function Ql(t){let e=mi(t,ve);if(!fi(e))return 0;try{return Rn(Xl(e,"utf-8"))}catch{return 0}}function Zl(t,e,r,o=1){let n=e<o,i=n?In(e).filter(s=>!r(s)):[];return{type:"context_status",projectId:t,templateVersion:e,currentVersion:o,outdated:n,missingPaths:i}}function Er(t,e){return Zl(e,Ql(t),r=>fi(mi(t,r)))}import{existsSync as mu,mkdirSync as gu,mkdtempSync as hu,rmSync as yu,writeFileSync as wi}from"node:fs";import{tmpdir as wu}from"node:os";import{dirname as bu,join as No}from"node:path";import{simpleGit as Oo}from"simple-git";var tt=class extends Error{constructor(e){super(e),this.name="PRNotFoundError"}};function gi(t,e){return t.length<=e?t:`\u2026(truncated)\u2026
28
+ `+t.slice(t.length-e)}async function Ne(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 Ar(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 Oe(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 eu(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 eu(t){try{let e=await t.json();return e.error?.message?`: ${e.error.message}`:""}catch{return""}}async function Ue(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 yi(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 jo=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 tt(`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()}`)}},Eo=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 tt(`GitHub PR not found: ${e.owner}/${e.repoName}#${r}`);if(n.status>=400)throw new Error(`github GET pulls/${r} \u2192 ${n.status} ${await n.text()}`);let i=await n.json();if(i.state==="closed"&&i.merged_at)return{state:"merged",merged:!0,ci:"none",mergeable:"unknown"};if(i.state==="closed")return{state:"closed",merged:!1,ci:"none",mergeable:"unknown"};let s=i.mergeable===!1||i.mergeable_state==="dirty"?"conflict":i.mergeable===!0?"mergeable":"unknown";return{state:"open",merged:!1,ci:i.head?.sha?await this.fetchCiStatus(e,i.head.sha):"none",mergeable:s}}async fetchCiStatus(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}/commits/${r}`;try{let[i,s]=await Promise.all([fetch(`${n}/check-runs?per_page=100`,{headers:o}),fetch(`${n}/status`,{headers:o})]),a=!1,c=!1,l=!1;if(i.ok){let p=await i.json();for(let f of p.check_runs??[])l=!0,f.status!=="completed"?a=!0:f.conclusion&&["failure","timed_out","cancelled","action_required","stale"].includes(f.conclusion)&&(c=!0)}if(s.ok){let p=await s.json();(p.total_count??0)>0&&(l=!0,p.state==="pending"?a=!0:(p.state==="failure"||p.state==="error")&&(c=!0))}return l?c?"failed":a?"running":"success":"none"}catch{return"none"}}async getCiFailureLog(e,r){let o={Accept:"application/vnd.github+json",Authorization:`Bearer ${this.token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"},n=`https://api.github.com/repos/${e.owner}/${e.repoName}`,i=["failure","timed_out","cancelled","action_required","startup_failure"];try{let s=await fetch(`${n}/pulls/${r}`,{headers:o});if(!s.ok)return;let a=(await s.json()).head?.sha;if(!a)return;let c=await fetch(`${n}/actions/runs?head_sha=${a}&per_page=20`,{headers:o});if(!c.ok)return;let l=(await c.json()).workflow_runs??[],p=[];for(let f of l.filter(u=>u.conclusion&&i.includes(u.conclusion))){let u=await fetch(`${n}/actions/runs/${f.id}/jobs?per_page=50`,{headers:o});if(!u.ok)continue;let d=(await u.json()).jobs??[];for(let g of d.filter(y=>y.conclusion==="failure")){let y=await fetch(`${n}/actions/jobs/${g.id}/logs`,{headers:o});if(!y.ok)continue;let v=await y.text();p.push(`### CI job: ${g.name}
29
29
 
30
- ${fi(S,8e3)}`)}}return p.length===0?void 0:fi(p.join(`
30
+ ${gi(v,8e3)}`)}}return p.length===0?void 0:gi(p.join(`
31
31
 
32
- `),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},jo=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 rt(`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=Zl(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 Zl(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 Eo=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(mi(e,r,"merge"))}async closePR(e,r,o){throw new Error(mi(e,r,"close"))}};function mi(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 Te(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Po(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new Io(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new jo(e)}return new Eo}function wt(t,e,r,o){return[{path:"README.md",content:lu(t,e)},{path:".gitignore",content:nu()},{path:"CLAUDE.md",content:su(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:iu()},{path:"knowledge/README.md",content:au()},{path:"knowledge/build.yaml",content:cu()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:ou()},{path:"adr/README.md",content:eu()},{path:"adr/0000-template.md",content:tu()},{path:"adr/INDEX.md",content:ru()},{path:ve,content:gr()}]}function eu(){return`# ADR \u2014 architecture decision records
32
+ `),16e3)}catch{return}}async mergePR(e,r,o,n){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}/merge`,{method:"PUT",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({merge_method:o})});if(!i.ok)throw new Error(`github merge PR #${r}: ${i.status} ${await i.text()}`);let s=await i.json().catch(()=>null);if(n){let a=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}});if(a.ok){let l=(await a.json()).head?.ref;l&&await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/git/refs/heads/${l}`,{method:"DELETE",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}}).catch(()=>{})}}return s?.sha?{mergedSha:s.sha}:{}}async closePR(e,r,o){if(o&&o.length>0){let i=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/issues/${r}/comments`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({body:o})});if(!i.ok)throw new Error(`github comment PR #${r}: ${i.status} ${await i.text()}`)}let n=await fetch(`https://api.github.com/repos/${e.owner}/${e.repoName}/pulls/${r}`,{method:"PATCH",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","Content-Type":"application/json","User-Agent":"codepipe-cli"},body:JSON.stringify({state:"closed"})});if(!n.ok)throw new Error(`github close PR #${r}: ${n.status} ${await n.text()}`)}},Ao=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 tt(`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=tu(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 tu(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 _o=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(hi(e,r,"merge"))}async closePR(e,r,o){throw new Error(hi(e,r,"close"))}};function hi(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 Te(t){if(t.host==="github"){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;if(e)return new Eo(e)}if(t.host==="bitbucket"){let e=process.env.BITBUCKET_EMAIL,r=process.env.BITBUCKET_API_TOKEN;if(e&&r)return new jo(e,r)}if(t.host==="gitlab"){let e=process.env.GITLAB_TOKEN;if(e)return new Ao(e)}return new _o}function bt(t,e,r,o){return[{path:"README.md",content:pu(t,e)},{path:".gitignore",content:su()},{path:"CLAUDE.md",content:cu(t)},{path:"prompts/.gitkeep",content:""},{path:"prompts/index.md",content:au()},{path:"knowledge/README.md",content:lu()},{path:"knowledge/build.yaml",content:uu()},{path:"tasks/.gitkeep",content:""},{path:"audit/README.md",content:iu()},{path:"adr/README.md",content:ru()},{path:"adr/0000-template.md",content:ou()},{path:"adr/INDEX.md",content:nu()},{path:ve,content:yr()}]}function ru(){return`# ADR \u2014 architecture decision records
33
33
 
34
34
  Accepted architectural decisions of this project \u2014 its **framework**. The
35
35
  agent reads this section (start with \`INDEX.md\`) at the beginning of every
@@ -57,7 +57,7 @@ During analysis the agent drafts a new/changed decision as a task artifact
57
57
  canonical section \u2014 numbered, dated and indexed \u2014 **only after the analysis
58
58
  is approved** (REVIEW gate). Editing an accepted ADR by hand is fine too:
59
59
  open a PR to this repository.
60
- `}function tu(){return`# ADR-NNNN: <title>
60
+ `}function ou(){return`# ADR-NNNN: <title>
61
61
 
62
62
  - **Status:** accepted | superseded by ADR-NNNN
63
63
  - **Date:** YYYY-MM-DD
@@ -79,12 +79,12 @@ What becomes easier, what becomes harder, what future tasks must keep doing.
79
79
  ## Alternatives considered
80
80
 
81
81
  - **<alternative>** \u2014 why it was rejected.
82
- `}function ru(){return`# ADR index
82
+ `}function nu(){return`# ADR index
83
83
 
84
84
  <!-- REGENERATED from adr/NNNN-*.md headers on every promote \u2014 do not edit. -->
85
85
 
86
86
  (no accepted ADRs yet)
87
- `}function ou(){return`# Audit
87
+ `}function iu(){return`# Audit
88
88
 
89
89
  Pipeline event logs. Naming is per-writer: each codepipe
90
90
  project appends only to its own file \u2014
@@ -93,14 +93,14 @@ project appends only to its own file \u2014
93
93
 
94
94
  \u2014 so several team members' CLIs never contend on one file. Do not create a
95
95
  shared aggregate here.
96
- `}function we(t,e,r,o){return{projectYaml:uu(t,r,o),regimenYaml:pu(t.automationLevel,e)}}function nu(){return`# codepipe project config is local to each member's workspace
96
+ `}function he(t,e,r,o){return{projectYaml:du(t,r,o),regimenYaml:fu(t.automationLevel,e)}}function su(){return`# codepipe project config is local to each member's workspace
97
97
  project.yaml
98
98
  regimen.yaml
99
99
 
100
100
  # codepipe runtime
101
101
  session.log
102
102
  apply-queue.json
103
- `}function iu(){return`# Index prompt
103
+ `}function au(){return`# Index prompt
104
104
 
105
105
  You are the **Indexer** agent on the CodePipe pipeline. Your one job is to build a
106
106
  navigation map of this project's repositories and save it to the Context Repo, so
@@ -157,7 +157,7 @@ current working directory; write nothing else under the Context Repo.
157
157
  Keep both durable and skimmable \u2014 they are read at the start of every future
158
158
  task. Prefer structure (headings, bullet lists) over prose. If a repository is
159
159
  empty or unavailable, say so briefly rather than inventing content.
160
- `}function su(t){return`# Project context for the CodePipe agent
160
+ `}function cu(t){return`# Project context for the CodePipe agent
161
161
 
162
162
  Instructions for AI agents working on **${t.name}** tasks. Claude Code
163
163
  auto-loads this file when the Context Repo is mounted. Keep it short and
@@ -185,7 +185,7 @@ project's architectural invariants: read them at the start of a task and treat
185
185
  them as binding. New or changed decisions do **not** go here directly \u2014 during
186
186
  analysis you draft them as task artifacts, and they are promoted into \`adr/\`
187
187
  only after the analysis is approved.
188
- `}function au(){return`# Knowledge
188
+ `}function lu(){return`# Knowledge
189
189
 
190
190
  Durable, reusable notes about this project \u2014 the CodePipe agent's long-lived
191
191
  **memory** across tasks. Architectural decisions, domain rules,
@@ -202,7 +202,7 @@ Keep each note in its own file \u2014 never grow one shared aggregate \u2014 so
202
202
  concurrent commits touch different files and rebase cleanly. \`INDEX.md\` is
203
203
  REGENERATED from the entries by the index job: don't hand-edit it, and treat
204
204
  any merge conflict in it as noise (either side converges on the next run).
205
- `}function cu(){return`# BUILD phase config. Discovered & maintained by the agent.
205
+ `}function uu(){return`# BUILD phase config. Discovered & maintained by the agent.
206
206
  # Steps run in a rootless Podman container in the SANDBOX, before the PR.
207
207
  # Success = every step exits 0. Credentials are NOT available inside the container.
208
208
  #
@@ -218,7 +218,7 @@ any merge conflict in it as noise (either side converges on the next run).
218
218
  # - name: test
219
219
  # run: npm test
220
220
  # timeout_sec: 600 # per-step timeout (optional, default 600)
221
- `}function lu(t,e){return`# ${e.name}
221
+ `}function pu(t,e){return`# ${e.name}
222
222
 
223
223
  Context Repo for the **${t.name}** project (CodePipe).
224
224
 
@@ -244,7 +244,7 @@ PRs to this repository (and the agent also writes to \`knowledge/\` and
244
244
  pipeline \u2014 don't edit them by hand.
245
245
 
246
246
  Automation level: **${t.automationLevel}**.
247
- `}function uu(t,e,r){let o=e?`
247
+ `}function du(t,e,r){let o=e?`
248
248
  tracker_url: ${e}`:`
249
249
  # tracker_url: https://your.youtrack.cloud`,n=r?`require_assignee: true
250
250
  assignee: ${r}`:`require_assignee: false
@@ -302,7 +302,7 @@ branch:
302
302
 
303
303
  repos:
304
304
  ${s}
305
- `}function pu(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
305
+ `}function fu(t,e){let r=t==="full",o=e?"true":"false";return`# CodePipe regimen \u2014 gates, automation, rework. Tweak via PR.
306
306
  automation:
307
307
  level: ${t}
308
308
 
@@ -417,22 +417,22 @@ parallelism:
417
417
  # # the previous task's branch (auto-merge without reworking the
418
418
  # # tail of the chain).
419
419
  # mode: parallel
420
- `}function wu(t){return`codepipe/context-migration-v${t}`}function bu(t){let e=Rn(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 \`${ve}\` 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(`
421
- `)}async function yi(t,e,r,o){let n=_o(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Pr(t,e);if(!i.outdated)return i;let s=wu(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 ku(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return o.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Te(c),p=await l.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:bu(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function ku(t,e,r,o,n,i,s){let a=_o(t),c=mu(Ao(hu(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={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(wt(l,p).map(g=>[g.path,g.content])),u=0;for(let g of o.missingPaths){if(g===ve)continue;let y=f.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let S=Ao(c,g);du(S)||(fu(yu(S),{recursive:!0}),hi(S,y),u++)}hi(Ao(c,ve),gr(o.currentVersion)),u++;let d=_o(c);await d.add(["-A","--",".",":(exclude)project.yaml",":(exclude)regimen.yaml"]),await d.commit(`chore(context): migrate format v${o.templateVersion} -> v${o.currentVersion}`),await d.push(["-u","origin",n]),s.info(`[ctx] migration branch ${n} pushed (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),gu(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as $u,createDecipheriv as xu,createHash as vu,createPrivateKey as Su,createPublicKey as No,diffieHellman as wi,generateKeyPairSync as bi,hkdfSync as ki,randomBytes as Cu}from"node:crypto";var $i=Buffer.from("devpipe-sealedbox-v1","utf-8");function Er(){let{publicKey:t,privateKey:e}=bi("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function be(t){let e=Buffer.from(t,"base64");return(vu("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function bt(t,e){let r=No({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=bi("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=wi({privateKey:n,publicKey:r}),c=Buffer.from(ki("sha256",a,Buffer.concat([i,s]),$i,32)),l=Cu(12),p=$u("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(f),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:d.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function Ar(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=Su({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=No({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=No(o).export({type:"spki",format:"der"}),a=wi({privateKey:o,publicKey:n}),c=Buffer.from(ki("sha256",a,Buffer.concat([i,s]),$i,32)),l=xu("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}function Tu(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 xi(t,e,r,o){let n=Tu(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=xr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=bt(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:l})}return s}import{X509Certificate as Ci}from"node:crypto";import{readFileSync as Ru}from"node:fs";import Be from"node:tls";var Ti=typeof Be.getCACertificates=="function"&&typeof Be.setDefaultCACertificates=="function",vi=!1,Si=new Map,Ri=t=>console.warn(t);function Iu(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function Ii(t=Ri){if(vi)return;vi=!0;let e=N("EXTRA_CA_FILE");if(!(!e||!Ti))try{let r=Iu(Ru(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Be.setDefaultCACertificates([...Be.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 Pi(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 Pu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
422
- `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function ju(t,e,r){return new Promise((o,n)=>{let i=Be.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 Ci(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Oo(t,e,r){return new Promise(o=>{let n=Be.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 Eu(t){try{let e=await fetch(t);return e.ok?new Ci(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function ji(t,e=443,r=Ri){let o=`${t}:${e}`,n=Si.get(o);if(n)return n;let i=Au(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Si.set(o,i),i}async function Au(t,e,r){if(!Ti)return!1;let o=8e3;if(await Oo(t,e,o))return!0;let n=await ju(t,e,o),i=Be.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=Pu(n);if(!c)break;let l=await Eu(c);if(!l)break;if(s.push(l.toString()),Be.setDefaultCACertificates([...i,...s]),await Oo(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;n=l}return Oo(t,e,o)}function ot(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function ke(t,e,r){Ii();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(Pi(s)&&await ji(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var Ei=t=>new Promise(e=>setTimeout(e,t));function _u(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Nu(){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 Ni(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Nu(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await ke(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(l){if(l.ok)return l;let p=await l.text();if(c<n&&_u(l.status,p)){await Ei(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<n){await Ei(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function De(t){let e;try{e=await ke(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 Oi(t){try{let e=await ke(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ai=new Map;async function Ou(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ai.get(o);if(n)return n;let i=await ke(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(l=>l.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(l=>l.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ai.set(o,c.id),c.id}async function Ui(t,e,r){let o=await Ou(t,e,r);await Ni(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 Li(t,e,r){return await(await Ni(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var _i=new Map;async function Uu(t,e){let r=_i.get(e);if(r)return r;let o=await ke(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 _i.set(e,i.id),i.id}async function Bi(t,e,r,o,n){let i=await Uu(t,e),s=await ke(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 Di(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await ke(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 Gi="attachments(id,name,url,size,mimeType)",Lu="links(direction,linkType(name),issues(idReadable))",Mi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Gi},${Lu}`,Bu=`id,text,created,author(login),${Gi}`;function Fi(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 Hi(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 Ki(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=${Mi}&$top=200`,i=await ke(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(Yi)}async function Wi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Mi}`,o=await ke(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return Yi(await o.json())}async function qi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Bu}&$top=500`,n=await ke(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=Fi(s.attachments);return c&&(a.attachments=c),a})}function Du(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 Yi(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=Fi(t.attachments);s&&(i.attachments=s);let a=Du(t.links);return a&&(i.links=a),i}function de(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Vi(t,e){let r=U(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await De({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:de(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:de(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await Oe(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:de(c)}),n.push({kind:"github",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Ue(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:de(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Le(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:de(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:de(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let p of e?.repos??[])if(p.host==="github")try{await jr(c,p.owner,p.repoName),o.push({name:`repo:${p.name}`,ok:!0})}catch(f){o.push({name:`repo:${p.name}`,ok:!1,detail:de(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await jr(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(p){o.push({name:"context-repo",ok:!1,detail:de(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await jr(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:de(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=dt(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Uo(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function Uo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function Ht(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 Kt(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 Wt(t,e=process.env){if(!t)return!1;let r=`https://${Je}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Lo(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function zi(t,e=process.env){return Lo(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Ht(t,e),e)}function Ji(t,e=process.env){return Lo(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>Kt(t,e),e)}function Xi(t,e=process.env){return Lo(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${Je}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Wt(t,e),e)}function Qi(t){let e=U(t);if(!e)return null;if(!e.sealKey){let r=Er();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},z(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:be(e.sealKey.publicKey)}}async function Zi(t,e,r,o){let n;try{n=JSON.parse(Ar(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=U(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Oe(n.token);return i.github={token:n.token},kt(i,()=>{process.env.GH_TOKEN=n.token,zi(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Le(n.token);return i.gitlab={token:n.token},kt(i,()=>{process.env.GITLAB_TOKEN=n.token,Ji(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Ue(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},kt(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Xi(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await De({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},kt(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Uo(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},kt(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},kt(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function kt(t,e){z(t),e()}import{existsSync as Gu,readFileSync as Mu,writeFileSync as Fu}from"node:fs";import{join as Hu}from"node:path";import{parseDocument as Ku}from"yaml";var es=64;async function ts(t,e){if(!Number.isInteger(e)||e<1||e>es)throw new Error(`maxJobs must be an integer in [1, ${es}], got ${e}`);let r=Hu(t,"regimen.yaml");if(!Gu(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=Ku(Mu(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Fu(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Wu,readFileSync as qu,writeFileSync as Yu}from"node:fs";import{join as Vu}from"node:path";import{isMap as rs,parseDocument as zu}from"yaml";async function os(t,e){let r=e.repoName?.trim(),o=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!o||!In(o))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let n=Vu(t,"project.yaml");if(!Wu(n))throw new Error(`project.yaml not found in context repo (${t})`);let i=zu(qu(n,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>rs(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!rs(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",o),Yu(n,i.toString()),{repoName:r,defaultBranch:o}}import{existsSync as ns,readFileSync as is,writeFileSync as Ju}from"node:fs";import{join as Bo}from"node:path";import{parseDocument as ss}from"yaml";async function as(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=Bo(t,"project.yaml");if(!ns(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=ss(is(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=Bo(t,"regimen.yaml");if(!ns(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=ss(is(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)Ju(Bo(t,i.path),i.content);return{files:r.map(i=>i.path)}}var cs=t=>console.log(t);function ls(t){cs=t}function qt(t,e="info"){cs(t,e)}import{homedir as Xu}from"node:os";import{existsSync as Qu,mkdirSync as Zu}from"node:fs";import{join as Do}from"node:path";import{simpleGit as us}from"simple-git";function Vt(t,e,r){let o=r??Do(Xu(),".codepipe","repos");return Do(o,t,e)}async function _r(t,e,r={}){let o=Vt(t,e.name,r.baseDir),n=r.cloneUrlOverride??ep(e);if(!Qu(Do(o,".git"))){Zu(o,{recursive:!0});let a=us();qt(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
423
- ${l.trim()}`)}}let i=us(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
424
- ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function Yt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var ps=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Nr(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&&qt(`[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 Yt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await Yt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...ps,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ds(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await Yt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await Yt(t,n)){let s=(await t.revparse([n])).trim();return await t.raw(["update-ref",o,s]).catch(()=>{}),s}let i=await r();return await t.raw(["update-ref",o,i]).catch(()=>{}),i}async function fs(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:f}=r,u=await ds(t,i,()=>Nr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await Yt(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...ps,"cherry-pick",u])}catch(x){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let v=x instanceof Error?x.message:String(x);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
425
- ${v.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),S=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(S),await t.push([o,"--delete",n]).catch(()=>{}),{commit:y}}async function ms(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await ds(t,i,()=>Nr(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:l}}async function gs(t,e,r){let{branchName:o,baseBranch:n,mergeMethod:i,deleteBranch:s}=r,a=`origin/${o}`;return i==="squash"?(await t.raw(["merge","--squash",a]),await t.commit(`Merge branch '${o}'`)):i==="rebase"?(await t.checkout(["-B",o,a]),await t.rebase([n]),await t.checkout(n),await t.merge(["--ff-only",o])):await t.merge(["--no-ff",a,"-m",`Merge branch '${o}'`]),await t.push(["origin",n]),s&&await t.push(["origin","--delete",o]).catch(()=>{}),{mergedSha:(await t.revparse(["HEAD"])).trim()}}function ep(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 Or=new Map;async function Go(t,e){let o=(Or.get(t)??Promise.resolve()).catch(()=>{}).then(e);Or.set(t,o);try{return await o}finally{Or.get(t)===o&&Or.delete(t)}}async function hs(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;qt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Go(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Vt(i,r.name,t.baseDir),{commit:c}=await fs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,baseRef:e.baseRef,commitMessage:e.commitMessage,defaultBranch:r.defaultBranch,force:e.force});return 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 H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Go(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Vt(i,r.name,t.baseDir),{commit:c,pushed:l}=await ms(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return H("no repo spec");let i=Te(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return H("no repo spec");let i=Te(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 H("no repo spec");let i=Te(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Go(`${i}/${r.name}`,async()=>{let s=await _r(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Vt(i,r.name,t.baseDir),{mergedSha:c}=await gs(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=ot();return i?t.trackerIssueId?(await Ui(i,t.trackerIssueId,e.newStatus),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=ot();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await Li(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=ot();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return H("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Bi(i,e.projectKey,e.title,e.body,e.targetStatus);return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=ot();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Di(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return H(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_parallelism":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await ts(t.contextDir,e.maxJobs);return Z({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await as(t.contextDir,e);return Z({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await os(t.contextDir,e);return Z({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):H("no context repo clone on this CLI")}}catch(i){return H(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}import{existsSync as Is,readFileSync as Ps}from"node:fs";import{join as js}from"node:path";import{homedir as tp}from"node:os";import{existsSync as rp,mkdirSync as op,readFileSync as np,writeFileSync as ip}from"node:fs";import{dirname as sp,join as ap}from"node:path";function Mo(){return N("FARM_PINS")??ap(tp(),".codepipe","farm-pins.json")}function ys(){let t=Mo();if(!rp(t))return{};try{return JSON.parse(np(t,"utf-8"))}catch{return{}}}function cp(t){let e=Mo();op(sp(e),{recursive:!0}),ip(e,JSON.stringify(t,null,2)+`
426
- `,{mode:384})}function lp(t){return ys()[t]}function Ur(t,e){let r=ys();r[t]=e,cp(r)}function Lr(t,e){let r=be(e),o=lp(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 ${Mo()}.`);return r}import up from"ws";function Br(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new up(r)}var _=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function $t(t,e,r){return Ge(t,e,"/projects",r)}async function ws(t,e){let r=await fetch(`${t}/farms`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new _(r.status,null,`GET /farms HTTP ${r.status}`);return await r.json()}async function Dr(t,e,r,o){return Ge(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Gr(t,e){let r=await fetch(`${t}/sandbox/reg-token/cli`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new _(r.status,null,`POST /sandbox/reg-token/cli HTTP ${r.status}`);return await r.json()}async function bs(t,e){let r=await fetch(`${t}/projects/cli`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new _(r.status,null,`GET /projects/cli HTTP ${r.status}`);return(await r.json()).projects}var zt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function ks(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 zt(e)}if(!r.ok)throw new _(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function $s(t,e){let r=await fetch(`${t}/cli/bootstrap-poll?request=${encodeURIComponent(e)}`);if(!r.ok)throw new _(r.status,null,`bootstrap-poll HTTP ${r.status}`);return await r.json()}async function xs(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-tasks`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new _(o.status,null,`GET cli-tasks HTTP ${o.status}`);return await o.json()}async function vs(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 _(n.status,null,`GET cli-task HTTP ${n.status}`);return await n.json()}async function Ss(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Cs(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function Ts(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function Rs(t,e,r,o,n){return Ge(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Mr(t,e,r,o){return Ge(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function Fo(t,e,r,o){await Ge(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function Q(t,e,r){let o=await fetch(`${t}/projects/${encodeURIComponent(r)}/cli-summary`,{headers:{Authorization:`Bearer ${e}`}});if(!o.ok)throw new _(o.status,null,`GET /projects/${r}/cli-summary HTTP ${o.status}`);return await o.json()}async function Ge(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new _(n.status,s,a)}return s}async function Es(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=be(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Lr(e.farmId,e.farmPublicKey);let s=U(t.projectId);if(!s)return n("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=js(r,"project.yaml"),d=js(r,"regimen.yaml");Is(u)&&Is(d)?c={projectYaml:Ps(u,"utf-8"),regimenYaml:Ps(d,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},p=bt(e.farmPublicKey,JSON.stringify(l));Ur(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await Dr(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var Fr=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=Te(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 rt){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=Te(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=pp(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function pp(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Hr=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=ot();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 u=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await Ki(r,{projectKey:e.projectKey,columns:u,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(u){this.log.warn(`[yt-sync] listIssues failed: ${u instanceof Error?u.message:String(u)}`);return}let i=[],s=new Set;for(let u of n){s.add(u.id);let d=await As(r,u.id,e.sinceMs,this.log);d&&i.push({issueId:u.id,comments:d})}let a=[];for(let u of e.offBoardIssueIds){if(s.has(u))continue;let d=await As(r,u,e.sinceMs,this.log);if(d&&i.push({issueId:u,comments:d}),e.requireAssignee){let g=await fp(r,u,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),l={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(l);let p=i.reduce((u,d)=>u+d.comments.length,0),f=c.reduce((u,d)=>u+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=[],l=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let u;try{u=await Hi(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=dp(p.name);l.has(d)&&(d=`${p.id}-${d}`),l.add(d),c.push({name:d,contentBase64:u.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function dp(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 fp(t,e,r){try{return await Wi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function As(t,e,r,o){try{return await qi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Ho="npm i -g @code-partner/codepipe@latest";function Kr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ce} (protocol ${ge})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&ni(n.contextDir,r);let i=_s("CLI_TRACKING_POLL_INTERVAL_SEC"),s=_s("CLI_YOUTRACK_POLL_INTERVAL_SEC"),a=(()=>{let d=parseInt(process.env.CLI_READINESS_INTERVAL_SEC??"600",10);return Number.isFinite(d)&&d>0?d*1e3:6e5})(),c=!1,l=!1,p=new Set,f=u();function u(){let d=Br(t.hubUrl,t.cliToken),g=null,y=new Fr(i,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),S=new Hr(s,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),x=null,v=async()=>{try{let C;try{let k=await Q(t.hubUrl,t.cliToken,t.projectId);C={repos:k.repos,contextRepo:k.contextRepo}}catch(k){r.warn(`[readiness] could not fetch project summary for push checks: ${k instanceof Error?k.message:String(k)}`)}let h=await Vi(t.projectId,C);if(d.readyState!==d.OPEN)return;let m={type:"cli_readiness",projectId:t.projectId,ready:h.ready,checks:h.checks,creds:h.creds,checkedAt:h.checkedAt};if(d.send(JSON.stringify(m)),h.ready)r.info("[readiness] ready");else{let k=h.checks.filter($=>!$.ok).map($=>`${$.name}(${$.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${k.join(", ")}`)}}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},A=()=>{v(),x=setInterval(()=>void v(),a),typeof x.unref=="function"&&x.unref()},I=()=>{x&&(clearInterval(x),x=null)},L=n?.contextDir?new Tr(n.contextDir,t.projectId,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let C=ei(t.projectId),h=N("ORIGIN")==="farm"?"farm":"local",m=N("FARM_ID"),k=t.accountEmail??C.email,$;try{let R=Qi(t.projectId);R&&($=R.publicKey,r.info(`[cred-channel] key fingerprint: ${R.fingerprint}`))}catch(R){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${R instanceof Error?R.message:String(R)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ce,protocolVersion:ge,accountId:C.accountId,accountLabel:C.label,origin:h,inFlightActionIds:[...p],...k?{accountEmail:k}:{},...h==="farm"&&m?{farmId:m}:{},...$?{sealPublicKey:$}:{}};d.send(JSON.stringify(w))}),d.on("message",async C=>{let h=C.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 k=m.type;if(k==="registered"){let w=m;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),o({kind:"registered",projectId:w.projectId??t.projectId}),y.start(),L?.start(),A(),n?.contextDir){let R=n.contextDir;try{let P=Pr(R,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify(P)),P.outdated&&(r.warn(`[ctx] context format outdated: v${P.templateVersion} \u2192 v${P.currentVersion}`+(P.missingPaths.length>0?` (missing: ${P.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let G;try{G=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let q=await yi(R,t.projectId,G,r);d.readyState===d.OPEN&&d.send(JSON.stringify(q))}catch(G){r.warn(`[ctx] context migration failed (non-fatal): ${G instanceof Error?G.message:String(G)}`)}})()))}catch(P){r.warn(`[ctx] context-format detect failed (non-fatal): ${P instanceof Error?P.message:String(P)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),o({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(k==="hello"){let w=m;g=mr(w.protocolVersion);let R=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${R}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ce}, protocol ${ge}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Ho}`),o({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Ho}));return}if(k==="tracking_targets"){y.setTargets(m.targets);return}if(k==="youtrack_sync_request"){S.setRequest(m);return}if(k==="sync_local"){await gp(m,n,d,r);return}if(k==="context_write"){await hp(m,n,d,r);return}if(k==="adr_promote"){await yp(m,n,d,r);return}if(k==="cred_update"){let w=m,R=U(t.projectId),P=R?.sealKey?await Zi(t.projectId,w.kind,w.sealed,R.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},G={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:P.ok,...P.detail?{detail:P.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(G)),P.ok?(r.info(`[cred] ${w.kind} replaced${P.detail?` \u2014 ${P.detail}`:""}`),v()):r.warn(`[cred] ${w.kind} replacement rejected: ${P.detail??"unknown"}`);return}if(k==="move_to_farm"){let w=m;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let R=await Es(t,w,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(R)),R.ok?r.info(`[farm-move] done \u2014 farm daemon ${R.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${R.error??"unknown error"}`);return}if(k==="sandbox_keys"){let w=U(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let R=dt(t.projectId),P=xi(m,w,R,r);for(let G of P)d.readyState===d.OPEN&&d.send(JSON.stringify(G));return}if(k!=="dispatch_action")return;let $=m;if(g===!1){let w=`refused: HUB protocol incompatible with CLI v${ce} (protocol ${ge})`;d.send(JSON.stringify({type:"action_result",actionId:$.actionId,status:"failed",error:w})),r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Ho}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:!1,error:w});return}p.add($.actionId);try{let w=await hs({action:$.action,repo:$.repo,trackerIssueId:$.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:L?()=>L.reportNow():void 0}).catch(G=>({status:"failed",error:G instanceof Error?G.message:String(G)}));d.send(JSON.stringify({type:"action_result",actionId:$.actionId,...w}));let R=w.status!=="failed",P=!R&&"error"in w?w.error:void 0;R?r.info(`[exec] ${$.actionId} (${$.action.type}) \u2192 done`):r.warn(`[exec] ${$.actionId} (${$.action.type}) \u2192 FAILED: ${P??"?"}`),o({kind:"action",actionId:$.actionId,actionType:$.action.type,ok:R,...P?{error:P}:{}})}finally{p.delete($.actionId)}}),d.on("close",(C,h)=>{let m=h?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${m?` reason=${m}`:""}`),y.stop(),S.stop(),L?.stop(),I(),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:C}),!c&&setTimeout(()=>{f=u()},2e3)}),d.on("error",C=>r.warn(`[ws] error: ${C.message}`)),d}return{stop(){c=!0,f.close()}}}async function gp(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=mp(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await ti(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function hp(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 Ir(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 yp(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 ui(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 _s(t){let e=parseInt(process.env[t]??"60",10);return Number.isFinite(e)&&e>0?e*1e3:6e4}import{existsSync as Gs,mkdirSync as Ms}from"node:fs";import{dirname as Fs}from"node:path";import{simpleGit as xt}from"simple-git";import{execFileSync as wp}from"node:child_process";import{mkdtempSync as bp,mkdirSync as kp,readFileSync as Ns,rmSync as $p,writeFileSync as xp}from"node:fs";import{tmpdir as vp}from"node:os";import{dirname as Sp,join as Os}from"node:path";function Us(t="codepipe-context"){let e=bp(Os(vp(),"codepipe-ssh-")),r=Os(e,"id_ed25519");try{return wp("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{$p(e,{recursive:!0,force:!0})}}async function Ls(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 Bs(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 Ds(t,e){kp(Sp(t),{recursive:!0});let r=e.endsWith(`
420
+ `}function ku(t){return`codepipe/context-migration-v${t}`}function $u(t){let e=Pn(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 \`${ve}\` 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(`
421
+ `)}async function bi(t,e,r,o){let n=Oo(t);await n.pull(void 0,void 0,["--rebase"]).catch(()=>{});let i=Er(t,e);if(!i.outdated)return i;let s=ku(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 xu(t,e,r,i,s,a,o):o.info(`[ctx] migration branch ${s} already on origin \u2014 reusing`)}catch(l){return o.warn(`[ctx] context migration branch failed (will retry next start): ${l instanceof Error?l.message:String(l)}`),i}if(!r)return i;let c={name:r.name,host:r.host,owner:r.owner,repoName:r.name};try{let l=Te(c),p=await l.findOpenPrByBranch?.(c,s)??null;if(p)return o.info(`[ctx] migration PR already open: ${p.url}`),{...i,migrationPrUrl:p.url};let f=await l.createPullRequest(c,{type:"create_pr",taskId:`context-migration::${e}`,repoName:r.name,branchName:s,baseBranch:a,title:`CodePipe: context format v${i.templateVersion} \u2192 v${i.currentVersion}`,body:$u(i)});return o.info(`[ctx] migration PR opened: ${f.url}`),{...i,migrationPrUrl:f.url}}catch(l){return o.warn(`[ctx] migration PR create/find failed (branch pushed, badge without link): ${l instanceof Error?l.message:String(l)}`),i}}async function xu(t,e,r,o,n,i,s){let a=Oo(t),c=hu(No(wu(),"codepipe-ctx-migration-"));try{await a.raw(["worktree","add","--force","-B",n,c,`origin/${i}`]);let l={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(bt(l,p).map(g=>[g.path,g.content])),u=0;for(let g of o.missingPaths){if(g===ve)continue;let y=f.get(g);if(y==null){s.warn(`[ctx] migration: no template for ${g} \u2014 skipped`);continue}let v=No(c,g);mu(v)||(gu(bu(v),{recursive:!0}),wi(v,y),u++)}wi(No(c,ve),yr(o.currentVersion)),u++;let d=Oo(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 (${u} file(s))`)}finally{await a.raw(["worktree","remove","--force",c]).catch(()=>{}),yu(c,{recursive:!0,force:!0}),await a.raw(["branch","-D",n]).catch(()=>{})}}import{createCipheriv as vu,createDecipheriv as Su,createHash as Cu,createPrivateKey as Tu,createPublicKey as Uo,diffieHellman as ki,generateKeyPairSync as $i,hkdfSync as xi,randomBytes as Ru}from"node:crypto";var vi=Buffer.from("devpipe-sealedbox-v1","utf-8");function _r(){let{publicKey:t,privateKey:e}=$i("x25519");return{publicKey:t.export({type:"spki",format:"der"}).toString("base64"),privateKey:e.export({type:"pkcs8",format:"der"}).toString("base64")}}function ye(t){let e=Buffer.from(t,"base64");return(Cu("sha256").update(e).digest("hex").slice(0,32).match(/.{2}/g)??[]).join(":")}function kt(t,e){let r=Uo({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),{publicKey:o,privateKey:n}=$i("x25519"),i=o.export({type:"spki",format:"der"}),s=r.export({type:"spki",format:"der"}),a=ki({privateKey:n,publicKey:r}),c=Buffer.from(xi("sha256",a,Buffer.concat([i,s]),vi,32)),l=Ru(12),p=vu("aes-256-gcm",c,l),f=typeof e=="string"?Buffer.from(e,"utf-8"):e,u=Buffer.concat([p.update(f),p.final()]),d=p.getAuthTag(),g={v:1,epk:i.toString("base64"),iv:l.toString("base64"),tag:d.toString("base64"),ct:u.toString("base64")};return Buffer.from(JSON.stringify(g),"utf-8").toString("base64")}function Nr(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=Tu({key:Buffer.from(t,"base64"),type:"pkcs8",format:"der"}),n=Uo({key:Buffer.from(r.epk,"base64"),type:"spki",format:"der"}),i=n.export({type:"spki",format:"der"}),s=Uo(o).export({type:"spki",format:"der"}),a=ki({privateKey:o,publicKey:n}),c=Buffer.from(xi("sha256",a,Buffer.concat([i,s]),vi,32)),l=Su("aes-256-gcm",c,Buffer.from(r.iv,"base64"));return l.setAuthTag(Buffer.from(r.tag,"base64")),Buffer.concat([l.update(Buffer.from(r.ct,"base64")),l.final()])}function Iu(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 Si(t,e,r,o){let n=Iu(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=Sr(t.projectId,a.sandboxId,a.fingerprint);if(c==="mismatch"){o.warn(`[cred] SANDBOX ${a.name} (${a.sandboxId}) key fingerprint CHANGED \u2014 refusing to seal creds. Expected the pinned key; got ${a.fingerprint}. If this is intentional, clear the pin in the secrets file and re-run.`);continue}c==="pinned"&&o.info(`[cred] pinned SANDBOX ${a.name} (${a.sandboxId}) fingerprint ${a.fingerprint}`);let l;try{l=kt(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:l})}return s}import{X509Certificate as Ri}from"node:crypto";import{readFileSync as Pu}from"node:fs";import Le from"node:tls";var Ii=typeof Le.getCACertificates=="function"&&typeof Le.setDefaultCACertificates=="function",Ci=!1,Ti=new Map,Pi=t=>console.warn(t);function ju(t){return t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[]}function ji(t=Pi){if(Ci)return;Ci=!0;let e=O("EXTRA_CA_FILE");if(!(!e||!Ii))try{let r=ju(Pu(e,"utf8"));if(r.length===0){t(`[tls] CODEPIPE_EXTRA_CA_FILE ${e} has no PEM certificates \u2014 ignored`);return}Le.setDefaultCACertificates([...Le.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 Ei(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 Eu(t){let e=t.infoAccess;if(!e)return null;for(let r of e.split(`
422
+ `)){let o=r.match(/CA Issuers - URI:\s*(https?:\/\/\S+)/i);if(o?.[1])return o[1].trim()}return null}function Au(t,e,r){return new Promise((o,n)=>{let i=Le.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 Ri(s.raw):null;i.end(),o(c)});i.on("error",n),i.setTimeout(r,()=>{i.destroy(),n(new Error("tls connect timeout"))})})}function Lo(t,e,r){return new Promise(o=>{let n=Le.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 _u(t){try{let e=await fetch(t);return e.ok?new Ri(Buffer.from(await e.arrayBuffer())):null}catch{return null}}function Ai(t,e=443,r=Pi){let o=`${t}:${e}`,n=Ti.get(o);if(n)return n;let i=Nu(t,e,r).catch(s=>(r(`[tls] chain repair for ${t} failed: ${s instanceof Error?s.message:String(s)}`),!1));return Ti.set(o,i),i}async function Nu(t,e,r){if(!Ii)return!1;let o=8e3;if(await Lo(t,e,o))return!0;let n=await Au(t,e,o),i=Le.getCACertificates(),s=[];for(let a=0;a<4&&n&&n.subject!==n.issuer;a++){let c=Eu(n);if(!c)break;let l=await _u(c);if(!l)break;if(s.push(l.toString()),Le.setDefaultCACertificates([...i,...s]),await Lo(t,e,o))return r(`[tls] completed certificate chain for ${t} via AIA (+${s.length} intermediate cert(s))`),!0;if(l.subject===l.issuer)break;n=l}return Lo(t,e,o)}function rt(){let t=process.env.YOUTRACK_URL,e=process.env.YOUTRACK_TOKEN;return!t||!e?null:{baseUrl:t.replace(/\/$/,""),token:e}}async function we(t,e,r){ji();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(Ei(s)&&await Ai(new URL(t.baseUrl).host))return await fetch(n,i);throw s}}var _i=t=>new Promise(e=>setTimeout(e,t));function Ou(t,e){return!!(t===429||t>=500||t===418&&/read-only|invalid_state/i.test(e))}function Uu(){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 Ui(t,e,r,o){let{attempts:n,baseMs:i,capMs:s}=Uu(),a=null;for(let c=1;c<=n;c++){let l=null;try{l=await we(t,r,o)}catch(p){a=new Error(`${e}: ${p instanceof Error?p.message:String(p)}`)}if(l){if(l.ok)return l;let p=await l.text();if(c<n&&Ou(l.status,p)){await _i(Math.min(s,i*2**(c-1)));continue}throw new Error(`${e}: ${l.status} ${p}`)}if(c<n){await _i(Math.min(s,i*2**(c-1)));continue}throw a??new Error(`${e}: request failed`)}throw a??new Error(`${e}: request failed`)}async function Be(t){let e;try{e=await we(t,"/api/users/me?fields=login,fullName")}catch(o){throw new Error(`cannot reach ${t.baseUrl} (${o instanceof Error?o.message:String(o)})`)}if(e.status===401)throw new Error("token rejected (401 \u2014 check the YouTrack PAT)");if(!e.ok)throw new Error(`YouTrack \u2192 ${e.status} ${e.statusText}`);let r=await e.json();return r.login??r.fullName??"ok"}async function Li(t){try{let e=await we(t,"/api/users/me?fields=login");return e.ok?(await e.json()).login??void 0:void 0}catch{return}}var Ni=new Map;async function Lu(t,e,r){let o=`${e.split("-")[0]}:${r}`,n=Ni.get(o);if(n)return n;let i=await we(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(l=>l.name==="Stage");if(!a)throw new Error(`yt: issue ${e} has no Stage custom field`);let c=a.projectCustomField.bundle.values.find(l=>l.name===r);if(!c)throw new Error(`yt: state "${r}" not found in bundle for ${e}`);return Ni.set(o,c.id),c.id}async function Bi(t,e,r){let o=await Lu(t,e,r);await Ui(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 Di(t,e,r){return await(await Ui(t,`yt addComment ${e}`,`/api/issues/${encodeURIComponent(e)}/comments?fields=id`,{method:"POST",body:JSON.stringify({text:r})})).json()}var Oi=new Map;async function Bu(t,e){let r=Oi.get(e);if(r)return r;let o=await we(t,"/api/admin/projects?fields=id,shortName&$top=200");if(!o.ok)throw new Error(`yt resolveProjectId: ${o.status} ${await o.text()}`);let i=(await o.json()).find(s=>s.shortName===e);if(!i)throw new Error(`yt: project "${e}" not found in /api/admin/projects`);return Oi.set(e,i.id),i.id}async function Gi(t,e,r,o,n){let i=await Bu(t,e),s=await we(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 Mi(t,e,r,o){let n=r==="subtask_of"?`subtask of ${o}`:`depends on ${o}`,i=await we(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 Fi="attachments(id,name,url,size,mimeType)",Du="links(direction,linkType(name),issues(idReadable))",Hi=`id,idReadable,summary,description,updated,customFields(name,value(name,login)),tags(name),${Fi},${Du}`,Gu=`id,text,created,author(login),${Fi}`;function Ki(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 Wi(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 qi(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=${Hi}&$top=200`,i=await we(t,n);if(!i.ok)throw new Error(`yt listIssues: ${i.status} ${await i.text()}`);return(await i.json()).map(zi)}async function Yi(t,e){let r=`/api/issues/${encodeURIComponent(e)}?fields=${Hi}`,o=await we(t,r);if(o.status===404)return null;if(!o.ok)throw new Error(`yt getIssue ${e}: ${o.status} ${await o.text()}`);return zi(await o.json())}async function Vi(t,e,r){let o=`/api/issues/${encodeURIComponent(e)}/comments?fields=${Gu}&$top=500`,n=await we(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=Ki(s.attachments);return c&&(a.attachments=c),a})}function Mu(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 zi(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=Ki(t.attachments);s&&(i.attachments=s);let a=Mu(t.links);return a&&(i.links=a),i}function pe(t){let e=t instanceof Error?t.message:String(t);return e.length>120?e.slice(0,117)+"\u2026":e}async function Ji(t,e){let r=L(t),o=[],n=[],i=()=>Date.now();if(r?.youtrack?.url&&r.youtrack.token)try{let c=await Be({baseUrl:r.youtrack.url,token:r.youtrack.token});o.push({name:"youtrack",ok:!0}),n.push({kind:"youtrack",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"youtrack",ok:!1,detail:pe(c)}),n.push({kind:"youtrack",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}else o.push({name:"youtrack",ok:!1,detail:"no YouTrack token"}),n.push({kind:"youtrack",present:!1,checkedAt:i()});let s=!1;if(r?.github?.token){s=!0;try{let c=await Ne(r.github.token);o.push({name:"github",ok:!0}),n.push({kind:"github",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"github",ok:!1,detail:pe(c)}),n.push({kind:"github",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}}else n.push({kind:"github",present:!1,checkedAt:i()});if(r?.bitbucket?.email&&r.bitbucket.apiToken){s=!0;try{let c=await Oe(r.bitbucket.email,r.bitbucket.apiToken);o.push({name:"bitbucket",ok:!0}),n.push({kind:"bitbucket",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"bitbucket",ok:!1,detail:pe(c)}),n.push({kind:"bitbucket",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}}else n.push({kind:"bitbucket",present:!1,checkedAt:i()});if(r?.gitlab?.token){s=!0;try{let c=await Ue(r.gitlab.token);o.push({name:"gitlab",ok:!0}),n.push({kind:"gitlab",present:!0,ok:!0,identity:c,checkedAt:i()})}catch(c){o.push({name:"gitlab",ok:!1,detail:pe(c)}),n.push({kind:"gitlab",present:!0,ok:!1,detail:pe(c),checkedAt:i()})}}else n.push({kind:"gitlab",present:!1,checkedAt:i()});if(s||o.push({name:"git",ok:!1,detail:"no GitHub/Bitbucket/GitLab credentials"}),r?.github?.token){let c=r.github.token;for(let p of e?.repos??[])if(p.host==="github")try{await Ar(c,p.owner,p.repoName),o.push({name:`repo:${p.name}`,ok:!0})}catch(f){o.push({name:`repo:${p.name}`,ok:!1,detail:pe(f)})}let l=e?.contextRepo;if(l?.host==="github")try{await Ar(c,l.owner,l.name),o.push({name:"context-repo",ok:!0})}catch(p){o.push({name:"context-repo",ok:!1,detail:pe(p)})}}if(r?.contextWrite?.token){let c=e?.contextRepo;if(c?.host==="github")try{await Ar(r.contextWrite.token,c.owner,c.name),n.push({kind:"contextWrite",present:!0,ok:!0,checkedAt:i()})}catch(l){n.push({kind:"contextWrite",present:!0,ok:!1,detail:pe(l),checkedAt:i()})}else n.push({kind:"contextWrite",present:!0,detail:"not live-checked",checkedAt:i()})}else n.push({kind:"contextWrite",present:!1,checkedAt:i()});let a=ft(t);if(!a)o.push({name:"claude",ok:!1,detail:"no Claude token (run `codepipe login`)"}),n.push({kind:"claude",present:!1,checkedAt:i()});else if(process.env.CLI_READINESS_CLAUDE_LIVE==="0")o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,detail:"not live-checked",checkedAt:i()});else{let c=await Bo(a);if(c==="invalid"){let l="Claude token rejected (401) \u2014 refresh via `claude setup-token`";o.push({name:"claude",ok:!1,detail:l}),n.push({kind:"claude",present:!0,ok:!1,detail:l,checkedAt:i()})}else o.push({name:"claude",ok:!0}),n.push({kind:"claude",present:!0,...c==="valid"?{ok:!0}:{detail:"check inconclusive"},checkedAt:i()})}return{ready:o.every(c=>c.ok),checks:o,creds:n,checkedAt:Date.now()}}async function Bo(t){let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);try{let o=await fetch("https://api.anthropic.com/v1/models?limit=1",{headers:{Authorization:`Bearer ${t}`,"anthropic-version":"2023-06-01","anthropic-beta":"oauth-2025-04-20"},signal:e.signal});return o.status===200?"valid":o.status===401?"invalid":"inconclusive"}catch{return"inconclusive"}finally{clearTimeout(r)}}function Wt(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 qt(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 Yt(t,e=process.env){if(!t)return!1;let r=`https://${ze}:${encodeURIComponent(t)}@bitbucket.org/`,o=Number.parseInt(e.GIT_CONFIG_COUNT??"0",10)||0,n=(i,s)=>{e[`GIT_CONFIG_KEY_${o+i}`]=`url.${r}.insteadOf`,e[`GIT_CONFIG_VALUE_${o+i}`]=s};return n(0,"git@bitbucket.org:"),n(1,"ssh://git@bitbucket.org/"),e.GIT_CONFIG_COUNT=String(o+2),!0}function Do(t,e,r,o){let n=Number.parseInt(o.GIT_CONFIG_COUNT??"0",10)||0,i=!1;for(let s=0;s<n;s++){let a=o[`GIT_CONFIG_KEY_${s}`];a&&t.test(a)&&(o[`GIT_CONFIG_KEY_${s}`]=`url.${e}.insteadOf`,i=!0)}return i||r()}function Xi(t,e=process.env){return Do(/^url\.https:\/\/[^@]+@github\.com\/\.insteadOf$/,`https://x-access-token:${t}@github.com/`,()=>Wt(t,e),e)}function Qi(t,e=process.env){return Do(/^url\.https:\/\/[^@]+@gitlab\.com\/\.insteadOf$/,`https://oauth2:${t}@gitlab.com/`,()=>qt(t,e),e)}function Zi(t,e=process.env){return Do(/^url\.https:\/\/[^@]+@bitbucket\.org\/\.insteadOf$/,`https://${ze}:${encodeURIComponent(t)}@bitbucket.org/`,()=>Yt(t,e),e)}function es(t){let e=L(t);if(!e)return null;if(!e.sealKey){let r=_r();e.sealKey={publicKey:r.publicKey,privateKey:r.privateKey},V(e)}return{publicKey:e.sealKey.publicKey,privateKey:e.sealKey.privateKey,fingerprint:ye(e.sealKey.publicKey)}}async function ts(t,e,r,o){let n;try{n=JSON.parse(Nr(o,r).toString("utf-8"))}catch(s){return{ok:!1,detail:`cannot open the sealed credential (${s instanceof Error?s.message:String(s)}) \u2014 wrong channel key?`}}let i=L(t);if(!i)return{ok:!1,detail:"no secrets file for this project on the CLI"};try{switch(e){case"github":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Ne(n.token);return i.github={token:n.token},$t(i,()=>{process.env.GH_TOKEN=n.token,Xi(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"gitlab":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Ue(n.token);return i.gitlab={token:n.token},$t(i,()=>{process.env.GITLAB_TOKEN=n.token,Qi(n.token)}),{ok:!0,detail:`authenticated as ${s}`}}case"bitbucket":{if(!n.email||!n.apiToken)return{ok:!1,detail:"payload needs email + apiToken"};let s=await Oe(n.email,n.apiToken);return i.bitbucket={email:n.email,apiToken:n.apiToken},$t(i,()=>{process.env.BITBUCKET_EMAIL=n.email,process.env.BITBUCKET_API_TOKEN=n.apiToken,Zi(n.apiToken)}),{ok:!0,detail:`authenticated as ${s}`}}case"youtrack":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=n.url?.trim().replace(/\/$/,"")||i.youtrack?.url;if(!s)return{ok:!1,detail:"no YouTrack URL (send one with the token)"};let a=await Be({baseUrl:s,token:n.token});return i.youtrack={url:s,token:n.token},$t(i,()=>{process.env.YOUTRACK_URL=s,process.env.YOUTRACK_TOKEN=n.token}),{ok:!0,detail:`authenticated as ${a}`}}case"claude":{if(!n.token)return{ok:!1,detail:"payload has no token"};let s=await Bo(n.token);return s==="invalid"?{ok:!1,detail:"Claude token rejected (401) \u2014 previous token kept"}:(i.claude={oauthToken:n.token},$t(i,()=>{}),{ok:!0,...s==="inconclusive"?{detail:"saved (live check inconclusive)"}:{}})}case"contextWrite":return n.token?(i.contextWrite={token:n.token},$t(i,()=>{}),{ok:!0,detail:"saved (verified on the next readiness pass)"}):{ok:!1,detail:"payload has no token"};default:return{ok:!1,detail:`unknown credential kind '${e}'`}}}catch(s){return{ok:!1,detail:`${s instanceof Error?s.message:String(s)} \u2014 previous credential kept`}}}function $t(t,e){V(t),e()}import{existsSync as Fu,readFileSync as Hu,writeFileSync as Ku}from"node:fs";import{join as Wu}from"node:path";import{parseDocument as qu}from"yaml";var rs=64;async function os(t,e){if(!Number.isInteger(e)||e<1||e>rs)throw new Error(`maxJobs must be an integer in [1, ${rs}], got ${e}`);let r=Wu(t,"regimen.yaml");if(!Fu(r))throw new Error(`regimen.yaml not found in context repo (${t})`);let o=qu(Hu(r,"utf-8"));return o.getIn(["parallelism","max_jobs"])===e?{maxJobs:e,unchanged:!0}:(o.setIn(["parallelism","max_jobs"],e),Ku(r,o.toString()),{maxJobs:e,unchanged:!1})}import{existsSync as Yu,readFileSync as Vu,writeFileSync as zu}from"node:fs";import{join as Ju}from"node:path";import{isMap as ns,parseDocument as Xu}from"yaml";async function is(t,e){let r=e.repoName?.trim(),o=e.defaultBranch?.trim();if(!r)throw new Error("repoName must be a non-empty string");if(!o||!jn(o))throw new Error(`"${e.defaultBranch}" is not a valid git branch name`);let n=Ju(t,"project.yaml");if(!Yu(n))throw new Error(`project.yaml not found in context repo (${t})`);let i=Xu(Vu(n,"utf-8")),s=i.get("repos"),c=(s&&typeof s=="object"&&"items"in s?s.items:[]).find(l=>ns(l)&&String(l.get("name")??l.get("repo")??"")===r);if(!ns(c))throw new Error(`repo "${r}" not found in project.yaml repos[]`);return c.set("default_branch",o),zu(n,i.toString()),{repoName:r,defaultBranch:o}}import{existsSync as ss,readFileSync as as,writeFileSync as Qu}from"node:fs";import{join as Go}from"node:path";import{parseDocument as cs}from"yaml";async function ls(t,e){let r=[];if(e.sourceColumns!==void 0||e.backlogColumn!==void 0||e.assignee!==void 0||e.requireAssignee!==void 0){let i=Go(t,"project.yaml");if(!ss(i))throw new Error(`project.yaml not found in context repo (${t})`);let s=cs(as(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=Go(t,"regimen.yaml");if(!ss(i))throw new Error(`regimen.yaml not found in context repo (${t})`);let s=cs(as(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)Qu(Go(t,i.path),i.content);return{files:r.map(i=>i.path)}}var us=t=>console.log(t);function ps(t){us=t}function Vt(t,e="info"){us(t,e)}import{homedir as Zu}from"node:os";import{existsSync as ep,mkdirSync as tp}from"node:fs";import{join as Mo}from"node:path";import{simpleGit as ds}from"simple-git";function Jt(t,e,r){let o=r??Mo(Zu(),".codepipe","repos");return Mo(o,t,e)}async function Or(t,e,r={}){let o=Jt(t,e.name,r.baseDir),n=r.cloneUrlOverride??rp(e);if(!ep(Mo(o,".git"))){tp(o,{recursive:!0});let a=ds();Vt(`[git] clone ${n} \u2192 ${o}`);try{await a.clone(n,o)}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`git clone failed: ${n}
423
+ ${l.trim()}`)}}let i=ds(o);try{await i.fetch()}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`git fetch failed in ${o}
424
+ ${c.trim()}`)}let s=e.defaultBranch??"main";return await i.checkout(["-B",s,`origin/${s}`]).catch(()=>{}),i}async function zt(t,e){try{return await t.raw(["cat-file","-e",`${e}^{commit}`]),!0}catch{return!1}}var fs=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"];async function Ur(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&&Vt(`[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 zt(t,i)||await t.fetch(["origin",i]).catch(()=>{}),!await zt(t,i))throw new Error(`apply_delivery: base commit ${i.slice(0,10)} unavailable \u2014 cannot re-parent the delivery`);let l=(await t.raw([...fs,"commit-tree",c,"-p",i,"-m",s])).trim();return await t.raw(["update-ref","-d","refs/codepipe-delivery"]).catch(()=>{}),l}async function ms(t,e,r){let o=`refs/codepipe/deliveries/${e}`;if(await zt(t,o))return(await t.revparse([o])).trim();let n=`refs/devpipe/deliveries/${e}`;if(await zt(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 gs(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,baseRef:c,commitMessage:l,defaultBranch:p,force:f}=r,u=await ms(t,i,()=>Ur(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:l}));f&&await t.raw(["branch","-D",a]).catch(()=>{});let d=`origin/${c}`;if(await zt(t,d)||(d=`origin/${p??c}`),(await t.revparse([d])).trim()===s)await t.raw(["branch","-f",a,u]),await t.checkout(a);else{await t.checkout(["-B",a,d]);try{await t.raw([...fs,"cherry-pick",u])}catch(x){await t.raw(["cherry-pick","--abort"]).catch(()=>{});let S=x instanceof Error?x.message:String(x);throw new Error(`apply_delivery: cherry-pick of ${i.slice(0,10)} onto ${c} hit conflicts
425
+ ${S.trim()}`)}}let y=(await t.revparse(["HEAD"])).trim(),v=f?["--force-with-lease","-u","origin",a]:["-u","origin",a];return await t.push(v),await t.push([o,"--delete",n]).catch(()=>{}),{commit:y}}async function hs(t,e,r){let{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,branchName:a,commitMessage:c,push:l}=r,p=await ms(t,i,()=>Ur(t,{contextRepoCloneUrl:o,deliveryRef:n,deliverySha:i,baseSha:s,commitMessage:c}));return await t.raw(["branch","-f",a,p]),l&&await t.push(["--force-with-lease","-u","origin",a]),{commit:p,pushed:l}}async function ys(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 rp(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 Lr=new Map;async function Fo(t,e){let o=(Lr.get(t)??Promise.resolve()).catch(()=>{}).then(e);Lr.set(t,o);try{return await o}finally{Lr.get(t)===o&&Lr.delete(t)}}async function ws(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;Vt(`[exec] ${e.type} task=${n} repo=${o}`);try{switch(e.type){case"apply_delivery":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Fo(`${i}/${r.name}`,async()=>{let s=await Or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Jt(i,r.name,t.baseDir),{commit:c}=await gs(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 H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Fo(`${i}/${r.name}`,async()=>{let s=await Or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Jt(i,r.name,t.baseDir),{commit:c,pushed:l}=await hs(s,a,{contextRepoCloneUrl:e.contextRepoCloneUrl,deliveryRef:e.deliveryRef,deliverySha:e.deliverySha,baseSha:e.baseSha,branchName:e.branchName,commitMessage:e.commitMessage,push:e.push});return Z({branch:e.branchName,commit:c,pushed:l})})}case"create_pr":{if(!r)return H("no repo spec");let i=Te(r),s=await i.createPullRequest(r,e);return Z({url:s.url,number:s.number,host:i.name})}case"merge_pr":{if(!r)return H("no repo spec");let i=Te(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 H("no repo spec");let i=Te(r);return await i.closePR(r,e.prNumber,e.comment),Z({prNumber:e.prNumber,host:i.name})}case"merge_branch":{if(!r)return H("no repo spec");let i=e.taskId.split(":",2)[0]??"?";return Fo(`${i}/${r.name}`,async()=>{let s=await Or(i,r,{baseDir:t.baseDir,cloneUrlOverride:t.cloneUrlOverride}),a=Jt(i,r.name,t.baseDir),{mergedSha:c}=await ys(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=rt();return i?t.trackerIssueId?(await Bi(i,t.trackerIssueId,e.newStatus),Z({issueId:t.trackerIssueId,newStatus:e.newStatus})):H("no tracker_issue_id provided"):H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env")}case"tracker_comment":{let i=rt();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!t.trackerIssueId)return H("no tracker_issue_id provided");let s=await Di(i,t.trackerIssueId,e.body);return Z({issueId:t.trackerIssueId,commentId:s.id})}case"create_tracker_issue":{let i=rt();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");if(!e.projectKey)return H("no projectKey in create_tracker_issue action");let{id:s,key:a}=await Gi(i,e.projectKey,e.title,e.body,e.targetStatus);return Z({issueKey:a,issueId:s})}case"apply_tracker_links":{let i=rt();if(!i)return H("YOUTRACK_URL/YOUTRACK_TOKEN not set in CLI env");let s=0;for(let a of e.links)try{await Mi(i,a.sourceIssueKey,a.rel,a.targetIssueKey),s++}catch(c){return H(`${c instanceof Error?c.message:String(c)} (applied ${s}/${e.links.length})`)}return Z({applied:s})}case"set_parallelism":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await os(t.contextDir,e.maxJobs);return Z({maxJobs:i.maxJobs,unchanged:i.unchanged})}case"set_youtrack_config":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await ls(t.contextDir,e);return Z({files:i.files})}case"set_repo_default_branch":{if(!t.contextDir)return H("no context repo clone on this CLI");let i=await is(t.contextDir,e);return Z({repoName:i.repoName,defaultBranch:i.defaultBranch})}case"sync_config":return t.requestConfigReport?(t.requestConfigReport(),Z({reported:!0})):H("no context repo clone on this CLI")}}catch(i){return H(i instanceof Error?i.message:String(i))}}function Z(t){return{status:"done",result:t}}function H(t){return{status:"failed",error:t}}import{existsSync as js,readFileSync as Es}from"node:fs";import{join as As}from"node:path";import{homedir as op}from"node:os";import{existsSync as np,mkdirSync as ip,readFileSync as sp,writeFileSync as ap}from"node:fs";import{dirname as cp,join as lp}from"node:path";function Ho(){return O("FARM_PINS")??lp(op(),".codepipe","farm-pins.json")}function bs(){let t=Ho();if(!np(t))return{};try{return JSON.parse(sp(t,"utf-8"))}catch{return{}}}function up(t){let e=Ho();ip(cp(e),{recursive:!0}),ap(e,JSON.stringify(t,null,2)+`
426
+ `,{mode:384})}function pp(t){return bs()[t]}function Br(t,e){let r=bs();r[t]=e,up(r)}function Dr(t,e){let r=ye(e),o=pp(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 ${Ho()}.`);return r}import dp from"ws";function Gr(t,e){let r=t.replace(/^http/,"ws")+`/cli/connect?token=${encodeURIComponent(e)}`;return new dp(r)}var A=class extends Error{constructor(r,o,n){super(n);this.status=r;this.payload=o;this.name="HubHttpError"}};async function xt(t,e,r){return De(t,e,"/projects",r)}async function ks(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 Mr(t,e,r,o){return De(t,e,`/farms/${encodeURIComponent(r)}/provision`,o)}async function Fr(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 $s(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 Xt=class extends Error{constructor(r){super("registration_required");this.email=r;this.name="RegistrationRequiredError"}};async function xs(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 Xt(e)}if(!r.ok)throw new A(r.status,null,`bootstrap-request HTTP ${r.status}`);return await r.json()}async function vs(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 Ss(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 Cs(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 Ts(t,e,r,o){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/apply-claim`,{})}async function Rs(t,e,r,o,n){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/applied`,{prs:n})}async function Is(t,e,r,o,n){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/abort`,{reason:n})}async function Ps(t,e,r,o,n){return De(t,e,`/projects/${encodeURIComponent(r)}/tasks/${encodeURIComponent(o)}/command`,{command:n})}async function Hr(t,e,r,o){return De(t,e,`/projects/${encodeURIComponent(r)}/index`,o)}async function Ko(t,e,r,o){await De(t,e,`/projects/${encodeURIComponent(r)}/init-status`,o)}async function Q(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 De(t,e,r,o){let n=await fetch(`${t}${r}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}),i=await n.text(),s=i?JSON.parse(i):null;if(!n.ok){let a=s&&typeof s=="object"&&"error"in s?String(s.error):`HTTP ${n.status}`;throw new A(n.status,s,a)}return s}async function _s(t,e,r,o){let n=i=>({type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!1,error:i});try{if(e.projectId!==t.projectId)return n(`project mismatch: this daemon serves ${t.projectId}, not ${e.projectId}`);let i=ye(e.farmPublicKey);if(i!==e.fingerprint)return n("farm key fingerprint does not match the confirmed one \u2014 refusing to seal (possible relay tampering)");Dr(e.farmId,e.farmPublicKey);let s=L(t.projectId);if(!s)return n("no secrets stored for this project on this CLI \u2014 cannot build the farm bundle");let a=await Q(t.hubUrl,t.cliToken,t.projectId),c;if(r){let u=As(r,"project.yaml"),d=As(r,"regimen.yaml");js(u)&&js(d)?c={projectYaml:Es(u,"utf-8"),regimenYaml:Es(d,"utf-8")}:o.warn("[farm-move] local project.yaml/regimen.yaml not found \u2014 the farm will seed defaults")}let l={projectId:t.projectId,config:{hubUrl:t.hubUrl,cliToken:t.cliToken,projectId:t.projectId},secrets:{...s.github?{github:s.github}:{},...s.bitbucket?{bitbucket:s.bitbucket}:{},...s.gitlab?{gitlab:s.gitlab}:{},...s.youtrack?{youtrack:s.youtrack}:{},...s.claude?{claude:s.claude}:{},...s.contextWrite?{contextWrite:s.contextWrite}:{},...s.contextSsh?{contextSsh:s.contextSsh}:{}},...a.contextRepo?{contextRepo:a.contextRepo}:{},...c?{projectConfig:c}:{}},p=kt(e.farmPublicKey,JSON.stringify(l));Br(e.farmId,i),o.info(`[farm-move] bundle sealed for farm ${e.farmName} (${i}) \u2014 handing off`);let f=await Mr(t.hubUrl,t.cliToken,e.farmId,{projectId:t.projectId,sealedBundle:p});return f.ok?{type:"move_to_farm_result",requestId:e.requestId,projectId:t.projectId,ok:!0,...f.daemonStatus?{daemonStatus:f.daemonStatus}:{}}:n(f.error??"farm provisioning failed")}catch(i){return n(i instanceof Error?i.message:String(i))}}var Kr=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=Te(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 tt){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=Te(r.prs[s].repoSpec);if(c.getCiFailureLog)try{let l=await c.getCiFailureLog(r.prs[s].repoSpec,a.number);l&&(a.ciFailureLog=l)}catch(l){this.log.warn(`[track] task=${e} pr=${a.url} ci-log fetch failed: ${l instanceof Error?l.message:String(l)}`)}}this.send({type:"pr_state_observed",taskId:e,prs:o}),this.lastSig.set(e,n);let i=fp(o);this.log.info(`[track] task=${e} snapshot signalled${i?` \u2192 ${i}`:""} (${o.length} PR(s))`)}};function fp(t){return t.length===0?null:t.some(e=>e.state==="closed"&&!e.merged)?"needs_manual":t.every(e=>e.merged)?"done":null}var Wr=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=rt();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 u=[...new Set([...e.sourceColumns,...e.rejectColumns??[],...e.backlogColumn?[e.backlogColumn]:[]])];n=await qi(r,{projectKey:e.projectKey,columns:u,...e.requireAssignee&&e.assignee?{assignee:e.assignee}:{},...e.requireAssignee&&!e.assignee?{requireAnyAssignee:!0}:{}})}catch(u){this.log.warn(`[yt-sync] listIssues failed: ${u instanceof Error?u.message:String(u)}`);return}let i=[],s=new Set;for(let u of n){s.add(u.id);let d=await Ns(r,u.id,e.sinceMs,this.log);d&&i.push({issueId:u.id,comments:d})}let a=[];for(let u of e.offBoardIssueIds){if(s.has(u))continue;let d=await Ns(r,u,e.sinceMs,this.log);if(d&&i.push({issueId:u,comments:d}),e.requireAssignee){let g=await gp(r,u,this.log);g&&a.push(g)}}let c=await this.collectAttachments(n,i,r),l={type:"youtrack_observation",projectId:e.projectId,issues:n,commentsBatch:i,...a.length>0?{offBoardIssues:a}:{},...c.length>0?{attachmentsBatch:c}:{},observedAtMs:o};this.send(l);let p=i.reduce((u,d)=>u+d.comments.length,0),f=c.reduce((u,d)=>u+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=[],l=new Set;for(let p of s){let f=`${i.id}:${p.id}`;if(this.shippedAttachments.has(f))continue;let u;try{u=await Wi(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=mp(p.name);l.has(d)&&(d=`${p.id}-${d}`),l.add(d),c.push({name:d,contentBase64:u.toString("base64"),...p.mimeType?{mimeType:p.mimeType}:{}}),this.shippedAttachments.add(f)}c.length>0&&n.push({issueId:i.id,files:c})}return n}};function mp(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 gp(t,e,r){try{return await Yi(t,e)}catch(o){return r.warn(`[yt-sync] getIssue ${e} failed: ${o instanceof Error?o.message:String(o)}`),null}}async function Ns(t,e,r,o){try{return await Vi(t,e,r)}catch(n){return o.warn(`[yt-sync] listComments ${e} failed: ${n instanceof Error?n.message:String(n)}`),null}}var Wo="npm i -g @code-partner/codepipe@latest";function qr(t,e={}){let r=e.log??{info:d=>console.log(d),warn:d=>console.warn(d)};r.info(`codepipe-cli v${ae} (protocol ${fe})`);let o=d=>e.onEvent?.(d),n=e.workspace;n?.contextDir&&si(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,l=!1,p=new Set,f=u();function u(){let d=Gr(t.hubUrl,t.cliToken),g=null,y=new Kr(i,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),v=new Wr(s,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r),x=null,S=async()=>{try{let C;try{let h=await Q(t.hubUrl,t.cliToken,t.projectId);C={repos:h.repos,contextRepo:h.contextRepo}}catch(h){r.warn(`[readiness] could not fetch project summary for push checks: ${h instanceof Error?h.message:String(h)}`)}let _=await Ji(t.projectId,C);if(d.readyState!==d.OPEN)return;let R={type:"cli_readiness",projectId:t.projectId,ready:_.ready,checks:_.checks,creds:_.creds,checkedAt:_.checkedAt};if(d.send(JSON.stringify(R)),_.ready)r.info("[readiness] ready");else{let h=_.checks.filter(m=>!m.ok).map(m=>`${m.name}(${m.detail??""})`);r.warn(`[readiness] NOT ready \u2014 ${h.join(", ")}`)}}catch(C){r.warn(`[readiness] check failed: ${C instanceof Error?C.message:String(C)}`)}},E=()=>{S(),x=setInterval(()=>void S(),a),typeof x.unref=="function"&&x.unref()},I=()=>{x&&(clearInterval(x),x=null)},B=n?.contextDir?new Ir(n.contextDir,t.projectId,C=>{d.readyState===d.OPEN&&d.send(JSON.stringify(C))},r):null;return d.on("open",()=>{r.info("[ws] connected"),o({kind:"connected"});let C=ri(t.projectId),_=O("ORIGIN")==="farm"?"farm":"local",R=O("FARM_ID"),h=t.accountEmail??C.email,m;try{let k=es(t.projectId);k&&(m=k.publicKey,r.info(`[cred-channel] key fingerprint: ${k.fingerprint}`))}catch(k){r.warn(`[cred-channel] key setup failed (token replacement via dashboard unavailable): ${k instanceof Error?k.message:String(k)}`)}let w={type:"register",projectId:t.projectId,platformVersion:ae,protocolVersion:fe,accountId:C.accountId,accountLabel:C.label,origin:_,inFlightActionIds:[...p],...h?{accountEmail:h}:{},..._==="farm"&&R?{farmId:R}:{},...m?{sealPublicKey:m}:{}};d.send(JSON.stringify(w))}),d.on("message",async C=>{let _=C.toString("utf-8");if(_==="pong"||_==="ping")return;let R;try{R=JSON.parse(_)}catch{return}if(!R||typeof R!="object")return;let h=R.type;if(h==="registered"){let w=R;if(w.ok){if(r.info(`[ws] registered for project ${w.projectId}`),o({kind:"registered",projectId:w.projectId??t.projectId}),y.start(),B?.start(),E(),n?.contextDir){let k=n.contextDir;try{let $=Er(k,t.projectId);d.readyState===d.OPEN&&d.send(JSON.stringify($)),$.outdated&&(r.warn(`[ctx] context format outdated: v${$.templateVersion} \u2192 v${$.currentVersion}`+($.missingPaths.length>0?` (missing: ${$.missingPaths.join(", ")})`:"")),l||(l=!0,(async()=>{try{let N;try{N=(await Q(t.hubUrl,t.cliToken,t.projectId)).contextRepo}catch{}let q=await bi(k,t.projectId,N,r);d.readyState===d.OPEN&&d.send(JSON.stringify(q))}catch(N){r.warn(`[ctx] context migration failed (non-fatal): ${N instanceof Error?N.message:String(N)}`)}})()))}catch($){r.warn(`[ctx] context-format detect failed (non-fatal): ${$ instanceof Error?$.message:String($)}`)}}}else r.warn(`[ws] register rejected: ${w.reason??"unknown"}`),o({kind:"register_rejected",reason:w.reason??"unknown"}),c=!0,d.close();return}if(h==="hello"){let w=R;g=hr(w.protocolVersion);let k=g?"compatible":"INCOMPATIBLE";r.info(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${k}`),g||(r.warn(`[ws] HUB protocol incompatible with this CLI (v${ae}, protocol ${fe}) \u2014 WriteActions will be refused until versions align.`),r.warn(`[ws] update the CLI: ${Wo}`),o({kind:"incompatible",hubVersion:typeof w.platformVersion=="string"?w.platformVersion:null,hubProtocol:typeof w.protocolVersion=="number"?w.protocolVersion:null,updateCommand:Wo}));return}if(h==="tracking_targets"){y.setTargets(R.targets);return}if(h==="youtrack_sync_request"){v.setRequest(R);return}if(h==="sync_local"){await yp(R,n,d,r);return}if(h==="context_write"){await wp(R,n,d,r);return}if(h==="adr_promote"){await bp(R,n,d,r);return}if(h==="cred_update"){let w=R,k=L(t.projectId),$=k?.sealKey?await ts(t.projectId,w.kind,w.sealed,k.sealKey.privateKey):{ok:!1,detail:"no cred-channel key on this CLI (restart the daemon)"},N={type:"cred_update_result",updateId:w.updateId,projectId:t.projectId,ok:$.ok,...$.detail?{detail:$.detail}:{}};d.readyState===d.OPEN&&d.send(JSON.stringify(N)),$.ok?(r.info(`[cred] ${w.kind} replaced${$.detail?` \u2014 ${$.detail}`:""}`),S()):r.warn(`[cred] ${w.kind} replacement rejected: ${$.detail??"unknown"}`);return}if(h==="move_to_farm"){let w=R;r.info(`[farm-move] request to move ${t.projectId} onto farm ${w.farmName} (${w.farmId})`);let k=await _s(t,w,n?.contextDir,r);d.readyState===d.OPEN&&d.send(JSON.stringify(k)),k.ok?r.info(`[farm-move] done \u2014 farm daemon ${k.daemonStatus??"started"}; expecting takeover`):r.warn(`[farm-move] failed: ${k.error??"unknown error"}`);return}if(h==="sandbox_keys"){let w=L(t.projectId);if(!w){r.warn(`[cred] sandbox_keys received but no secrets for ${t.projectId} \u2014 cannot seal`);return}let k=ft(t.projectId),$=Si(R,w,k,r);for(let N of $)d.readyState===d.OPEN&&d.send(JSON.stringify(N));return}if(h!=="dispatch_action")return;let m=R;if(g===!1){let w=`refused: HUB protocol incompatible with CLI v${ae} (protocol ${fe})`;d.send(JSON.stringify({type:"action_result",actionId:m.actionId,status:"failed",error:w})),r.warn(`[exec] ${m.actionId} (${m.action.type}) \u2192 REFUSED: ${w}`),r.warn(`[exec] update the CLI to clear this: ${Wo}`),o({kind:"action",actionId:m.actionId,actionType:m.action.type,ok:!1,error:w});return}p.add(m.actionId);try{let w=await ws({action:m.action,repo:m.repo,trackerIssueId:m.trackerIssueId,contextDir:n?.contextDir,requestConfigReport:B?()=>B.reportNow():void 0}).catch(N=>({status:"failed",error:N instanceof Error?N.message:String(N)}));d.send(JSON.stringify({type:"action_result",actionId:m.actionId,...w}));let k=w.status!=="failed",$=!k&&"error"in w?w.error:void 0;k?r.info(`[exec] ${m.actionId} (${m.action.type}) \u2192 done`):r.warn(`[exec] ${m.actionId} (${m.action.type}) \u2192 FAILED: ${$??"?"}`),o({kind:"action",actionId:m.actionId,actionType:m.action.type,ok:k,...$?{error:$}:{}})}finally{p.delete(m.actionId)}}),d.on("close",(C,_)=>{let R=_?.toString("utf-8")??"";if(r.info(`[ws] closed code=${C}${R?` reason=${R}`:""}`),y.stop(),v.stop(),B?.stop(),I(),R==="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:C}),!c&&setTimeout(()=>{f=u()},2e3)}),d.on("error",C=>r.warn(`[ws] error: ${C.message}`)),d}return{stop(){c=!0,f.close()}}}async function yp(t,e,r,o){if(!e){o.info(`[sync] sync_local for ${t.taskId} \u2014 no workspace (headless), skipped`);return}for(let n of t.repos){let i=e.repos.find(l=>l.name===n.repoName),s=hp(e.root,i?.mountAs??n.repoName),a=i?.defaultBranch??n.defaultBranch,c=await oi(s,a).catch(l=>({status:"warn",reason:l instanceof Error?l.message:String(l)}));c.status==="updated"?o.info(`[sync] ${n.repoName}: fast-forwarded ${a} \u2192 origin`):c.status==="skipped"?o.info(`[sync] ${n.repoName}: not cloned in workspace \u2014 skipped`):(o.warn(`[sync] ${n.repoName}: ${c.reason??"sync skipped"}`),r.readyState===r.OPEN&&r.send(JSON.stringify({type:"local_sync_warning",taskId:t.taskId,repoName:n.repoName,reason:c.reason??"sync skipped"})))}}async function wp(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 jr(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 bp(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 di(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 Fs,mkdirSync as Hs}from"node:fs";import{dirname as Ks}from"node:path";import{simpleGit as vt}from"simple-git";import{execFileSync as kp}from"node:child_process";import{mkdtempSync as $p,mkdirSync as xp,readFileSync as Us,rmSync as vp,writeFileSync as Sp}from"node:fs";import{tmpdir as Cp}from"node:os";import{dirname as Tp,join as Ls}from"node:path";function Bs(t="codepipe-context"){let e=$p(Ls(Cp(),"codepipe-ssh-")),r=Ls(e,"id_ed25519");try{return kp("ssh-keygen",["-t","ed25519","-N","","-C",t,"-f",r,"-q"],{stdio:"ignore"}),{privateKey:Us(r,"utf-8"),publicKey:Us(`${r}.pub`,"utf-8").trim()}}finally{vp(e,{recursive:!0,force:!0})}}async function Ds(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 Gs(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 Ms(t,e){xp(Tp(t),{recursive:!0});let r=e.endsWith(`
427
427
  `)?e:e+`
428
- `;return xp(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Cp(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 Tp(t,e){return e?.contextWrite?.token?{user:yr(t),secret:e.contextWrite.token}:t===Gt.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Gt.bitbucket?e?.bitbucket?.apiToken?{user:Je,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Wr(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await Q(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=Tp(ut(s.cloneUrl),r);if(a){let c=await Rp({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 Ip({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 Rp(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Cp(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=l=>l.split(o.secret).join("***").split(a).join("***");try{if(Gs(`${r}/.git`)){let l=xt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=So(r);await l.reset(["--hard",`origin/${s}`]),Co(r,p),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Ms(Fs(r),{recursive:!0}),await xt().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Hs(r)}catch(l){return n.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function Ip(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Ds(i,o),a=Bs(e.cloneUrl),c=e.branch;try{if(Gs(`${r}/.git`)){let l=xt(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let p=So(r);await l.reset(["--hard",`origin/${c}`]),Co(r,p),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Ms(Fs(r),{recursive:!0}),await xt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await xt(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Hs(r),{root:r,contextDir:r,repos:[]}}catch(l){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function Hs(t){let e=xt(t);await e.raw(["config","user.email"]).then(o=>o.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function Ks(t={profile:void 0}){let{cfg:e,profile:r}=$r(t.profile),o=U(e.projectId);o&&Mt(o),Ht(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),Kt(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Wt(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=Jt(Ko(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Sr("CLI_LOG",i,n);if(s.enabled){let u=new mt(s);Cr(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=br(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let u=Jt(Ko(),".codepipe",r?Jt("profiles",r,"context"):"context");if(await Fo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Wr({cfg:e,secrets:o,contextDir:u,log:{info:d=>console.log(d),warn:d=>console.warn(d)}}),a||await Fo(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let d=Jt(Ko(),".codepipe",r?Jt("profiles",r,"context-config"):"context-config");Rr(a.contextDir,d,{info:g=>console.log(g),warn:g=>console.warn(g)})}}let l=Kr(e,{...a?{workspace:a}:{},onEvent:u=>{u.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))}}),p=!1;function f(u){p||(p=!0,console.log(`
429
- [${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as Op}from"node:os";import{spawnSync as Pp}from"node:child_process";function jp(){try{return Pp("podman",["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}}function Ws(t={}){let e=process.platform==="darwin"?"darwin":process.platform==="win32"?"windows":"linux",r=process.arch==="arm64"?"arm64":"x64";return{os:e,arch:r,containers:jp(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as vt}from"node:os";import{mkdirSync as Ep,readFileSync as qs,writeFileSync as Ap,existsSync as Wo}from"node:fs";import{dirname as _p,join as Me}from"node:path";Wo(".env")&&process.loadEnvFile(".env");function Fe(t){let e=N("SANDBOX_CONFIG");if(e)return e;let r=Me(vt(),".codepipe","worker");return t?Me(r,"profiles",t,"config.json"):Me(r,"config.json")}function Ys(){return Me(vt(),".devpipe-sandbox","config.json")}function qr(){Xe(Me(vt(),".devpipe"),Me(vt(),".codepipe")),N("SANDBOX_CONFIG")||Xe(Me(vt(),".devpipe-sandbox"),Me(vt(),".codepipe-sandbox"))}function oe(t){let e=Fe(t);return Wo(e)?JSON.parse(qs(e,"utf-8")):!t&&!N("SANDBOX_CONFIG")&&Wo(Ys())?JSON.parse(qs(Ys(),"utf-8")):null}function Vs(t,e){let r=Fe(e);Ep(_p(r),{recursive:!0}),Ap(r,JSON.stringify(t,null,2)+`
430
- `,{mode:384})}import Np from"ws";var St=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 Np(e)}};async function nt(t){qr();let e=oe(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Fe(t.profile)}.`),process.exit(1));let r=t.name??Op(),o=Ws({projects:t.projects??[],llm:t.llm??null}),n=new St(t.hub.replace(/\/$/,"")),i=Er(),s=be(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Vs({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 ${Fe(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 $d,readFileSync as Ia,readdirSync as xd,writeFileSync as vd}from"node:fs";import{dirname as Sd,join as ro,resolve as Cd}from"node:path";import{spawn as Up}from"node:child_process";import{existsSync as Lp}from"node:fs";var Ct=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},Yr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Bp=5e3,Xt=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new Yr;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="",l=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let y=Fp(g.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(g.type==="assistant"){let y=g.message;typeof y?.model=="string"&&(c=y.model);let S=y?.usage;S&&(a+=1,s.input+=ne(S.input_tokens),s.output+=ne(S.output_tokens),s.cacheRead+=ne(S.cache_read_input_tokens),s.cacheCreate+=ne(S.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,d=g=>{if(u)for(let y of Kp(g,e.workspaceDir))try{u(y)}catch{}};return u?.({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,y)=>{let S=Up(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});S.stdout.setEncoding("utf-8"),S.stderr.setEncoding("utf-8");let x=!1,v=null,A=()=>{x=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),S.kill("SIGTERM"),v=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),S.kill("SIGKILL")},Bp)};e.signal?.addEventListener("abort",A,{once:!0});let I=()=>{v&&clearTimeout(v),e.signal?.removeEventListener("abort",A)},L="";S.stdout.on("data",C=>{o.push(C),L+=C;let h;for(;(h=L.indexOf(`
431
- `))!==-1;){let m=L.slice(0,h).trim();if(L=L.slice(h+1),m){let k=zs(m);p(k),k&&d(k)}}}),S.stderr.on("data",C=>{o.push(C),n.push(C);for(let h of C.split(`
432
- `)){let m=h.trim();m&&console.warn(`[claude:stderr] ${m}`)}}),S.on("error",C=>{I(),y(C)}),S.on("close",C=>{if(I(),x){y(new Yr);return}if(L.trim()){let m=zs(L.trim());p(m),m&&d(m)}let h=i?.is_error===!0;if(C!==0||h){let m=typeof i?.api_error_status=="number"?i.api_error_status:void 0,k=typeof i?.subtype=="string"?i.subtype:void 0,$=typeof i?.result=="string"?i.result:void 0;y(new Ct(Dp(C,i,n.join("")),{code:C,apiErrorStatus:m,subtype:k,resultText:$,retryAfterMs:Gp(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:Hp(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&Lp(o))}};function zs(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: ${He(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=Mp(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=Xs(n.content);console.log(`[claude] tool_result (error)${i?`: ${He(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)} ${He(JSON.stringify(e),200)}`),e}function Dp(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(He(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(He(r.trim().split(`
428
+ `;return Sp(t,r,{mode:384}),`ssh -i "${t}" -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new`}function Rp(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 Ip(t,e){return e?.contextWrite?.token?{user:br(t),secret:e.contextWrite.token}:t===Ft.gitlab?e?.gitlab?.token?{user:"oauth2",secret:e.gitlab.token}:null:t===Ft.bitbucket?e?.bitbucket?.apiToken?{user:ze,secret:e.bitbucket.apiToken}:null:e?.github?.token?{user:"x-access-token",secret:e.github.token}:null}async function Yr(t){let{cfg:e,secrets:r,contextDir:o,log:n}=t,i;try{i=await Q(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=Ip(pt(s.cloneUrl),r);if(a){let c=await Pp({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 jp({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 Pp(t){let{ctx:e,contextDir:r,cred:o,log:n}=t,i=Rp(e.cloneUrl,o.secret,o.user),s=e.branch,a=encodeURIComponent(o.secret),c=l=>l.split(o.secret).join("***").split(a).join("***");try{if(Fs(`${r}/.git`)){let l=vt(r);await l.remote(["set-url","origin",i]),await l.fetch("origin",s),await l.checkout(s);let p=To(r);await l.reset(["--hard",`origin/${s}`]),Ro(r,p),n.info(`[ctx] updated Context Repo clone \u2192 ${r}@${s}`)}else Hs(Ks(r),{recursive:!0}),await vt().clone(i,r,["--branch",s]),n.info(`[ctx] cloned Context Repo ${e.owner}/${e.name}@${s} \u2192 ${r}`);await Ws(r)}catch(l){return n.warn(`[ctx] Context Repo clone/update failed: ${c(l instanceof Error?l.message:String(l))}`),null}return{root:r,contextDir:r,repos:[]}}async function jp(t){let{ctx:e,contextDir:r,privateKey:o,log:n}=t,i=`${r}.deploy-key`,s=Ms(i,o),a=Gs(e.cloneUrl),c=e.branch;try{if(Fs(`${r}/.git`)){let l=vt(r);await l.addConfig("core.sshCommand",s,!1,"local"),await l.remote(["set-url","origin",a]),await l.fetch("origin",c),await l.checkout(c);let p=To(r);await l.reset(["--hard",`origin/${c}`]),Ro(r,p),n.info(`[ctx] updated Context Repo clone (ssh) \u2192 ${r}@${c}`)}else Hs(Ks(r),{recursive:!0}),await vt().env({...process.env,GIT_SSH_COMMAND:s}).clone(a,r,["--branch",c]),await vt(r).addConfig("core.sshCommand",s,!1,"local"),n.info(`[ctx] cloned Context Repo (ssh) ${e.owner}/${e.name}@${c} \u2192 ${r}`);return await Ws(r),{root:r,contextDir:r,repos:[]}}catch(l){return n.warn(`[ctx] Context Repo ssh clone/update failed: ${l instanceof Error?l.message:String(l)}`),null}}async function Ws(t){let e=vt(t);await e.raw(["config","user.email"]).then(o=>o.trim()).catch(()=>"")||(await e.addConfig("user.email","farm@codepipe.local",!1,"local"),await e.addConfig("user.name","CodePipe Farm CLI",!1,"local"))}async function qs(t={profile:void 0}){let{cfg:e,profile:r}=vr(t.profile),o=L(e.projectId);o&&Ht(o),Wt(o?.github?.token??process.env.GH_TOKEN)&&console.log("[git] github.com over token-HTTPS (insteadOf) \u2014 farm transport"),qt(o?.gitlab?.token??process.env.GITLAB_TOKEN)&&console.log("[git] gitlab.com over token-HTTPS (insteadOf) \u2014 farm transport"),Yt(o?.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)&&console.log("[git] bitbucket.org over token-HTTPS (insteadOf) \u2014 farm transport");let n=Qt(qo(),".codepipe","logs"),i=r?`cli-daemon-${r}`:"cli-daemon",s=Tr("CLI_LOG",i,n);if(s.enabled){let u=new gt(s);Rr(u),console.log(`[log] file logging \u2192 ${u.path} (rotate at ${s.maxBytes}B, keep ${s.maxFiles})`)}console.log(`codepipe daemon \u2192 ${e.hubUrl} (project=${e.projectId})`);let a=null,c=$r(e.projectId);if(c&&(a={root:c.root,contextDir:c.contextDir,repos:c.spec.repos},console.log(`[ctx] workspace found at ${c.root} \u2014 using its Context Repo clone`)),!a){let u=Qt(qo(),".codepipe",r?Qt("profiles",r,"context"):"context");if(await Ko(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning"}).catch(()=>{}),a=await Yr({cfg:e,secrets:o,contextDir:u,log:{info:d=>console.log(d),warn:d=>console.warn(d)}}),a||await Ko(e.hubUrl,e.cliToken,e.projectId,{phase:"context_cloning",error:"could not clone the Context Repo \u2014 check the context credentials (the daemon continues without config reporting)"}).catch(()=>{}),a?.contextDir){let d=Qt(qo(),".codepipe",r?Qt("profiles",r,"context-config"):"context-config");Pr(a.contextDir,d,{info:g=>console.log(g),warn:g=>console.warn(g)})}}let l=qr(e,{...a?{workspace:a}:{},onEvent:u=>{u.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))}}),p=!1;function f(u){p||(p=!0,console.log(`
429
+ [${u}] shutting down`),l.stop(),setTimeout(()=>process.exit(0),200))}process.on("SIGINT",()=>f("SIGINT")),process.on("SIGTERM",()=>f("SIGTERM")),await new Promise(()=>{})}import{hostname as Lp}from"node:os";import{spawnSync as Ep}from"node:child_process";function Ap(){try{return Ep("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:Ap(),node:process.versions.node,browser:!1,projects:t.projects??[],llm:t.llm??null}}import{homedir as St}from"node:os";import{mkdirSync as _p,readFileSync as Vs,writeFileSync as Np,existsSync as Yo}from"node:fs";import{dirname as Op,join as Ge}from"node:path";Yo(".env")&&process.loadEnvFile(".env");function Me(t){let e=O("SANDBOX_CONFIG");if(e)return e;let r=Ge(St(),".codepipe","worker");return t?Ge(r,"profiles",t,"config.json"):Ge(r,"config.json")}function zs(){return Ge(St(),".devpipe-sandbox","config.json")}function Vr(){Je(Ge(St(),".devpipe"),Ge(St(),".codepipe")),O("SANDBOX_CONFIG")||Je(Ge(St(),".devpipe-sandbox"),Ge(St(),".codepipe-sandbox"))}function oe(t){let e=Me(t);return Yo(e)?JSON.parse(Vs(e,"utf-8")):!t&&!O("SANDBOX_CONFIG")&&Yo(zs())?JSON.parse(Vs(zs(),"utf-8")):null}function Js(t,e){let r=Me(e);_p(Op(r),{recursive:!0}),Np(r,JSON.stringify(t,null,2)+`
430
+ `,{mode:384})}import Up from"ws";var Ct=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 Up(e)}};async function ot(t){Vr();let e=oe(t.profile);e&&!t.force&&(console.error(`sandbox already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl}.`),console.error(`pass --force to overwrite ${Me(t.profile)}.`),process.exit(1));let r=t.name??Lp(),o=Ys({projects:t.projects??[],llm:t.llm??null}),n=new Ct(t.hub.replace(/\/$/,"")),i=_r(),s=ye(i.publicKey),{sandboxId:a,token:c}=await n.register({name:r,registrationToken:t.token,capabilities:o,publicKey:i.publicKey});Js({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 ${Me(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 vd,readFileSync as ja,readdirSync as Sd,writeFileSync as Cd}from"node:fs";import{homedir as Td}from"node:os";import{dirname as Rd,join as nr}from"node:path";import{spawn as Bp}from"node:child_process";import{existsSync as Dp}from"node:fs";var Tt=class extends Error{details;constructor(e,r){super(e),this.details=r,this.name="ClaudeRunError"}},zr=class extends Error{constructor(){super("run aborted by pause"),this.name="ClaudeAbortError"}},Gp=5e3,Zt=class{binary;constructor(e="claude"){this.binary=e}name(){return"claude-headless"}async run(e){if(e.signal?.aborted)throw new zr;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="",l=null,p=g=>{if(g){if(g.type==="result"){i=g;return}if(g.type==="rate_limit_event"){let y=Kp(g.rate_limit_info);y&&(!l||y.utilization>l.utilization)&&(l=y);return}if(g.type==="assistant"){let y=g.message;typeof y?.model=="string"&&(c=y.model);let v=y?.usage;v&&(a+=1,s.input+=ne(v.input_tokens),s.output+=ne(v.output_tokens),s.cacheRead+=ne(v.cache_read_input_tokens),s.cacheCreate+=ne(v.cache_creation_input_tokens))}}},f=e.role,u=e.onActivity,d=g=>{if(u)for(let y of qp(g,e.workspaceDir))try{u(y)}catch{}};return u?.({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,y)=>{let v=Bp(this.binary,r,{cwd:e.workspaceDir,stdio:["ignore","pipe","pipe"],env:{...process.env,...e.env??{}}});v.stdout.setEncoding("utf-8"),v.stderr.setEncoding("utf-8");let x=!1,S=null,E=()=>{x=!0,console.warn(`[claude] pause \u2014 sending SIGTERM to role=${f}`),v.kill("SIGTERM"),S=setTimeout(()=>{console.warn("[claude] still alive after SIGTERM \u2014 sending SIGKILL"),v.kill("SIGKILL")},Gp)};e.signal?.addEventListener("abort",E,{once:!0});let I=()=>{S&&clearTimeout(S),e.signal?.removeEventListener("abort",E)},B="";v.stdout.on("data",C=>{o.push(C),B+=C;let _;for(;(_=B.indexOf(`
431
+ `))!==-1;){let R=B.slice(0,_).trim();if(B=B.slice(_+1),R){let h=Xs(R);p(h),h&&d(h)}}}),v.stderr.on("data",C=>{o.push(C),n.push(C);for(let _ of C.split(`
432
+ `)){let R=_.trim();R&&console.warn(`[claude:stderr] ${R}`)}}),v.on("error",C=>{I(),y(C)}),v.on("close",C=>{if(I(),x){y(new zr);return}if(B.trim()){let R=Xs(B.trim());p(R),R&&d(R)}let _=i?.is_error===!0;if(C!==0||_){let R=typeof i?.api_error_status=="number"?i.api_error_status:void 0,h=typeof i?.subtype=="string"?i.subtype:void 0,m=typeof i?.result=="string"?i.result:void 0;y(new Tt(Mp(C,i,n.join("")),{code:C,apiErrorStatus:R,subtype:h,resultText:m,retryAfterMs:Fp(i)}));return}console.log("[claude] exit code=0"),g({artifactPaths:[],log:o.join(""),usage:Wp(i,s,a,c),...l?{rateLimit:l}:{}})})})}static isAvailable(e="claude"){return[e,`/usr/local/bin/${e}`,`/opt/homebrew/bin/${e}`].some(o=>o.includes("/")&&Dp(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: ${Fe(s,200)}`)}else if(i==="tool_use"){let s=String(n.name??""),a=n.input,c=Hp(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=Zs(n.content);console.log(`[claude] tool_result (error)${i?`: ${Fe(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)} ${Fe(JSON.stringify(e),200)}`),e}function Mp(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(Fe(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(Fe(r.trim().split(`
433
433
  `).slice(-5).join(`
434
- `),500)),o.join(" \u2014 ")}function Gp(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 Xs(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Mp(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=${He(r,80)}`}return""}function He(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ne(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Fp(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ne(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:ne(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 Hp(t,e,r,o){let n=hr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=ne(i.input_tokens),n.outputTokens=ne(i.output_tokens),n.cacheReadInputTokens=ne(i.cache_read_input_tokens),n.cacheCreationInputTokens=ne(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=ne(t?.total_cost_usd),n.numTurns=t&&ne(t.num_turns)>0?ne(t.num_turns):r,n.durationMs=ne(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Js=200;function Kp(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:He(c,Js)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,f=Wp(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?He(Xs(s.content),Js):"";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 Wp(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 qp,writeFileSync as Qt}from"node:fs";import{dirname as Yp,join as Zt}from"node:path";function Qs(t,e,r){let o=Zt(t,e);qp(Yp(o),{recursive:!0}),Qt(o,r)}var er=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=Vp(o,n,i);Qt(Zt(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Qt(Zt(e.workspaceDir,"SOLUTION.md"),zp(o,n,i,a)),s.push("SOLUTION.md"),Qt(Zt(e.workspaceDir,"QUESTIONS.md"),Jp(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;Qs(e.workspaceDir,"changes/sample.patch",Xp(o,n,a)),s.push("changes/sample.patch"),Qs(e.workspaceDir,"diff-summary.md",Qp(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(Qt(Zt(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
435
- `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:hr()}}};function Vp(t,e,r){return`# ${t} \u2014 Estimate
434
+ `),500)),o.join(" \u2014 ")}function Fp(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 Zs(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"?String(e.text??""):"").join(" ").trim():""}function Hp(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=${Fe(r,80)}`}return""}function Fe(t,e){return t.length>e?t.slice(0,e)+"\u2026":t}function ne(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Kp(t){if(!t||typeof t!="object")return null;let e=t;if(typeof e.utilization!="number")return null;let r=ne(e.utilization),o=r>1?r/100:r,n={status:typeof e.status=="string"?e.status:"",resetsAt:ne(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 Wp(t,e,r,o){let n=wr(),i=t&&typeof t.usage=="object"?t.usage:null;i?(n.inputTokens=ne(i.input_tokens),n.outputTokens=ne(i.output_tokens),n.cacheReadInputTokens=ne(i.cache_read_input_tokens),n.cacheCreationInputTokens=ne(i.cache_creation_input_tokens)):(n.inputTokens=e.input,n.outputTokens=e.output,n.cacheReadInputTokens=e.cacheRead,n.cacheCreationInputTokens=e.cacheCreate),n.totalCostUsd=ne(t?.total_cost_usd),n.numTurns=t&&ne(t.num_turns)>0?ne(t.num_turns):r,n.durationMs=ne(t?.duration_ms);let s=typeof t?.model=="string"?t.model:"";return n.model=s||o,n}var Qs=200;function qp(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:Fe(c,Qs)})}else if(a==="tool_use"){let c=String(s.name??""),l=s.input,p=l?.file_path??l?.path??l?.notebook_path,f=Yp(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?Fe(Zs(s.content),Qs):"";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 Yp(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 Vp,writeFileSync as er}from"node:fs";import{dirname as zp,join as tr}from"node:path";function ea(t,e,r){let o=tr(t,e);Vp(zp(o),{recursive:!0}),er(o,r)}var rr=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=Jp(o,n,i);er(tr(e.workspaceDir,"ESTIMATE.md"),a),s.push("ESTIMATE.md")}else if(e.role==="analyze"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;er(tr(e.workspaceDir,"SOLUTION.md"),Xp(o,n,i,a)),s.push("SOLUTION.md"),er(tr(e.workspaceDir,"QUESTIONS.md"),Qp(o)),s.push("QUESTIONS.md")}else if(e.role==="implement"){let a=typeof r.reworkInstruction=="string"?r.reworkInstruction:void 0;ea(e.workspaceDir,"changes/sample.patch",Zp(o,n,a)),s.push("changes/sample.patch"),ea(e.workspaceDir,"diff-summary.md",ed(o,n,a)),s.push("diff-summary.md")}else e.role==="rework"&&(er(tr(e.workspaceDir,"NOTE.md"),`# rework not supported by mock runner yet (task ${o})
435
+ `),s.push("NOTE.md"));return{artifactPaths:s,log:`mock runner produced ${s.length} artifact(s) for role=${e.role}`,usage:wr()}}};function Jp(t,e,r){return`# ${t} \u2014 Estimate
436
436
 
437
437
  **Title:** ${e}
438
438
 
@@ -453,7 +453,7 @@ production-grade estimates.)
453
453
  ${r.split(`
454
454
  `).slice(0,8).join(`
455
455
  `).trim()||"(empty)"}
456
- `}function zp(t,e,r,o){let n=o?`
456
+ `}function Xp(t,e,r,o){let n=o?`
457
457
  ## Reviewer rework instruction
458
458
 
459
459
  > ${o.split(`
@@ -482,10 +482,10 @@ TBD (mock runner does not yet inspect project code).
482
482
  ${r.split(`
483
483
  `).slice(0,8).join(`
484
484
  `).trim()||"(empty)"}
485
- `}function Jp(t){return`# ${t} \u2014 Open questions
485
+ `}function Qp(t){return`# ${t} \u2014 Open questions
486
486
 
487
487
  (none \u2014 mock runner did not surface ambiguities.)
488
- `}function Xp(t,e,r){let o=r?` (rework: ${r.split(`
488
+ `}function Zp(t,e,r){let o=r?` (rework: ${r.split(`
489
489
  `)[0].slice(0,80)})`:"";return`diff --git a/CHANGELOG.md b/CHANGELOG.md
490
490
  index 0000000..1111111 100644
491
491
  --- a/CHANGELOG.md
@@ -496,7 +496,7 @@ index 0000000..1111111 100644
496
496
  +- mock-runner placeholder change for slice 5 testing.
497
497
  +
498
498
  # Changelog
499
- `}function Qp(t,e,r){return`# ${t} \u2014 Diff summary
499
+ `}function ed(t,e,r){return`# ${t} \u2014 Diff summary
500
500
 
501
501
  **Title:** ${e}
502
502
  ${r?`
@@ -507,81 +507,81 @@ ${r?`
507
507
  - \`CHANGELOG.md\` \u2014 added entry for ${t}.
508
508
 
509
509
  (Mock-runner output. Replace with claude-headless for production patches.)
510
- `}function Zs(t){switch(t){case"mock":return new er;case"claude-headless":return new Xt;default:return null}}function ra(t=process.env){return{maxAttempts:Vr(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Vr(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Vr(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Vr(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var Zp=new Set([429,500,502,503,529]),ea=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,ed=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,td=new Set(["error_max_turns"]);function rd(t){if(t instanceof Ct){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return ed.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&td.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:Zp.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:ea.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 ea.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var ta=/(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 oa(t){if(t instanceof Ct){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&ta.test(o)}let e=t instanceof Error?t.message:String(t);return ta.test(e)}function od(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 na(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=rd(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=od(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 Vr(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as nd,rmSync as id,writeFileSync as ia}from"node:fs";import{tmpdir as sd}from"node:os";import{join as qo}from"node:path";function zr(t){return`[url "https://${t}/"]
510
+ `}function ta(t){switch(t){case"mock":return new rr;case"claude-headless":return new Zt;default:return null}}function na(t=process.env){return{maxAttempts:Jr(t.SANDBOX_LLM_RETRY_MAX_ATTEMPTS,2),baseDelayMs:Jr(t.SANDBOX_LLM_RETRY_BASE_MS,2e3),maxDelayMs:Jr(t.SANDBOX_LLM_RETRY_MAX_MS,3e4),totalBudgetMs:Jr(t.SANDBOX_LLM_RETRY_BUDGET_MS,3e5)}}var td=new Set([429,500,502,503,529]),ra=/(ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|EPIPE|socket hang up|network error|fetch failed|connection (?:reset|closed|error)|timed? ?out|overloaded)/i,rd=/(out of credit|credit balance|insufficient (?:credit|fund)|overage)/i,od=new Set(["error_max_turns"]);function nd(t){if(t instanceof Tt){let{apiErrorStatus:r,subtype:o,resultText:n,retryAfterMs:i}=t.details,s=n??"";return rd.test(s)?{retryable:!1,reason:"out_of_credits"}:o&&od.has(o)?{retryable:!1,reason:o}:typeof r=="number"?r===429?{retryable:!0,reason:"api_status=429 (rate limit)",retryAfterMs:i}:td.has(r)?{retryable:!0,reason:`api_status=${r}`}:{retryable:!1,reason:`api_status=${r}`}:ra.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 ra.test(e)?{retryable:!0,reason:"network/timeout"}:{retryable:!1,reason:"non-retryable"}}var oa=/(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 ia(t){if(t instanceof Tt){let{apiErrorStatus:r,resultText:o}=t.details;return r===401||r===403?!0:!!o&&oa.test(o)}let e=t instanceof Error?t.message:String(t);return oa.test(e)}function id(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 sa(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=nd(a),l=s>=r.policy.maxAttempts;if(!c.retryable||l||r.aborted())throw s>1?new Error(`agent failed after ${s} attempts: ${i}`):a;let p=id(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 Jr(t,e){let r=Number(t);return Number.isFinite(r)&&r>0?Math.floor(r):e}import{mkdtempSync as sd,rmSync as ad,writeFileSync as aa}from"node:fs";import{tmpdir as cd}from"node:os";import{join as Vo}from"node:path";function Xr(t){return`[url "https://${t}/"]
511
511
  insteadOf = git@${t}:
512
512
  insteadOf = ssh://git@${t}/
513
- `}var ad=zr("github.com"),cd=zr("bitbucket.org"),ld=zr("gitlab.com");function sa(t,e){if(t.length===0)return null;let r=nd(qo(sd(),"devpipe-gitcreds-")),o=qo(r,"credentials"),n=qo(r,"gitconfig");return ia(o,t.join(`
513
+ `}var ld=Xr("github.com"),ud=Xr("bitbucket.org"),pd=Xr("gitlab.com");function ca(t,e){if(t.length===0)return null;let r=sd(Vo(cd(),"devpipe-gitcreds-")),o=Vo(r,"credentials"),n=Vo(r,"gitconfig");return aa(o,t.join(`
514
514
  `)+`
515
- `,{mode:384}),ia(n,`[credential]
515
+ `,{mode:384}),aa(n,`[credential]
516
516
  helper = store --file=${o}
517
- `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{id(r,{recursive:!0,force:!0})}catch{}}}}function Yo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(ad)),t.bitbucket?.apiToken&&(e.push(`https://${Je}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(cd)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(ld)),sa(e,r)}function aa(t,e){if(t.contextWrite?.token){let r=ut(e)??"github.com",o=yr(r);return sa([`https://${o}:${t.contextWrite.token}@${r}`],[zr(r)])}return Yo(t)}import{spawn as la}from"node:child_process";import{existsSync as Jr,mkdirSync as Xr,readFileSync as ud,rmSync as Vo,symlinkSync as pd}from"node:fs";import{homedir as dd}from"node:os";import{dirname as Qr,join as it}from"node:path";function ua(){return it(dd(),".codepipe-sandbox","repos")}function ca(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 pa(t,e,r,o,n){if(Jr(it(t,".git"))){let i=async s=>{await J(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await J(t,["reset","--hard",`origin/${s}`],n),await J(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!ca(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Jr(t)&&Vo(t,{recursive:!0,force:!0}),Xr(Qr(t),{recursive:!0});try{return await J(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!ca(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Jr(t)&&Vo(t,{recursive:!0,force:!0}),Xr(Qr(t),{recursive:!0}),await J(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function da(t){await J(t.workspacePath,["reset","--hard",t.baseSha]),await J(t.workspacePath,["clean","-fdx"])}var Zr="CodePipe Agent",eo="codepipe@codepartner.ee";async function fa(t,e){let r=t.workspacePath;await J(r,["add","-A"]);let o=(await $e(r,["write-tree"])).trim(),n=(await $e(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:Zr,GIT_AUTHOR_EMAIL:eo,GIT_COMMITTER_NAME:Zr,GIT_COMMITTER_EMAIL:eo};return(await $e(r,["commit-tree",o,"-m",e],i)).trim()}async function ma(t,e,r,o,n){try{await J(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw ut(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 ga(t,e){return $e(t.workspacePath,["diff","--binary",t.baseSha,e])}async function ha(t,e,r,o,n){await J(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await J(t.workspacePath,["checkout","--force",r])}async function zo(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:Zr,GIT_AUTHOR_EMAIL:eo,GIT_COMMITTER_NAME:Zr,GIT_COMMITTER_EMAIL:eo};(await $e(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await J(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await J(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await J(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await $e(o,["diff","--name-only","--diff-filter=U"])).split(`
518
- `).map(l=>l.trim()).filter(l=>l.length>0),c=await $e(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 J(t,e,r){return new Promise((o,n)=>{let i=la("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}):
519
- ${s.join("").trim()||"(no stderr)"}`))})})}function $e(t,e,r){return new Promise((o,n)=>{let i=la("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}):
520
- ${a.join("").trim()||"(no stderr)"}`))})})}function ya(t,e){Jr(t)&&Vo(t,{recursive:!0,force:!0}),Xr(Qr(t),{recursive:!0}),pd(e,t,"dir")}async function wa(t,e,r){await J(t,["worktree","prune"]).catch(()=>{}),Xr(Qr(r),{recursive:!0}),await J(t,["worktree","add","--detach",r,`origin/${e}`])}async function ba(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=it(ua(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await pa(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await $e(a,["rev-parse","HEAD"])).trim(),p=it(t,"code",s.name);o==="direct"?(ya(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await wa(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:l})}return i}async function ka(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=it(ua(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await pa(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=it(t,"context");o==="direct"?(ya(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await wa(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await $e(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function $a(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await J(r,["add","-A",...o]).catch(()=>{});let n;try{n=await $e(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
521
- `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=ud(it(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as fd}from"node:fs";import{join as md}from"node:path";var Jo=8*1024,Tt=class extends Error{},tr="meta/build-result.json";function xa(t){let e=md(t,tr),r;try{r=fd(e,"utf-8")}catch{throw new Tt(`BUILD produced no ${tr} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new Tt(`${tr} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new Tt(`${tr} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Tt(`${tr}: "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,u=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(u===null||d===null)return[];let g={name:u,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?gd(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let p=a.find(f=>f.exitCode!==0);p&&(l.failedStep=p.name)}return l}function gd(t){let e=Buffer.from(t,"utf-8");return e.length<=Jo?t:`\u2026 [${e.length-Jo} bytes elided] \u2026
522
- `+e.subarray(e.length-Jo).toString("utf-8")}import{lstatSync as hd,mkdtempSync as yd,readFileSync as wd,readdirSync as Sa,rmSync as va}from"node:fs";import{tmpdir as bd}from"node:os";import{join as to,relative as kd}from"node:path";var Ca=new Set(["code","context"]);function Ta(t){let e=yd(to(bd(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>va(e,{recursive:!0,force:!0}),listFiles:()=>Ra(e,e),readFile:r=>wd(to(e,r),"utf-8"),clean:()=>{for(let r of Sa(e))Ca.has(r)||va(to(e,r),{recursive:!0,force:!0})}}}function Ra(t,e){let r=[];for(let o of Sa(e)){let n=to(e,o),i=hd(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Ca.has(o))continue;r.push(...Ra(t,n))}else r.push(kd(t,n))}return r}var oo=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Td=new Set(["implement","resolve-conflict"]);function Rd(t){let e=Buffer.from(t,"utf-8");if(e.length<=oo)return t;let r=Math.floor(oo/4),o=oo-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}
517
+ `+e.join(""),{mode:384}),{env:{...process.env,GIT_CONFIG_GLOBAL:n,GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"},cleanup:()=>{try{ad(r,{recursive:!0,force:!0})}catch{}}}}function zo(t){let e=[],r=[];return t.github?.token&&(e.push(`https://x-access-token:${t.github.token}@github.com`),r.push(ld)),t.bitbucket?.apiToken&&(e.push(`https://${ze}:${encodeURIComponent(t.bitbucket.apiToken)}@bitbucket.org`),r.push(ud)),t.gitlab?.token&&(e.push(`https://oauth2:${t.gitlab.token}@gitlab.com`),r.push(pd)),ca(e,r)}function la(t,e){if(t.contextWrite?.token){let r=pt(e)??"github.com",o=br(r);return ca([`https://${o}:${t.contextWrite.token}@${r}`],[Xr(r)])}return zo(t)}import{spawn as pa}from"node:child_process";import{existsSync as Qr,mkdirSync as Zr,readFileSync as dd,rmSync as Jo,symlinkSync as fd}from"node:fs";import{homedir as md}from"node:os";import{dirname as eo,join as nt}from"node:path";function da(){return nt(md(),".codepipe-sandbox","repos")}function ua(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 fa(t,e,r,o,n){if(Qr(nt(t,".git"))){let i=async s=>{await z(t,["fetch","--depth=1","origin",`+refs/heads/${s}:refs/remotes/origin/${s}`],n),await z(t,["reset","--hard",`origin/${s}`],n),await z(t,["clean","-fdx"],n)};try{return await i(r),r}catch(s){if(!o||o===r||!ua(s))throw s;return console.log(`[git] ref ${r} gone upstream \u2014 falling back to ${o}`),await i(o),o}}Qr(t)&&Jo(t,{recursive:!0,force:!0}),Zr(eo(t),{recursive:!0});try{return await z(void 0,["clone","--depth=1","--single-branch","--branch",r,e,t],n),r}catch(i){if(!o||o===r||!ua(i))throw i;return console.log(`[git] branch ${r} not found on clone \u2014 falling back to ${o}`),Qr(t)&&Jo(t,{recursive:!0,force:!0}),Zr(eo(t),{recursive:!0}),await z(void 0,["clone","--depth=1","--single-branch","--branch",o,e,t],n),o}}async function ma(t){await z(t.workspacePath,["reset","--hard",t.baseSha]),await z(t.workspacePath,["clean","-fdx"])}var to="CodePipe Agent",ro="codepipe@codepartner.ee";async function ga(t,e){let r=t.workspacePath;await z(r,["add","-A"]);let o=(await be(r,["write-tree"])).trim(),n=(await be(r,["rev-parse",`${t.baseSha}^{tree}`])).trim();if(o===n)return null;let i={...process.env,GIT_AUTHOR_NAME:to,GIT_AUTHOR_EMAIL:ro,GIT_COMMITTER_NAME:to,GIT_COMMITTER_EMAIL:ro};return(await be(r,["commit-tree",o,"-m",e],i)).trim()}async function ha(t,e,r,o,n){try{await z(t.workspacePath,["push","--force",o,`${e}:refs/heads/${r}`],n)}catch(i){let s=i instanceof Error?i.message:String(i);throw pt(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 ya(t,e){return be(t.workspacePath,["diff","--binary",t.baseSha,e])}async function wa(t,e,r,o,n){await z(t.workspacePath,["fetch",o,`+refs/heads/${e}:refs/codepipe-build-delivery`],n),await z(t.workspacePath,["checkout","--force",r])}async function Xo(t,e,r){let o=t.workspacePath,n={...r??process.env,GIT_AUTHOR_NAME:to,GIT_AUTHOR_EMAIL:ro,GIT_COMMITTER_NAME:to,GIT_COMMITTER_EMAIL:ro};(await be(o,["rev-parse","--is-shallow-repository"])).trim()==="true"&&await z(o,["fetch","--unshallow","origin",`+refs/heads/${t.ref}:refs/remotes/origin/${t.ref}`],r).catch(l=>{console.warn(`[git] resolve-conflict: --unshallow ${t.ref} failed: ${String(l)}`)}),await z(o,["fetch","origin",`+refs/heads/${e}:refs/remotes/origin/${e}`],r);let s=null;try{await z(o,["merge","--no-commit","--no-ff",`origin/${e}`],n)}catch(l){s=l instanceof Error?l.message:String(l)}let a=(await be(o,["diff","--name-only","--diff-filter=U"])).split(`
518
+ `).map(l=>l.trim()).filter(l=>l.length>0),c=await be(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 z(t,e,r){return new Promise((o,n)=>{let i=pa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[];i.stderr.setEncoding("utf-8"),i.stderr.on("data",a=>s.push(a)),i.on("error",n),i.on("close",a=>{if(a===0)return o();n(new Error(`git ${e[0]} failed (exit ${a}):
519
+ ${s.join("").trim()||"(no stderr)"}`))})})}function be(t,e,r){return new Promise((o,n)=>{let i=pa("git",e,{cwd:t,stdio:["ignore","pipe","pipe"],env:r??{...process.env}}),s=[],a=[];i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",c=>s.push(c)),i.stderr.on("data",c=>a.push(c)),i.on("error",n),i.on("close",c=>{if(c===0)return o(s.join(""));n(new Error(`git ${e[0]} failed (exit ${c}):
520
+ ${a.join("").trim()||"(no stderr)"}`))})})}function ba(t,e){Qr(t)&&Jo(t,{recursive:!0,force:!0}),Zr(eo(t),{recursive:!0}),fd(e,t,"dir")}async function ka(t,e,r){await z(t,["worktree","prune"]).catch(()=>{}),Zr(eo(r),{recursive:!0}),await z(t,["worktree","add","--detach",r,`origin/${e}`])}async function $a(t,e,r,o="worktree",n){if(r.length===0)return[];let i=[];for(let s of r){let a=nt(da(),e,s.name);console.log(`[git] code: ensure ${s.cloneUrl} @ ${s.ref} \u2192 ${a}`);let c;try{c=await fa(a,s.cloneUrl,s.ref,s.defaultBranch,n)}catch(f){throw new Error(`failed to materialize project repo "${s.name}" (${s.cloneUrl}): `+(f instanceof Error?f.message:String(f)))}let l=(await be(a,["rev-parse","HEAD"])).trim(),p=nt(t,"code",s.name);o==="direct"?(ba(p,a),console.log(`[git] code: linked ${p} \u2192 ${a} @ ${l.slice(0,10)}`)):(await ka(a,c,p),console.log(`[git] code: worktree ${p} \u2190 ${a} @ ${l.slice(0,10)}`)),i.push({name:s.name,workspacePath:p,cachePath:a,ref:c,baseSha:l})}return i}async function xa(t,e,r,o="worktree",n){if(!r||!r.cloneUrl)return null;let i=nt(da(),e,"_context");console.log(`[git] context: ensure ${r.cloneUrl} @ ${r.ref} \u2192 ${i}`);try{await fa(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=nt(t,"context");o==="direct"?(ba(s,i),console.log(`[git] context: linked ${s} \u2192 ${i}`)):(await ka(i,r.ref,s),console.log(`[git] context: worktree ${s} \u2190 ${i}`));let a=(await be(i,["rev-parse","HEAD"])).trim();return{workspacePath:s,cachePath:i,baseSha:a}}async function va(t,e=[]){let r=t.workspacePath,o=["knowledge",...e];await z(r,["add","-A",...o]).catch(()=>{});let n;try{n=await be(r,["diff","--cached","--name-only","--diff-filter=d",t.baseSha,"--",...o])}catch{return[]}let i=n.split(`
521
+ `).map(a=>a.trim()).filter(a=>a.length>0),s=[];for(let a of i)try{let c=dd(nt(r,a)).toString("base64");s.push({path:a,contentBase64:c})}catch{}return s}import{readFileSync as gd}from"node:fs";import{join as hd}from"node:path";var Qo=8*1024,Rt=class extends Error{},or="meta/build-result.json";function Sa(t){let e=hd(t,or),r;try{r=gd(e,"utf-8")}catch{throw new Rt(`BUILD produced no ${or} verdict \u2014 inconclusive run`)}let o;try{o=JSON.parse(r)}catch(p){throw new Rt(`${or} is not valid JSON: ${p instanceof Error?p.message:String(p)}`)}if(!o||typeof o!="object")throw new Rt(`${or} must be a JSON object`);let n=o;if(typeof n.ok!="boolean")throw new Rt(`${or}: "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,u=typeof f.name=="string"?f.name:null,d=typeof f.exitCode=="number"?f.exitCode:null;if(u===null||d===null)return[];let g={name:u,exitCode:d};return typeof f.durationMs=="number"&&(g.durationMs=f.durationMs),[g]}),c=typeof n.logTail=="string"?yd(n.logTail):"",l={ok:i,steps:a,logTail:c};if(typeof n.failedStep=="string"&&n.failedStep)l.failedStep=n.failedStep;else if(!i){let p=a.find(f=>f.exitCode!==0);p&&(l.failedStep=p.name)}return l}function yd(t){let e=Buffer.from(t,"utf-8");return e.length<=Qo?t:`\u2026 [${e.length-Qo} bytes elided] \u2026
522
+ `+e.subarray(e.length-Qo).toString("utf-8")}import{lstatSync as wd,mkdtempSync as bd,readFileSync as kd,readdirSync as Ta,rmSync as Ca}from"node:fs";import{tmpdir as $d}from"node:os";import{join as oo,relative as xd}from"node:path";var Ra=new Set(["code","context"]);function Ia(t){let e=bd(oo($d(),`codepipe-job-${t}-`));return{dir:e,dispose:()=>Ca(e,{recursive:!0,force:!0}),listFiles:()=>Pa(e,e),readFile:r=>kd(oo(e,r),"utf-8"),clean:()=>{for(let r of Ta(e))Ra.has(r)||Ca(oo(e,r),{recursive:!0,force:!0})}}}function Pa(t,e){let r=[];for(let o of Ta(e)){let n=oo(e,o),i=wd(n);if(!i.isSymbolicLink())if(i.isDirectory()){if(e===t&&Ra.has(o))continue;r.push(...Pa(t,n))}else r.push(xd(t,n))}return r}var no=Number(process.env.SANDBOX_MAX_LOG_BYTES??256*1024),Id=new Set(["implement","resolve-conflict"]);function Pd(t){let e=Buffer.from(t,"utf-8");if(e.length<=no)return t;let r=Math.floor(no/4),o=no-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}
523
523
 
524
- \u2026 [${s} bytes elided \u2014 log capped at ${oo} bytes for upload] \u2026
524
+ \u2026 [${s} bytes elided \u2014 log capped at ${no} bytes for upload] \u2026
525
525
 
526
- ${i}`}async function rr(t={}){qr();let e=oe(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=Sr("SANDBOX_LOG","sandbox",Cd("./logs"));if(o.enabled){let h=new mt(o);Cr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${o.maxBytes}B, keep ${o.maxFiles})`)}console.log(`codepipe-sandbox v${ce} (protocol ${ge})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let n=Zs(e.llm);console.log(`llm backend: ${n?n.name():"(none \u2014 will not claim agent jobs)"}`);let i=ra();console.log(`llm retry: maxAttempts=${i.maxAttempts} backoff=${i.baseDelayMs}\u2013${i.maxDelayMs}ms budget=${i.totalBudgetMs}ms`);let s=new St(e.hubUrl,e.token),a=!1,c=new AbortController,l=null,p=null,f=!1,u=null,d=null,g=!1,y=()=>{let h=s.openControlSocket();return u=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ce,protocolVersion:ge};h.send(JSON.stringify(m))}),h.on("message",m=>{let k=m.toString("utf-8"),$=null;try{let w=JSON.parse(k);w&&typeof w=="object"&&($=w)}catch{}if($&&$.type==="hello"){let w=$;d=mr(w.protocolVersion);let R=d?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${w.platformVersion} (protocol ${w.protocolVersion}) \u2014 ${R}`),d&&(g=!1);return}if($&&$.type==="pause_job"){let w=typeof $.jobId=="string"?$.jobId:"";w&&w===l?(console.warn(`[ws] pause_job ${w} \u2014 aborting agent`),f=!0,p?.abort()):console.log(`[ws] pause_job ${w} \u2014 not the active job, ignoring`),w&&h.send(JSON.stringify({type:"job_paused",jobId:w}));return}console.log(`[ws] ${k}`)}),h.on("close",(m,k)=>{console.log(`[ws] closed code=${m} reason=${k?.toString()||""}`),u===h&&(u=null),!a&&setTimeout(y,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},S=y(),x=async()=>{for(;!a;){if(d===!1){g||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ce}, protocol ${ge}) \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(k=>setTimeout(k,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(k=>setTimeout(k,5e3))}}};async function v(h,m){l=m.jobId,p=new AbortController,f=!1;let k=!1,$=null,w=null,R=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),P=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(k=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(B){let pe=B instanceof Error?B.message:String(B);console.warn(`[job] ${m.jobId} heartbeat error: ${pe}`)}};P();let G=setInterval(()=>{P()},R),q=new Date().toISOString();console.log(`[job] ${m.jobId} claimed \u2014 role=${m.role} task=${m.taskId} phase=${m.phase}`),console.log(`[job] ${m.jobId} prompt (${m.prompt.length} chars):`),console.log(I(m.prompt," \u2502 "));let se=[],Ie=null,fo=400,T=25,ae=500,fe=()=>{if(Ie&&(clearTimeout(Ie),Ie=null),se.length===0)return;let B=se.splice(0,se.length),pe=u;if(!pe||pe.readyState!==pe.OPEN)return;let je={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:B};try{pe.send(JSON.stringify(je))}catch{}},Ye=B=>{se.push(B),se.length>ae&&se.shift(),se.length>=T?fe():Ie||(Ie=setTimeout(fe,fo))},dr=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,Pe=new Set,Y=null;try{if(!n){k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:q,finishedAt:new Date().toISOString()});return}let B=Ta(m.jobId);console.log(`[job] ${m.jobId} workspace=${B.dir}`);let pe=A(m,r);$=pe.gitCreds,w=pe.contextGitCreds;let je=$?.env,yn=pe.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:pe.claudeOauthToken}:void 0,Ee=[],fr=null,mo=null;try{let j="worktree";Ee=await ba(B.dir,m.projectId,m.projectRepos,j,je);let E=await ka(B.dir,m.projectId,m.contextRepo,j,je);mo=E,fr=E?.workspacePath??null}catch(j){let E=j instanceof Error?j.message:String(j);console.warn(`[job] ${m.jobId} materialize failed: ${E}`),k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${E}`},startedAt:q,finishedAt:new Date().toISOString()}),B.dispose();return}let wn=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let j=m.contextRepo?.cloneUrl;if(!j||!je)throw new Error(j?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let E of m.deliveries){let F=Ee.find(ie=>ie.name===E.name);F&&(await ha(F,E.deliveryRef,E.deliverySha,j,je),console.log(`[job] ${m.jobId} ${F.name}: checked out delivery ${E.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await wn()}catch(j){let E=j instanceof Error?j.message:String(j);console.warn(`[job] ${m.jobId} delivery checkout failed: ${E}`),k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${E}`},startedAt:q,finishedAt:new Date().toISOString()}),B.dispose();return}let bn=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},kn="";if(m.role==="resolve-conflict")try{let j=[];for(let E of Ee){let F=bn[E.name];if(!F)continue;let ie=await zo(E,F,je);console.log(`[job] ${m.jobId} ${E.name}: merged ${F} into ${E.ref} \u2014 ${ie.length} conflicted file(s)`),ie.length>0?j.push(`- **${E.name}**:`,...ie.map(lt=>` - \`${lt}\``)):j.push(`- **${E.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}kn=`
526
+ ${i}`}async function ir(t={}){Vr();let e=oe(t.profile);e||(console.error("sandbox not registered. run `codepipe worker register` first."),process.exit(1));let r=e.sealPrivateKey,o=t.profile?`sandbox-${t.profile}`:"sandbox",n=nr(Td(),".codepipe","logs"),i=Tr("SANDBOX_LOG",o,n);if(i.enabled){let h=new gt(i);Rr(h),console.log(`[log] file logging \u2192 ${h.path} (rotate at ${i.maxBytes}B, keep ${i.maxFiles})`)}console.log(`codepipe-sandbox v${ae} (protocol ${fe})`),console.log(`starting sandbox ${e.sandboxId} (${e.name}) \u2192 ${e.hubUrl}`);let s=ta(e.llm);console.log(`llm backend: ${s?s.name():"(none \u2014 will not claim agent jobs)"}`);let a=na();console.log(`llm retry: maxAttempts=${a.maxAttempts} backoff=${a.baseDelayMs}\u2013${a.maxDelayMs}ms budget=${a.totalBudgetMs}ms`);let c=new Ct(e.hubUrl,e.token),l=!1,p=new AbortController,f=null,u=null,d=!1,g=null,y=null,v=!1,x=()=>{let h=c.openControlSocket();return g=h,h.on("open",()=>{console.log("[ws] connected");let m={type:"sandbox_hello",platformVersion:ae,protocolVersion:fe};h.send(JSON.stringify(m))}),h.on("message",m=>{let w=m.toString("utf-8"),k=null;try{let $=JSON.parse(w);$&&typeof $=="object"&&(k=$)}catch{}if(k&&k.type==="hello"){let $=k;y=hr($.protocolVersion);let N=y?"compatible":"INCOMPATIBLE";console.log(`[ws] hub v${$.platformVersion} (protocol ${$.protocolVersion}) \u2014 ${N}`),y&&(v=!1);return}if(k&&k.type==="pause_job"){let $=typeof k.jobId=="string"?k.jobId:"";$&&$===f?(console.warn(`[ws] pause_job ${$} \u2014 aborting agent`),d=!0,u?.abort()):console.log(`[ws] pause_job ${$} \u2014 not the active job, ignoring`),$&&h.send(JSON.stringify({type:"job_paused",jobId:$}));return}console.log(`[ws] ${w}`)}),h.on("close",(m,w)=>{console.log(`[ws] closed code=${m} reason=${w?.toString()||""}`),g===h&&(g=null),!l&&setTimeout(x,2e3)}),h.on("error",m=>console.warn(`[ws] error: ${m.message}`)),h},S=x(),E=async()=>{for(;!l;){if(y===!1){v||(console.error(`[claim] HUB protocol incompatible with this SANDBOX (v${ae}, protocol ${fe}) \u2014 not claiming jobs until versions align.`),v=!0),await new Promise(h=>setTimeout(h,5e3));continue}try{let h=await c.claim(p.signal);if(h.status===204)continue;if(h.status===401){console.error("[claim] 401 unauthorized \u2014 sandbox token rejected. exiting."),l=!0;break}if(!h.ok){console.warn(`[claim] ${h.status} \u2014 backoff 5s`),await new Promise(w=>setTimeout(w,5e3));continue}let m=await h.json();await I(c,m)}catch(h){if(p.signal.aborted)break;let m=h instanceof Error?h.message:String(h);console.warn(`[claim] error: ${m} \u2014 backoff 5s`),await new Promise(w=>setTimeout(w,5e3))}}};async function I(h,m){f=m.jobId,u=new AbortController,d=!1;let w=!1,k=null,$=null,N=Number(process.env.SANDBOX_HEARTBEAT_INTERVAL_MS??3e4),q=async()=>{try{await h.heartbeat(m.jobId)==="claim_lost"&&(w=!0,console.warn(`[job] ${m.jobId} claim lost \u2014 HUB sweeper took it`))}catch(D){let ue=D instanceof Error?D.message:String(D);console.warn(`[job] ${m.jobId} heartbeat error: ${ue}`)}};q();let ct=setInterval(()=>{q()},N),ke=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(C(m.prompt," \u2502 "));let $e=[],T=null,se=400,Ie=25,qe=500,Dt=()=>{if(T&&(clearTimeout(T),T=null),$e.length===0)return;let D=$e.splice(0,$e.length),ue=g;if(!ue||ue.readyState!==ue.OPEN)return;let Pe={type:"agent_activity",jobId:m.jobId,taskId:m.taskId,projectId:m.projectId,role:m.role,phase:m.phase,events:D};try{ue.send(JSON.stringify(Pe))}catch{}},lt=D=>{$e.push(D),$e.length>qe&&$e.shift(),$e.length>=Ie?Dt():T||(T=setTimeout(Dt,se))},X=m.role==="analysis"&&m.taskId.startsWith("draft::")?m.taskId.slice(7):null,mo=new Set,go=null;try{if(!s){w||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:"sandbox has no LLM backend configured"},startedAt:ke,finishedAt:new Date().toISOString()});return}let D=Ia(m.jobId);console.log(`[job] ${m.jobId} workspace=${D.dir}`);let ue=B(m,r);k=ue.gitCreds,$=ue.contextGitCreds;let Pe=k?.env,bn=ue.claudeOauthToken?{CLAUDE_CODE_OAUTH_TOKEN:ue.claudeOauthToken}:void 0,je=[],gr=null,ho=null;try{let P="worktree";je=await $a(D.dir,m.projectId,m.projectRepos,P,Pe);let j=await xa(D.dir,m.projectId,m.contextRepo,P,Pe);ho=j,gr=j?.workspacePath??null}catch(P){let j=P instanceof Error?P.message:String(P);console.warn(`[job] ${m.jobId} materialize failed: ${j}`),w||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`materialize failed: ${j}`},startedAt:ke,finishedAt:new Date().toISOString()}),D.dispose();return}let kn=async()=>{if(!m.deliveries||m.deliveries.length===0)return;let P=m.contextRepo?.cloneUrl;if(!P||!Pe)throw new Error(P?"no git credentials in bundle":"no contextRepo cloneUrl in job spec");for(let j of m.deliveries){let F=je.find(ie=>ie.name===j.name);F&&(await wa(F,j.deliveryRef,j.deliverySha,P,Pe),console.log(`[job] ${m.jobId} ${F.name}: checked out delivery ${j.deliverySha.slice(0,10)} for ${m.role}`))}};if(m.role==="build"||m.role==="implement")try{await kn()}catch(P){let j=P instanceof Error?P.message:String(P);console.warn(`[job] ${m.jobId} delivery checkout failed: ${j}`),w||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`delivery checkout failed: ${j}`},startedAt:ke,finishedAt:new Date().toISOString()}),D.dispose();return}let $n=m.role==="resolve-conflict"?m.metadata?.taskBranchByRepo??{}:{},xn="";if(m.role==="resolve-conflict")try{let P=[];for(let j of je){let F=$n[j.name];if(!F)continue;let ie=await Xo(j,F,Pe);console.log(`[job] ${m.jobId} ${j.name}: merged ${F} into ${j.ref} \u2014 ${ie.length} conflicted file(s)`),ie.length>0?P.push(`- **${j.name}**:`,...ie.map(ut=>` - \`${ut}\``)):P.push(`- **${j.name}**: merged cleanly (no markers \u2014 verify it still builds)`)}xn=`
527
527
 
528
528
  ## Conflicts to resolve
529
529
 
530
- `+(j.length>0?j.join(`
530
+ `+(P.length>0?P.join(`
531
531
  `):"(no task branches to merge)")+`
532
- `}catch(j){let E=j instanceof Error?j.message:String(j);console.warn(`[job] ${m.jobId} conflict merge failed: ${E}`),k||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${E}`},startedAt:q,finishedAt:new Date().toISOString()}),B.dispose();return}let Fc=L(m.prompt,Ee,fr)+kn,go=[...Ee.map(j=>j.workspacePath),...fr?[fr]:[]];go.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${go.join(", ")}`),dr&&(Y=setInterval(()=>{let E=u;if(!E||E.readyState!==E.OPEN)return;let F;try{F=xd(ro(B.dir,"drafts")).filter(ie=>ie.endsWith(".json")).sort()}catch{return}for(let ie of F){if(Pe.has(ie))continue;if(Pe.size>=Pn)break;let lt;try{let re=JSON.parse(Ia(ro(B.dir,"drafts",ie),"utf-8")),O=typeof re.localRef=="string"?re.localRef:"",V=typeof re.title=="string"?re.title:"",Ve=typeof re.body=="string"?re.body:"";if(!O||!V)continue;lt={localRef:O,title:V,body:Ve,...re.isEpic===!0?{isEpic:!0}:{},...Array.isArray(re.links)?{links:re.links}:{}}}catch{continue}Pe.add(ie);let Bt={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:dr,child:lt};try{E.send(JSON.stringify(Bt))}catch{}}},1500));try{let j=await na(n,{workspaceDir:B.dir,role:m.role,prompt:Fc,addDirs:go,metadata:m.metadata??{},...m.model?{model:m.model}:{},...yn?{env:yn}:{},signal:p.signal,onActivity:Ye},{jobId:m.jobId,policy:i,onBeforeRetry:async()=>{B.clean();for(let O of Ee)try{await da(O);let V=bn[O.name];m.role==="resolve-conflict"&&V&&await zo(O,V,je)}catch(V){let Ve=V instanceof Error?V.message:String(V);console.warn(`[job] ${m.jobId} worktree reset failed (${O.name}): ${Ve}`)}try{await wn()}catch(O){let V=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${V}`)}},aborted:()=>k||f}),E=[];if(Td.has(m.role)&&Ee.length>0){let O=m.metadata??{},V=typeof O.commitMessage=="string"?O.commitMessage:`${m.taskId}: changes`,Ve=m.contextRepo?.cloneUrl,$n=w?.env;if(!Ve||!$n)throw new Error("delivery requested but "+(Ve?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Hc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let xe of Ee){let Dt=await fa(xe,V);if(!Dt){console.log(`[job] ${m.jobId} ${xe.name}: no changes \u2014 no delivery`);continue}let ho=`codepipe/deliveries/${Hc}/${m.jobId}/${xe.name}`;await ma(xe,Dt,ho,Ve,$n),E.push({name:xe.name,deliveryRef:ho,deliverySha:Dt,baseSha:xe.baseSha}),console.log(`[job] ${m.jobId} ${xe.name}: delivered ${Dt.slice(0,10)} \u2192 ${ho}`);let xn=await ga(xe,Dt);if(xn.trim().length>0){let Kc=ro("display",`${xe.name}.diff`),vn=ro(B.dir,Kc);$d(Sd(vn),{recursive:!0}),vd(vn,xn)}}}if(m.role==="resolve-conflict"&&E.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 F;m.role==="build"&&(F=xa(B.dir),console.log(`[job] ${m.jobId} build verdict: ok=${F.ok}`+(F.failedStep?` failedStep=${F.failedStep}`:"")));let ie=j.artifactPaths.length>0?j.artifactPaths:B.listFiles(),lt=Array.from(new Set(ie)),Bt;if(mo)try{let O=await $a(mo,m.role==="index"?["adr/SOURCES.md"]:[]);O.length>0&&(Bt=O,console.log(`[job] ${m.jobId} captured ${O.length} knowledge file(s) for Context Repo`))}catch(O){let V=O instanceof Error?O.message:String(O);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${V}`)}let re={jobId:m.jobId,status:"succeeded",artifacts:lt.map(O=>({path:O,contentBase64:Ia(`${B.dir}/${O}`).toString("base64")})),...Bt?{contextWrites:Bt}:{},...E.length>0?{deliveries:E}:{},log:Rd(j.log),startedAt:q,finishedAt:new Date().toISOString(),usage:j.usage,...j.rateLimit?{rateLimit:j.rateLimit}:{},...F?{build:F}:{}};if(k||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(re),console.log(`[job] ${m.jobId} done \u2014 uploaded ${re.artifacts.length} artifact(s):`);for(let O of re.artifacts){let V=Buffer.from(O.contentBase64,"base64").length;console.log(` \xB7 ${O.path} (${V} bytes)`)}re.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(j){let E=j instanceof Error?j.message:String(j);if(f)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(k)console.warn(`[job] ${m.jobId} failed after claim lost (${E}) \u2014 skipping result upload`);else{let F=oa(j);console.warn(F?`[job] ${m.jobId} failed: ${E} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${E}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:E},startedAt:q,finishedAt:new Date().toISOString(),...F?{authError:!0}:{}})}}finally{B.dispose()}}finally{clearInterval(G),Y&&clearInterval(Y),fe(),l=null,p=null,$?.cleanup(),w?.cleanup()}}function A(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 k;try{k=JSON.parse(Ar(m,h.credBundle).toString("utf-8"))}catch(P){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${P instanceof Error?P.message:String(P)}`),{gitCreds:null,contextGitCreds:null}}let $=Yo(k);$&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let w=aa(k,h.contextRepo.cloneUrl),R={gitCreds:$,contextGitCreds:w};return k.claudeOauthToken&&(R.claudeOauthToken=k.claudeOauthToken),R}function I(h,m){return h.split(`
533
- `).map(k=>m+k).join(`
534
- `)}function L(h,m,k){let $=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,$).replace(/\{\{codeRoot\}\}/g,$?$.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,k??"")}let C=h=>{if(a)return;a=!0,console.log(`
535
- [${h}] shutting down`),c.abort();let m=new AbortController,k=setTimeout(()=>m.abort(),3e3);(async()=>{let $=l;if($)try{await s.releaseJob($,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${$}`)}catch(w){let R=w instanceof Error?w.message:String(w);console.warn(`[${h}] release failed: ${R} (sweeper will reclaim)`)}clearTimeout(k),S.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>C("SIGINT")),process.on("SIGTERM",()=>C("SIGTERM")),await x()}async function Pa(t={profile:void 0}){let e=_e(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Br(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let p=l.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",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${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 Q(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=oe(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as zd}from"node:child_process";import{existsSync as jt,mkdirSync as Va,readFileSync as za,readdirSync as Jd,writeFileSync as Ja}from"node:fs";import{join as st,resolve as Xa}from"node:path";import{setTimeout as en}from"node:timers/promises";import{cancel as Xd,confirm as Et,intro as Qa,isCancel as on,log as b,outro as tn,password as At,select as at,spinner as Za,text as K}from"@clack/prompts";import{simpleGit as so}from"simple-git";async function It(t,e,r){return e.host==="github"?Pd(t,e,r):e.host==="gitlab"?Ud(t,e,r):Bd(t,e,r)}async function ja(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 We(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await Ea(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 Ke(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Aa(e.gitlabToken,t):n}}return e.bitbucket?(await Rt(e.bitbucket,"GET",`/repositories/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await _a(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 Ea(t,e){let r=!1;try{r=(await We(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 Aa(t,e){let r=!1;try{r=(await Ke(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 _a(t,e){let r=!1;try{r=(await Rt(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 Id="https://api.github.com";async function We(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(Id+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 Pd(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 jd(o,e,r),i=await Ad(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=wt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await _d(o,n.owner,n.name,a.path,i)||await Nd(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 jd(t,e,r){let o=await We(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 Ea(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await Ed(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 We(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 Ed(t,e){let{status:r,data:o}=await We(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function Ad(t,e,r){let{data:o}=await We(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function _d(t,e,r,o,n){let{status:i,data:s}=await We(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Nd(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 We(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Od="https://gitlab.com/api/v4";async function Ke(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(Od+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 Ud(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 Ke(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 Aa(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await Ke(o,"GET","/user"),u={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 Ke(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`);u.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await Ke(o,"POST","/projects",u);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=wt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let d=(await Ke(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)l.add(g.path);if(d.length<100)break}let p=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await Ke(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 Ld="https://api.bitbucket.org/2.0";async function Rt(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(Ld+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 Bd(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 Rt(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 _a(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 Rt(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=wt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await Rt(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of l)f.set(d.path,d.content);if((await Rt(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 Dd={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Re(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=Dd[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 Gd}from"node:crypto";import{existsSync as Na,mkdirSync as Md,readFileSync as Oa,readdirSync as Fd,rmSync as no,writeFileSync as Hd}from"node:fs";import{homedir as Kd}from"node:os";import{dirname as Wd,join as Xo}from"node:path";var qd=24*60*60*1e3;function Ua(){return Xo(Kd(),".codepipe","init-drafts")}function Qo(t){let e=Gd("sha256").update(t).digest("hex").slice(0,16);return Xo(Ua(),`${e}.json`)}function La(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=qd)}function Ba(t){let e=Qo(t);if(!Na(e))return null;try{let r=JSON.parse(Oa(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:La(r.savedAt)?(no(e,{force:!0}),null):r}catch{return null}}function Zo(t){no(Qo(t),{force:!0})}function Da(){let t=Ua();if(Na(t))for(let e of Fd(t)){let r=Xo(t,e);try{let o=JSON.parse(Oa(r,"utf-8"));La(o.savedAt)&&no(r,{force:!0})}catch{no(r,{force:!0})}}}var Pt=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(){Zo(this.cwd)}persist(){let e=Qo(this.cwd);Md(Wd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Hd(e,JSON.stringify(r,null,2)+`
536
- `,{mode:384})}};function Ga(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{existsSync as Fa}from"node:fs";import{join as Ha}from"node:path";import{simpleGit as Ka}from"simple-git";var Yd={info:t=>console.log(t),warn:t=>console.warn(t)};async function or(t,e,r={}){let o=r.log??Yd,n=[];for(let i of e){let s=Ha(t,i.mountAs),a=_n(i);if(!Fa(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(!Fa(Ha(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),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Vd(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(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 Vd(t,e){return Wa(t)===Wa(e)}function Wa(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function qa(t={}){let e=Qe();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 or(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 Ya=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function M(t){Xd(t),process.exit(1)}function le(t){return on(t)&&M("aborted"),t}function D(t){return on(t)&&M("aborted"),typeof t=="string"?t:""}async function ec(t={}){Qa("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Da();let r=Ba(e),o,n=!1;r&&Object.keys(r.answers).length>0?le(await Et({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(b.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new Pt(e,r),n=!0):(Zo(e),o=new Pt(e)):o=new Pt(e);let i=t.force===!0?null:await nn(e),s=await o.ask("target",async()=>le(await at({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?b.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):n&&o.get("contextRepo")!==void 0||rc(e,t.force===!0));let c=await o.ask("hubUrl",async()=>D(await K({message:"HUB URL",placeholder:me,initialValue:N("HUB_URL")??me,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>ao()),{cliToken:p,accountEmail:f}=await o.ask("bootstrap",()=>co(c,l)),u=null;s==="farm"&&(u=await Qd(c,p));let d=a?ef(a.parsed.repoName):"",g=await o.ask("projectId",async()=>D(await K({message:"project id (slug)",placeholder:d||"acme",...d?{initialValue:d}:{},validate:T=>ze.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await o.ask("projectName",async()=>D(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),S=await o.ask("automationLevel",async()=>le(await at({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"}))),x=await o.ask("youtrack",()=>lc()),v=await o.ask("youtrackProjectKey",async()=>D(await K({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),A=await o.ask("youtrackWrites",async()=>le(await Et({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),I=o.get("tokens")??{},L=()=>o.set("tokens",I),C=await o.ask("repos",()=>nf(I,l,a,{onCred:L,initial:o.get("reposPartial")??[],onProgress:T=>o.set("reposPartial",T)}));o.delete("reposPartial");let h=await sf(await o.ask("contextRepo",()=>sc(g,C,I,l)),g,C,I,l,L,T=>o.set("contextRepo",T)),{spec:m,mode:k}=h;b.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let $=await o.ask("assigneeLogin",async()=>D(await K({message:"your YouTrack login (the assignee value)",...x.login?{initialValue:x.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),w=await o.ask("claudeToken",()=>ff(s==="farm")),R={projectId:g,name:y,automationLevel:S,repos:C,youtrackProjectKey:v,ownerEmail:f};b.step(`${k==="attach"?"attaching to":"provisioning"} Context Repo ${m.owner}/${m.name} (${m.host})\u2026`);let P;try{P=await It(R,m,{...ac(I),youtrackWrites:A,trackerUrl:x.url,mode:k,log:{info:T=>b.message(T),warn:T=>b.warn(T)}})}catch(T){M(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}R.contextRepo=P,b.success(`Context Repo ready: ${P.owner}/${P.name}@${P.branch}`),b.step(`registering project on ${c}\u2026`);let G;try{G=await $t(c,p,R)}catch(T){if(T instanceof _&&T.status===409){b.warn(`project ${g} already exists on HUB \u2014 reusing it`);try{G=await Q(c,p,g)}catch(ae){throw ae instanceof _&&M(`HUB \u2192 ${ae.status} ${ae.message}`),ae}}else if(T instanceof _&&T.status===401)o.delete("cliToken"),M("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof _)M(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let q=G.contextRepo??P;b.success(`project ${G.projectId} ready (${G.provisioningStatus})`);let se=await pf(q),Ie={url:x.url,token:x.token};if(s==="farm"){let T=u,ae={...I,...se?{contextWrite:se}:{},...w?{claude:{oauthToken:w}}:{},youtrack:Ie},fe=I.github?.token;if(q.host==="github"&&fe)try{let Y=Us(`devpipe-${g}`);await Ls(q,fe,Y.publicKey,`devpipe-${g}`),ae.contextSsh={privateKey:Y.privateKey},b.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(Y){b.warn(`could not set up Context Repo SSH deploy key (${Y instanceof Error?Y.message:String(Y)}); the farm will fall back to the token path.`)}let Ye={projectId:g,config:{hubUrl:c,cliToken:p,projectId:g},secrets:ae,contextRepo:q,projectConfig:we(R,A,x.url,$||void 0)},dr=bt(T.farm.publicKey,JSON.stringify(Ye));b.step(`handing project ${g} to farm ${T.farm.name}\u2026`);let Pe;try{Pe=await Dr(c,p,T.farm.farmId,{projectId:g,sealedBundle:dr})}catch(Y){throw Y instanceof _&&M(Y.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:Y.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${Y.status} ${Y.message}`),Y}Pe.ok||M(`farm rejected provisioning: ${Pe.error??"unknown error"}`),await rn(c,p,g,q,fe),o.clear(),tn(`done. project ${g} is now hosted on farm ${T.farm.name} (daemon ${Pe.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}cc(I),await oc(e,q.cloneUrl,q.branch),ic(e),a&&await rf(e);{let T=st(e,he);yt(T);let ae=we(R,A,x.url,$||void 0),fe=Ft(T,ae);fe.length>0&&b.success(`local project config \u2192 .codepipe/{${fe.join(", ")}}`),tt(g,ae,{info:Ye=>b.message(Ye),warn:Ye=>b.warn(Ye)})}await nc(e,G.repos);let fo={hubUrl:c,cliToken:p,projectId:g,...I,...se?{contextWrite:se}:{},...w?{claude:{oauthToken:w}}:{},youtrack:Ie};z(fo),Ze({hubUrl:c,cliToken:p,projectId:g,accountEmail:f},g),b.success(`secrets \u2192 ${et(g)}`),await rn(c,p,g,q,I.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),tn("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function rn(t,e,r,o,n){let i=await Ma(o,n),s=Ga(i),a=await at({message:s.message,options:s.options,initialValue:s.initialValue});if(!(on(a)||a!==s.proceedValue))try{let{jobId:c}=await Mr(t,e,r,{reindex:s.reindex});b.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){b.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function Qd(t,e){let r;try{r=await ws(t,e)}catch(c){throw c instanceof _&&M(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&M("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let n=le(await at({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=Lr(i.farmId,i.publicKey)}catch(c){M(c instanceof Error?c.message:String(c))}return le(await Et({message:`confirm farm ${i.name} cred-channel fingerprint:
532
+ `}catch(P){let j=P instanceof Error?P.message:String(P);console.warn(`[job] ${m.jobId} conflict merge failed: ${j}`),w||await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:`conflict merge failed: ${j}`},startedAt:ke,finishedAt:new Date().toISOString()}),D.dispose();return}let Kc=_(m.prompt,je,gr)+xn,yo=[...je.map(P=>P.workspacePath),...gr?[gr]:[]];yo.length>0&&console.log(`[job] ${m.jobId} --add-dir: ${yo.join(", ")}`),X&&(go=setInterval(()=>{let j=g;if(!j||j.readyState!==j.OPEN)return;let F;try{F=Sd(nr(D.dir,"drafts")).filter(ie=>ie.endsWith(".json")).sort()}catch{return}for(let ie of F){if(mo.has(ie))continue;if(mo.size>=En)break;let ut;try{let re=JSON.parse(ja(nr(D.dir,"drafts",ie),"utf-8")),U=typeof re.localRef=="string"?re.localRef:"",Y=typeof re.title=="string"?re.title:"",Ye=typeof re.body=="string"?re.body:"";if(!U||!Y)continue;ut={localRef:U,title:Y,body:Ye,...re.isEpic===!0?{isEpic:!0}:{},...Array.isArray(re.links)?{links:re.links}:{}}}catch{continue}mo.add(ie);let Gt={type:"child_draft",jobId:m.jobId,projectId:m.projectId,draftId:X,child:ut};try{j.send(JSON.stringify(Gt))}catch{}}},1500));try{let P=await sa(s,{workspaceDir:D.dir,role:m.role,prompt:Kc,addDirs:yo,metadata:m.metadata??{},...m.model?{model:m.model}:{},...bn?{env:bn}:{},signal:u.signal,onActivity:lt},{jobId:m.jobId,policy:a,onBeforeRetry:async()=>{D.clean();for(let U of je)try{await ma(U);let Y=$n[U.name];m.role==="resolve-conflict"&&Y&&await Xo(U,Y,Pe)}catch(Y){let Ye=Y instanceof Error?Y.message:String(Y);console.warn(`[job] ${m.jobId} worktree reset failed (${U.name}): ${Ye}`)}try{await kn()}catch(U){let Y=U instanceof Error?U.message:String(U);console.warn(`[job] ${m.jobId} delivery re-checkout failed: ${Y}`)}},aborted:()=>w||d}),j=[];if(Id.has(m.role)&&je.length>0){let U=m.metadata??{},Y=typeof U.commitMessage=="string"?U.commitMessage:`${m.taskId}: changes`,Ye=m.contextRepo?.cloneUrl,vn=$?.env;if(!Ye||!vn)throw new Error("delivery requested but "+(Ye?"no context-write credentials in bundle":"no contextRepo cloneUrl in job spec"));let Wc=m.taskId.includes(":")?m.taskId.slice(m.taskId.indexOf(":")+1):m.taskId;for(let xe of je){let Mt=await ga(xe,Y);if(!Mt){console.log(`[job] ${m.jobId} ${xe.name}: no changes \u2014 no delivery`);continue}let wo=`codepipe/deliveries/${Wc}/${m.jobId}/${xe.name}`;await ha(xe,Mt,wo,Ye,vn),j.push({name:xe.name,deliveryRef:wo,deliverySha:Mt,baseSha:xe.baseSha}),console.log(`[job] ${m.jobId} ${xe.name}: delivered ${Mt.slice(0,10)} \u2192 ${wo}`);let Sn=await ya(xe,Mt);if(Sn.trim().length>0){let qc=nr("display",`${xe.name}.diff`),Cn=nr(D.dir,qc);vd(Rd(Cn),{recursive:!0}),Cd(Cn,Sn)}}}if(m.role==="resolve-conflict"&&j.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 F;m.role==="build"&&(F=Sa(D.dir),console.log(`[job] ${m.jobId} build verdict: ok=${F.ok}`+(F.failedStep?` failedStep=${F.failedStep}`:"")));let ie=P.artifactPaths.length>0?P.artifactPaths:D.listFiles(),ut=Array.from(new Set(ie)),Gt;if(ho)try{let U=await va(ho,m.role==="index"?["adr/SOURCES.md"]:[]);U.length>0&&(Gt=U,console.log(`[job] ${m.jobId} captured ${U.length} knowledge file(s) for Context Repo`))}catch(U){let Y=U instanceof Error?U.message:String(U);console.warn(`[job] ${m.jobId} knowledge capture failed (non-fatal): ${Y}`)}let re={jobId:m.jobId,status:"succeeded",artifacts:ut.map(U=>({path:U,contentBase64:ja(`${D.dir}/${U}`).toString("base64")})),...Gt?{contextWrites:Gt}:{},...j.length>0?{deliveries:j}:{},log:Pd(P.log),startedAt:ke,finishedAt:new Date().toISOString(),usage:P.usage,...P.rateLimit?{rateLimit:P.rateLimit}:{},...F?{build:F}:{}};if(w||d)console.warn(`[job] ${m.jobId} skipping result upload \u2014 ${d?"paused by operator":"claim was lost"}; HUB will re-execute on next claim`);else{await h.submitResult(re),console.log(`[job] ${m.jobId} done \u2014 uploaded ${re.artifacts.length} artifact(s):`);for(let U of re.artifacts){let Y=Buffer.from(U.contentBase64,"base64").length;console.log(` \xB7 ${U.path} (${Y} bytes)`)}re.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(P){let j=P instanceof Error?P.message:String(P);if(d)console.log(`[job] ${m.jobId} paused \u2014 agent stopped; HUB requeued it (restarts from phase start on resume)`);else if(w)console.warn(`[job] ${m.jobId} failed after claim lost (${j}) \u2014 skipping result upload`);else{let F=ia(P);console.warn(F?`[job] ${m.jobId} failed: ${j} (Claude auth \u2014 token invalid/expired)`:`[job] ${m.jobId} failed: ${j}`),await h.submitResult({jobId:m.jobId,status:"failed",artifacts:[],error:{message:j},startedAt:ke,finishedAt:new Date().toISOString(),...F?{authError:!0}:{}})}}finally{D.dispose()}}finally{clearInterval(ct),go&&clearInterval(go),Dt(),f=null,u=null,k?.cleanup(),$?.cleanup()}}function B(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 w;try{w=JSON.parse(Nr(m,h.credBundle).toString("utf-8"))}catch(q){return console.warn(`[job] ${h.jobId} failed to open credBundle: ${q instanceof Error?q.message:String(q)}`),{gitCreds:null,contextGitCreds:null}}let k=zo(w);k&&console.log(`[job] ${h.jobId} cred bundle opened \u2014 git creds configured`);let $=la(w,h.contextRepo.cloneUrl),N={gitCreds:k,contextGitCreds:$};return w.claudeOauthToken&&(N.claudeOauthToken=w.claudeOauthToken),N}function C(h,m){return h.split(`
533
+ `).map(w=>m+w).join(`
534
+ `)}function _(h,m,w){let k=m[0]?.workspacePath??"";return h.replace(/\{\{codeDir\}\}/g,k).replace(/\{\{codeRoot\}\}/g,k?k.replace(/\/[^/]+$/,""):"").replace(/\{\{contextDir\}\}/g,w??"")}let R=h=>{if(l)return;l=!0,console.log(`
535
+ [${h}] shutting down`),p.abort();let m=new AbortController,w=setTimeout(()=>m.abort(),3e3);(async()=>{let k=f;if(k)try{await c.releaseJob(k,`sandbox ${h}`,m.signal),console.log(`[${h}] released job ${k}`)}catch($){let N=$ instanceof Error?$.message:String($);console.warn(`[${h}] release failed: ${N} (sweeper will reclaim)`)}clearTimeout(w),S.close(),setTimeout(()=>process.exit(0),200)})()};process.on("SIGINT",()=>R("SIGINT")),process.on("SIGTERM",()=>R("SIGTERM")),await E()}async function Ea(t={profile:void 0}){let e=Ae(t.profile);console.log(`connecting to ${e.hubUrl} (project=${e.projectId}) \u2026`);let r=Gr(e.hubUrl,e.cliToken),o=await new Promise(i=>{let s=[],a=!1,c=setTimeout(()=>{s.push("timeout"),r.close(),i({ok:!1,events:s})},5e3);r.on("open",()=>{s.push("open");let l={type:"register",projectId:e.projectId};r.send(JSON.stringify(l))}),r.on("message",l=>{let p=l.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",l=>s.push(`error:${l.message}`)),r.on("close",(l,p)=>{s.push(`close:${l}:${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 Q(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=oe(t.profile);n?n.hubUrl===e.hubUrl.replace(/\/$/,"")?console.log(`worker: registered as ${n.sandboxId} (${n.name}), llm=${n.llm??"none"} \u2014 live state on the dashboard`):console.log(`worker: registered against a different HUB (${n.hubUrl})`):console.log("worker: not registered (run `codepipe up` or `codepipe worker register`)")}import{spawn as Xd}from"node:child_process";import{existsSync as Et,mkdirSync as Ja,readFileSync as Xa,readdirSync as Qd,writeFileSync as Qa}from"node:fs";import{join as it,resolve as Za}from"node:path";import{setTimeout as rn}from"node:timers/promises";import{cancel as Zd,confirm as At,intro as ec,isCancel as sn,log as b,outro as on,password as _t,select as st,spinner as tc,text as K}from"@clack/prompts";import{simpleGit as ao}from"simple-git";async function Pt(t,e,r){return e.host==="github"?Ed(t,e,r):e.host==="gitlab"?Bd(t,e,r):Gd(t,e,r)}async function Aa(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 Ke(e.githubToken,"GET",`/repos/${t.owner}/${encodeURIComponent(t.name)}`)).status!==404?{found:!0}:{found:!1,detail:o?await _a(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 He(e.gitlabToken,"GET",`/projects/${s}`)).status!==404?{found:!0}:{found:!1,detail:o?await Na(e.gitlabToken,t):n}}return e.bitbucket?(await It(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 _a(t,e){let r=!1;try{r=(await Ke(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 Na(t,e){let r=!1;try{r=(await He(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 It(t,"GET",`/workspaces/${encodeURIComponent(e.owner)}`)).status===200}catch{}return r?`Bitbucket repo ${e.owner}/${e.name} does not exist in workspace "${e.owner}" (which the credential can see) \u2014 check the repo name, or the API token lacks access to it`:`Bitbucket workspace "${e.owner}" is not visible to this credential \u2014 check the workspace name and the token's read:repository:bitbucket scope`}var jd="https://api.github.com";async function Ke(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(jd+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 Ed(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 Ad(o,e,r),i=await Nd(o,n.owner,n.name);r.log.info(`scaffolding Context Repo files \u2192 ${n.owner}/${n.name}@${i}`);let s=bt(t,e,r.youtrackWrites,r.trackerUrl);for(let a of s)await Od(o,n.owner,n.name,a.path,i)||await Ud(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 Ad(t,e,r){let o=await Ke(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 _a(t,e)} (attach joins an existing Context Repo and never creates one)`);let n=await _d(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 Ke(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 _d(t,e){let{status:r,data:o}=await Ke(t,"GET",`/users/${e}`);return r===404||!o?!1:o.type==="Organization"}async function Nd(t,e,r){let{data:o}=await Ke(t,"GET",`/repos/${e}/${r}`);if(!o)throw new Error("GitHub getDefaultBranch: empty response");return o.default_branch}async function Od(t,e,r,o,n){let{status:i,data:s}=await Ke(t,"GET",`/repos/${e}/${r}/contents/${encodeURI(o)}?ref=${encodeURIComponent(n)}`);return i===404||!s?null:s.sha}async function Ud(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 Ke(t,"PUT",`/repos/${e}/${r}/contents/${encodeURI(o)}`,c)}var Ld="https://gitlab.com/api/v4";async function He(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(Ld+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 Bd(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 He(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 Na(o,e)} (attach joins an existing Context Repo and never creates one)`);let f=await He(o,"GET","/user"),u={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 He(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`);u.namespace_id=g.data.id}r.log.info(`creating Context Repo ${e.owner}/${e.name} (gitlab)`);let d=await He(o,"POST","/projects",u);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=bt(t,e,r.youtrackWrites,r.trackerUrl),l=new Set;for(let f=1;;f++){let d=(await He(o,"GET",`/projects/${i.id}/repository/tree?recursive=true&per_page=100&page=${f}&ref=${encodeURIComponent(a)}`)).data??[];for(let g of d)l.add(g.path);if(d.length<100)break}let p=c.filter(f=>!l.has(f.path)).map(f=>({action:"create",file_path:f.path,content:f.content}));return p.length>0?await He(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 Dd="https://api.bitbucket.org/2.0";async function It(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(Dd+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 Gd(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 It(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 It(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=bt(t,e,r.youtrackWrites,r.trackerUrl),l=[];for(let f of c)(await It(o,"GET",`${n}/src/${encodeURIComponent(a)}/${f.path}?format=meta`)).status===404&&l.push(f);if(l.length>0){let f=new URLSearchParams;f.set("message","chore(codepipe): scaffold context repo files"),f.set("branch",a);for(let d of l)f.set(d.path,d.content);if((await It(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 Md={"github.com":"github","gitlab.com":"gitlab","bitbucket.org":"bitbucket"};function Re(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=Md[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 Fd}from"node:crypto";import{existsSync as Ua,mkdirSync as Hd,readFileSync as La,readdirSync as Kd,rmSync as io,writeFileSync as Wd}from"node:fs";import{homedir as qd}from"node:os";import{dirname as Yd,join as Zo}from"node:path";var Vd=24*60*60*1e3;function Ba(){return Zo(qd(),".codepipe","init-drafts")}function en(t){let e=Fd("sha256").update(t).digest("hex").slice(0,16);return Zo(Ba(),`${e}.json`)}function Da(t){let e=Date.now()-Date.parse(t);return!(e>=0&&e<=Vd)}function Ga(t){let e=en(t);if(!Ua(e))return null;try{let r=JSON.parse(La(e,"utf-8"));return!r||r.cwd!==t||typeof r.answers!="object"||!r.answers?null:Da(r.savedAt)?(io(e,{force:!0}),null):r}catch{return null}}function tn(t){io(en(t),{force:!0})}function Ma(){let t=Ba();if(Ua(t))for(let e of Kd(t)){let r=Zo(t,e);try{let o=JSON.parse(La(r,"utf-8"));Da(o.savedAt)&&io(r,{force:!0})}catch{io(r,{force:!0})}}}var jt=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(){tn(this.cwd)}persist(){let e=en(this.cwd);Hd(Yd(e),{recursive:!0});let r={cwd:this.cwd,savedAt:new Date().toISOString(),answers:this.answers};Wd(e,JSON.stringify(r,null,2)+`
536
+ `,{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 Ha(t,e){if(t.host!=="github"||!e)return!1;try{return(await fetch(`https://api.github.com/repos/${t.owner}/${t.name}/contents/knowledge/INDEX.md?ref=${encodeURIComponent(t.branch)}`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"codepipe-cli"}})).status===200}catch{return!1}}import{existsSync as Ka}from"node:fs";import{join as Wa}from"node:path";import{simpleGit as qa}from"simple-git";var zd={info:t=>console.log(t),warn:t=>console.warn(t)};async function sr(t,e,r={}){let o=r.log??zd,n=[];for(let i of e){let s=Wa(t,i.mountAs),a=On(i);if(!Ka(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 qa().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(!Ka(Wa(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=qa(s),l="";try{l=(await c.remote(["get-url","origin"]))?.toString().trim()??""}catch{l=""}if(!Jd(l,a)){o.warn(`${i.mountAs}/ origin (${l||"none"}) != expected (${a}) \u2014 skipping`),n.push({mountAs:i.mountAs,status:"skipped-origin-mismatch",detail:l});continue}if(r.dryRun){o.info(`would fetch ${i.mountAs}/`),n.push({mountAs:i.mountAs,status:"fetched",detail:"(dry-run)"});continue}try{await c.fetch(),n.push({mountAs:i.mountAs,status:"fetched"})}catch(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 Jd(t,e){return Ya(t)===Ya(e)}function Ya(t){return t.trim().replace(/\.git$/,"").replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/:/g,"/").toLowerCase()}async function Va(t={}){let e=Xe();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 sr(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 za=["# codepipe runtime \u2014 added by `codepipe init`","session.log","apply-queue.json"];function M(t){Zd(t),process.exit(1)}function ce(t){return sn(t)&&M("aborted"),t}function G(t){return sn(t)&&M("aborted"),typeof t=="string"?t:""}async function rc(t={}){ec("codepipe init \u2014 register a project locally or on a farm");let e=process.cwd();Ma();let r=Ga(e),o,n=!1;r&&Object.keys(r.answers).length>0?ce(await At({message:"You have not completed the initialization, do you want to continue?",initialValue:!0}))?(b.message("continuing with the saved answers \u2014 only the missing ones are asked"),o=new jt(e,r),n=!0):(tn(e),o=new jt(e)):o=new jt(e);let i=t.force===!0?null:await an(e),s=await o.ask("target",async()=>ce(await st({message:"where should this project run?",options:[{value:"local",label:"local \u2014 a CLI daemon on this machine, in this folder"},{value:"farm",label:"farm \u2014 a CLI daemon on a remote farm host"}],initialValue:"local"}))),a=null;s==="local"&&(a=i,a?b.message(`this folder is a git checkout of ${a.parsed.owner}/${a.parsed.repoName} \u2014 registering this repo in place (.codepipe/ will live inside it)`):n&&o.get("contextRepo")!==void 0||nc(e,t.force===!0));let c=await o.ask("hubUrl",async()=>G(await K({message:"HUB URL",placeholder:de,initialValue:O("HUB_URL")??de,validate:T=>T.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,"")),l=await o.ask("email",()=>co()),{cliToken:p,accountEmail:f}=await o.ask("bootstrap",()=>lo(c,l)),u=null;s==="farm"&&(u=await ef(c,p));let d=a?rf(a.parsed.repoName):"",g=await o.ask("projectId",async()=>G(await K({message:"project id (slug)",placeholder:d||"acme",...d?{initialValue:d}:{},validate:T=>Ve.test(T.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim()),y=await o.ask("projectName",async()=>G(await K({message:"project name (human-readable)",placeholder:a?.parsed.repoName??"Acme",...a?{initialValue:a.parsed.repoName}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),v=await o.ask("automationLevel",async()=>ce(await st({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"}))),x=await o.ask("youtrack",()=>pc()),S=await o.ask("youtrackProjectKey",async()=>G(await K({message:"YouTrack project key",placeholder:"DEV",validate:T=>T.trim().length>0?void 0:"required"})).trim()),E=await o.ask("youtrackWrites",async()=>ce(await At({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0}))),I=o.get("tokens")??{},B=()=>o.set("tokens",I),C=await o.ask("repos",()=>af(I,l,a,{onCred:B,initial:o.get("reposPartial")??[],onProgress:T=>o.set("reposPartial",T)}));o.delete("reposPartial");let _=await cf(await o.ask("contextRepo",()=>cc(g,C,I,l)),g,C,I,l,B,T=>o.set("contextRepo",T)),{spec:R,mode:h}=_;b.message("Only YouTrack tasks assigned to you enter this pipeline (to lift the filter later, set require_assignee: false in .codepipe/project.yaml).");let m=await o.ask("assigneeLogin",async()=>G(await K({message:"your YouTrack login (the assignee value)",...x.login?{initialValue:x.login}:{},validate:T=>T.trim().length>0?void 0:"required"})).trim()),w=await o.ask("claudeToken",()=>gf(s==="farm")),k={projectId:g,name:y,automationLevel:v,repos:C,youtrackProjectKey:S,ownerEmail:f};b.step(`${h==="attach"?"attaching to":"provisioning"} Context Repo ${R.owner}/${R.name} (${R.host})\u2026`);let $;try{$=await Pt(k,R,{...lc(I),youtrackWrites:E,trackerUrl:x.url,mode:h,log:{info:T=>b.message(T),warn:T=>b.warn(T)}})}catch(T){M(`Context Repo provisioning failed: ${T instanceof Error?T.message:String(T)}`)}k.contextRepo=$,b.success(`Context Repo ready: ${$.owner}/${$.name}@${$.branch}`),b.step(`registering project on ${c}\u2026`);let N;try{N=await xt(c,p,k)}catch(T){if(T instanceof A&&T.status===409){b.warn(`project ${g} already exists on HUB \u2014 reusing it`);try{N=await Q(c,p,g)}catch(se){throw se instanceof A&&M(`HUB \u2192 ${se.status} ${se.message}`),se}}else if(T instanceof A&&T.status===401)o.delete("cliToken"),M("HUB rejected the sign-in token (401) \u2014 re-run `codepipe init` to sign in again");else if(T instanceof A)M(`HUB \u2192 ${T.status} ${T.message}`);else throw T}let q=N.contextRepo??$;b.success(`project ${N.projectId} ready (${N.provisioningStatus})`);let ct=await ff(q),ke={url:x.url,token:x.token};if(s==="farm"){let T=u,se={...I,...ct?{contextWrite:ct}:{},...w?{claude:{oauthToken:w}}:{},youtrack:ke},Ie=I.github?.token;if(q.host==="github"&&Ie)try{let X=Bs(`devpipe-${g}`);await Ds(q,Ie,X.publicKey,`devpipe-${g}`),se.contextSsh={privateKey:X.privateKey},b.success("Context Repo SSH deploy key registered (no contextWrite PAT needed on the farm)")}catch(X){b.warn(`could not set up Context Repo SSH deploy key (${X instanceof Error?X.message:String(X)}); the farm will fall back to the token path.`)}let qe={projectId:g,config:{hubUrl:c,cliToken:p,projectId:g},secrets:se,contextRepo:q,projectConfig:he(k,E,x.url,m||void 0)},Dt=kt(T.farm.publicKey,JSON.stringify(qe));b.step(`handing project ${g} to farm ${T.farm.name}\u2026`);let lt;try{lt=await Mr(c,p,T.farm.farmId,{projectId:g,sealedBundle:Dt})}catch(X){throw X instanceof A&&M(X.status===409?`farm ${T.farm.name} is offline \u2014 start it and re-run.`:X.status===504?`farm ${T.farm.name} did not respond in time.`:`HUB \u2192 ${X.status} ${X.message}`),X}lt.ok||M(`farm rejected provisioning: ${lt.error??"unknown error"}`),await nn(c,p,g,q,Ie),o.clear(),on(`done. project ${g} is now hosted on farm ${T.farm.name} (daemon ${lt.daemonStatus}). Watch the setup progress on the dashboard \u2014 the project card shows each step until the project is ready.`);return}uc(I),await ic(e,q.cloneUrl,q.branch),ac(e),a&&await nf(e);{let T=it(e,me);wt(T);let se=he(k,E,x.url,m||void 0),Ie=Kt(T,se);Ie.length>0&&b.success(`local project config \u2192 .codepipe/{${Ie.join(", ")}}`),et(g,se,{info:qe=>b.message(qe),warn:qe=>b.warn(qe)})}await sc(e,N.repos);let $e={hubUrl:c,cliToken:p,projectId:g,...I,...ct?{contextWrite:ct}:{},...w?{claude:{oauthToken:w}}:{},youtrack:ke};V($e),Qe({hubUrl:c,cliToken:p,projectId:g,accountEmail:f},g),b.success(`secrets \u2192 ${Ze(g)}`),await nn(c,p,g,q,I.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),o.clear(),on("done. next: `codepipe up` from this folder \u2014 starts the daemon and an agent worker. (`codepipe` opens the interactive REPL.)")}async function nn(t,e,r,o,n){let i=await Ha(o,n),s=Fa(i),a=await st({message:s.message,options:s.options,initialValue:s.initialValue});if(!(sn(a)||a!==s.proceedValue))try{let{jobId:c}=await Hr(t,e,r,{reindex:s.reindex});b.success(`indexing queued (job ${c}); knowledge/INDEX.md will appear in the Context Repo once the project daemon is running and a SANDBOX picks up the job.`)}catch(c){b.warn(`could not start indexing: ${c instanceof Error?c.message:String(c)}. You can retry later \u2014 registration is not affected.`)}}async function ef(t,e){let r;try{r=await ks(t,e)}catch(c){throw c instanceof A&&M(`could not list farms: HUB \u2192 ${c.status} ${c.message}`),c}let o=r.filter(c=>c.publicKey);o.length===0&&M("no farm is available to this account. Farms are assigned by the operator \u2014 ask them to assign one to you (or, if you run your own farm host: `codepipe-farm register --hub <url> --token <token>` and `codepipe-farm start`, then have the operator assign it).");let n=ce(await st({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=Dr(i.farmId,i.publicKey)}catch(c){M(c instanceof Error?c.message:String(c))}return ce(await At({message:`confirm farm ${i.name} cred-channel fingerprint:
537
537
  ${s}
538
- (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||M("farm fingerprint not confirmed \u2014 aborting."),Ur(i.farmId,s),{farm:i,fingerprint:s}}async function tc(t){Qa(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();rc(e,t.force===!0);let r=D(await K({message:"HUB URL",initialValue:N("HUB_URL")??me,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await ao(),{cliToken:n,accountEmail:i}=await co(r,o);b.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,n,t.projectId)}catch(f){throw f instanceof _&&M(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||M(`project ${t.projectId} has no Context Repo on HUB`);let a=await lc(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await io(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(u=>u.host===f)?.owner,o);cc(c),await oc(e,s.contextRepo.cloneUrl,s.contextRepo.branch),ic(e);{let f=st(e,he);yt(f);let u={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},d=we(u,!0,a.url),g=Ft(f,d);g.length>0&&b.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),tt(t.projectId,d,{info:y=>b.message(y),warn:y=>b.warn(y)})}await nc(e,s.repos);let p={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};z(p),Ze({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),b.success(`secrets \u2192 ${et(t.projectId)}`),await rn(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),tn("done.")}function rc(t,e){if(!jt(t)){Va(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Jd(t).filter(n=>!r.has(n));o.length!==0&&(e||M(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function nn(t){if(!jt(st(t,".git")))return null;try{let r=(await so(t).remote(["get-url","origin"])||"").toString().trim(),o=r?Re(r):null;return o?{parsed:o,defaultBranch:await Zd(t)}:null}catch{return null}}async function Zd(t){let e=so(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 ef(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return ze.test(e)?e:""}function tf(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function rf(t){let e=st(t,".gitignore"),r=jt(e)?za(e,"utf-8"):"";if(tf(r))return;if(!le(await Et({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){b.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
538
+ (compare with the farm host's \`codepipe-farm register\` output)`,initialValue:!0}))||M("farm fingerprint not confirmed \u2014 aborting."),Br(i.farmId,s),{farm:i,fingerprint:s}}async function oc(t){ec(`codepipe clone ${t.projectId} \u2014 reconstruct workspace`);let e=process.cwd();nc(e,t.force===!0);let r=G(await K({message:"HUB URL",initialValue:O("HUB_URL")??de,validate:f=>f.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),o=await co(),{cliToken:n,accountEmail:i}=await lo(r,o);b.step(`fetching project ${t.projectId} from HUB\u2026`);let s;try{s=await Q(r,n,t.projectId)}catch(f){throw f instanceof A&&M(`HUB \u2192 ${f.status} ${f.message}`),f}s.contextRepo||M(`project ${t.projectId} has no Context Repo on HUB`);let a=await pc(),c={},l=new Set(s.repos.map(f=>f.host));l.add(s.contextRepo.host);for(let f of l)await so(f,c,f===s.contextRepo.host?s.contextRepo.owner:s.repos.find(u=>u.host===f)?.owner,o);uc(c),await ic(e,s.contextRepo.cloneUrl,s.contextRepo.branch),ac(e);{let f=it(e,me);wt(f);let u={projectId:t.projectId,name:s.name,automationLevel:s.automationLevel,repos:s.repos,...s.youtrackProjectKey?{youtrackProjectKey:s.youtrackProjectKey}:{}},d=he(u,!0,a.url),g=Kt(f,d);g.length>0&&b.success(`local project config \u2192 .codepipe/{${g.join(", ")}} (defaults \u2014 review and adjust)`),et(t.projectId,d,{info:y=>b.message(y),warn:y=>b.warn(y)})}await sc(e,s.repos);let p={hubUrl:r,cliToken:n,projectId:t.projectId,...c,youtrack:{url:a.url,token:a.token}};V(p),Qe({hubUrl:r,cliToken:n,projectId:t.projectId,accountEmail:i},t.projectId),b.success(`secrets \u2192 ${Ze(t.projectId)}`),await nn(r,n,t.projectId,s.contextRepo,c.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),on("done.")}function nc(t,e){if(!Et(t)){Ja(t,{recursive:!0});return}let r=new Set([".DS_Store",".codepipe",".devpipe"]),o=Qd(t).filter(n=>!r.has(n));o.length!==0&&(e||M(`cwd ${t} is not empty (contains: ${o.slice(0,5).join(", ")}${o.length>5?", \u2026":""}). use --force to bypass.`))}async function an(t){if(!Et(it(t,".git")))return null;try{let r=(await ao(t).remote(["get-url","origin"])||"").toString().trim(),o=r?Re(r):null;return o?{parsed:o,defaultBranch:await tf(t)}:null}catch{return null}}async function tf(t){let e=ao(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 rf(t){let e=t.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^[-0-9]+/,"").replace(/-+$/,"").slice(0,31);return Ve.test(e)?e:""}function of(t){return t.split(/\r?\n/).some(e=>{let r=e.trim();return r===".codepipe"||r===".codepipe/"||r==="/.codepipe"||r==="/.codepipe/"})}async function nf(t){let e=it(t,".gitignore"),r=Et(e)?Xa(e,"utf-8"):"";if(of(r))return;if(!ce(await At({message:"add .codepipe/ to this repo's .gitignore? (recommended \u2014 workspace state, not code)",initialValue:!0}))){b.warn("skipped \u2014 remember that .codepipe/ is a separate git repo living inside this one");return}let n=r.length===0||r.endsWith(`
539
539
  `)?"":`
540
- `;Ja(e,r+n+`
540
+ `;Qa(e,r+n+`
541
541
  # codepipe workspace (added by \`codepipe init\`)
542
542
  .codepipe/
543
- `),b.success(`.codepipe/ added to ${Xa(e)}`)}function of(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=zd(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function ao(){let t="";try{t=(await so().raw(["config","--global","user.email"])||"").trim()}catch{}return D(await K({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function co(t,e){b.step(`connecting account ${e}`);let r;try{r=await ks(t,e)}catch(s){throw s instanceof zt&&M(`${e} is not authorized on this HUB yet.
543
+ `),b.success(`.codepipe/ added to ${Za(e)}`)}function sf(t){let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{let o=Xd(e,r,{detached:!0,stdio:"ignore"});o.on("error",()=>{}),o.unref()}catch{}}async function co(){let t="";try{t=(await ao().raw(["config","--global","user.email"])||"").trim()}catch{}return G(await K({message:"Your account email",...t?{initialValue:t}:{},validate:e=>e.includes("@")?void 0:"must be a valid email"})).trim().toLowerCase()}async function lo(t,e){b.step(`connecting account ${e}`);let r;try{r=await xs(t,e)}catch(s){throw s instanceof Xt&&M(`${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.`),s}r.accountCreated&&b.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&b.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(of(r.authorizeUrl),b.message(`a browser tab was opened to confirm this CLI:
546
+ \`codepipe init\` with the same email.`),s}r.accountCreated&&b.message(`no account for ${e} yet \u2014 one was just created.`),r.emailSent&&b.message("click the link in your inbox to confirm your email."),r.authorizeUrl&&(sf(r.authorizeUrl),b.message(`a browser tab was opened to confirm this CLI:
547
547
  ${r.authorizeUrl}
548
548
  `+(r.emailSent?" (already signed in to the dashboard there? just click Connect)":` if you're signed in to the CodePipe dashboard, just click Connect \u2014
549
- otherwise use the emailed link the page offers.`))),r.approvalRequired&&b.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),b.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let o=!1,n=Date.now(),i=n+15*6e4;for(;Date.now()<i;){let s;try{s=await $s(t,r.requestId)}catch(a){b.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await en(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&b.message(`connected as ${a} (the account confirmed in the browser).`),b.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&M("the HUB rejected this account"),s.status==="expired"&&M("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,b.message(`email confirmed. waiting for the operator to approve your account\u2026
550
- (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await en(5e3);continue}await en(2e3)}M("bootstrap timed out")}async function oc(t,e,r){let o=st(t,he);if(jt(st(o,".git"))){b.message(`${o} already cloned \u2014 skipping`);return}jt(o)&&M(`${o} exists but is not a git repo \u2014 remove it and re-run`),Va(o,{recursive:!0}),b.step(`cloning Context Repo \u2192 ${o}`);try{await so().clone(e,o,["--branch",r]),b.success(`cloned ${e}`)}catch(n){M(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function nc(t,e){if(e.length===0)return;b.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await or(t,r,{log:{info:n=>b.message(n),warn:n=>b.warn(n)}});for(let n of o)b.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function ic(t){let e=st(t,he,".gitignore"),r="";if(jt(e)&&(r=za(e,"utf-8")),Ya.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
549
+ otherwise use the emailed link the page offers.`))),r.approvalRequired&&b.warn("during the beta, new accounts require operator approval \u2014 you'll be held at that step until it happens."),b.message(`waiting for confirmation\u2026 (request ${r.requestId})`);let o=!1,n=Date.now(),i=n+15*6e4;for(;Date.now()<i;){let s;try{s=await vs(t,r.requestId)}catch(a){b.message(` (still waiting \u2014 HUB not reachable right now: ${a instanceof Error?a.message:String(a)})`),await rn(5e3);continue}if(s.status==="confirmed"&&s.cliToken){let a=s.email??e;return a!==e&&b.message(`connected as ${a} (the account confirmed in the browser).`),b.success("confirmed"),{cliToken:s.cliToken,accountEmail:a}}if(s.status==="rejected"&&M("the HUB rejected this account"),s.status==="expired"&&M("the request expired \u2014 re-run init"),s.status==="waiting_approval"||s.status==="email_confirmed"){o||(o=!0,i=n+24*60*6e4,b.message(`email confirmed. waiting for the operator to approve your account\u2026
550
+ (you'll get an email when it happens; it's safe to Ctrl+C and re-run init later)`)),await rn(5e3);continue}await rn(2e3)}M("bootstrap timed out")}async function ic(t,e,r){let o=it(t,me);if(Et(it(o,".git"))){b.message(`${o} already cloned \u2014 skipping`);return}Et(o)&&M(`${o} exists but is not a git repo \u2014 remove it and re-run`),Ja(o,{recursive:!0}),b.step(`cloning Context Repo \u2192 ${o}`);try{await ao().clone(e,o,["--branch",r]),b.success(`cloned ${e}`)}catch(n){M(`git clone failed: ${n instanceof Error?n.message:String(n)}`)}}async function sc(t,e){if(e.length===0)return;b.step(`cloning ${e.length} project repo(s) as siblings of .codepipe/`);let r=e.map(n=>({name:n.name,host:n.host,owner:n.owner,repoName:n.repoName,defaultBranch:n.defaultBranch??"main",mountAs:n.mountAs??n.name})),o=await sr(t,r,{log:{info:n=>b.message(n),warn:n=>b.warn(n)}});for(let n of o)b.message(` ${n.mountAs}: ${n.status}${n.detail?` \u2014 ${n.detail}`:""}`)}function ac(t){let e=it(t,me,".gitignore"),r="";if(Et(e)&&(r=Xa(e,"utf-8")),za.filter(s=>s.startsWith("#")?!1:!r.split(/\r?\n/).includes(s)).length===0)return;let n=r.endsWith(`
551
551
  `)||r.length===0?"":`
552
- `,i=Ya.join(`
552
+ `,i=za.join(`
553
553
  `)+`
554
- `;Ja(e,r+n+(r?`
555
- `:"")+i),b.message(`appended runtime entries to ${Xa(e)}`)}async function nf(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;b.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await io(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(),l=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:l,mountAs:"."}),o.onProgress?.(n)}for(;le(await Et({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()||Re(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=Re(a);b.message(`${c.host}: ${c.owner}/${c.repoName}`),await io(c.host,t,c.owner,e),i?.();let l=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:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),f&&f!==l&&(u.mountAs=f),n.push(u),o.onProgress?.(n)}return n}async function sc(t,e,r,o){b.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let n=le(await at({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&b.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=D(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Se(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!Re(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=Re(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await af(),l=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:Se(t),initialValue:Se(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:n}}function ac(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??ft()}}async function sf(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await io(c.host,o,c.owner,n),i?.();let p=Za();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await ja(c,ac(o),{explain:l==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="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(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let u=le(await at({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(u==="abort"&&M("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await sc(e,r,o,n),s(a)}}async function af(){return le(await at({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function nr(t,e){let r=Za();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 cc(t){Ht(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),Kt(t.gitlab?.token??process.env.GITLAB_TOKEN),Wt(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function io(t,e,r,o){if(!e[t])if(t==="github"){let n=await cf(r);n?e.github=n:b.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await lf(r,o);n?e.bitbucket=n:b.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let n=await uf();n?e.gitlab=n:b.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function cf(t){for(;;){let e=D(await At({message:`GitHub PAT \u2014 blank to skip
554
+ `;Qa(e,r+n+(r?`
555
+ `:"")+i),b.message(`appended runtime entries to ${Za(e)}`)}async function af(t,e,r,o={}){let n=[...o.initial??[]],i=o.onCred;if(r&&n.length===0){let{parsed:s,defaultBranch:a}=r;b.message(`this repo: ${s.host}: ${s.owner}/${s.repoName} (mounted in place)`),await so(s.host,t,s.owner,e),i?.();let c=G(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(),l=G(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:l,mountAs:"."}),o.onProgress?.(n)}for(;ce(await At({message:n.length===0?"Add a project repository?":"Want to add another repository?",initialValue:n.length===0}));){let a=G(await K({message:"repo clone URL \u2014 blank to go back",placeholder:"git@github.com:acme/api.git",validate:d=>!d||!d.trim()||Re(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=Re(a);b.message(`${c.host}: ${c.owner}/${c.repoName}`),await so(c.host,t,c.owner,e),i?.();let l=G(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=G(await K({message:"default branch (optional)",placeholder:"main"})).trim(),f=G(await K({message:"local folder name (sibling of .codepipe/, optional)",placeholder:l})).trim(),u={name:l,host:c.host,owner:c.owner,repoName:c.repoName};p&&(u.defaultBranch=p),f&&f!==l&&(u.mountAs=f),n.push(u),o.onProgress?.(n)}return n}async function cc(t,e,r,o){b.message("Context Repo \u2014 where CodePipe stores prompts, knowledge and task artifacts. It can live on a different host/owner than your project repos.");let n=ce(await st({message:"Context Repo:",options:[{value:"create",label:"create a new one \u2014 this project starts its own context"},{value:"attach",label:"attach to an existing one \u2014 join a team's shared context (read/write token is enough)"}],initialValue:"create"}));n==="attach"&&b.message("attach: the repo must already exist; the scaffold only fills missing files and never touches the team's CLAUDE.md / prompts/ / knowledge/.");let i=e[0]?.host,s=e[0]?.owner,a;if(i&&s){let c=G(await K({message:`Context Repo \u2014 a name (hosted at ${i}: ${s}/<name>) or a full clone URL`,initialValue:Se(t),validate:p=>{let f=(p??"").trim();if(!f)return"required";if(!Re(f)&&!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(f))return"enter a repo name, or a full clone URL (git@\u2026 / https://\u2026)"}})).trim(),l=Re(c);a=l?{host:l.host,owner:l.owner,name:l.repoName}:{host:i,owner:s,name:c}}else{let c=await lf(),l=G(await K({message:"Context Repo owner (org / group / workspace / user)",placeholder:"your-org",validate:f=>f.trim().length>0?void 0:"required"})).trim(),p=G(await K({message:"Context Repo name",placeholder:Se(t),initialValue:Se(t),validate:f=>f.trim().length>0?void 0:"required"})).trim();a={host:c,owner:l,name:p}}return{spec:a,mode:n}}function lc(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??mt()}}async function cf(t,e,r,o,n,i,s){let a=t;for(;;){let{spec:c,mode:l}=a;await so(c.host,o,c.owner,n),i?.();let p=tc();p.start(`checking ${c.owner}/${c.name} on ${c.host}\u2026`);let f=await Aa(c,lc(o),{explain:l==="attach"});if(f.found===!0)return p.stop(`${c.owner}/${c.name} found${l==="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(l==="create")return p.stop(`${c.owner}/${c.name} not found \u2014 will be created`),a;p.stop(f.detail,1);let u=ce(await st({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(u==="abort"&&M("aborted"),u==="create")return a={spec:c,mode:"create"},s(a),a;a=await cc(e,r,o,n),s(a)}}async function lf(){return ce(await st({message:"Context Repo host",options:[{value:"github",label:"github"},{value:"gitlab",label:"gitlab"},{value:"bitbucket",label:"bitbucket"}],initialValue:"github"}))}async function ar(t,e){let r=tc();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 uc(t){Wt(t.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN),qt(t.gitlab?.token??process.env.GITLAB_TOKEN),Yt(t.bitbucket?.apiToken||process.env.BITBUCKET_API_TOKEN)}async function so(t,e,r,o){if(!e[t])if(t==="github"){let n=await uf(r);n?e.github=n:b.warn("no GitHub token \u2014 private github repos won't clone and PRs won't open.")}else if(t==="bitbucket"){let n=await pf(r,o);n?e.bitbucket=n:b.warn("no Bitbucket API token \u2014 git falls back to this machine's SSH keys / BITBUCKET_* env; private repos won't clone over HTTPS and PRs won't open.")}else{let n=await df();n?e.gitlab=n:b.warn("no GitLab token \u2014 private gitlab repos won't clone and MRs won't open.")}}async function uf(t){for(;;){let e=G(await _t({message:`GitHub PAT \u2014 blank to skip
556
556
  classic PAT: 'repo' (+ 'workflow' if no separate contextWrite token)
557
557
  fine-grained PAT: Administration RW + Contents RW + Workflows RW + Metadata R;
558
558
  if org: approve token in org Settings \u2192 Personal access tokens.
559
559
  (Workflows RW lets the delivery push carry .github/workflows/* to the Context Repo;
560
- set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await nr("GitHub",()=>Oe(e,t?{owner:t}:void 0)))return{token:e};b.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function lf(t,e){for(b.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
560
+ set a dedicated contextWrite token in secrets to scope it to the Context Repo only.)`})).trim();if(!e)return;if(await ar("GitHub",()=>Ne(e,t?{owner:t}:void 0)))return{token:e};b.warn("re-enter the GitHub PAT (or leave blank to skip).")}}async function pf(t,e){for(b.message(`Bitbucket authenticates with an Atlassian API token (app passwords are retired).
561
561
  How to get one: https://id.atlassian.com \u2192 Security \u2192 API tokens \u2192
562
562
  'Create API token with scopes' \u2192 app: Bitbucket \u2192 scopes: read:account,
563
563
  read:repository:bitbucket + write:repository:bitbucket, write:pullrequest:bitbucket
564
564
  (+ admin:repository:bitbucket if this token will provision the Context Repo).
565
- 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 At({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){b.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await nr("Bitbucket",()=>Ue(r,o,t)))return{email:r,apiToken:o};b.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function uf(){for(;;){let t=D(await At({message:`GitLab PAT \u2014 blank to skip
566
- scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await nr("GitLab",()=>Le(t))){let e=await gi(t);return e&&b.warn(e),{token:t}}b.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function pf(t){if(le(await Et({message:`Issue a separate context-write token (scoped to the Context Repo only)?
565
+ The token is shown ONCE \u2014 copy it right away.`);;){let r=G(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=G(await _t({message:"Bitbucket API token (BITBUCKET_API_TOKEN)"})).trim();if(!o){b.warn("the API token is required for Bitbucket \u2014 re-enter (or clear the email to skip).");continue}if(await ar("Bitbucket",()=>Oe(r,o,t)))return{email:r,apiToken:o};b.warn("re-enter the Atlassian email / API token (or clear the email to skip).")}}async function df(){for(;;){let t=G(await _t({message:`GitLab PAT \u2014 blank to skip
566
+ scopes: 'api' (or 'read_api' + 'write_repository') to create MRs and push.`})).trim();if(!t)return;if(await ar("GitLab",()=>Ue(t))){let e=await yi(t);return e&&b.warn(e),{token:t}}b.warn("re-enter the GitLab PAT (or leave blank to skip).")}}async function ff(t){if(ce(await At({message:`Issue a separate context-write token (scoped to the Context Repo only)?
567
567
  Without it the SANDBOX pushes delivery commits with the project ${t.host}
568
568
  credential. A scoped token hardens setups where the SANDBOX runs outside
569
569
  your trusted network.`,initialValue:!1})))for(t.host==="github"?b.message(`Recommended: a fine-grained PAT scoped to ONLY ${t.owner}/${t.name},
570
570
  permissions Contents: Read and write + Workflows: Read and write (Workflows is
571
571
  required \u2014 deliveries carry .github/workflows/*). Classic PAT: 'repo' + 'workflow'.`):b.message(`A token scoped to ONLY ${t.owner}/${t.name} with repository write access
572
- (${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 At({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await nr("contextWrite",()=>df(r,t)))return{token:r};b.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function df(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 ff(t){if(bo()?.claude?.oauthToken&&!t)return b.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";b.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
573
- Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=D(await At({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||b.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(b.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function lc(){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 At({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await nr("YouTrack",()=>De({baseUrl:t,token:e}))){let r=await Oi({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as mf}from"node:fs";function W(t){throw new Error(t)}function X(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function ir(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 gf(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=X(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=X(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=X(i.id,"project.id");ze.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=X(i.name,"project.name"),c=X(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||W("config: 'project.repos' must be an array");let p=l.map((v,A)=>{(!v||typeof v!="object")&&W(`config: project.repos[${A}] must be an object`);let I=v,L=X(I.host,`project.repos[${A}].host`);L!=="github"&&L!=="bitbucket"&&L!=="gitlab"&&W(`config: project.repos[${A}].host must be 'github', 'bitbucket' or 'gitlab'`);let C={name:X(I.name,`project.repos[${A}].name`),host:L,owner:X(I.owner,`project.repos[${A}].owner`),repoName:X(I.repoName,`project.repos[${A}].repoName`)},h=ir(I.defaultBranch,`project.repos[${A}].defaultBranch`);h&&(C.defaultBranch=h);let m=ir(I.mountAs,`project.repos[${A}].mountAs`);return m&&(C.mountAs=m),C}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let u=f,d=ir(u.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:X(u.owner,"project.contextRepo.owner"),name:ir(u.name,"project.contextRepo.name")??Se(s)},y={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},S=ir(i.youtrackProjectKey,"project.youtrackProjectKey");S&&(y.project.youtrackProjectKey=S),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let x=e.secrets;if(x!==void 0){(typeof x!="object"||x===null)&&W("config: 'secrets' must be an object");let v=x,A={};if(v.github){let I=v.github;A.github={token:X(I.token,"secrets.github.token")}}if(v.bitbucket){let I=v.bitbucket;A.bitbucket={email:X(I.email,"secrets.bitbucket.email"),apiToken:X(I.apiToken,"secrets.bitbucket.apiToken")}}if(v.gitlab){let I=v.gitlab;A.gitlab={token:X(I.token,"secrets.gitlab.token")}}if(v.youtrack){let I=v.youtrack;A.youtrack={url:X(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:X(I.token,"secrets.youtrack.token")}}if(v.contextWrite){let I=v.contextWrite;A.contextWrite={token:X(I.token,"secrets.contextWrite.token")}}y.secrets=A}return y}async function hf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function yf(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await Oe(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 Ue(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Le(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await De({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function uc(t){let e=!t.configPath||t.configPath==="-"?await hf():mf(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){W(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let o=gf(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 yf(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await It(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??ft(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){W(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await $t(n,i,a)}catch(u){if(u instanceof _&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await Q(n,i,s.id);else if(u instanceof _)W(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(z(f),Ze({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${et(s.id)}`),tt(s.id,we(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await Mr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as pc,intro as dc,isCancel as fc,log as sn,outro as wf,password as mc}from"@clack/prompts";async function bf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function gc(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await bf(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){dc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),sn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await mc({message:"Claude OAuth token"});fc(i)&&(pc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Vn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${vr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=_e(t.profile);if(!e){dc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),sn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await mc({message:"Claude OAuth token"});fc(i)&&(pc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=U(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},z(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(sn.success("Claude OAuth token saved."),wf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as kf,confirm as $f,intro as xf,isCancel as hc,log as ee,outro as vf,select as yc,text as qe}from"@clack/prompts";function wc(t){kf(t),process.exit(1)}function _t(t){return hc(t)&&wc("aborted"),t}function sr(t){return hc(t)&&wc("aborted"),typeof t=="string"?t:""}async function Sf(t,e){let r=_t(await yc({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=sr(await qe({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=sr(await qe({message:"Context Repo name",placeholder:Se(t),initialValue:Se(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function bc(t={profile:void 0}){let e=_e(t.profile);xf(`codepipe project add \u2192 ${e.hubUrl}`);let r=_t(await qe({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>ze.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=_t(await qe({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),n=_t(await yc({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=_t(await qe({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=_t(await $f({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=sr(await qe({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:x=>!x||!x.trim()||Re(x)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let d=Re(u);ee.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=sr(await qe({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:x=>x.trim().length>0?void 0:"required"})).trim(),y=sr(await qe({message:"default branch (optional)",placeholder:"main"})).trim(),S={name:g,host:d.host,owner:d.owner,repoName:d.repoName};y&&(S.defaultBranch=y),a.push(S)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await Sf(r,a),p=U(e.projectId);ee.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await It(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??ft(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>ee.message(u),warn:u=>ee.warn(u)}})}catch(u){ee.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,ee.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await $t(e.hubUrl,e.cliToken,c);ee.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),tt(r,we(c,s,p?.youtrack?.url),{info:d=>ee.message(d),warn:d=>ee.warn(d)}),u.contextRepo&&(ee.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),ee.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&ee.error(` error: ${u.provisioningError}`),vf("done")}catch(u){u instanceof _?(ee.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&ee.message(JSON.stringify(u.payload,null,2))):ee.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{spawn as Cf}from"node:child_process";import{existsSync as kc}from"node:fs";import{homedir as Tf,hostname as Rf}from"node:os";import{join as lo}from"node:path";async function If(t,e,r){let o=oe(e);if(o){if(o.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`);return}throw new Error(`worker config ${Fe(e)} points at a different HUB (${o.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 n;try{({secret:n}=await Gr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof _&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof _&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof _?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await nt({hub:t.hubUrl,token:n,name:r.name??`${Rf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function Pf(t,e){let r=oe(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=be(r.sealPublicKey);if(!U(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=xr(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 jf(t,e){let r=process.cwd(),o=lo(r,he);if(br(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(kc(o)){console.warn(`[up] ${o} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let n;try{n=await Q(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await nn(r);if(!An(r,i?.parsed??null,n.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=U(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Wr({cfg:t,secrets:s,contextDir:o,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=lo(Tf(),".codepipe",e?lo("profiles",e,"context-config"):"context-config");if(Rr(c.contextDir,l,a),!kc(lo(c.contextDir,"project.yaml"))){yt(c.contextDir);let p={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};Ft(c.contextDir,we(p,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function $c(t){let{cfg:e,profile:r}=$r(t.profile);await jf(e,r),await If(e,r,t),Pf(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(d,g)=>{let y=S=>x=>{for(let v of x.toString("utf-8").split(`
574
- `))v.length>0&&S.write(`${g} ${v}
575
- `)};d.stdout?.on("data",y(process.stdout)),d.stderr?.on("data",y(process.stderr))},i=(d,g)=>{let y=Cf(process.execPath,[o,...g],{stdio:["ignore","pipe","pipe"],env:process.env});return n(y,d),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,p=d=>{if(!l){l=!0,console.log(`
576
- [up] ${d} \u2014 stopping both roles`);for(let{child:g}of c)g.exitCode===null&&g.kill(d);setTimeout(()=>{for(let{name:g,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${g} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let f=c.map(({name:d,child:g})=>new Promise(y=>{g.on("exit",(S,x)=>y({name:d,code:S??(x?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(f),process.exit(u.code)}import{existsSync as _c,mkdirSync as Of,readFileSync as Uf,writeFileSync as Lf}from"node:fs";import{homedir as Bf}from"node:os";import{dirname as Df,join as Nc}from"node:path";import*as Ot from"node:readline";import{existsSync as ln,readFileSync as Ef,writeFileSync as Af}from"node:fs";import{join as cr}from"node:path";import{simpleGit as cn}from"simple-git";var xc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],_f="apply-queue.json";function vc(t){return cr(t,_f)}function Nt(t){let e=vc(t);if(!ln(e))return{};try{return JSON.parse(Ef(e,"utf-8"))}catch{return{}}}function Sc(t,e){Af(vc(t),JSON.stringify(e,null,2)+`
577
- `)}async function Cc(t,e,r,o,n){let i;try{i=await Ss(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let d=t.spec.repos.find(x=>x.name===u.repoName);if(!d)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let g=cr(t.root,d.mountAs);if(!ln(cr(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await cn(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:d,dir:g})}let a=[];for(let u of s){let d=cn(u.dir),g=await Nf(d),y=u.claimRepo;try{await d.fetch()}catch(v){return await an(a,n),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${ar(v)}`}}let S=`origin/${y.baseRef}`,x;try{x=await Nr(d,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(v){return await an(a,n),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${ar(v)}`}}a.push({git:d,dir:u.dir,mountAs:u.spec.mountAs,originalRef:g,branch:y.branchName,baseSha:S,deliveryCommit:x,startPoint:S})}let c=[];for(let u of a)try{if(o==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...xc,"cherry-pick",u.deliveryCommit]);let d=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:d})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...xc,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(d){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await an(a,n),{ok:!1,message:`apply failed in ${u.mountAs}: ${ar(d)} (rolled back all repos)`}}let l=Nt(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},Sc(t.contextDir,l);let p=c.map(u=>u.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}
572
+ (${t.host==="gitlab"?"project access token, 'write_repository' scope":"Bitbucket repository access token, Repositories: Read & write \u2014 the only Bitbucket credential scopeable to a single repo; an account-wide API token would defeat the scoping"}).`);;){let r=G(await _t({message:"contextWrite token \u2014 blank to skip"})).trim();if(!r)return;if(t.host!=="github")return{token:r};if(await ar("contextWrite",()=>mf(r,t)))return{token:r};b.warn("re-enter the contextWrite token (or leave blank to skip).")}}async function mf(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 gf(t){if($o()?.claude?.oauthToken&&!t)return b.message("Claude: this machine already has a shared OAuth token \u2014 the project will use it (set a project-specific one later with `codepipe login`)."),"";b.message("Claude login \u2014 pipeline agents run on your Claude subscription.\n Get a token: install Claude Code (https://claude.com/claude-code), run\n `claude setup-token` in a terminal and paste the result here."+(t?`
573
+ Blank to skip \u2014 the farm's shared Claude token (if set) is used.`:""));let r=G(await _t({message:"Claude OAuth token \u2014 blank to skip"})).trim();return r?(r.startsWith("sk-ant-")||b.warn("the token doesn't look like `claude setup-token` output (sk-ant-\u2026) \u2014 saved anyway; if jobs fail to authenticate, re-run `codepipe login`."),r):(b.warn(t?"skipped \u2014 jobs will run only if the farm host has a shared token (`codepipe login --shared`).":"skipped \u2014 jobs won't run until you set the token with `codepipe login`."),"")}async function pc(){for(;;){let t=G(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=G(await _t({message:"YouTrack PAT (YOUTRACK_TOKEN)",validate:r=>r&&r.trim().length>0?void 0:"required"})).trim();if(await ar("YouTrack",()=>Be({baseUrl:t,token:e}))){let r=await Li({baseUrl:t,token:e});return{url:t,token:e,...r?{login:r}:{}}}b.warn("re-enter the YouTrack URL / token.")}}import{readFileSync as hf}from"node:fs";function W(t){throw new Error(t)}function J(t,e){return(typeof t!="string"||t.trim().length===0)&&W(`config: '${e}' must be a non-empty string`),t.trim()}function cr(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 yf(t){(!t||typeof t!="object")&&W("config: expected a JSON object");let e=t,r=J(e.hubUrl,"hubUrl").replace(/\/$/,"");r.startsWith("http")||W("config: 'hubUrl' must start with http(s)://");let o=J(e.cliToken,"cliToken"),n=e.project;(!n||typeof n!="object")&&W("config: 'project' is required");let i=n,s=J(i.id,"project.id");Ve.test(s)||W("config: 'project.id' must match /^[a-z][a-z0-9-]{1,30}$/");let a=J(i.name,"project.name"),c=J(i.automationLevel,"project.automationLevel");c!=="assisted"&&c!=="full"&&W("config: 'project.automationLevel' must be 'assisted' or 'full'");let l=i.repos;Array.isArray(l)||W("config: 'project.repos' must be an array");let p=l.map((S,E)=>{(!S||typeof S!="object")&&W(`config: project.repos[${E}] must be an object`);let I=S,B=J(I.host,`project.repos[${E}].host`);B!=="github"&&B!=="bitbucket"&&B!=="gitlab"&&W(`config: project.repos[${E}].host must be 'github', 'bitbucket' or 'gitlab'`);let C={name:J(I.name,`project.repos[${E}].name`),host:B,owner:J(I.owner,`project.repos[${E}].owner`),repoName:J(I.repoName,`project.repos[${E}].repoName`)},_=cr(I.defaultBranch,`project.repos[${E}].defaultBranch`);_&&(C.defaultBranch=_);let R=cr(I.mountAs,`project.repos[${E}].mountAs`);return R&&(C.mountAs=R),C}),f=i.contextRepo;(!f||typeof f!="object")&&W("config: 'project.contextRepo' is required");let u=f,d=cr(u.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:J(u.owner,"project.contextRepo.owner"),name:cr(u.name,"project.contextRepo.name")??Se(s)},y={hubUrl:r,cliToken:o,project:{id:s,name:a,automationLevel:c,repos:p,contextRepo:g}},v=cr(i.youtrackProjectKey,"project.youtrackProjectKey");v&&(y.project.youtrackProjectKey=v),i.index!==void 0&&(typeof i.index!="boolean"&&W("config: 'project.index' must be a boolean"),y.project.index=i.index),i.youtrackWrites!==void 0&&(typeof i.youtrackWrites!="boolean"&&W("config: 'project.youtrackWrites' must be a boolean"),y.project.youtrackWrites=i.youtrackWrites);let x=e.secrets;if(x!==void 0){(typeof x!="object"||x===null)&&W("config: 'secrets' must be an object");let S=x,E={};if(S.github){let I=S.github;E.github={token:J(I.token,"secrets.github.token")}}if(S.bitbucket){let I=S.bitbucket;E.bitbucket={email:J(I.email,"secrets.bitbucket.email"),apiToken:J(I.apiToken,"secrets.bitbucket.apiToken")}}if(S.gitlab){let I=S.gitlab;E.gitlab={token:J(I.token,"secrets.gitlab.token")}}if(S.youtrack){let I=S.youtrack;E.youtrack={url:J(I.url,"secrets.youtrack.url").replace(/\/$/,""),token:J(I.token,"secrets.youtrack.token")}}if(S.contextWrite){let I=S.contextWrite;E.contextWrite={token:J(I.token,"secrets.contextWrite.token")}}y.secrets=E}return y}async function wf(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}async function bf(t){let e=t.secrets;if(e){if(e.github){let r=t.project.contextRepo,o=await Ne(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 Oe(e.bitbucket.email,e.bitbucket.apiToken,r);console.log(` Bitbucket OK \u2014 ${o}`)}if(e.gitlab){let r=await Ue(e.gitlab.token);console.log(` GitLab OK \u2014 ${r}`)}if(e.youtrack){let r=await Be({baseUrl:e.youtrack.url,token:e.youtrack.token});console.log(` YouTrack OK \u2014 ${r}`)}}}async function dc(t){let e=!t.configPath||t.configPath==="-"?await wf():hf(t.configPath,"utf-8"),r;try{r=JSON.parse(e)}catch(u){W(`config: invalid JSON \u2014 ${u instanceof Error?u.message:String(u)}`)}let o=yf(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 bf(o));let a={projectId:s.id,name:s.name,automationLevel:s.automationLevel,repos:s.repos};s.youtrackProjectKey&&(a.youtrackProjectKey=s.youtrackProjectKey),console.log(`provisioning Context Repo ${s.contextRepo.owner}/${s.contextRepo.name} (${s.contextRepo.host})\u2026`);let c=o.secrets?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,l;try{l=await Pt(a,s.contextRepo,{githubToken:c,gitlabToken:o.secrets?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:o.secrets?.bitbucket??mt(),youtrackWrites:s.youtrackWrites??!0,trackerUrl:o.secrets?.youtrack?.url,log:{info:u=>console.log(` ${u}`),warn:u=>console.warn(` ${u}`)}})}catch(u){W(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`)}a.contextRepo=l,console.log(`Context Repo ready: ${l.owner}/${l.name}@${l.branch}`),console.log(`registering project on ${n}\u2026`);let p;try{p=await xt(n,i,a)}catch(u){if(u instanceof A&&u.status===409)console.log(`project ${s.id} already exists on HUB \u2014 reusing it`),p=await Q(n,i,s.id);else if(u instanceof A)W(`HUB \u2192 ${u.status} ${u.message}`);else throw u}console.log(`project ${p.projectId} ready (${p.provisioningStatus})`);let f={hubUrl:n,cliToken:i,projectId:s.id,...o.secrets??{}};if(V(f),Qe({hubUrl:n,cliToken:i,projectId:s.id},s.id),console.log(`config + secrets written (profile ${s.id}) \u2192 ${Ze(s.id)}`),et(s.id,he(a,s.youtrackWrites??!0,o.secrets?.youtrack?.url),{info:u=>console.log(u),warn:u=>console.warn(u)}),s.index)try{let{jobId:u}=await Hr(n,i,s.id,{reindex:!1});console.log(`index job enqueued (job ${u}); runs once a SANDBOX claims it.`)}catch(u){console.warn(`could not enqueue index job: ${u instanceof Error?u.message:String(u)} (registration succeeded; retry later).`)}console.log(`done. start the daemon: codepipe --profile ${s.id} daemon`)}import{cancel as fc,intro as mc,isCancel as gc,log as cn,outro as kf,password as hc}from"@clack/prompts";async function $f(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8").trim()}async function yc(t){let e=t.token?.trim()??"";if(!e&&t.stdin&&(e=await $f(),e||(console.error("login: no token on stdin"),process.exit(1))),t.shared){if(!e){mc("codepipe login --shared \u2014 set the farm/machine-wide Claude OAuth token"),cn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hc({message:"Claude OAuth token"});gc(i)&&(fc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1)),Jn({claude:{oauthToken:e}}),console.log(`Claude OAuth token saved to ${Cr()} (shared). `),console.log("Every project without its own token will use it on the next job.");return}let r=Ae(t.profile);if(!e){mc(`codepipe login \u2014 set the Claude OAuth token for project ${r.projectId}`),cn.message("Run `claude setup-token` and paste the token below (input hidden).");let i=await hc({message:"Claude OAuth token"});gc(i)&&(fc("aborted"),process.exit(1)),e=i.trim()}e||(console.error("login: no token provided"),process.exit(1));let n=L(r.projectId)??{hubUrl:r.hubUrl,cliToken:r.cliToken,projectId:r.projectId};n.claude={oauthToken:e},V(n),t.stdin?console.log(`Claude OAuth token saved for project ${r.projectId}.`):(cn.success("Claude OAuth token saved."),kf("It will be sealed into job bundles when a SANDBOX (re)connects."))}import{cancel as xf,confirm as vf,intro as Sf,isCancel as wc,log as ee,outro as Cf,select as bc,text as We}from"@clack/prompts";function kc(t){xf(t),process.exit(1)}function Nt(t){return wc(t)&&kc("aborted"),t}function lr(t){return wc(t)&&kc("aborted"),typeof t=="string"?t:""}async function Tf(t,e){let r=Nt(await bc({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=lr(await We({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=lr(await We({message:"Context Repo name",placeholder:Se(t),initialValue:Se(t),validate:s=>s.trim().length>0?void 0:"required"})).trim();return{host:r,owner:n,name:i}}async function $c(t={profile:void 0}){let e=Ae(t.profile);Sf(`codepipe project add \u2192 ${e.hubUrl}`);let r=Nt(await We({message:"project_id (lowercase letters, digits, dashes; starts with a letter)",placeholder:"cp",validate:u=>Ve.test(u.trim())?void 0:"must match /^[a-z][a-z0-9-]{1,30}$/"})).trim(),o=Nt(await We({message:"project name (human-readable)",placeholder:"CodePartner",validate:u=>u.trim().length>0?void 0:"required"})).trim(),n=Nt(await bc({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=Nt(await We({message:"YouTrack project key (optional)",placeholder:"DEV"})).trim(),s=Nt(await vf({message:"Allow CodePipe to write to YouTrack? (status changes, PR comments, dashboard mirror)",initialValue:!0})),a=[];for(;;){let u=lr(await We({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:x=>!x||!x.trim()||Re(x)?void 0:"use git@host:owner/repo.git or https://host/owner/repo (github.com / gitlab.com / bitbucket.org)"})).trim();if(!u)break;let d=Re(u);ee.message(`${d.host}: ${d.owner}/${d.repoName}`);let g=lr(await We({message:"repo logical name (used inside Context Repo paths)",placeholder:d.repoName,initialValue:d.repoName,validate:x=>x.trim().length>0?void 0:"required"})).trim(),y=lr(await We({message:"default branch (optional)",placeholder:"main"})).trim(),v={name:g,host:d.host,owner:d.owner,repoName:d.repoName};y&&(v.defaultBranch=y),a.push(v)}let c={projectId:r,name:o,automationLevel:n,repos:a};i&&(c.youtrackProjectKey=i);let l=await Tf(r,a),p=L(e.projectId);ee.info(`provisioning Context Repo ${l.owner}/${l.name} (${l.host})\u2026`);let f;try{f=await Pt(c,l,{githubToken:p?.github?.token??process.env.GH_TOKEN??process.env.GITHUB_TOKEN,gitlabToken:p?.gitlab?.token??process.env.GITLAB_TOKEN,bitbucket:p?.bitbucket??mt(),youtrackWrites:s,trackerUrl:p?.youtrack?.url,log:{info:u=>ee.message(u),warn:u=>ee.warn(u)}})}catch(u){ee.error(`Context Repo provisioning failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}c.contextRepo=f,ee.info(`submitting \u2192 ${e.hubUrl}/projects`);try{let u=await xt(e.hubUrl,e.cliToken,c);ee.success(`project "${u.projectId}" \u2014 ${u.provisioningStatus}`),et(r,he(c,s,p?.youtrack?.url),{info:d=>ee.message(d),warn:d=>ee.warn(d)}),u.contextRepo&&(ee.message(` context repo: ${u.contextRepo.owner}/${u.contextRepo.name} (${u.contextRepo.cloneUrl})`),ee.message(` branch: ${u.contextRepo.branch}`)),u.provisioningError&&ee.error(` error: ${u.provisioningError}`),Cf("done")}catch(u){u instanceof A?(ee.error(`HUB \u2192 ${u.status} ${u.message}`),u.payload&&typeof u.payload=="object"&&ee.message(JSON.stringify(u.payload,null,2))):ee.error(u instanceof Error?u.message:String(u)),process.exit(1)}}import{spawn as Rf}from"node:child_process";import{existsSync as xc}from"node:fs";import{homedir as If,hostname as Pf}from"node:os";import{join as uo}from"node:path";async function jf(t,e,r){let o=oe(e);if(o){if(o.hubUrl===t.hubUrl.replace(/\/$/,"")){console.log(`[up] worker already registered as ${o.sandboxId} (${o.name})`);return}throw new Error(`worker config ${Me(e)} points at a different HUB (${o.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 n;try{({secret:n}=await Fr(t.hubUrl.replace(/\/$/,""),t.cliToken))}catch(i){throw i instanceof A&&i.status===401?new Error("HUB rejected the CLI token (401) \u2014 run `codepipe init` / check the config"):i instanceof A&&i.status===404?new Error("this HUB has no account-issued sandbox registration. Update the HUB, or register the worker manually: codepipe worker register --hub \u2026 --token \u2026"):i instanceof A?i:new Error(`cannot reach the HUB at ${t.hubUrl} (${i instanceof Error?i.message:String(i)}) \u2014 check the hub URL, or run from the project folder / pass --profile`)}await ot({hub:t.hubUrl,token:n,name:r.name??`${Pf()}-up`,llm:r.llm??"claude-headless",projects:r.projects??[],...e?{profile:e}:{}})}function Ef(t,e){let r=oe(e);if(!r?.sealPublicKey){console.warn("[up] worker has no cred-channel key \u2014 cred bundles will not flow (re-register)");return}let o=ye(r.sealPublicKey);if(!L(t)){console.warn(`[up] no secrets file for ${t} yet \u2014 the worker key pins on first sandbox_keys (TOFU)`);return}let n=Sr(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 Af(t,e){let r=process.cwd(),o=uo(r,me);if($r(t.projectId,r)){console.log(`[up] using the workspace context at ${o}`);return}if(xc(o)){console.warn(`[up] ${o} exists but is not this project's workspace \u2014 the context stays under ~/.codepipe/profiles`);return}let n;try{n=await Q(t.hubUrl,t.cliToken,t.projectId)}catch(p){console.warn(`[up] could not fetch the project summary (${p instanceof Error?p.message:String(p)}) \u2014 the context stays under ~/.codepipe/profiles`);return}let i=await an(r);if(!Nn(r,i?.parsed??null,n.repos)){console.log(`[up] this folder is neither empty nor a repo of ${t.projectId} \u2014 the context stays under ~/.codepipe/profiles`);return}let s=L(t.projectId),a={info:p=>console.log(p),warn:p=>console.warn(p)},c=await Yr({cfg:t,secrets:s,contextDir:o,log:a});if(!c?.contextDir){console.warn("[up] could not clone the Context Repo here \u2014 the context stays under ~/.codepipe/profiles");return}let l=uo(If(),".codepipe",e?uo("profiles",e,"context-config"):"context-config");if(Pr(c.contextDir,l,a),!xc(uo(c.contextDir,"project.yaml"))){wt(c.contextDir);let p={projectId:t.projectId,name:n.name,automationLevel:n.automationLevel,repos:n.repos,...n.youtrackProjectKey?{youtrackProjectKey:n.youtrackProjectKey}:{}};Kt(c.contextDir,he(p,!0,s?.youtrack?.url)),console.log("[up] local project config seeded with defaults \u2014 review .codepipe/project.yaml")}console.log(`[up] project context materialized \u2192 ${o}`)}async function vc(t){let{cfg:e,profile:r}=vr(t.profile);await Af(e,r),await jf(e,r,t),Ef(e.projectId,r);let o=process.argv[1];if(!o)throw new Error("cannot resolve the codepipe entry script for child processes");let n=(d,g)=>{let y=v=>x=>{for(let S of x.toString("utf-8").split(`
574
+ `))S.length>0&&v.write(`${g} ${S}
575
+ `)};d.stdout?.on("data",y(process.stdout)),d.stderr?.on("data",y(process.stderr))},i=(d,g)=>{let y=Rf(process.execPath,[o,...g],{stdio:["ignore","pipe","pipe"],env:process.env});return n(y,d),y};console.log(`[up] starting CLI daemon + embedded worker (project=${e.projectId})`);let s=i("[cli]",[...r?["--profile",r]:[],"daemon"]),a=i("[worker]",[...r?["--profile",r]:[],"worker","start"]),c=[{name:"daemon",child:s},{name:"worker",child:a}],l=!1,p=d=>{if(!l){l=!0,console.log(`
576
+ [up] ${d} \u2014 stopping both roles`);for(let{child:g}of c)g.exitCode===null&&g.kill(d);setTimeout(()=>{for(let{name:g,child:y}of c)y.exitCode===null&&(console.warn(`[up] ${g} did not stop \u2014 SIGKILL`),y.kill("SIGKILL"))},8e3).unref()}};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM"));let f=c.map(({name:d,child:g})=>new Promise(y=>{g.on("exit",(v,x)=>y({name:d,code:v??(x?1:0)}))})),u=await Promise.race(f);l||(console.log(`[up] ${u.name} exited (code ${u.code}) \u2014 stopping the other role`),p("SIGTERM")),await Promise.all(f),process.exit(u.code)}import{existsSync as Oc,mkdirSync as Lf,readFileSync as Bf,writeFileSync as Df}from"node:fs";import{homedir as Gf}from"node:os";import{dirname as Mf,join as Uc}from"node:path";import*as Ut from"node:readline";import{existsSync as pn,readFileSync as _f,writeFileSync as Nf}from"node:fs";import{join as pr}from"node:path";import{simpleGit as un}from"simple-git";var Sc=["-c","user.name=CodePipe","-c","user.email=codepipe@codepartner.ee"],Of="apply-queue.json";function Cc(t){return pr(t,Of)}function Ot(t){let e=Cc(t);if(!pn(e))return{};try{return JSON.parse(_f(e,"utf-8"))}catch{return{}}}function Tc(t,e){Nf(Cc(t),JSON.stringify(e,null,2)+`
577
+ `)}async function Rc(t,e,r,o,n){let i;try{i=await Ts(e.hubUrl,e.cliToken,t.spec.projectId,r)}catch(u){return{ok:!1,message:`claim failed: ${u instanceof Error?u.message:String(u)}`}}let s=[];for(let u of i.repos){let d=t.spec.repos.find(x=>x.name===u.repoName);if(!d)return{ok:!1,message:`repo "${u.repoName}" not in project.yaml \u2014 run /sync`};let g=pr(t.root,d.mountAs);if(!pn(pr(g,".git")))return{ok:!1,message:`${d.mountAs}/ not cloned \u2014 run /sync first`};if(!(await un(g).status()).isClean())return{ok:!1,message:`${d.mountAs}/ has uncommitted changes \u2014 commit or stash first`};s.push({claimRepo:u,spec:d,dir:g})}let a=[];for(let u of s){let d=un(u.dir),g=await Uf(d),y=u.claimRepo;try{await d.fetch()}catch(S){return await ln(a,n),{ok:!1,message:`fetch failed in ${u.spec.mountAs}: ${ur(S)}`}}let v=`origin/${y.baseRef}`,x;try{x=await Ur(d,{contextRepoCloneUrl:y.contextRepoCloneUrl,deliveryRef:y.deliveryRef,deliverySha:y.deliverySha,baseSha:y.baseSha,commitMessage:y.commitMessage})}catch(S){return await ln(a,n),{ok:!1,message:`fetch delivery failed in ${u.spec.mountAs}: ${ur(S)}`}}a.push({git:d,dir:u.dir,mountAs:u.spec.mountAs,originalRef:g,branch:y.branchName,baseSha:v,deliveryCommit:x,startPoint:v})}let c=[];for(let u of a)try{if(o==="apply"){await u.git.checkout(["-B",u.branch,u.startPoint]),await u.git.raw([...Sc,"cherry-pick",u.deliveryCommit]);let d=(await u.git.revparse(["HEAD"])).trim();c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha,appliedSha:d})}else await u.git.checkout(["--detach",u.startPoint]),await u.git.raw([...Sc,"cherry-pick","--no-commit",u.deliveryCommit]),await u.git.raw(["cherry-pick","--quit"]).catch(()=>{}),c.push({mountAs:u.mountAs,branch:u.branch,baseSha:u.baseSha})}catch(d){return await u.git.raw(["cherry-pick","--abort"]).catch(()=>{}),await ln(a,n),{ok:!1,message:`apply failed in ${u.mountAs}: ${ur(d)} (rolled back all repos)`}}let l=Ot(t.contextDir);l[r]={mode:o,claimedAt:new Date().toISOString(),repos:c},Tc(t.contextDir,l);let p=c.map(u=>u.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}
578
578
  ${f}
579
- or: /abort ${r} --reason "..."`}}function un(t,e){let r=Nt(t);r[e]&&(delete r[e],Sc(t,r))}async function an(t,e){for(let r of t)try{await r.git.raw(["cherry-pick","--quit"]).catch(()=>{}),await r.git.checkout(["-f",r.originalRef]),await r.git.reset(["--hard",r.originalRef]),await r.git.raw(["branch","-D",r.branch]).catch(()=>{})}catch(o){e.warn(`rollback failed in ${r.mountAs}: ${ar(o)} \u2014 check manually`)}}async function Tc(t,e,r){let n=Nt(t.contextDir)[e];if(n){for(let i of n.repos){let s=cr(t.root,i.mountAs);if(!ln(cr(s,".git")))continue;let a=cn(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${ar(p)} \u2014 check manually`)}}un(t.contextDir,e)}}async function Nf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function ar(t){return t instanceof Error?t.message.trim():String(t)}var uo=Nc(Bf(),".codepipe","history"),Rc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Oc=500,Ic=40;async function Uc(){let t=Qe();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=U(t.spec.projectId);e||(console.error(`no secrets for project ${t.spec.projectId} at ~/.codepipe/secrets/${t.spec.projectId}.json. run \`codepipe init\` or \`codepipe clone\` to set them up.`),process.exit(1)),Mt(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=Nt(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
579
+ or: /abort ${r} --reason "..."`}}function dn(t,e){let r=Ot(t);r[e]&&(delete r[e],Tc(t,r))}async function ln(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}: ${ur(o)} \u2014 check manually`)}}async function Ic(t,e,r){let n=Ot(t.contextDir)[e];if(n){for(let i of n.repos){let s=pr(t.root,i.mountAs);if(!pn(pr(s,".git")))continue;let a=un(s),c=t.spec.repos.find(p=>p.mountAs===i.mountAs),l=c?`origin/${c.defaultBranch}`:i.baseSha;try{await a.checkout(["-f",l]),await a.reset(["--hard",l]),await a.raw(["branch","-D",i.branch]).catch(()=>{})}catch(p){r.warn(`rollback failed in ${i.mountAs}: ${ur(p)} \u2014 check manually`)}}dn(t.contextDir,e)}}async function Uf(t){let e=(await t.revparse(["--abbrev-ref","HEAD"])).trim();return e&&e!=="HEAD"?e:(await t.revparse(["HEAD"])).trim()}function ur(t){return t instanceof Error?t.message.trim():String(t)}var po=Uc(Gf(),".codepipe","history"),Pc=["/help","/status","/tasks","/task","/sync","/apply","/unstash","/applied","/abort","/approve","/merge","/logs","/monitor","/secret","/login","/quit"],Lc=500,jc=40;async function Bc(){let t=Xe();t||(console.error("no .codepipe/ workspace found here or in any parent. run `codepipe init` first."),process.exit(1));let e=L(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)),Ht(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=Ot(t.contextDir),o=Object.keys(r);o.length>0&&console.log(`
580
580
  \u26A0 unfinished local apply: ${o.map(s=>`${s} (${r[s].repos.map(a=>a.mountAs).join(", ")})`).join("; ")}
581
- finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Ot.createInterface({input:process.stdin,output:process.stdout,completer:Gf,history:sm(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ls(s=>ct(i,s)),i.daemon=Kr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>ct(i,s),warn:s=>ct(i,s)},onEvent:s=>em(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),dn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Mf(i,a)){Ac(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,dn(i),n.prompt()}),n.on("close",()=>{Ac(i)})}function Gf(t){let e=Rc.filter(r=>r.startsWith(t));return[e.length?e:Rc,t]}async function Mf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Ff(),!1;case"/status":return await Hf(t),!1;case"/tasks":return await Kf(t,o),!1;case"/task":return await Wf(t,o),!1;case"/sync":return await qf(t),!1;case"/logs":return tm(t,o),!1;case"/monitor":return rm(t),!1;case"/apply":return await Pc(t,o,"apply"),!1;case"/unstash":return await Pc(t,o,"unstash"),!1;case"/applied":return await Yf(t,o),!1;case"/abort":return await Vf(t,o),!1;case"/approve":return await jc(t,o,"approve"),!1;case"/merge":return await jc(t,o,"merge"),!1;case"/login":return Jf(t,o),!1;case"/secret":return Xf(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Ff(){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(`
582
- `))}async function Hf(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=_c(Nc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function Kf(t,e){let r=om(e,"--phase");try{let o=await xs(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){ur(o)}}async function Wf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await vs(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){ur(o)}}async function qf(t){let e=await or(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 Pc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}let n=await Cc(t.ws,t.secrets,o,r,{info:i=>console.log(i),warn:i=>console.warn(i)});console.log(` ${n.message}`)}async function Yf(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=Nt(t.ws.contextDir)[r],i=nm(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),p,f;if(l>0?(p=c.slice(0,l),f=c.slice(l+1)):(f=c,p=n?.repos.length===1?zf(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 u=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(u[1])})}try{let c=await Cs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);un(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){ur(c)}}async function jc(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await Rs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){ur(n)}}async function Vf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=im(e,"--reason")||"local apply aborted";await Tc(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await Ts(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){ur(n)}}function zf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Jf(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 Xf(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(`
583
- `)}`:" (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}Qf(t.secrets,o,i),z(t.secrets),Mt(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}Zf(t.secrets,o),z(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function Qf(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 Zf(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 em(t,e){switch(e.kind){case"connected":t.connection="connecting",ct(t,"[hub] connected");break;case"registered":t.connection="registered",ct(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",lr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",ct(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",lr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":lr(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?ct(t,`[hub] action ${e.actionType} done`):lr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function ct(t,e){t.logBuffer.push(e),t.logBuffer.length>Oc&&t.logBuffer.shift(),t.follow&&lr(t,e)}function tm(t,e){let r=e[0];if(r==="follow"||r==="on"){pn(t,!0);return}if(r==="off"){pn(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(Oc,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 rm(t){pn(t,!t.follow)}function pn(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function lr(t,e){Ot.cursorTo(process.stdout,0),Ot.clearLine(process.stdout,0),process.stdout.write(e+`
584
- `),t.unread+=1,dn(t),t.rl.prompt(!0)}function dn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var Ec=!1;function Ac(t){Ec||(Ec=!0,am(t.rl),t.daemon.stop(),console.log(`
585
- bye.`),setTimeout(()=>process.exit(0),150))}function om(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function nm(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 im(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function ur(t){t instanceof _?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function sm(){if(!_c(uo))return[];try{return Uf(uo,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function am(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{Of(Df(uo),{recursive:!0}),Lf(uo,r.slice().reverse().join(`
581
+ finish with /applied <key> --pr <url> or /abort <key>`),console.log("");let n=Ut.createInterface({input:process.stdin,output:process.stdout,completer:Ff,history:cm(),removeHistoryDuplicates:!0}),i={ws:t,secrets:e,connection:"connecting",rl:n,unread:0,daemon:void 0,follow:!1,logBuffer:[]};ps(s=>at(i,s)),i.daemon=qr({hubUrl:e.hubUrl,cliToken:e.cliToken,projectId:t.spec.projectId},{log:{info:s=>at(i,s),warn:s=>at(i,s)},onEvent:s=>rm(i,s),workspace:{root:t.root,contextDir:t.contextDir,repos:t.spec.repos.map(s=>({name:s.name,mountAs:s.mountAs,defaultBranch:s.defaultBranch}))}}),mn(i),n.prompt(),n.on("line",async s=>{let a=s.trim();if(a.length>0)try{if(await Hf(i,a)){Nc(i);return}}catch(c){console.error(c instanceof Error?c.message:String(c))}i.unread=0,mn(i),n.prompt()}),n.on("close",()=>{Nc(i)})}function Ff(t){let e=Pc.filter(r=>r.startsWith(t));return[e.length?e:Pc,t]}async function Hf(t,e){let[r,...o]=e.split(/\s+/);switch(r){case"/help":return Kf(),!1;case"/status":return await Wf(t),!1;case"/tasks":return await qf(t,o),!1;case"/task":return await Yf(t,o),!1;case"/sync":return await Vf(t),!1;case"/logs":return om(t,o),!1;case"/monitor":return nm(t),!1;case"/apply":return await Ec(t,o,"apply"),!1;case"/unstash":return await Ec(t,o,"unstash"),!1;case"/applied":return await zf(t,o),!1;case"/abort":return await Jf(t,o),!1;case"/approve":return await Ac(t,o,"approve"),!1;case"/merge":return await Ac(t,o,"merge"),!1;case"/login":return Qf(t,o),!1;case"/secret":return Zf(t,o),!1;case"/quit":case"/exit":return!0;default:return console.log(`unknown command: ${r}. /help for the list.`),!1}}function Kf(){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(`
582
+ `))}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=Oc(Uc(t.ws.root,r.mountAs,".git"));console.log(` ${r.mountAs}: ${o?"present":"missing (run /sync)"}`)}}async function qf(t,e){let r=im(e,"--phase");try{let o=await Ss(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){fr(o)}}async function Yf(t,e){let r=e[0];if(!r){console.log("usage: /task <key>");return}try{let o=await Cs(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){fr(o)}}async function Vf(t){let e=await sr(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 Ec(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 zf(t,e){let r=e[0];if(!r){console.log("usage: /applied <key> --pr <url> (or --pr repo=<url> per repo)");return}let n=Ot(t.ws.contextDir)[r],i=sm(e,"--pr");if(i.length===0){console.log(" --pr <url> required (the PR you opened after pushing)");return}let s=t.ws.spec.repos.map(c=>c.name),a=[];for(let c of i){let l=c.indexOf("="),p,f;if(l>0?(p=c.slice(0,l),f=c.slice(l+1)):(f=c,p=n?.repos.length===1?Xf(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 u=f.match(/(?:pull|pull-requests)\/(\d+)/);if(!u){console.log(` cannot parse PR number from ${f}`);return}a.push({repoName:p,url:f,number:Number(u[1])})}try{let c=await Rs(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,a);dn(t.ws.contextDir,r),console.log(` ${r} \u2192 ${c.task.phase}`)}catch(c){fr(c)}}async function Ac(t,e,r){let o=e[0];if(!o){console.log(`usage: /${r} <key>`);return}try{let n=await Ps(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,o,r);console.log(` ${r} ${o} \u2192 ${n.task.phase}`)}catch(n){fr(n)}}async function Jf(t,e){let r=e[0];if(!r){console.log('usage: /abort <key> --reason "why"');return}let o=am(e,"--reason")||"local apply aborted";await Ic(t.ws,r,{info:n=>console.log(n),warn:n=>console.warn(n)});try{let n=await Is(t.secrets.hubUrl,t.secrets.cliToken,t.ws.spec.projectId,r,o);console.log(` ${r} \u2192 ${n.task.phase} (rolled back locally)`)}catch(n){fr(n)}}function Xf(t,e){return t.ws.spec.repos.find(r=>r.mountAs===e)?.name??""}function Qf(t,e){let r=e.join(" ").trim();if(!r){console.log("usage: /login <claude-oauth-token>"),console.log(" get one with `claude setup-token`, then paste it here."),console.log(" (this line is scrubbed from history; takes effect on next SANDBOX reconnect)");return}t.secrets.claude={oauthToken:r},V(t.secrets),console.log(" Claude OAuth token saved. It will be sealed into job bundles for SANDBOXes."),console.log(" Re-seal happens when a SANDBOX (re)connects; restart it if you need it now.")}function Zf(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(`
583
+ `)}`:" (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}em(t.secrets,o,i),V(t.secrets),Ht(t.secrets),console.log(` set ${o}`);return}if(r==="unset"){if(!o){console.log("usage: /secret unset <key>");return}tm(t.secrets,o),V(t.secrets),console.log(` unset ${o}`);return}console.log("usage: /secret set|list|unset")}function em(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 tm(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 rm(t,e){switch(e.kind){case"connected":t.connection="connecting",at(t,"[hub] connected");break;case"registered":t.connection="registered",at(t,`[hub] registered for ${e.projectId}`);break;case"register_rejected":t.connection="rejected",dr(t,`[hub] register rejected: ${e.reason}`);break;case"disconnected":t.connection="offline",at(t,`[hub] disconnected (code ${e.code})`);break;case"replaced":t.connection="rejected",dr(t,"[hub] this project was taken over by another CLI \u2014 daemon stood down (run one CLI per project)");break;case"incompatible":dr(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?at(t,`[hub] action ${e.actionType} done`):dr(t,`[hub] action ${e.actionType} FAILED: ${e.error??"?"}`);break}}function at(t,e){t.logBuffer.push(e),t.logBuffer.length>Lc&&t.logBuffer.shift(),t.follow&&dr(t,e)}function om(t,e){let r=e[0];if(r==="follow"||r==="on"){fn(t,!0);return}if(r==="off"){fn(t,!1);return}if(r==="clear"){t.logBuffer=[],console.log(" log buffer cleared");return}let o=r?Math.max(1,Math.min(Lc,Number(r)||jc)):jc,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 nm(t){fn(t,!t.follow)}function fn(t,e){t.follow=e,console.log(e?" live daemon logs ON \u2014 /monitor or /logs off to stop":" live daemon logs OFF")}function dr(t,e){Ut.cursorTo(process.stdout,0),Ut.clearLine(process.stdout,0),process.stdout.write(e+`
584
+ `),t.unread+=1,mn(t),t.rl.prompt(!0)}function mn(t){let e=t.unread>0?" \u2605":"";t.rl.setPrompt(`codepipe (${t.ws.spec.projectId})${e} > `)}var _c=!1;function Nc(t){_c||(_c=!0,lm(t.rl),t.daemon.stop(),console.log(`
585
+ bye.`),setTimeout(()=>process.exit(0),150))}function im(t,e){let r=t.indexOf(e);if(r>=0&&t[r+1])return t[r+1]}function sm(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 am(t,e){let r=t.indexOf(e);return r<0?"":t.slice(r+1).join(" ").replace(/^["']|["']$/g,"").trim()}function fr(t){t instanceof A?console.log(` HUB \u2192 ${t.status} ${t.message}`):console.log(` ${t instanceof Error?t.message:String(t)}`)}function cm(){if(!Oc(po))return[];try{return Bf(po,"utf-8").split(/\r?\n/).filter(Boolean).reverse()}catch{return[]}}function lm(t){let r=(t.history??[]).filter(o=>!/^\/secret\s+set\b/.test(o)&&!/^\/login\b/.test(o));try{Lf(Mf(po),{recursive:!0}),Df(po,r.slice().reverse().join(`
586
586
  `)+`
587
- `)}catch{}}import{hostname as cm}from"node:os";import{cancel as lm,confirm as Lc,intro as um,isCancel as Gc,log as Ut,multiselect as pm,outro as Bc,password as dm,select as fn,text as mn}from"@clack/prompts";function pr(t){lm(t),process.exit(1)}function Lt(t){return Gc(t)&&pr("aborted"),t}function po(t){return Gc(t)&&pr("aborted"),typeof t=="string"?t:""}function gn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Dc(t,e){try{let{secret:r}=await Gr(t,e);return r}catch(r){throw r instanceof _&&r.status===404&&pr("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 fm(t,e){if(Lt(await fn({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 bs(t,e);if(n.length>0)return Lt(await pm({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}));Ut.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){Ut.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return po(await mn({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 hn(t){um("codepipe worker \u2014 set up this machine as a runner");let e=oe(t.profile);e&&(Ut.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Lt(await Lc({message:"re-register this worker?",initialValue:!1}))||pr("keeping the existing registration"));let r=Ce(t.profile)??Ce(),o=po(await mn({message:"HUB URL",placeholder:me,initialValue:N("HUB_URL")??r?.hubUrl??me,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=Lt(await fn({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 Dc(o,a),Ut.success("account-issued registration token minted");else if(i==="login"){let u=await ao();a=(await co(o,u)).cliToken,s=await Dc(o,a),Ut.success("account-issued registration token minted")}else s=po(await dm({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||pr("a registration token is required");let c=await fm(o,a),l=po(await mn({message:"worker name",initialValue:cm(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Lt(await fn({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 nt({hub:o,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Ut.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Lt(await Lc({message:"start the claim-loop now?",initialValue:!0}))){Bc("registered. start later with `codepipe worker`.");return}Bc("starting the claim-loop\u2026"),await rr(t.profile?{profile:t.profile}:{})}function gm(){let t=process.argv;for(let e=0;e<t.length;e++){let r=t[e];if(r==="--profile")return t[e+1];if(r&&r.startsWith("--profile="))return r.slice(10)}return N("PROFILE")}var te=gm();Ln(te);Gn();var ue=new mm;ue.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ce).option("--profile <id>","Profile id (project id). Picks `~/.codepipe/profiles/<id>/config.json` and `cli/profiles/<id>/.env`. Default = no profile = legacy single-project config at `~/.codepipe/config.json`.").action(async()=>{try{await Uc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await uc({configPath:t.config,skipVerify:t.skipVerify===!0}):await ec({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","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 zn({...t,profile:te})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await tc({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});ue.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await Ks({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await qa({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await gc({profile:te,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});ue.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Pa({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await $c({profile:te,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Mc=ue.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Mc.command("register").description("Register this machine as a SANDBOX worker with a HUB (no flags on a TTY \u2192 interactive wizard)").option("--hub <url>","HUB base URL (env CODEPIPE_HUB_URL)").option("--token <token>","Registration token (env CODEPIPE_WORKER_REG_TOKEN)").option("--name <name>","Human-readable name (env CODEPIPE_WORKER_NAME; defaults to hostname)").option("--projects <ids...>","Project IDs this worker can serve (env CODEPIPE_WORKER_PROJECTS, comma/space separated; empty = all your projects)").option("--llm <backend>","Agent backend: 'claude-headless' | 'mock' (env CODEPIPE_WORKER_LLM; omit for none)").option("--force","Overwrite existing registration",!1).action(async t=>{try{let e=t.hub??N("HUB_URL")??Ce(te)?.hubUrl??me,r=t.token??N("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&gn()){await hn({profile:te});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=N("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??N("WORKER_NAME"),i=t.llm??N("WORKER_LLM");await nt({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...te?{profile:te}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Mc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!oe(te)&&gn()){await hn({profile:te});return}await rr(te?{profile:te}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var hm=ue.command("project").description("Manage CodePipe projects");hm.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await bc({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});ue.parseAsync();
587
+ `)}catch{}}import{hostname as um}from"node:os";import{cancel as pm,confirm as Dc,intro as dm,isCancel as Fc,log as Lt,multiselect as fm,outro as Gc,password as mm,select as gn,text as hn}from"@clack/prompts";function mr(t){pm(t),process.exit(1)}function Bt(t){return Fc(t)&&mr("aborted"),t}function fo(t){return Fc(t)&&mr("aborted"),typeof t=="string"?t:""}function yn(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}async function Mc(t,e){try{let{secret:r}=await Fr(t,e);return r}catch(r){throw r instanceof A&&r.status===404&&mr("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 gm(t,e){if(Bt(await gn({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 $s(t,e);if(n.length>0)return Bt(await fm({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}));Lt.warn("your account owns no projects yet \u2014 enter the ids manually")}catch(n){Lt.warn(`could not list projects (${n instanceof Error?n.message:String(n)}) \u2014 enter the ids manually`)}return fo(await hn({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 wn(t){dm("codepipe worker \u2014 set up this machine as a runner");let e=oe(t.profile);e&&(Lt.warn(`already registered as ${e.sandboxId} (${e.name}) at ${e.hubUrl} \u2014 the wizard will replace this registration`),Bt(await Dc({message:"re-register this worker?",initialValue:!1}))||mr("keeping the existing registration"));let r=Ce(t.profile)??Ce(),o=fo(await hn({message:"HUB URL",placeholder:de,initialValue:O("HUB_URL")??r?.hubUrl??de,validate:u=>u.trim().startsWith("http")?void 0:"must start with http(s)://"})).trim().replace(/\/$/,""),n=r!==null&&r.hubUrl.replace(/\/$/,"")===o,i=Bt(await gn({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 Mc(o,a),Lt.success("account-issued registration token minted");else if(i==="login"){let u=await co();a=(await lo(o,u)).cliToken,s=await Mc(o,a),Lt.success("account-issued registration token minted")}else s=fo(await mm({message:"registration token (from Status \u2192 SANDBOX)"})).trim(),s||mr("a registration token is required");let c=await gm(o,a),l=fo(await hn({message:"worker name",initialValue:um(),validate:u=>u.trim().length>0?void 0:"required"})).trim(),p=Bt(await gn({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 ot({hub:o,token:s,name:l,projects:c,...p?{llm:p}:{},force:e!==null,...t.profile?{profile:t.profile}:{}}),Lt.message("the fingerprint above pins on the project CLI on first sight (TOFU); `codepipe up` pins it automatically"),!Bt(await Dc({message:"start the claim-loop now?",initialValue:!0}))){Gc("registered. start later with `codepipe worker`.");return}Gc("starting the claim-loop\u2026"),await ir(t.profile?{profile:t.profile}:{})}function ym(){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 O("PROFILE")}var te=ym();Dn(te);Fn();var le=new hm;le.name("codepipe").description("CodePipe CLI \u2014 local client that talks to HUB and performs real-world writes").version(ae).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 Bc()}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("init").description("Bootstrap a project: in an empty folder (repos clone as siblings) or in-place inside an existing git repo (origin prefilled, .codepipe/ inside). Magic-link auth; secrets to ~/.codepipe/secrets/<id>.json").option("--force","Bypass the empty-cwd guard",!1).option("--headless","Non-interactive provisioning from a JSON config (no prompts, no magic-link, no local clone) \u2014 for CLI farms").option("--config <path>","Headless config JSON path; '-' or omitted reads stdin").option("--skip-verify","Headless: skip live credential verification").action(async t=>{try{t.headless?await dc({configPath:t.config,skipVerify:t.skipVerify===!0}):await rc({force:t.force===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("config").description("Persist HUB URL, CLI token and project id without provisioning/cloning (dev & mock flow; used by `make cli-init`)").requiredOption("--hub <url>","HUB base URL, e.g. http://localhost:3030").requiredOption("--token <token>","CLI token (matches HUB_CLI_TOKEN on HUB)").requiredOption("--project <id>","Project id this CLI is bound to").option("--force","Overwrite existing config",!1).action(async t=>{try{await Xn({...t,profile:te})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("clone").description("Reconstruct an existing project's workspace in the current empty folder \u2014 for continuing work on another machine").argument("<projectId>","Project id (as registered on HUB)").option("--force","Bypass the empty-cwd guard",!1).action(async(t,e)=>{try{await oc({projectId:t,force:e.force===!0})}catch(r){console.error(r instanceof Error?r.message:r),process.exit(1)}});le.command("daemon").description("Long-running WS daemon that executes WriteActions dispatched by HUB").action(async()=>{try{await qs({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("sync").description("Clone/fetch project repos as siblings of .codepipe/ per project.yaml").option("--dry-run","Show what would happen without touching the filesystem",!1).action(async t=>{try{await Va({dryRun:t.dryRun===!0})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("login").description("Set the Claude OAuth token (sealed into job bundles)").option("--token <token>","Provide the token non-interactively").option("--shared","Save to the machine/farm-wide ~/.codepipe/shared.json instead of this project").option("--stdin","Read the token from stdin (for scripted/ssh delivery)").action(async t=>{try{await yc({profile:te,token:t.token,shared:t.shared,stdin:t.stdin})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});le.command("hello").description("Open WS to HUB, ping/pong, exit (smoke-test for connectivity & auth)").action(async()=>{try{await Ea({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.command("up").description("Run the CLI daemon and an embedded SANDBOX worker together (solo-developer mode)").option("--name <name>","Worker name (defaults to <hostname>-up; used on first registration)").option("--llm <backend>","Worker agent backend on first registration: 'claude-headless' (default) | 'mock'").option("--projects <ids...>","Project IDs the worker may serve on first registration (empty = all your projects)").action(async t=>{try{await vc({profile:te,...t})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});var Hc=le.command("worker").description("SANDBOX worker role \u2014 claims jobs from HUB and executes agent work");Hc.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??O("HUB_URL")??Ce(te)?.hubUrl??de,r=t.token??O("WORKER_REG_TOKEN");if(!r){if(!t.hub&&!t.token&&yn()){await wn({profile:te});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=O("WORKER_PROJECTS")?.split(/[\s,]+/).filter(Boolean),n=t.name??O("WORKER_NAME"),i=t.llm??O("WORKER_LLM");await ot({hub:e,token:r,projects:t.projects?.length?t.projects:o??[],force:t.force===!0,...n?{name:n}:{},...i?{llm:i}:{},...te?{profile:te}:{}})}catch(e){console.error(e instanceof Error?e.message:e),process.exit(1)}});Hc.command("start",{isDefault:!0}).description("Connect to HUB and run the claim-loop (default subcommand)").action(async()=>{try{if(!oe(te)&&yn()){await wn({profile:te});return}await ir(te?{profile:te}:{})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});var wm=le.command("project").description("Manage CodePipe projects");wm.command("add").description("Interactive wizard to register a project with HUB and auto-provision Context Repo").action(async()=>{try{await $c({profile:te})}catch(t){console.error(t instanceof Error?t.message:t),process.exit(1)}});le.parseAsync();